@0xpolygonid/js-sdk 1.45.0 → 1.46.1

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.
@@ -420,7 +420,7 @@ if (cid) {
420
420
  `?i="":(i!==""&&(i+=" "),i+=l)},showSharedRWMemory:function(){u()}}}),s=e;return new IO(o,s);function c(){let l="",d=o.exports.getMessageChar();for(;d!=0;)l+=String.fromCharCode(d),d=o.exports.getMessageChar();return l}function u(){let l=o.exports.getFieldNumLen32(),d=new Uint32Array(l);for(let h=0;h<l;h++)d[l-1-h]=o.exports.readSharedRWMemory(h);i!==""&&(i+=" "),i+=AO(d).toString()}}var IO=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=AO(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=BLe(o),a=parseInt(s.slice(0,8),16),c=parseInt(s.slice(8,16),16),u=TLe(e[o]),l=this.instance.exports.getInputSignalSize(a,c);if(l<0)throw new Error(`Signal ${o} not found
421
421
  `);if(u.length<l)throw new Error(`Not enough values for input signal ${o}
422
422
  `);if(u.length>l)throw new Error(`Too many values for input signal ${o}
423
- `);for(let d=0;d<u.length;d++){let h=DLe(BigInt(u[d])%this.prime,this.n32);for(let f=0;f<this.n32;f++)this.instance.exports.writeSharedRWMemory(f,h[this.n32-1-f]);try{this.instance.exports.setInputSignal(a,c,d),i++}catch(f){throw new Error(f)}}}),i<this.instance.exports.getInputSize())throw new Error(`Not all inputs have been set. Only ${i} out of ${this.instance.exports.getInputSize()}`)}async calculateWitness(e,t){let r=[];await this._doCalculateWitness(e,t);for(let i=0;i<this.witnessSize;i++){this.instance.exports.getWitness(i);let o=new Uint32Array(this.n32);for(let s=0;s<this.n32;s++)o[this.n32-1-s]=this.instance.exports.readSharedRWMemory(s);r.push(AO(o))}return r}async calculateBinWitness(e,t){let r=new Uint32Array(this.witnessSize*this.n32),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t);for(let o=0;o<this.witnessSize;o++){this.instance.exports.getWitness(o);let s=o*this.n32;for(let a=0;a<this.n32;a++)r[s+a]=this.instance.exports.readSharedRWMemory(a)}return i}async calculateWTNSBin(e,t){let r=new Uint32Array(this.witnessSize*this.n32+this.n32+11),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t),i[0]=119,i[1]=116,i[2]=110,i[3]=115,r[1]=2,r[2]=2,r[3]=1;let o=this.n32*4,a=(8+o).toString(16);r[4]=parseInt(a.slice(0,8),16),r[5]=parseInt(a.slice(8,16),16),r[6]=o,this.instance.exports.getRawPrime();let c=7;for(let d=0;d<this.n32;d++)r[c+d]=this.instance.exports.readSharedRWMemory(d);c+=this.n32,r[c]=this.witnessSize,c++,r[c]=2,c++;let l=(o*this.witnessSize).toString(16);r[c]=parseInt(l.slice(0,8),16),r[c+1]=parseInt(l.slice(8,16),16),c+=2;for(let d=0;d<this.witnessSize;d++){this.instance.exports.getWitness(d);for(let h=0;h<this.n32;h++)r[c+h]=this.instance.exports.readSharedRWMemory(h);c+=this.n32}return i}};function DLe(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 AO(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 TLe(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 BLe(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 Vy=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function $E(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function xO(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Kc(n,...e){if(!$E(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 Fee(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");xO(n.outputLen),xO(n.blockLen)}function $C(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 PLe(n,e){Kc(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function e8(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function dO(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Ju(n,e){return n<<32-e|n>>>e}var Nee=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kLe=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function zy(n){if(Kc(n),Nee)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=kLe[n[t]];return e}var wd={_0:48,_9:57,A:65,F:70,a:97,f:102};function mee(n){if(n>=wd._0&&n<=wd._9)return n-wd._0;if(n>=wd.A&&n<=wd.F)return n-(wd.A-10);if(n>=wd.a&&n<=wd.f)return n-(wd.a-10)}function t8(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(Nee)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=mee(n.charCodeAt(o)),a=mee(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 eI(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function KO(n){return typeof n=="string"&&(n=eI(n)),Kc(n),n}function Fi(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];Kc(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 n8=class{};function MLe(n){let e=r=>n().update(KO(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function JO(n=32){if(Vy&&typeof Vy.getRandomValues=="function")return Vy.getRandomValues(new Uint8Array(n));if(Vy&&typeof Vy.randomBytes=="function")return Uint8Array.from(Vy.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function OLe(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,u=r?0:4;n.setUint32(e+c,s,r),n.setUint32(e+u,a,r)}function FLe(n,e,t){return n&e^~n&t}function NLe(n,e,t){return n&e^n&t^e&t}var vO=class extends n8{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=dO(this.buffer)}update(e){$C(this),e=KO(e),Kc(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=dO(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){$C(this),PLe(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,e8(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;OLe(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=dO(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,l[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()}},yh=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ULe=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]),wh=new Uint32Array(64),SO=class extends vO{constructor(e=32){super(64,e,8,!1),this.A=yh[0]|0,this.B=yh[1]|0,this.C=yh[2]|0,this.D=yh[3]|0,this.E=yh[4]|0,this.F=yh[5]|0,this.G=yh[6]|0,this.H=yh[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)wh[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=wh[d-15],f=wh[d-2],m=Ju(h,7)^Ju(h,18)^h>>>3,w=Ju(f,17)^Ju(f,19)^f>>>10;wh[d]=w+wh[d-7]+m+wh[d-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:u,H:l}=this;for(let d=0;d<64;d++){let h=Ju(a,6)^Ju(a,11)^Ju(a,25),f=l+h+FLe(a,c,u)+ULe[d]+wh[d]|0,w=(Ju(r,2)^Ju(r,13)^Ju(r,22))+NLe(r,i,o)|0;l=u,u=c,c=a,a=s+f|0,s=o,o=i,i=r,r=f+w|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,u=u+this.G|0,l=l+this.H|0,this.set(r,i,o,s,a,c,u,l)}roundClean(){e8(wh)}destroy(){this.set(0,0,0,0,0,0,0,0),e8(this.buffer)}},Uee=MLe(()=>new SO);var qO=BigInt(0),r8=BigInt(1);function i8(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function K0(n,e,t=""){let r=$E(n),i=n?.length,o=e!==void 0;if(!r||o&&i!==e){let s=t&&`"${t}" `,a=o?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof n}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return n}function jC(n){let e=n.toString(16);return e.length&1?"0"+e:e}function Gee(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?qO:BigInt("0x"+n)}function tI(n){return Gee(zy(n))}function Hee(n){return Kc(n),Gee(zy(Uint8Array.from(n).reverse()))}function VO(n,e){return t8(n.toString(16).padStart(e*2,"0"))}function Kee(n,e){return VO(n,e).reverse()}function ao(n,e,t){let r;if(typeof e=="string")try{r=t8(e)}catch(i){throw new Error(n+" must be hex string or Uint8Array, cause: "+i)}else if($E(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");return r}var fO=n=>typeof n=="bigint"&&qO<=n;function Jee(n,e,t){return fO(n)&&fO(e)&&fO(t)&&e<=n&&n<t}function GLe(n,e,t,r){if(!Jee(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function WE(n){let e;for(e=0;n>qO;n>>=r8,e+=1);return e}function HLe(n,e){return n>>BigInt(e)&r8}var nI=n=>(r8<<BigInt(n))-r8;function KLe(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},u=(...f)=>t(s,o,...f),l=(f=r(0))=>{s=u(i(0),f),o=u(),f.length!==0&&(s=u(i(1),f),o=u())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,m=[];for(;f<e;){o=u();let w=o.slice();m.push(w),f+=o.length}return Fi(...m)};return(f,m)=>{c(),l(f);let w;for(;!(w=m(d()));)l();return c(),w}}function JLe(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function u8(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 ui=()=>{throw new Error("not implemented")};function CO(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 ea=BigInt(0),Wo=BigInt(1),J0=BigInt(2),qee=BigInt(3),Vee=BigInt(4),Qee=BigInt(5),qLe=BigInt(7),zee=BigInt(8),VLe=BigInt(9),Yee=BigInt(16);function Ha(n,e){let t=n%e;return t>=ea?t:e+t}function gee(n,e){if(n===ea)throw new Error("invert: expected non-zero number");if(e<=ea)throw new Error("invert: expected positive modulus, got "+e);let t=Ha(n,e),r=e,i=ea,o=Wo;for(;t!==ea;){let a=r/t,c=r%t,u=i-o*a;r=t,t=c,i=o,o=u}if(r!==Wo)throw new Error("invert: does not exist");return Ha(i,e)}function QO(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function jee(n,e){let t=(n.ORDER+Wo)/Vee,r=n.pow(e,t);return QO(n,r,e),r}function QLe(n,e){let t=(n.ORDER-Qee)/zee,r=n.mul(e,J0),i=n.pow(r,t),o=n.mul(e,i),s=n.mul(n.mul(o,J0),i),a=n.mul(o,n.sub(s,n.ONE));return QO(n,a,e),a}function zLe(n){let e=jy(n),t=Wee(n),r=t(e,e.neg(e.ONE)),i=t(e,r),o=t(e,e.neg(r)),s=(n+qLe)/Yee;return(a,c)=>{let u=a.pow(c,s),l=a.mul(u,r),d=a.mul(u,i),h=a.mul(u,o),f=a.eql(a.sqr(l),c),m=a.eql(a.sqr(d),c);u=a.cmov(u,l,f),l=a.cmov(h,d,m);let w=a.eql(a.sqr(l),c),b=a.cmov(u,l,w);return QO(a,b,c),b}}function Wee(n){if(n<qee)throw new Error("sqrt is not defined for small field");let e=n-Wo,t=0;for(;e%J0===ea;)e/=J0,t++;let r=J0,i=jy(n);for(;o8(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return jee;let o=i.pow(r,e),s=(e+Wo)/J0;return function(c,u){if(c.is0(u))return u;if(o8(c,u)!==1)throw new Error("Cannot find square root");let l=t,d=c.mul(c.ONE,o),h=c.pow(u,e),f=c.pow(u,s);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let m=1,w=c.sqr(h);for(;!c.eql(w,c.ONE);)if(m++,w=c.sqr(w),m===l)throw new Error("Cannot find square root");let b=Wo<<BigInt(l-m-1),S=c.pow(d,b);l=m,d=c.sqr(S),h=c.mul(h,d),f=c.mul(f,S)}return f}}function YLe(n){return n%Vee===qee?jee:n%zee===Qee?QLe:n%Yee===VLe?zLe(n):Wee(n)}var jLe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function WLe(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=jLe.reduce((r,i)=>(r[i]="function",r),e);return u8(n,t),n}function l8(n,e,t){if(t<ea)throw new Error("invalid exponent, negatives unsupported");if(t===ea)return n.ONE;if(t===Wo)return e;let r=n.ONE,i=e;for(;t>ea;)t&Wo&&(r=n.mul(r,i)),i=n.sqr(i),t>>=Wo;return r}function rI(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 o8(n,e){let t=(n.ORDER-Wo)/J0,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 Zee(n,e){e!==void 0&&xO(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function jy(n,e,t=!1,r={}){if(n<=ea)throw new Error("invalid field: expected ORDER > 0, got "+n);let i,o,s=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||t)throw new Error("cannot specify opts in two arguments");let h=e;h.BITS&&(i=h.BITS),h.sqrt&&(o=h.sqrt),typeof h.isLE=="boolean"&&(t=h.isLE),typeof h.modFromBytes=="boolean"&&(s=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(o=r.sqrt);let{nBitLength:c,nByteLength:u}=Zee(n,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l,d=Object.freeze({ORDER:n,isLE:t,BITS:c,BYTES:u,MASK:nI(c),ZERO:ea,ONE:Wo,allowedLengths:a,create:h=>Ha(h,n),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return ea<=h&&h<n},is0:h=>h===ea,isValidNot0:h=>!d.is0(h)&&d.isValid(h),isOdd:h=>(h&Wo)===Wo,neg:h=>Ha(-h,n),eql:(h,f)=>h===f,sqr:h=>Ha(h*h,n),add:(h,f)=>Ha(h+f,n),sub:(h,f)=>Ha(h-f,n),mul:(h,f)=>Ha(h*f,n),pow:(h,f)=>l8(d,h,f),div:(h,f)=>Ha(h*gee(f,n),n),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>gee(h,n),sqrt:o||(h=>(l||(l=YLe(n)),l(d,h))),toBytes:h=>t?Kee(h,u):VO(h,u),fromBytes:(h,f=!0)=>{if(a){if(!a.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);let w=new Uint8Array(u);w.set(h,t?0:w.length-h.length),h=w}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let m=t?Hee(h):tI(h);if(s&&(m=Ha(m,n)),!f&&!d.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:h=>rI(d,h),cmov:(h,f,m)=>m?f:h});return Object.freeze(d)}function Xee(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 zO(n){let e=Xee(n);return e+Math.ceil(e/2)}function _ee(n,e,t=!1){let r=n.length,i=Xee(e),o=zO(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?Hee(n):tI(n),a=Ha(s,e-Wo)+Wo;return t?Kee(a,i):VO(a,i)}var Yy=BigInt(0),q0=BigInt(1);function s8(n,e){let t=e.negate();return n?t:e}function jE(n,e){let t=rI(n.Fp,e.map(r=>r.Z));return e.map((r,i)=>n.fromAffine(r.toAffine(t[i])))}function $ee(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function hO(n,e){$ee(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=nI(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function yee(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+=q0);let u=e*r,l=u+Math.abs(a)-1,d=a===0,h=a<0,f=e%2!==0;return{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:f,offsetF:u}}function ZLe(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 XLe(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 pO=new WeakMap,ete=new WeakMap;function mO(n){return ete.get(n)||1}function wee(n){if(n!==Yy)throw new Error("invalid wNAF")}var LO=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let i=e;for(;t>Yy;)t&q0&&(r=r.add(i)),i=i.double(),t>>=q0;return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=hO(t,this.bits),o=[],s=e,a=s;for(let c=0;c<r;c++){a=s,o.push(a);for(let u=1;u<i;u++)a=a.add(s),o.push(a);s=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=hO(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:h,offsetF:f}=yee(r,a,s);r=c,l?o=o.add(s8(h,t[f])):i=i.add(s8(d,t[u]))}return wee(r),{p:i,f:o}}wNAFUnsafe(e,t,r,i=this.ZERO){let o=hO(e,this.bits);for(let s=0;s<o.windows&&r!==Yy;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=yee(r,s,o);if(r=a,!u){let d=t[c];i=i.add(l?d.negate():d)}}return wee(r),i}getPrecomputes(e,t,r){let i=pO.get(t);return i||(i=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(i=r(i)),pO.set(t,i))),i}cached(e,t,r){let i=mO(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let o=mO(e);return o===1?this._unsafeLadder(e,t,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,i)}createCache(e,t){$ee(t,this.bits),ete.set(e,t),pO.delete(e)}hasCache(e){return mO(e)!==1}};function _Le(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Yy||r>Yy;)t&q0&&(o=o.add(i)),r&q0&&(s=s.add(i)),i=i.double(),t>>=q0,r>>=q0;return{p1:o,p2:s}}function $Le(n,e,t,r){ZLe(t,n),XLe(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=WE(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=nI(c),l=new Array(Number(u)+1).fill(s),d=Math.floor((e.BITS-1)/c)*c,h=s;for(let f=d;f>=0;f-=c){l.fill(s);for(let w=0;w<o;w++){let b=r[w],S=Number(b>>BigInt(f)&u);l[S]=l[S].add(t[w])}let m=s;for(let w=l.length-1,b=s;w>0;w--)b=b.add(l[w]),m=m.add(b);if(h=h.add(m),f!==0)for(let w=0;w<c;w++)h=h.double()}return h}function bee(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return WLe(e),e}else return jy(n,{isLE:t})}function eRe(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>Yy))throw new Error(`CURVE.${c} must be positive bigint`)}let i=bee(e.p,t.Fp,r),o=bee(e.n,t.Fn,r),a=["Gx","Gy","a","b"];for(let c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}var tRe=tI;function bh(n,e){if(ZE(n),ZE(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 nRe(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 ZE(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function tte(n){if(!$E(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or string");return typeof n=="string"?eI(n):n}function rRe(n,e,t,r){Kc(n),ZE(t),e=tte(e),e.length>255&&(e=r(Fi(eI("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=Fi(e,bh(e.length,1)),c=bh(0,o),u=bh(t,2),l=new Array(s),d=r(Fi(c,n,u,bh(0,1),a));l[0]=r(Fi(d,bh(1,1),a));for(let f=1;f<=s;f++){let m=[nRe(d,l[f-1]),bh(f+1,1),a];l[f]=r(Fi(...m))}return Fi(...l).slice(0,t)}function iRe(n,e,t,r,i){if(Kc(n),ZE(t),e=tte(e),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update(eI("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(bh(t,2)).update(e).update(bh(e.length,1)).digest()}function gO(n,e,t){u8(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:c}=t;if(!JLe(t.hash))throw new Error("expected valid hash");Kc(n),ZE(e);let u=r.toString(2).length,l=Math.ceil((u+i)/8),d=e*o*l,h;if(a==="xmd")h=rRe(n,c,d,s);else if(a==="xof")h=iRe(n,c,d,i,s);else if(a==="_internal_pass")h=n;else throw new Error('expand must be "xmd" or "xof"');let f=new Array(e);for(let m=0;m<e;m++){let w=new Array(o);for(let b=0;b<o;b++){let S=l*(b+m*o),R=h.subarray(S,S+l);w[b]=Ha(tRe(R),r)}f[m]=w}return f}var oRe=eI("HashToScalar-");function Eee(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=Object.assign({},t,s),c=gO(o,2,a),u=r(c[0]),l=r(c[1]);return i(u.add(l))},encodeToCurve(o,s){let a=t.encodeDST?{DST:t.encodeDST}:{},c=Object.assign({},t,a,s),u=gO(o,1,c),l=r(u[0]);return i(l)},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))},hashToScalar(o,s){let a=n.Fn.ORDER,c=Object.assign({},t,{p:a,m:1,DST:oRe},s);return gO(o,1,c)[0][0]}}}var a8=class extends n8{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Fee(e);let r=KO(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),e8(o)}update(e){return $C(this),this.iHash.update(e),this}digestInto(e){$C(this),Kc(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()}},nte=(n,e,t)=>new a8(n,e).update(t).digest();nte.create=(n,e)=>new a8(n,e);var Iee=(n,e)=>(n+(n>=0?e:-e)/rte)/e;function sRe(n,e,t){let[[r,i],[o,s]]=e,a=Iee(s*n,t),c=Iee(-i*n,t),u=n-a*r-c*o,l=-a*i-c*s,d=u<Ed,h=l<Ed;d&&(u=-u),h&&(l=-l);let f=nI(Math.ceil(WE(t)/2))+V0;if(u<Ed||u>=f||l<Ed||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:d,k1:u,k2neg:h,k2:l}}function RO(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function yO(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return i8(t.lowS,"lowS"),i8(t.prehash,"prehash"),t.format!==void 0&&RO(t.format),t}var DO=class extends Error{constructor(e=""){super(e)}},bd={Err:DO,_tlv:{encode:(n,e)=>{let{Err:t}=bd;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=jC(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?jC(i.length/2|128):"";return jC(n)+o+i+e},decode(n,e){let{Err:t}=bd,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 u=e.subarray(r,r+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)s=s<<8|l;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}=bd;if(n<Ed)throw new e("integer: negative integers are not allowed");let t=jC(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}=bd;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 tI(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=bd,i=ao("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:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(n){let{_tlv:e,_int:t}=bd,r=e.encode(2,t.encode(n.r)),i=e.encode(2,t.encode(n.s)),o=r+i;return e.encode(48,o)}},Ed=BigInt(0),V0=BigInt(1),rte=BigInt(2),WC=BigInt(3),aRe=BigInt(4);function Id(n,e){let{BYTES:t}=n,r;if(typeof e=="bigint")r=e;else{let i=ao("private key",e);try{r=n.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!n.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function ite(n,e={}){let t=eRe("weierstrass",n,e),{Fp:r,Fn:i}=t,o=t.CURVE,{h:s,n:a}=o;u8(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!r.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=ste(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(Q,v,p){let{x,y}=v.toAffine(),I=r.toBytes(x);if(i8(p,"isCompressed"),p){l();let C=!r.isOdd(y);return Fi(ote(C),I)}else return Fi(Uint8Array.of(4),I,r.toBytes(y))}function h(Q){K0(Q,void 0,"Point");let{publicKey:v,publicKeyUncompressed:p}=u,x=Q.length,y=Q[0],I=Q.subarray(1);if(x===v&&(y===2||y===3)){let C=r.fromBytes(I);if(!r.isValid(C))throw new Error("bad point: is not on curve, wrong x");let F=w(C),N;try{N=r.sqrt(F)}catch(q){let _=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+_)}l();let O=r.isOdd(N);return(y&1)===1!==O&&(N=r.neg(N)),{x:C,y:N}}else if(x===p&&y===4){let C=r.BYTES,F=r.fromBytes(I.subarray(0,C)),N=r.fromBytes(I.subarray(C,C*2));if(!b(F,N))throw new Error("bad point: is not on curve");return{x:F,y:N}}else throw new Error(`bad point: got length ${x}, expected compressed=${v} or uncompressed=${p}`)}let f=e.toBytes||d,m=e.fromBytes||h;function w(Q){let v=r.sqr(Q),p=r.mul(v,Q);return r.add(r.add(p,r.mul(Q,o.a)),o.b)}function b(Q,v){let p=r.sqr(v),x=w(Q);return r.eql(p,x)}if(!b(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=r.mul(r.pow(o.a,WC),aRe),R=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(S,R)))throw new Error("bad curve params: a or b");function G(Q,v,p=!1){if(!r.isValid(v)||p&&r.is0(v))throw new Error(`bad point coordinate ${Q}`);return v}function U(Q){if(!(Q instanceof z))throw new Error("ProjectivePoint expected")}function H(Q){if(!c||!c.basises)throw new Error("no endo");return sRe(Q,c.basises,i.ORDER)}let M=CO((Q,v)=>{let{X:p,Y:x,Z:y}=Q;if(r.eql(y,r.ONE))return{x:p,y:x};let I=Q.is0();v==null&&(v=I?r.ONE:r.inv(y));let C=r.mul(p,v),F=r.mul(x,v),N=r.mul(y,v);if(I)return{x:r.ZERO,y:r.ZERO};if(!r.eql(N,r.ONE))throw new Error("invZ was invalid");return{x:C,y:F}}),A=CO(Q=>{if(Q.is0()){if(e.allowInfinityPoint&&!r.is0(Q.Y))return;throw new Error("bad point: ZERO")}let{x:v,y:p}=Q.toAffine();if(!r.isValid(v)||!r.isValid(p))throw new Error("bad point: x or y not field elements");if(!b(v,p))throw new Error("bad point: equation left != right");if(!Q.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function T(Q,v,p,x,y){return p=new z(r.mul(p.X,Q),p.Y,p.Z),v=s8(x,v),p=s8(y,p),v.add(p)}class z{constructor(v,p,x){this.X=G("x",v),this.Y=G("y",p,!0),this.Z=G("z",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(v){let{x:p,y:x}=v||{};if(!v||!r.isValid(p)||!r.isValid(x))throw new Error("invalid affine point");if(v instanceof z)throw new Error("projective point not allowed");return r.is0(p)&&r.is0(x)?z.ZERO:new z(p,x,r.ONE)}static fromBytes(v){let p=z.fromAffine(m(K0(v,void 0,"point")));return p.assertValidity(),p}static fromHex(v){return z.fromBytes(ao("pointHex",v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,p=!0){return Y.createCache(this,v),p||this.multiply(WC),this}assertValidity(){A(this)}hasEvenY(){let{y:v}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(v)}equals(v){U(v);let{X:p,Y:x,Z:y}=this,{X:I,Y:C,Z:F}=v,N=r.eql(r.mul(p,F),r.mul(I,y)),O=r.eql(r.mul(x,F),r.mul(C,y));return N&&O}negate(){return new z(this.X,r.neg(this.Y),this.Z)}double(){let{a:v,b:p}=o,x=r.mul(p,WC),{X:y,Y:I,Z:C}=this,F=r.ZERO,N=r.ZERO,O=r.ZERO,D=r.mul(y,y),q=r.mul(I,I),_=r.mul(C,C),L=r.mul(y,I);return L=r.add(L,L),O=r.mul(y,C),O=r.add(O,O),F=r.mul(v,O),N=r.mul(x,_),N=r.add(F,N),F=r.sub(q,N),N=r.add(q,N),N=r.mul(F,N),F=r.mul(L,F),O=r.mul(x,O),_=r.mul(v,_),L=r.sub(D,_),L=r.mul(v,L),L=r.add(L,O),O=r.add(D,D),D=r.add(O,D),D=r.add(D,_),D=r.mul(D,L),N=r.add(N,D),_=r.mul(I,C),_=r.add(_,_),D=r.mul(_,L),F=r.sub(F,D),O=r.mul(_,q),O=r.add(O,O),O=r.add(O,O),new z(F,N,O)}add(v){U(v);let{X:p,Y:x,Z:y}=this,{X:I,Y:C,Z:F}=v,N=r.ZERO,O=r.ZERO,D=r.ZERO,q=o.a,_=r.mul(o.b,WC),L=r.mul(p,I),g=r.mul(x,C),K=r.mul(y,F),E=r.add(p,x),V=r.add(I,C);E=r.mul(E,V),V=r.add(L,g),E=r.sub(E,V),V=r.add(p,y);let J=r.add(I,F);return V=r.mul(V,J),J=r.add(L,K),V=r.sub(V,J),J=r.add(x,y),N=r.add(C,F),J=r.mul(J,N),N=r.add(g,K),J=r.sub(J,N),D=r.mul(q,V),N=r.mul(_,K),D=r.add(N,D),N=r.sub(g,D),D=r.add(g,D),O=r.mul(N,D),g=r.add(L,L),g=r.add(g,L),K=r.mul(q,K),V=r.mul(_,V),g=r.add(g,K),K=r.sub(L,K),K=r.mul(q,K),V=r.add(V,K),L=r.mul(g,V),O=r.add(O,L),L=r.mul(J,V),N=r.mul(E,N),N=r.sub(N,L),L=r.mul(E,g),D=r.mul(J,D),D=r.add(D,L),new z(N,O,D)}subtract(v){return this.add(v.negate())}is0(){return this.equals(z.ZERO)}multiply(v){let{endo:p}=e;if(!i.isValidNot0(v))throw new Error("invalid scalar: out of range");let x,y,I=C=>Y.cached(this,C,F=>jE(z,F));if(p){let{k1neg:C,k1:F,k2neg:N,k2:O}=H(v),{p:D,f:q}=I(F),{p:_,f:L}=I(O);y=q.add(L),x=T(p.beta,D,_,C,N)}else{let{p:C,f:F}=I(v);x=C,y=F}return jE(z,[x,y])[0]}multiplyUnsafe(v){let{endo:p}=e,x=this;if(!i.isValid(v))throw new Error("invalid scalar: out of range");if(v===Ed||x.is0())return z.ZERO;if(v===V0)return x;if(Y.hasCache(this))return this.multiply(v);if(p){let{k1neg:y,k1:I,k2neg:C,k2:F}=H(v),{p1:N,p2:O}=_Le(z,x,I,F);return T(p.beta,N,O,y,C)}else return Y.unsafe(x,v)}multiplyAndAddUnsafe(v,p,x){let y=this.multiplyUnsafe(p).add(v.multiplyUnsafe(x));return y.is0()?void 0:y}toAffine(v){return M(this,v)}isTorsionFree(){let{isTorsionFree:v}=e;return s===V0?!0:v?v(z,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:v}=e;return s===V0?this:v?v(z,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(v=!0){return i8(v,"isCompressed"),this.assertValidity(),f(z,this,v)}toHex(v=!0){return zy(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(v=!0){return this.toBytes(v)}_setWindowSize(v){this.precompute(v)}static normalizeZ(v){return jE(z,v)}static msm(v,p){return $Le(z,i,v,p)}static fromPrivateKey(v){return z.BASE.multiply(Id(i,v))}}z.BASE=new z(o.Gx,o.Gy,r.ONE),z.ZERO=new z(r.ZERO,r.ONE,r.ZERO),z.Fp=r,z.Fn=i;let j=i.BITS,Y=new LO(z,e.endo?Math.ceil(j/2):j);return z.BASE.precompute(8),z}function ote(n){return Uint8Array.of(n?2:3)}function ste(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function cRe(n,e={}){let{Fn:t}=n,r=e.randomBytes||JO,i=Object.assign(ste(n.Fp,t),{seed:zO(t.ORDER)});function o(f){try{return!!Id(t,f)}catch{return!1}}function s(f,m){let{publicKey:w,publicKeyUncompressed:b}=i;try{let S=f.length;return m===!0&&S!==w||m===!1&&S!==b?!1:!!n.fromBytes(f)}catch{return!1}}function a(f=r(i.seed)){return _ee(K0(f,i.seed,"seed"),t.ORDER)}function c(f,m=!0){return n.BASE.multiply(Id(t,f)).toBytes(m)}function u(f){let m=a(f);return{secretKey:m,publicKey:c(m)}}function l(f){if(typeof f=="bigint")return!1;if(f instanceof n)return!0;let{secretKey:m,publicKey:w,publicKeyUncompressed:b}=i;if(t.allowedLengths||m===w)return;let S=ao("key",f).length;return S===w||S===b}function d(f,m,w=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let b=Id(t,f);return n.fromHex(m).multiply(b).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:u,Point:n,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:f=>Id(t,f),precompute(f=8,m=n.BASE){return m.precompute(f,!1)}},lengths:i})}function uRe(n,e,t={}){Fee(e),u8(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=t.randomBytes||JO,i=t.hmac||((p,...x)=>nte(e,p,Fi(...x))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f}=cRe(n,t),m={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function b(p){let x=a>>V0;return p>x}function S(p,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${p}: out of range 1..Point.Fn.ORDER`);return x}function R(p,x){RO(x);let y=f.signature,I=x==="compact"?y:x==="recovered"?y+1:void 0;return K0(p,I,`${x} signature`)}class G{constructor(x,y,I){this.r=S("r",x),this.s=S("s",y),I!=null&&(this.recovery=I),Object.freeze(this)}static fromBytes(x,y=w){R(x,y);let I;if(y==="der"){let{r:O,s:D}=bd.toSig(K0(x));return new G(O,D)}y==="recovered"&&(I=x[0],y="compact",x=x.subarray(1));let C=s.BYTES,F=x.subarray(0,C),N=x.subarray(C,C*2);return new G(s.fromBytes(F),s.fromBytes(N),I)}static fromHex(x,y){return this.fromBytes(t8(x),y)}addRecoveryBit(x){return new G(this.r,this.s,x)}recoverPublicKey(x){let y=o.ORDER,{r:I,s:C,recovery:F}=this;if(F==null||![0,1,2,3].includes(F))throw new Error("recovery id invalid");if(a*rte<y&&F>1)throw new Error("recovery id is ambiguous for h>1 curve");let O=F===2||F===3?I+a:I;if(!o.isValid(O))throw new Error("recovery id 2 or 3 invalid");let D=o.toBytes(O),q=n.fromBytes(Fi(ote((F&1)===0),D)),_=s.inv(O),L=H(ao("msgHash",x)),g=s.create(-L*_),K=s.create(C*_),E=n.BASE.multiplyUnsafe(g).add(q.multiplyUnsafe(K));if(E.is0())throw new Error("point at infinify");return E.assertValidity(),E}hasHighS(){return b(this.s)}toBytes(x=w){if(RO(x),x==="der")return t8(bd.hexFromSig(this));let y=s.toBytes(this.r),I=s.toBytes(this.s);if(x==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Fi(Uint8Array.of(this.recovery),y,I)}return Fi(y,I)}toHex(x){return zy(this.toBytes(x))}assertValidity(){}static fromCompact(x){return G.fromBytes(ao("sig",x),"compact")}static fromDER(x){return G.fromBytes(ao("sig",x),"der")}normalizeS(){return this.hasHighS()?new G(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return zy(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return zy(this.toBytes("compact"))}}let U=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let y=tI(x),I=x.length*8-c;return I>0?y>>BigInt(I):y},H=t.bits2int_modN||function(x){return s.create(U(x))},M=nI(c);function A(p){return GLe("num < 2^"+c,p,Ed,M),s.toBytes(p)}function T(p,x){return K0(p,void 0,"message"),x?K0(e(p),void 0,"prehashed message"):p}function z(p,x,y){if(["recovered","canonical"].some(g=>g in y))throw new Error("sign() legacy options not supported");let{lowS:I,prehash:C,extraEntropy:F}=yO(y,m);p=T(p,C);let N=H(p),O=Id(s,x),D=[A(O),A(N)];if(F!=null&&F!==!1){let g=F===!0?r(f.secretKey):F;D.push(ao("extraEntropy",g))}let q=Fi(...D),_=N;function L(g){let K=U(g);if(!s.isValidNot0(K))return;let E=s.inv(K),V=n.BASE.multiply(K).toAffine(),J=s.create(V.x);if(J===Ed)return;let B=s.create(E*s.create(_+J*O));if(B===Ed)return;let X=(V.x===J?0:2)|Number(V.y&V0),ce=B;return I&&b(B)&&(ce=s.neg(B),X^=1),new G(J,ce,X)}return{seed:q,k2sig:L}}function j(p,x,y={}){p=ao("message",p);let{seed:I,k2sig:C}=z(p,x,y);return KLe(e.outputLen,s.BYTES,i)(I,C)}function Y(p){let x,y=typeof p=="string"||$E(p),I=!y&&p!==null&&typeof p=="object"&&typeof p.r=="bigint"&&typeof p.s=="bigint";if(!y&&!I)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(I)x=new G(p.r,p.s);else if(y){try{x=G.fromBytes(ao("sig",p),"der")}catch(C){if(!(C instanceof bd.Err))throw C}if(!x)try{x=G.fromBytes(ao("sig",p),"compact")}catch{return!1}}return x||!1}function Q(p,x,y,I={}){let{lowS:C,prehash:F,format:N}=yO(I,m);if(y=ao("publicKey",y),x=T(ao("message",x),F),"strict"in I)throw new Error("options.strict was renamed to lowS");let O=N===void 0?Y(p):G.fromBytes(ao("sig",p),N);if(O===!1)return!1;try{let D=n.fromBytes(y);if(C&&O.hasHighS())return!1;let{r:q,s:_}=O,L=H(x),g=s.inv(_),K=s.create(L*g),E=s.create(q*g),V=n.BASE.multiplyUnsafe(K).add(D.multiplyUnsafe(E));return V.is0()?!1:s.create(V.x)===q}catch{return!1}}function v(p,x,y={}){let{prehash:I}=yO(y,m);return x=T(x,I),G.fromBytes(p,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f,Point:n,sign:j,verify:Q,recoverPublicKey:v,Signature:G,hash:e})}function Aee(n){let{CURVE:e,curveOpts:t}=ate(n),r=ite(e,t);return fRe(n,r)}function ate(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=n.allowedPrivateKeyLengths?Array.from(new Set(n.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,i=jy(e.n,{BITS:n.nBitLength,allowedLengths:r,modFromBytes:n.wrapPrivateKey}),o={Fp:t,Fn:i,allowInfinityPoint:n.allowInfinityPoint,endo:n.endo,isTorsionFree:n.isTorsionFree,clearCofactor:n.clearCofactor,fromBytes:n.fromBytes,toBytes:n.toBytes};return{CURVE:e,curveOpts:o}}function lRe(n){let{CURVE:e,curveOpts:t}=ate(n),r={hmac:n.hmac,randomBytes:n.randomBytes,lowS:n.lowS,bits2int:n.bits2int,bits2int_modN:n.bits2int_modN};return{CURVE:e,curveOpts:t,hash:n.hash,ecdsaOpts:r}}function dRe(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 fRe(n,e){let{Fp:t,Fn:r}=e;function i(s){return Jee(s,V0,r.ORDER)}let o=dRe(t,n.a,n.b);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s=>Id(r,s),weierstrassEquation:o,isWithinCurveOrder:i})}function hRe(n,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},n,Zee(t.Fn.ORDER,t.Fn.BITS))})}function pRe(n){let{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:i}=lRe(n),o=ite(e,t),s=uRe(o,r,i);return hRe(n,s)}var mRe=BigInt(0),ZC=BigInt(1),xee=BigInt(2),Qy=BigInt(3);function gRe(n){let e=[];for(;n>ZC;n>>=ZC)(n&ZC)===mRe?e.unshift(0):(n&Qy)===Qy?(e.unshift(-1),n+=ZC):e.unshift(1);return e}function wO(n){if(!Array.isArray(n)||n.length===0)throw new Error("expected non-empty array")}function yRe(n,e,t,r){let{Fp2:i,Fp12:o}=n,{twistType:s,ateLoopSize:a,xNegative:c,postPrecompute:u}=r,l;if(s==="multiplicative")l=(G,U,H,M,A,T)=>o.mul014(M,G,i.mul(U,A),i.mul(H,T));else if(s==="divisive")l=(G,U,H,M,A,T)=>o.mul034(M,i.mul(H,T),i.mul(U,A),G);else throw new Error("bls: unknown twist type");let d=i.div(i.ONE,i.mul(i.ONE,xee));function h(G,U,H,M){let A=i.sqr(H),T=i.sqr(M),z=i.mulByB(i.mul(T,Qy)),j=i.mul(z,Qy),Y=i.sub(i.sub(i.sqr(i.add(H,M)),T),A),Q=i.sub(z,A),v=i.mul(i.sqr(U),Qy),p=i.neg(Y);return G.push([Q,v,p]),U=i.mul(i.mul(i.mul(i.sub(A,j),U),H),d),H=i.sub(i.sqr(i.mul(i.add(A,j),d)),i.mul(i.sqr(z),Qy)),M=i.mul(A,Y),{Rx:U,Ry:H,Rz:M}}function f(G,U,H,M,A,T){let z=i.sub(H,i.mul(T,M)),j=i.sub(U,i.mul(A,M)),Y=i.sub(i.mul(z,A),i.mul(j,T)),Q=i.neg(z),v=j;G.push([Y,Q,v]);let p=i.sqr(j),x=i.mul(p,j),y=i.mul(p,U),I=i.add(i.sub(x,i.mul(y,xee)),i.mul(i.sqr(z),M));return U=i.mul(j,I),H=i.sub(i.mul(i.sub(y,I),z),i.mul(x,H)),M=i.mul(M,x),{Rx:U,Ry:H,Rz:M}}let m=gRe(a),w=CO(G=>{let U=G,{x:H,y:M}=U.toAffine(),A=H,T=M,z=i.neg(M),j=A,Y=T,Q=i.ONE,v=[];for(let p of m){let x=[];({Rx:j,Ry:Y,Rz:Q}=h(x,j,Y,Q)),p&&({Rx:j,Ry:Y,Rz:Q}=f(x,j,Y,Q,A,p===-1?z:T)),v.push(x)}if(u){let p=v[v.length-1];u(j,Y,Q,A,T,f.bind(null,p))}return v});function b(G,U=!1){let H=o.ONE;if(G.length){let M=G[0][0].length;for(let A=0;A<M;A++){H=o.sqr(H);for(let[T,z,j]of G)for(let[Y,Q,v]of T[A])H=l(Y,Q,v,H,z,j)}}return c&&(H=o.conjugate(H)),U?o.finalExponentiate(H):H}function S(G,U=!0){let H=[];jE(e,G.map(({g1:M})=>M)),jE(t,G.map(({g2:M})=>M));for(let{g1:M,g2:A}of G){if(M.is0()||A.is0())throw new Error("pairing is not available for ZERO point");M.assertValidity(),A.assertValidity();let T=M.toAffine();H.push([w(A),T.x,T.y])}return b(H,U)}function R(G,U,H=!0){return S([{g1:G,g2:U}],H)}return{Fp12:o,millerLoopBatch:b,pairing:R,pairingBatch:S,calcPairingPrecomputes:w}}function vee(n,e,t,r,i){let{Fp12:o,pairingBatch:s}=n;function a(d){return d instanceof e.Point?d:e.Point.fromHex(d)}function c(d){return d instanceof t.Point?d:t.Point.fromHex(d)}function u(d){if(!(d instanceof t.Point))throw new Error(`expected valid message hashed to ${i?"G1":"G2"} curve`);return d}let l=i?(d,h)=>({g1:h,g2:d}):(d,h)=>({g1:d,g2:h});return{getPublicKey(d){let h=Id(e.Point.Fn,d);return e.Point.BASE.multiply(h)},sign(d,h,f){if(f!=null)throw new Error("sign() expects 2 arguments");let m=Id(e.Point.Fn,h);return u(d).assertValidity(),d.multiply(m)},verify(d,h,f,m){if(m!=null)throw new Error("verify() expects 3 arguments");d=c(d),f=a(f);let w=f.negate(),b=e.Point.BASE,S=u(h),R=d,G=s([l(w,S),l(b,R)]);return o.eql(G,o.ONE)},verifyBatch(d,h,f){if(wO(h),f.length!==h.length)throw new Error("amount of public keys and messages should be equal");let m=c(d),w=h,b=f.map(a),S=new Map;for(let U=0;U<b.length;U++){let H=b[U],M=w[U],A=S.get(M);A===void 0&&(A=[],S.set(M,A)),A.push(H)}let R=[],G=e.Point.BASE;try{for(let[U,H]of S){let M=H.reduce((A,T)=>A.add(T));R.push(l(M,U))}return R.push(l(G.negate(),m)),o.eql(s(R),o.ONE)}catch{return!1}},aggregatePublicKeys(d){wO(d),d=d.map(f=>a(f));let h=d.reduce((f,m)=>f.add(m),e.Point.ZERO);return h.assertValidity(),h},aggregateSignatures(d){wO(d),d=d.map(f=>c(f));let h=d.reduce((f,m)=>f.add(m),t.Point.ZERO);return h.assertValidity(),h},hash(d,h){Kc(d);let f=h?{DST:h}:void 0;return t.hashToCurve(d,f)},Signature:r}}function wRe(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=Aee(n.G1),a=Object.assign(s,Eee(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),c=Aee(n.G2),u=Object.assign(c,Eee(c.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),l=yRe(n.fields,a.Point,u.Point,{...n.params,postPrecompute:n.postPrecompute}),{millerLoopBatch:d,pairing:h,pairingBatch:f,calcPairingPrecomputes:m}=l,w=vee(l,a,u,n.G2.Signature,!1),b=vee(l,u,a,n.G1.ShortSignature,!0),S=n.randomBytes||JO,R=()=>{let C=zO(t.ORDER);return _ee(S(C),t.ORDER)},G={randomSecretKey:R,randomPrivateKey:R,calcPairingPrecomputes:m},{ShortSignature:U}=n.G1,{Signature:H}=n.G2;function M(C,F){return C instanceof a.Point?C:b.hash(ao("point",C),F?.DST)}function A(C,F){return C instanceof u.Point?C:w.hash(ao("point",C),F?.DST)}function T(C){return w.getPublicKey(C).toBytes(!0)}function z(C){return b.getPublicKey(C).toBytes(!0)}function j(C,F,N){let O=A(C,N),D=w.sign(O,F);return C instanceof u.Point?D:H.toBytes(D)}function Y(C,F,N){let O=M(C,N),D=b.sign(O,F);return C instanceof a.Point?D:U.toBytes(D)}function Q(C,F,N,O){let D=A(F,O);return w.verify(C,D,N)}function v(C,F,N,O){let D=M(F,O);return b.verify(C,D,N)}function p(C){let F=w.aggregatePublicKeys(C);return C[0]instanceof a.Point?F:F.toBytes(!0)}function x(C){let F=w.aggregateSignatures(C);return C[0]instanceof u.Point?F:H.toBytes(F)}function y(C){let F=b.aggregateSignatures(C);return C[0]instanceof a.Point?F:U.toBytes(F)}function I(C,F,N,O){let D=F.map(q=>A(q,O));return w.verifyBatch(C,D,N)}return a.Point.BASE.precompute(4),{longSignatures:w,shortSignatures:b,millerLoopBatch:d,pairing:h,pairingBatch:f,verifyBatch:I,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:T,getPublicKeyForShortSignatures:z,sign:j,signShortSignature:Y,verify:Q,verifyShortSignature:v,aggregatePublicKeys:p,aggregateSignatures:x,aggregateShortSignatures:y,G1:a,G2:u,Signature:H,ShortSignature:U}}var See=BigInt(0),Ad=BigInt(1),jo=BigInt(2),Cee=BigInt(3);function YO(n,e,t,r,i=1,o){let s=BigInt(o===void 0?r:o),a=t**BigInt(r),c=[];for(let u=0;u<i;u++){let l=BigInt(u+1),d=[];for(let h=0,f=Ad;h<r;h++){let m=(l*f-l)/s%a;d.push(n.pow(e,m)),f*=t}c.push(d)}return c}function bRe(n,e,t){let r=e.pow(t,(n.ORDER-Ad)/Cee),i=e.pow(t,(n.ORDER-Ad)/jo);function o(h,f){let m=e.mul(e.frobeniusMap(h,1),r),w=e.mul(e.frobeniusMap(f,1),i);return[m,w]}let s=e.pow(t,(n.ORDER**jo-Ad)/Cee),a=e.pow(t,(n.ORDER**jo-Ad)/jo);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 u=h=>(f,m)=>{let w=m.toAffine(),b=h(w.x,w.y);return f.fromAffine({x:b[0],y:b[1]})},l=u(o),d=u(c);return{psi:o,psi2:c,G2psi:l,G2psi2:d,PSI_X:r,PSI_Y:i,PSI2_X:s,PSI2_Y:a}}var Lee=(n,e)=>{if(e.length!==2)throw new Error("invalid tuple");let t=e.map(r=>n.create(r));return{c0:t[0],c1:t[1]}},TO=class{constructor(e,t={}){this.MASK=Ad;let r=e.ORDER,i=r*r;this.Fp=e,this.ORDER=i,this.BITS=WE(i),this.BYTES=Math.ceil(WE(i)/8),this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO},this.Fp_NONRESIDUE=e.create(t.NONRESIDUE||BigInt(-1)),this.Fp_div2=e.div(e.ONE,jo),this.NONRESIDUE=Lee(e,t.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=YO(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=t.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return Lee(this.Fp,e)}create(e){return e}isValid({c0:e,c1:t}){function r(i,o){return typeof i=="bigint"&&See<=i&&i<o}return r(e,this.ORDER)&&r(t,this.ORDER)}is0({c0:e,c1:t}){return this.Fp.is0(e)&&this.Fp.is0(t)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}eql({c0:e,c1:t},{c0:r,c1:i}){return this.Fp.eql(e,r)&&this.Fp.eql(t,i)}neg({c0:e,c1:t}){return{c0:this.Fp.neg(e),c1:this.Fp.neg(t)}}pow(e,t){return l8(this,e,t)}invertBatch(e){return rI(this,e)}add(e,t){let{c0:r,c1:i}=e,{c0:o,c1:s}=t;return{c0:this.Fp.add(r,o),c1:this.Fp.add(i,s)}}sub({c0:e,c1:t},{c0:r,c1:i}){return{c0:this.Fp.sub(e,r),c1:this.Fp.sub(t,i)}}mul({c0:e,c1:t},r){let{Fp:i}=this;if(typeof r=="bigint")return{c0:i.mul(e,r),c1:i.mul(t,r)};let{c0:o,c1:s}=r,a=i.mul(e,o),c=i.mul(t,s),u=i.sub(a,c),l=i.sub(i.mul(i.add(e,t),i.add(o,s)),i.add(a,c));return{c0:u,c1:l}}sqr({c0:e,c1:t}){let{Fp:r}=this,i=r.add(e,t),o=r.sub(e,t),s=r.add(e,e);return{c0:r.mul(i,o),c1:r.mul(s,t)}}addN(e,t){return this.add(e,t)}subN(e,t){return this.sub(e,t)}mulN(e,t){return this.mul(e,t)}sqrN(e){return this.sqr(e)}div(e,t){let{Fp:r}=this;return this.mul(e,typeof t=="bigint"?r.inv(r.create(t)):this.inv(t))}inv({c0:e,c1:t}){let{Fp:r}=this,i=r.inv(r.create(e*e+t*t));return{c0:r.mul(i,r.create(e)),c1:r.mul(i,r.create(-t))}}sqrt(e){let{Fp:t}=this,r=this,{c0:i,c1:o}=e;if(t.is0(o))return o8(t,i)===1?r.create({c0:t.sqrt(i),c1:t.ZERO}):r.create({c0:t.ZERO,c1:t.sqrt(t.div(i,this.Fp_NONRESIDUE))});let s=t.sqrt(t.sub(t.sqr(i),t.mul(t.sqr(o),this.Fp_NONRESIDUE))),a=t.mul(t.add(s,i),this.Fp_div2);o8(t,a)===-1&&(a=t.sub(a,s));let u=t.sqrt(a),l=r.create({c0:u,c1:t.div(t.mul(o,this.Fp_div2),u)});if(!r.eql(r.sqr(l),e))throw new Error("Cannot find square root");let d=l,h=r.neg(d),{re:f,im:m}=r.reim(d),{re:w,im:b}=r.reim(h);return m>b||m===b&&f>w?d:h}isOdd(e){let{re:t,im:r}=this.reim(e),i=t%jo,o=t===See,s=r%jo;return BigInt(i||o&&s)==Ad}fromBytes(e){let{Fp:t}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);return{c0:t.fromBytes(e.subarray(0,t.BYTES)),c1:t.fromBytes(e.subarray(t.BYTES))}}toBytes({c0:e,c1:t}){return Fi(this.Fp.toBytes(e),this.Fp.toBytes(t))}cmov({c0:e,c1:t},{c0:r,c1:i},o){return{c0:this.Fp.cmov(e,r,o),c1:this.Fp.cmov(t,i,o)}}reim({c0:e,c1:t}){return{re:e,im:t}}Fp4Square(e,t){let r=this,i=r.sqr(e),o=r.sqr(t);return{first:r.add(r.mulByNonresidue(o),i),second:r.sub(r.sub(r.sqr(r.add(e,t)),i),o)}}mulByNonresidue({c0:e,c1:t}){return this.mul({c0:e,c1:t},this.NONRESIDUE)}frobeniusMap({c0:e,c1:t},r){return{c0:e,c1:this.Fp.mul(t,this.FROBENIUS_COEFFICIENTS[r%2])}}},BO=class{constructor(e){this.MASK=Ad,this.Fp2=e,this.ORDER=e.ORDER,this.BITS=3*e.BITS,this.BYTES=3*e.BYTES,this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO,c2:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO,c2:e.ZERO};let{Fp:t}=e,r=YO(e,e.NONRESIDUE,t.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=r[0],this.FROBENIUS_COEFFICIENTS_2=r[1],Object.seal(this)}add({c0:e,c1:t,c2:r},{c0:i,c1:o,c2:s}){let{Fp2:a}=this;return{c0:a.add(e,i),c1:a.add(t,o),c2:a.add(r,s)}}sub({c0:e,c1:t,c2:r},{c0:i,c1:o,c2:s}){let{Fp2:a}=this;return{c0:a.sub(e,i),c1:a.sub(t,o),c2:a.sub(r,s)}}mul({c0:e,c1:t,c2:r},i){let{Fp2:o}=this;if(typeof i=="bigint")return{c0:o.mul(e,i),c1:o.mul(t,i),c2:o.mul(r,i)};let{c0:s,c1:a,c2:c}=i,u=o.mul(e,s),l=o.mul(t,a),d=o.mul(r,c);return{c0:o.add(u,o.mulByNonresidue(o.sub(o.mul(o.add(t,r),o.add(a,c)),o.add(l,d)))),c1:o.add(o.sub(o.mul(o.add(e,t),o.add(s,a)),o.add(u,l)),o.mulByNonresidue(d)),c2:o.sub(o.add(l,o.mul(o.add(e,r),o.add(s,c))),o.add(u,d))}}sqr({c0:e,c1:t,c2:r}){let{Fp2:i}=this,o=i.sqr(e),s=i.mul(i.mul(e,t),jo),a=i.mul(i.mul(t,r),jo),c=i.sqr(r);return{c0:i.add(i.mulByNonresidue(a),o),c1:i.add(i.mulByNonresidue(c),s),c2:i.sub(i.sub(i.add(i.add(s,i.sqr(i.add(i.sub(e,t),r))),a),o),c)}}addN(e,t){return this.add(e,t)}subN(e,t){return this.sub(e,t)}mulN(e,t){return this.mul(e,t)}sqrN(e){return this.sqr(e)}create(e){return e}isValid({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return i.isValid(e)&&i.isValid(t)&&i.isValid(r)}is0({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return i.is0(e)&&i.is0(t)&&i.is0(r)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return{c0:i.neg(e),c1:i.neg(t),c2:i.neg(r)}}eql({c0:e,c1:t,c2:r},{c0:i,c1:o,c2:s}){let{Fp2:a}=this;return a.eql(e,i)&&a.eql(t,o)&&a.eql(r,s)}sqrt(e){return ui()}div(e,t){let{Fp2:r}=this,{Fp:i}=r;return this.mul(e,typeof t=="bigint"?i.inv(i.create(t)):this.inv(t))}pow(e,t){return l8(this,e,t)}invertBatch(e){return rI(this,e)}inv({c0:e,c1:t,c2:r}){let{Fp2:i}=this,o=i.sub(i.sqr(e),i.mulByNonresidue(i.mul(r,t))),s=i.sub(i.mulByNonresidue(i.sqr(r)),i.mul(e,t)),a=i.sub(i.sqr(t),i.mul(e,r)),c=i.inv(i.add(i.mulByNonresidue(i.add(i.mul(r,s),i.mul(t,a))),i.mul(e,o)));return{c0:i.mul(c,o),c1:i.mul(c,s),c2:i.mul(c,a)}}fromBytes(e){let{Fp2:t}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);let r=t.BYTES;return{c0:t.fromBytes(e.subarray(0,r)),c1:t.fromBytes(e.subarray(r,r*2)),c2:t.fromBytes(e.subarray(2*r))}}toBytes({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return Fi(i.toBytes(e),i.toBytes(t),i.toBytes(r))}cmov({c0:e,c1:t,c2:r},{c0:i,c1:o,c2:s},a){let{Fp2:c}=this;return{c0:c.cmov(e,i,a),c1:c.cmov(t,o,a),c2:c.cmov(r,s,a)}}fromBigSix(e){let{Fp2:t}=this;if(!Array.isArray(e)||e.length!==6)throw new Error("invalid Fp6 usage");return{c0:t.fromBigTuple(e.slice(0,2)),c1:t.fromBigTuple(e.slice(2,4)),c2:t.fromBigTuple(e.slice(4,6))}}frobeniusMap({c0:e,c1:t,c2:r},i){let{Fp2:o}=this;return{c0:o.frobeniusMap(e,i),c1:o.mul(o.frobeniusMap(t,i),this.FROBENIUS_COEFFICIENTS_1[i%6]),c2:o.mul(o.frobeniusMap(r,i),this.FROBENIUS_COEFFICIENTS_2[i%6])}}mulByFp2({c0:e,c1:t,c2:r},i){let{Fp2:o}=this;return{c0:o.mul(e,i),c1:o.mul(t,i),c2:o.mul(r,i)}}mulByNonresidue({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return{c0:i.mulByNonresidue(r),c1:e,c2:t}}mul1({c0:e,c1:t,c2:r},i){let{Fp2:o}=this;return{c0:o.mulByNonresidue(o.mul(r,i)),c1:o.mul(e,i),c2:o.mul(t,i)}}mul01({c0:e,c1:t,c2:r},i,o){let{Fp2:s}=this,a=s.mul(e,i),c=s.mul(t,o);return{c0:s.add(s.mulByNonresidue(s.sub(s.mul(s.add(t,r),o),c)),a),c1:s.sub(s.sub(s.mul(s.add(i,o),s.add(e,t)),a),c),c2:s.add(s.sub(s.mul(s.add(e,r),i),a),c)}}},PO=class{constructor(e,t){this.MASK=Ad;let{Fp2:r}=e,{Fp:i}=r;this.Fp6=e,this.ORDER=r.ORDER,this.BITS=2*e.BITS,this.BYTES=2*e.BYTES,this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO},this.FROBENIUS_COEFFICIENTS=YO(r,r.NONRESIDUE,i.ORDER,12,1,6)[0],this.X_LEN=t.X_LEN,this.finalExponentiate=t.Fp12finalExponentiate}create(e){return e}isValid({c0:e,c1:t}){let{Fp6:r}=this;return r.isValid(e)&&r.isValid(t)}is0({c0:e,c1:t}){let{Fp6:r}=this;return r.is0(e)&&r.is0(t)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:t}){let{Fp6:r}=this;return{c0:r.neg(e),c1:r.neg(t)}}eql({c0:e,c1:t},{c0:r,c1:i}){let{Fp6:o}=this;return o.eql(e,r)&&o.eql(t,i)}sqrt(e){ui()}inv({c0:e,c1:t}){let{Fp6:r}=this,i=r.inv(r.sub(r.sqr(e),r.mulByNonresidue(r.sqr(t))));return{c0:r.mul(e,i),c1:r.neg(r.mul(t,i))}}div(e,t){let{Fp6:r}=this,{Fp2:i}=r,{Fp:o}=i;return this.mul(e,typeof t=="bigint"?o.inv(o.create(t)):this.inv(t))}pow(e,t){return l8(this,e,t)}invertBatch(e){return rI(this,e)}add({c0:e,c1:t},{c0:r,c1:i}){let{Fp6:o}=this;return{c0:o.add(e,r),c1:o.add(t,i)}}sub({c0:e,c1:t},{c0:r,c1:i}){let{Fp6:o}=this;return{c0:o.sub(e,r),c1:o.sub(t,i)}}mul({c0:e,c1:t},r){let{Fp6:i}=this;if(typeof r=="bigint")return{c0:i.mul(e,r),c1:i.mul(t,r)};let{c0:o,c1:s}=r,a=i.mul(e,o),c=i.mul(t,s);return{c0:i.add(a,i.mulByNonresidue(c)),c1:i.sub(i.mul(i.add(e,t),i.add(o,s)),i.add(a,c))}}sqr({c0:e,c1:t}){let{Fp6:r}=this,i=r.mul(e,t);return{c0:r.sub(r.sub(r.mul(r.add(r.mulByNonresidue(t),e),r.add(e,t)),i),r.mulByNonresidue(i)),c1:r.add(i,i)}}addN(e,t){return this.add(e,t)}subN(e,t){return this.sub(e,t)}mulN(e,t){return this.mul(e,t)}sqrN(e){return this.sqr(e)}fromBytes(e){let{Fp6:t}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);return{c0:t.fromBytes(e.subarray(0,t.BYTES)),c1:t.fromBytes(e.subarray(t.BYTES))}}toBytes({c0:e,c1:t}){let{Fp6:r}=this;return Fi(r.toBytes(e),r.toBytes(t))}cmov({c0:e,c1:t},{c0:r,c1:i},o){let{Fp6:s}=this;return{c0:s.cmov(e,r,o),c1:s.cmov(t,i,o)}}fromBigTwelve(e){let{Fp6:t}=this;return{c0:t.fromBigSix(e.slice(0,6)),c1:t.fromBigSix(e.slice(6,12))}}frobeniusMap(e,t){let{Fp6:r}=this,{Fp2:i}=r,{c0:o,c1:s,c2:a}=r.frobeniusMap(e.c1,t),c=this.FROBENIUS_COEFFICIENTS[t%12];return{c0:r.frobeniusMap(e.c0,t),c1:r.create({c0:i.mul(o,c),c1:i.mul(s,c),c2:i.mul(a,c)})}}mulByFp2({c0:e,c1:t},r){let{Fp6:i}=this;return{c0:i.mulByFp2(e,r),c1:i.mulByFp2(t,r)}}conjugate({c0:e,c1:t}){return{c0:e,c1:this.Fp6.neg(t)}}mul014({c0:e,c1:t},r,i,o){let{Fp6:s}=this,{Fp2:a}=s,c=s.mul01(e,r,i),u=s.mul1(t,o);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(s.sub(s.mul01(s.add(t,e),r,a.add(i,o)),c),u)}}mul034({c0:e,c1:t},r,i,o){let{Fp6:s}=this,{Fp2:a}=s,c=s.create({c0:a.mul(e.c0,r),c1:a.mul(e.c1,r),c2:a.mul(e.c2,r)}),u=s.mul01(t,i,o),l=s.mul01(s.add(e,t),a.add(r,i),o);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(l,s.add(c,u))}}_cyclotomicSquare({c0:e,c1:t}){let{Fp6:r}=this,{Fp2:i}=r,{c0:o,c1:s,c2:a}=e,{c0:c,c1:u,c2:l}=t,{first:d,second:h}=i.Fp4Square(o,u),{first:f,second:m}=i.Fp4Square(c,a),{first:w,second:b}=i.Fp4Square(s,l),S=i.mulByNonresidue(b);return{c0:r.create({c0:i.add(i.mul(i.sub(d,o),jo),d),c1:i.add(i.mul(i.sub(f,s),jo),f),c2:i.add(i.mul(i.sub(w,a),jo),w)}),c1:r.create({c0:i.add(i.mul(i.add(S,c),jo),S),c1:i.add(i.mul(i.add(h,u),jo),h),c2:i.add(i.mul(i.add(m,l),jo),m)})}}_cyclotomicExp(e,t){let r=this.ONE;for(let i=this.X_LEN-1;i>=0;i--)r=this._cyclotomicSquare(r),HLe(t,i)&&(r=this.mul(r,e));return r}};function ERe(n){let e=jy(n.ORDER),t=new TO(e,n),r=new BO(t),i=new PO(r,n);return{Fp:e,Fp2:t,Fp6:r,Fp12:i}}var IRe=BigInt(0),kO=BigInt(1),cte=BigInt(2),ARe=BigInt(3),ute=BigInt(6),d8=BigInt("4965661367192848881"),xRe=WE(d8),vRe=ute*d8**cte,f8={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:kO,a:IRe,b:ARe,Gx:kO,Gy:BigInt(2)},Ree=jy(f8.n),lte={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:XE,Fp2:qu,Fp6:SRe,Fp12:zn}=ERe({ORDER:f8.p,X_LEN:xRe,FP2_NONRESIDUE:[BigInt(9),kO],Fp2mulByB:n=>qu.mul(n,lte),Fp12finalExponentiate:n=>{let e=l=>zn.conjugate(zn._cyclotomicExp(l,d8)),t=zn.mul(zn.conjugate(n),zn.inv(n)),r=zn.mul(zn.frobeniusMap(t,2),t),i=zn._cyclotomicSquare(e(r)),o=zn.mul(zn._cyclotomicSquare(i),i),s=e(o),a=e(zn._cyclotomicSquare(s)),c=zn.mul(zn.mul(zn.conjugate(a),s),zn.conjugate(o)),u=zn.mul(c,i);return zn.mul(zn.frobeniusMap(zn.mul(zn.conjugate(r),u),3),zn.mul(zn.frobeniusMap(c,2),zn.mul(zn.frobeniusMap(u,1),zn.mul(zn.mul(c,s),r))))}}),{G2psi:CRe,psi:Dee}=bRe(XE,qu,qu.NONRESIDUE),bO=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:XE.ORDER,m:2,k:128,expand:"xmd",hash:Uee}),LRe=(n,e,t,r,i,o)=>{let s=Dee(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=Dee(s[0],s[1]);o(n,e,t,a[0],qu.neg(a[1]))},RRe={p:qu.ORDER,n:f8.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:qu.ZERO,b:lte,Gx:qu.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:qu.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},Q0=wRe({fields:{Fp:XE,Fp2:qu,Fp6:SRe,Fp12:zn,Fr:Ree},G1:{...f8,Fp:XE,htfDefaults:{...bO,m:1,DST:"BN254G2_XMD:SHA-256_SVDW_RO_"},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:ui,fromBytes:ui,toBytes:ui,ShortSignature:{fromBytes:ui,fromHex:ui,toBytes:ui,toRawBytes:ui,toHex:ui}},G2:{...RRe,Fp:qu,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...bO},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(vRe).equals(CRe(n,e)),mapToCurve:ui,fromBytes:ui,toBytes:ui,Signature:{fromBytes:ui,fromHex:ui,toBytes:ui,toRawBytes:ui,toHex:ui}},params:{ateLoopSize:d8*ute+cte,r:Ree.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:bO,postPrecompute:LRe});pRe({a:BigInt(0),b:BigInt(3),Fp:XE,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:Uee});var h8="groth16",DRe="auth",TRe="authV2",BRe="authV3",PRe="authV3-8-32",kRe=new TextDecoder,Tee=BigInt(0),Bee=Q0.fields.Fp2,Pee=Q0.fields.Fp12;async function jO(n,e,t){let r=await RLe(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:c}=await YC.prove(e,s);return{proof:a,pub_signals:c}}var[MO,MRe]=[Q0.G1.ProjectivePoint,Q0.G2.ProjectivePoint],XC=([n,e])=>MO.fromAffine({x:BigInt(n),y:BigInt(e)}),_C=([[n,e],[t,r]])=>MRe.fromAffine({x:Bee.fromBigTuple([BigInt(n),BigInt(e)]),y:Bee.fromBigTuple([BigInt(t),BigInt(r)])});async function WO(n,e,t,r){if(r(e.pub_signals).challenge!==zI(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(kRe.decode(t));return ZO(e,o)}function ZO(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=MO.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<Tee||BigInt(r[s])>=Q0.G1.CURVE.n)throw new Error(`Input value is not in the field ${Q0.G1.CURVE.n}`);if(BigInt(r[s])!==Tee){let[a,c]=e.IC[s+1].map(BigInt);i=i.add(MO.fromAffine({x:a,y:c}).multiply(BigInt(r[s])))}}i=i.add(XC(e.IC[0]));let o=Q0.pairingBatch([{g1:XC(t.pi_a).negate(),g2:_C(t.pi_b)},{g1:i,g2:_C(e.vk_gamma_2)},{g1:XC(t.pi_c),g2:_C(e.vk_delta_2)},{g1:XC(e.vk_alpha_1),g2:_C(e.vk_beta_2)}]);return Pee.eql(o,Pee.ONE)}var OO=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=Xe.fromBigInt(BigInt(e[2])),t}async verify(e,t,r){return WO(e,t,r,this.unmarshall)}prove(e,t,r){return jO(e,t,r)}},FO=new OO(new Hc(h8,DRe)),NO=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 WO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await jO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await VE(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:Xe.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},UO=new NO(new Hc(h8,TRe)),c8=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 WO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await jO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await VE(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:Xe.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},GO=new c8(new Hc(h8,BRe)),HO=new c8(new Hc(h8,PRe));_E(FO.methodAlg,()=>FO);_E(UO.methodAlg,()=>UO);_E(GO.methodAlg,()=>GO);_E(HO.methodAlg,()=>HO);var Wy={registerProvingMethod:_E,getProvingMethod:Oee,provingMethodGroth16AuthInstance:FO,provingMethodGroth16AuthV2Instance:UO,provingMethodGroth16AuthV3Instance:GO,provingMethodGroth16AuthV3_8_32Instance:HO};var Jc=Wy.provingMethodGroth16AuthV2Instance.methodAlg;function ORe(n){return Object.values(Oy).includes(n)}function FRe(n){return Object.values(_s).includes(n)}function NRe(n){return Object.values(IC).includes(n)}function URe(n){return Object.values(Fy).includes(n)}function GRe(n){return Object.values(AC).includes(n)}var dte=n=>{let[e,t]=n.toString().split(":");return`iden3comm/v1;env=application/iden3-zkp-json;circuitId=${t};alg=${e}`},fte=(n,e)=>{let[t,r]=e.toString().split(":");for(let i of n){let{env:o,circuits:s,alg:a}=vs(i);if(o==="application/iden3-zkp-json"&&s?.includes(r)&&(!a||a?.includes(t)))return!0}return!1};function HRe(n){return Object.values(xC).includes(n)}var KRe=n=>{let e=[];for(let t of n){let r=`${t.protocolVersion};env=${t.env}`;t.circuits?.length&&(r+=`;circuitId=${t.circuits.join(",")}`),t.alg?.length&&(r+=`;alg=${t.alg.join(",")}`),e.push(r)}return e},vs=n=>{let e=n.split(";");if(e.length<2)throw new Error("Invalid accept profile");let t=e[0].trim();if(!ORe(t))throw new Error(`Protocol version '${t}' not supported`);if(e[1].split("=").length!==2)throw new Error("Invalid accept profile 'env' parameter");let i=e[1].split("=")[1].trim();if(!FRe(i))throw new Error(`Envelop '${i}' not supported`);let o=e.findIndex(l=>l.includes("circuitId="));if(i!=="application/iden3-zkp-json"&&o>0)throw new Error(`Circuits not supported for env '${i}'`);let s;o>0&&(s=e[o].split("=")[1].split(",").map(l=>l.trim()).map(l=>{if(!NRe(l))throw new Error(`Circuit '${l}' not supported`);return l}));let a=e.findIndex(l=>l.includes("alg="));if(a===-1)return{protocolVersion:t,env:i,circuits:s,alg:void 0};let c=e[a].split("=")[1].split(",").map(l=>l.trim()),u=[];switch(i){case"application/iden3-zkp-json":u=c.map(l=>{if(!GRe(l))throw new Error(`Algorithm '${l}' not supported for '${i}'`);return l});break;case"application/iden3comm-signed-json":u=c.map(l=>{if(!URe(l))throw new Error(`Algorithm '${l}' not supported for '${i}'`);return l});break;case"application/iden3comm-encrypted-json":u=c.map(l=>{if(!HRe(l))throw new Error(`Algorithm '${l}' not supported for '${i}'`);return l});break;default:throw new Error(`Algorithms not supported for '${i}'`)}return{protocolVersion:t,env:i,circuits:s,alg:u}},XO=(n,e,t)=>{if(!t?.length)return Jc;let r=[Wy.provingMethodGroth16AuthV3_8_32Instance.methodAlg,Wy.provingMethodGroth16AuthV3Instance.methodAlg];if(e){let i=r.indexOf(e);i!==-1&&r.splice(i,1),r.unshift(e)}for(let i of r)if(n.isProfileSupported("application/iden3-zkp-json",dte(i))&&fte(t,i))return i;return Jc};var p8="https://www.w3.org/ns/did/v1",m8="https://w3id.org/security/suites/jws-2020/v1",iI=class{constructor(e,t=p8){this._did=e;let r=[t].flat();this._context=r.includes(p8)?r:[p8,...r]}_verificationMethods=[];_keyAgreements=[];_context;async addVerificationMethod(e,t){let r=await e.build(this._did);return this._verificationMethods.push(r),this._keyAgreements.push(r.id),t&&(this._context=[...new Set([...this._context,...Array.isArray(t)?t:[t]])]),this}build(){return{"@context":this._context,id:this._did,keyAgreement:this._keyAgreements,verificationMethod:this._verificationMethods}}},oI=class{constructor(e,t){this._keyProvider=e;this._alias=t?.alias}_alias;async build(e){let t=this._alias?{type:this._keyProvider.keyType,id:this._alias}:await this._keyProvider.newPrivateKey(),r=await this._keyProvider.publicKey(t),i=this._alias??t.id;return{id:`${e}#${i}`,type:"JsonWebKey2020",controller:e,publicKeyJwk:EM(r,t.type)}}};var _O=(n,e)=>Promise.all(n.map(async t=>{if(!t.did)throw new Error("Missing recipient DID");let r=t.didDocument??(await e.resolve(t.did.string()))?.didDocument;if(!r)throw new Error("Recipient DID document not found");let i=Ny(r);if(!i.length)throw new Error(`No verification methods defined in the DID document of ${r.id}`);let o=t.keyType??"JsonWebKey2020",s=t.alg??"RSA-OAEP-256",a=i.find(u=>u.controller===t.did.string()&&u.type===o&&u.publicKeyJwk?.alg===s);if(!a)throw new Error(`No key found with id ${t.did.string()} and type ${o} in DID document of ${r.id}`);let c=JRe(a);if(!c)throw new Error("No public key found");if(c instanceof Uint8Array)throw new Error("Public key is not a JWK");return{did:t.did.string(),keyType:o,kid:a.id,alg:s,recipientJWK:c}})),JRe=n=>n.publicKeyBase58?mw(n.publicKeyBase58):n.publicKeyBase64?Xu(n.publicKeyBase64):n.publicKeyHex?di(n.publicKeyHex):n.publicKeyJwk?n.publicKeyJwk:null;var $O=class{constructor(e,t){this._joseService=e;this._documentResolver=t}_supportedProtocolVersions=["iden3comm/v1"];_supportedAlgorithms=["RSA-OAEP-256","ECDH-ES+A256KW"];packMessage(e,t){return this.packInternal(e,t)}getSupportedAlgorithms(){return this._supportedAlgorithms}registerSupportedAlgorithm(e){this._supportedAlgorithms=[...new Set([...this._supportedAlgorithms,e])]}async pack(e,t){let r=JSON.parse(lt.decode(e));return this.packInternal(r,t)}async unpack(e){let{plaintext:t}=await this._joseService.decrypt(JSON.parse(lt.decode(e)));return JSON.parse(lt.decode(t))}mediaType(){return"application/iden3comm-encrypted-json"}getSupportedProfiles(){return this._supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this._supportedAlgorithms.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=vs(e);if(!this._supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);return!!o?.some(s=>this._supportedAlgorithms.includes(s))}async packInternal(e,t){let{enc:r,recipients:i}=t;if(!r)throw new Error("Missing encryption algorithm");if(!i.length)throw new Error("Missing recipients");if(!e.to)throw new Error("Missing recipient DID");let o=await _O(i,this._documentResolver),s=ke.encode(JSON.stringify(e)),a=await this._joseService.encrypt(s,{enc:r,typ:"application/iden3comm-encrypted-json",recipients:o});return ke.encode(JSON.stringify(a))}};var eF=class{constructor(e,t){this._kms=e;this._documentResolver=t}supportedAlgorithms=["ES256K","ES256K-R"];supportedProtocolVersions=["iden3comm/v1"];packMessage(e,t){return this.packInternal(e,t)}async pack(e,t){let r=JSON.parse(lt.decode(e));return this.packInternal(r,t)}async unpack(e){let t=lt.decode(e),[r,i]=t.split("."),o=JSON.parse(XI(r)),s=JSON.parse(XI(i)),a=Jj(o.kid)?.did;if(a&&a!==s.from)throw new Error(`Sender does not match DID in message with kid ${o?.kid}`);let c=await this.resolveDidDoc(s.from),u=Ny(c);if(!u?.length)throw new Error(`No verification methods defined in the DID document of ${c.id}`);if(o.kid){let d=u.find(h=>h.id===o.kid);if(!d)throw new Error(`verification method with specified kid ${o.kid} is not found in the DID Document`);u=[d]}if(!aW(t,u))throw new Error("JWS verification failed");return s}mediaType(){return"application/iden3comm-signed-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=vs(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);return!o?.length||o.some(a=>this.supportedAlgorithms.includes(a))}async resolveDidDoc(e){let t;try{let r=await this._documentResolver.resolve(e);if(!r?.didDocument?.id)throw new Error(`did document for ${e} is not found in resolution result`);t=r.didDocument}catch(r){throw new Error(`did document for ${e} is not resolved: ${r.message}`)}return t}async packInternal(e,t){if(!t.alg)throw new Error("Missing algorithm");let r=e.from??"";if(!r)throw new Error("Missing sender DID");if(!My[t.alg]?.length)throw new Error(`No supported verification methods for algorithm ${t.alg}`);let o=t.didDocument??await this.resolveDidDoc(r),s=Ny(o);if(!s.length)throw new Error(`No verification methods defined in the DID document of ${o.id}`);let a=t.kid?s.find(S=>S.id===t.kid):s[0];if(!a)throw new Error(`No key found with id ${t.kid} in DID document of ${o.id}`);let{publicKeyBytes:c,kmsKeyType:u}=bM(a);if(!c&&!u&&(a.blockchainAccountId||a.ethereumAddress)&&!t.signer)throw new Error(`No signer provided for ${a.blockchainAccountId||a.ethereumAddress}`);let l=a.id,d={alg:t.alg,kid:l,typ:"application/iden3comm-signed-json"},h=ZI(JSON.stringify(d)),f=ZI(JSON.stringify(e)),m=`${h}.${f}`,w=ke.encode(m),b;if(t.signer){let S=await t.signer(a,w);b=Lh(S)}else{if(!c)throw new Error("No public key found");if(!u)throw new Error("No KMS key type found");let S=await this._kms.sign({type:u,id:fo(u,Br(c))},w,{alg:t.alg});b=Lh(S)}return ke.encode(`${m}.${b}`)}};var tF=class{supportedProtocolVersions=["iden3comm/v1"];packMessage(e){return e.typ="application/iden3comm-plain-json",Promise.resolve(ke.encode(JSON.stringify(e)))}async pack(e){let t=JSON.parse(lt.decode(e));return t.typ="application/iden3comm-plain-json",Promise.resolve(ke.encode(JSON.stringify(t)))}async unpack(e){return JSON.parse(lt.decode(e))}mediaType(){return"application/iden3comm-plain-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=vs(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);if(o)throw new Error(`Algorithms are not supported for ${r} media type`);return!0}};var hte="unknown circuit ID. can't verify msg sender",g8="sender of message is not used for jwz token creation",pte="message was packed with unsupported circuit",mte="message proof is invalid",gte="message state verification failed",yte="unknown proving method algorithm";var{getProvingMethod:qRe}=Wy,sI=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},aI=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},cI=class{constructor(e,t,r={acceptedStateTransitionDelay:gM}){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(ke.encode(JSON.stringify(e)),t)}async pack(e,t){let r=await qRe(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(yte);let o=new Eh(r,lt.decode(e),(a,c)=>i?.dataPreparer?.prepare(a,t.senderDID,c));o.setHeader(Ka.Type,"application/iden3-zkp-json");let s=await o.prove(i.provingKey,i.wasm);return ke.encode(s)}async unpackMessage(e,t){let r=this.verificationParamsMap.get(t.toString());if(!r?.key)throw new Error(pte);if(!await e.verify(r?.key))throw new Error(mte);if(!await r?.verificationFn?.verify(e.circuitId,e.zkProof.pub_signals,this._opts))throw new Error(gte);let s=JSON.parse(e.getPayload());return await VRe(e,s),s}parseToken(e){return Eh.parse(lt.decode(e))}async unpack(e){let t=await this.parseToken(e),r=new Hc(t.alg,t.circuitId);return this.unpackMessage(t,r)}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}=vs(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;let s=this.supportedCircuitIds,a=!i?.length||i.some(l=>s.includes(l)),c=this.supportedAlgorithms;return(!o?.length||o.some(l=>c.includes(l)))&&a}},VRe=async(n,e)=>{switch(n.circuitId){case"authV2":case"authV3-8-32":case"authV3":{if(!e.from)throw new Error(g8);let t=(n.circuitId==="authV2"?new Ws:new ku).pubSignalsUnmarshal(ke.encode(JSON.stringify(n.zkProof.pub_signals))),r=ve.parseFromId(t.userID),i=await n.getMessageHash();if(It.bytesToInt(i.reverse())!==t.challenge)throw new Error(g8);if(e.from!==r.string())throw new Error(g8)}break;default:throw new Error(hte)}};var nF=class extends cI{constructor(t,r,i){super(new Map,new Map,{...i});this.circuitStorage=t;this.proofService=r;this.supportedCircuitIds=["authV2","authV3","authV3-8-32"]}async pack(t,r){let i=r.provingMethodAlg,o=i.circuitId,s=i.toString();if(!this.provingParamsMap.has(s)){let{provingKey:a,wasm:c}=await this.circuitStorage.loadCircuitData(o,{mode:"proving"});if(!a||!c)throw new Error(`circuit data not found for circuit id: ${o}`);this.provingParamsMap.set(s,{provingKey:a,wasm:c,dataPreparer:new sI(this.proofService.generateAuthInputs.bind(this.proofService))})}return super.pack(t,r)}async unpack(t){let r=await this.parseToken(t),i=r.circuitId,o=new Hc(r.alg,i);if(!this.verificationParamsMap.has(o.toString())){let{verificationKey:s}=await this.circuitStorage.loadCircuitData(i,{mode:"verification"});if(!s)throw new Error(`verification key not found for circuit id: ${i}`);this.verificationParamsMap.set(o.toString(),{key:s,verificationFn:new aI(this.proofService.verifyState.bind(this.proofService))})}return super.unpackMessage(r,o)}};var wte=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(wte||{});var rF=(o=>(o.AUTHV2="authV2",o.AUTHV3="authV3",o.AUTHV3_8_32="authV3-8-32",o.ETH_IDENTITY="ethIdentity",o.EMBEDDED_AUTH="embeddedAuth",o))(rF||{});var bte=(e=>(e.FeatureType="feature-type",e))(bte||{}),Ete=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(Ete||{});var Ni=class{nextMessageHandler;setNext(e){return this.nextMessageHandler=e,e}async handle(e,t){return t.allowExpiredMessages||Lr(e),this.nextMessageHandler?this.nextMessageHandler.handle(e,t):Promise.reject("Message handler not provided or message not supported")}},iF=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 qc(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 qc(e)},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};async function qc(n){try{let e=lt.decode(n);return(await Eh.parse(e)).method.methodAlg}catch{return Jc}}var Ite=n=>n.reduce((e,t)=>{let r=t.query;if(!r)return e;let i=r.groupId;if(!i)return e;let o=e.get(i);if(!o){let a=zc(12),u=new DataView(a.buffer).getUint32(0);return e.set(i,{query:r,linkNonce:u}),e}let s=R4(o.query.credentialSubject,r.credentialSubject);return e.set(i,{...o,query:{skipClaimRevocationCheck:o.query.skipClaimRevocationCheck||r.skipClaimRevocationCheck,...o.query,credentialSubject:s}}),e},new Map),Zy=async(n,e,t,r,i)=>{let o=e??[],s=Ite(o),a=new Map,c=[];for(let u of o){let l;try{if(!i.supportedCircuits.includes(u.circuitId)){if(u.optional){console.log(`Circuit ${u.circuitId} is not supported, skipping optional proof request`);continue}throw new Error(`Circuit ${u.circuitId} is not allowed`)}let h=u.query,f=i.credentials?.get(u.id.toString());if(f){l=await r.generateProof(u,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h?.skipClaimRevocationCheck,credential:f.credential,linkNonce:f.linkNonce,bypassCache:i.bypassProofsCache,allowExpiredCredentials:i.allowExpiredCredentials}),c.push(l);continue}let m=h?.groupId,w=s.get(m);if(m){if(!w)throw new Error(`Invalid group id ${h?.groupId}`);let S=w.query;if(!a.has(m)){let R=await r.findCredentialByProofQuery(n,w.query);if(!R.cred){if(u.optional){console.log("No credential found for optional proof request, skipping");continue}throw new Error(Ue.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(S)}`)}a.set(m,R)}}let b=a.get(m);l=await r.generateProof(u,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h?.skipClaimRevocationCheck,credential:b?.cred,credentialRevocationStatus:b?.revStatus,linkNonce:w?.linkNonce?BigInt(w.linkNonce):void 0,bypassCache:i.bypassProofsCache,allowExpiredCredentials:i.allowExpiredCredentials})}catch(d){let h=[Ue.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,Ue.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,Ue.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED,Ue.ERRORS.PROOF_SERVICE_CREDENTIAL_IS_EXPIRED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(Ue.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY))&&u.optional){console.log(`Error in optional proof request: ${d.message}, skipping`);continue}throw d}c.push(l)}return c},oF=async(n,e,t)=>{switch(t.acceptProfile||(t.acceptProfile=vC),t.acceptProfile.env){case"application/iden3comm-plain-json":return{authProof:{authMethod:"embeddedAuth"}};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=Ate(t.senderAddress,t.zkpResponses),o=await e.generateAuthProof(r,n,{challenge:i});return{authProof:{authMethod:r,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")}},uI=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=dh(n.proof),o=DE(t,i.a,i.b,i.c),s=mn.AbiCoder.defaultAbiCoder().encode(["string"],[n.circuitId]);return{requestId:e,zkProofEncoded:o,metadata:s}},Ate=(n,e)=>{let t=e.map(r=>{let i=uI(r);return{requestId:i.requestId,proof:i.zkProofEncoded,metadata:i.metadata}});return BigInt(mn.keccak256(new mn.AbiCoder().encode(["address","(uint256 requestId,bytes proof,bytes metadata)[]"],[n,t])))&BigInt("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")},QRe=n=>new mn.AbiCoder().encode(["tuple(string key,bytes value)[]"],[n]),Lr=n=>{if(n?.expires_time&&n.expires_time<Lt(new Date))throw new Error("Message expired")},ta=(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||Jc,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}`)},sF=(n,e,t)=>{if(t?.length)for(let r of t){let i=vs(r),o=Number(n.split("/").at(-2));if(!(i.protocolVersion!=="iden3comm/v1"||i.protocolVersion==="iden3comm/v1"&&(o<1||o>=2))&&e.isProfileSupported(i.env,r))return i}return vC};function zRe(n,e,t,r){return xte(n,"",e,t,r)}function xte(n,e,t,r,i){let o=Ut();return{id:o,thid:o,from:t,typ:"application/iden3comm-plain-json",type:at.AUTHORIZATION_REQUEST_MESSAGE_TYPE,body:{accept:i?.accept,reason:n,message:e,callbackUrl:r,scope:i?.scope??[]},created_time:Lt(new Date),expires_time:i?.expires_time?Lt(i.expires_time):void 0,attachments:i?.attachments}}var aF=class extends Ni{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=Object.values(Lc);handle(t,r){switch(t.type){case at.AUTHORIZATION_REQUEST_MESSAGE_TYPE:return this.handleAuthRequest(t,r);case at.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!==at.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!==at.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for authorization request");let i=t.to?ve.parse(t.to):r.senderDid,o=Ut();if(!t.from)throw new Error("auth request should contain from field");let s=at.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,a=this.getSupportedMediaTypeByProfile(r,t.body.accept),c=ve.parse(t.from),u=await Zy(i,t?.body.scope,c,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits,bypassProofsCache:r.bypassProofsCache,allowExpiredCredentials:r.allowExpiredCredentials,credentials:r.credentials});return{id:o,typ:a,type:s,thid:t.thid??o,body:{message:t?.body?.message,scope:u},created_time:Lt(new Date),from:i.string(),to:t.from}}async handleAuthorizationRequest(t,r,i){let o=await this.parseAuthorizationRequest(r);i?.allowExpiredMessages||Lr(o),i||(i={mediaType:"application/iden3-zkp-json"});let s=await this.handleAuthRequest(o,{senderDid:t,mediaType:i.mediaType,bypassProofsCache:i.bypassProofsCache,allowExpiredCredentials:i.allowExpiredCredentials}),a=ke.encode(JSON.stringify(s)),c=ta(i.mediaType,i.packerOptions,{provingMethodAlg:XO(this._packerMgr,i.preferredAuthProvingMethod,o.body.accept),senderDID:t}),u=lt.decode(await this._packerMgr.pack(i.mediaType,a,c));return{authRequest:o,authResponse:s,token:u}}async handleAuthResponse(t,r){let i=r.request;if(t.type!==at.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 u=c.query?.groupId,l=s.find(w=>w.id.toString()===c.id.toString());if(!l){if(c.optional)continue;throw new Error(`proof is not given for requestId ${c.id}`)}let d=D6(c.circuitId);if(!d.includes(l.circuitId))throw new Error(`proof is not given for requested circuit expected: ${d.join(", ")}, given ${l.circuitId} `);let h=c.params??{};h.verifierDid=ve.parse(i.from);let f=[r.acceptedProofGenerationDelay,r.acceptedStateTransitionDelay].some(w=>w!==void 0)?{acceptedProofGenerationDelay:r.acceptedProofGenerationDelay,acceptedStateTransitionDelay:r.acceptedStateTransitionDelay}:void 0,{linkID:m}=await this._proofService.verifyZKPResponse(l,{query:c.query,sender:t.from,params:h,opts:f});m&&u&&a.set(u,[...a.get(u)??[],{linkID:m.toString(),requestId:l.id}])}for(let[c,u]of a.entries())if(u.some(l=>l.linkID!==u[0].linkID))throw new Error(`Link id validation failed for group ${c}, request linkID to requestIds info: ${JSON.stringify(u)}`);return t}async handleAuthorizationResponse(t,r,i){i?.allowExpiredMessages||Lr(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;if(!s)continue;let a=s.groupId;if(a){let c=r[a]??[];for(let u of c){let l=u.query;if(!l)continue;if(l.type!==s?.type)throw new Error("all requests in the group should have the same type");if(l.context!==s?.context)throw new Error("all requests in the group should have the same context");let d=s?.allowedIssuers,h=l.allowedIssuers;if(!(d.includes("*")||d.every(f=>h.includes(f))))throw new Error("all requests in the group should have the same issuer")}r[a]=[...r[a]??[],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}=vs(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}};var vte=[{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 lI=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new jt(e.url);let i=new Ln(t,vte,this._provider);this._signer&&(this._signer=this._signer.connect(this._provider),i=i.connect(this._signer)),this._contract=i,this._transactionService=new Xs(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()}),kt.fromJSON({existence:e.existence,node_aux:t,siblings:r})}};function jRe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function WRe(n){return(jRe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function Xy(n,e){return WRe(n).includes(e)}function z0(n){return Xy(n,Ue.ERRORS.IDENTITY_DOES_NOT_EXIST)||Xy(n,Ue.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function cF(n){return Xy(n,Ue.ERRORS.STATE_DOES_NOT_EXIST)||Xy(n,Ue.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function uF(n){return Xy(n,Ue.ERRORS.ROOT_DOES_NOT_EXIST)||Xy(n,Ue.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var lF=class{constructor(e,t){this._configs=e;this._stateStorage=new dI(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=ve.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(!z0(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(!mf(t,f))throw new Error(`latest state not found and state parameter ${s} is not genesis state`);c=f}let u=ve.idFromDID(t);return await this._getOnChainRevocationStorageForIssuer(i,r).getRevocationStatusByIdAndState(u.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],u=r.searchParams.get("revocationNonce")||e.revocationNonce;if(u==null)throw new Error("revocationNonce not found in credentialStatus id field");let l=typeof u=="number"?u:parseInt(u,10);return{contractAddress:c,chainId:a,revocationNonce:l,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 lI(r,t)}};var Y0=class{async resolve(e){let r=await(await fetch(e.id)).json();return y8(r)}},y8=({issuer:n,mtp:e})=>({mtp:kt.fromJSON(e),issuer:n});var j0=class n{constructor(e=Ne,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 dF=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 Y0().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=ve.idFromDID(t),s;try{let l=await this._state.getLatestStateById(o.bigInt());if(!l.state)throw new Error("state contract returned empty state");s=l.state}catch(l){if(!z0(l))throw l;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=be.fromHex(d).bigInt(),f=wp(t);if(!f&&!mf(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)),u=be.fromBigInt(s);return await this.getRevocationStatusFromRHS(c,u,a)}getRevocationStatusFromIssuerData(e,t,r){if(r&&mf(e,r.value.bigInt()))return{mtp:new kt,issuer:{state:r.value.hex(),revocationTreeRoot:r.revocationTreeRoot.hex(),rootOfRoots:r.rootOfRoots.hex(),claimsTreeRoot:r.claimsTreeRoot.hex()}};if(t&&mf(e,t.state.value))return{mtp:new kt,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,u]=o.children,l=be.fromHex(c);return{mtp:await this.rhsGenerateProof(l,e,`${r}/node`),issuer:{state:s,claimsTreeRoot:a,revocationTreeRoot:c,rootOfRoots:u}}}async rhsGenerateProof(e,t,r){let i=!1,o=[],s,a=()=>new kt({siblings:o,existence:i,nodeAux:s}),c=e;for(let u=0;u<t.bytes.length*8;u++){if(c.bytes.every(f=>f===0))return a();let d=(await(await fetch(`${r}/${c.hex()}`)).json())?.node,h=j0.fromHex(d);switch(h.nodeType()){case 2:return t.bytes.every((f,m)=>f===h.children[0].bytes[m])?(i=!0,a()):(s={key:h.children[0],value:h.children[1]},a());case 1:Iw(t.bytes,u)?(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 ZRe(n,e){let t=ve.parse(n),r=ve.idFromDID(t),{method:i,blockchain:o,networkId:s}=ve.decodePartsFromId(r),a=It.hexToBytes(e),c=It.bytesToInt(a),u=Wc(i,o,s);return Ste(ve.idFromDID(t).bigInt(),c,u)}function Ste(n,e,t){let r=Xe.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var fI=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var hI=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=XRe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return y8(a.body)}};function XRe(n,e,t){return{id:Ut(),typ:"application/iden3comm-plain-json",type:at.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE,body:{revocation_nonce:t},thid:Ut(),from:n,to:e}}var pI=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)}},fF=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=pb.getInstance();r.then(s=>o.publish(NR.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},W0=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 hF=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 pF=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new fI,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new Y0),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new hI))}getCredentialStatusResolverRegistry(){return this._credentialStatusResolverRegistry}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:Ue.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ue.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(Ue.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:Ue.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ue.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=ve.parse(e.issuer),s=Xl(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(Ue.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(Ue.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:${Ut()}`,i.issuanceDate=i.issuanceDate?i.issuanceDate*1e3:Date.now(),Er.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(Ue.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function w8(n,e,t,r){let i=await b8(r,e,n);await new W0().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function b8(n,e,t){let r=new mF;return n&&await $Re(r,e,n),await _Re(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new j0(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function _Re(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function $Re(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var mF=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 Xc(o,s),c=await eDe(i,a);for(let u of c)this.seen.get(u.hash.hex())||(this.nodes.push(u),this.seen.set(u.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 eDe(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 j0;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=Iw(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=Rh([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var gF=class n extends Ni{constructor(t,r){super();this._packerMgr=t;this.opts=r}async handle(t,r){switch(t.type){case at.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 at.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:return this.handleFetchRequest(t);case at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:return this.handleIssuanceResponseMsg(t);case at.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}case at.ENCRYPTED_CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:return await this.handleEncryptedIssuanceResponseMessage(t),null;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=ve.parse(t.from),s=ve.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=Ut(),a={id:s,typ:r.mediaType,type:at.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE,thid:t.thid??s,body:{id:o.id},from:t.to,to:t.from},c=ke.encode(JSON.stringify(a)),u=ve.parse(t.to),l=ta(r.mediaType,r.packerOptions,{senderDID:u}),d=lt.decode(await this._packerMgr.pack(r.mediaType,c,l));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":pM[r.mediaType],...r.headers},body:d})).arrayBuffer();if(!f.byteLength)throw new Error(`could not fetch , ${o?.id}, response is empty`);let{unpackedMessage:m}=await this._packerMgr.unpack(new Uint8Array(f));if(m.type===at.ENCRYPTED_CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE)return await this.handleEncryptedIssuanceResponseMessage(m),[];if(m.type!==at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE)return m;i.push(Er.fromJSON(m.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,at.CREDENTIAL_OFFER_MESSAGE_TYPE);r?.allowExpiredMessages||Lr(i);let o=r?.mediaType||"application/iden3-zkp-json",s=ta(o,r?.packerOptions,{provingMethodAlg:r?.messageProvingMethodAlg||await qc(t),senderDID:ve.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,at.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=ve.parse(t.to),i=ve.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(Xl(r,s).string()!==i.string())throw new Error("credential subject is not a sender DID");return{id:Ut(),type:at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE,typ:t.typ??"application/iden3comm-plain-json",thid:t.thid??Ut(),body:{credential:s},from:t.to,to:t.from}}async handleCredentialFetchRequest(t,r){let i=await n.unpackMessage(this._packerMgr,t,at.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);r?.allowExpiredMessages||Lr(i);let o=await this.handleFetchRequest(i);return this._packerMgr.pack("application/iden3comm-plain-json",ke.encode(JSON.stringify(o)),{})}async handleEncryptedIssuanceResponseMessage(t){if(!this.opts?.joseService)throw new Error("JoseService is not initialized. Encrypted issuance response cannot be handled");let{plaintext:r}=await this.opts.joseService.decrypt(t.body.data),i=Er.fromJSON({...JSON.parse(lt.decode(r)),proof:t.body.proof});if(!this.opts?.credentialWallet)throw new Error("please provide credential wallet in options for encrypted issuance response handling");if(!this.opts?.didResolverUrl)throw new Error("please provide resolver URL in options for encrypted issuance response handling");if(!this.opts?.merklizeOptions)throw new Error("please provide merklize options for encrypted issuance response handling");let o=this.opts.credentialWallet.getCredentialStatusResolverRegistry();if(!o)throw new Error("credential status resolver registry is not available in credential wallet");if(!await i.verifyProofs(this.opts.didResolverUrl,{credStatusResolverRegistry:o,merklizeOptions:this.opts.merklizeOptions}))throw new Error("credential proof verification failed");return await this.opts?.credentialWallet?.save(i),null}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");let r=t.body.credential;if(!(r instanceof Er)){if(typeof r!="object"||r===null)throw new Error("credential object is not properly unmarshaled");r=Er.fromJSON(r)}return await this.opts.credentialWallet.save(r),null}async handleIssuanceResponseMessage(t,r){let i=await n.unpackMessage(this._packerMgr,t,at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);return r?.allowExpiredMessages||Lr(i),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 yF=class extends Ni{constructor(t,r,i){super();this._packerMgr=t;this._proofService=r;this._zkpVerifier=i}_supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","credentialAtomicQueryV3OnChain","authV2","authV3","authV3-8-32","linkedMultiQuery10-beta.1","credentialAtomicQueryV3","linkedMultiQuery"];async handle(t,r){switch(t.type){case at.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!==at.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 u=t.from?ve.parse(t.from):void 0,{scope:l=[]}=t.body,d=await Zy(i,l,u,this._proofService,{ethSigner:o,challenge:s??It.bytesToInt(di(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),m=new Map;for(let[w,b]of f)m.set(w,{responses:b});return t.body.transaction_data.txHash=f.keys().next().value,m}case"b68967e2":{let f=await this._zkpVerifier.submitZKPResponse(o,t.body.transaction_data,d),m=new Map;for(let[w,b]of f)m.set(w,{responses:[b]});return t.body.transaction_data.txHash=f.keys().next().value,m}case"06c86a91":{if(!t.to)throw new Error("failed message. empty 'to' field");let f=sF(at.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE,this._packerMgr,t.body.accept),m=ve.parse(t.to),{authProof:w}=await oF(m,this._proofService,{supportedCircuits:this._supportedCircuits,acceptProfile:f,senderAddress:await o.getAddress(),zkpResponses:d}),b=await this._zkpVerifier.submitResponse(o,t.body.transaction_data,d,w);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.'")}}async parseContractInvokeRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==at.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:at.CONTRACT_INVOKE_RESPONSE_MESSAGE_TYPE,from:t.to,to:t.from,body:{transaction_data:t.body.transaction_data,scope:[]},created_time:Lt(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||Lr(o),o.body.transaction_data.method_id!=="b68967e2")throw new Error("please use handle method to work with other method ids");if(o.type!==at.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 l=o.from?ve.parse(o.from):void 0,d=await Zy(t,o?.body?.scope,l,this._proofService,{ethSigner:s,challenge:a,supportedCircuits:this._supportedCircuits});return this._zkpVerifier.submitZKPResponse(s,o.body.transaction_data,d)}};var wF=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=ve.parse(r),o=t?.mediaType||"application/iden3-zkp-json",s=t?.packerOptions??{senderDID:i,provingMethodAlg:Jc},a={id:Ut(),typ:"application/iden3-zkp-json",type:at.CREDENTIAL_REFRESH_MESSAGE_TYPE,thid:Ut(),body:{id:e.id,reason:t?.reason??"credential is expired"},from:r,to:e.issuer},c=ke.encode(JSON.stringify(a)),u=await this._options.packageManager.pack(o,c,s),l=await fetch(e.refreshService.id,{method:"post",headers:{"Content-Type":"application/json"},body:u.buffer});if(l.status!==200)throw new Error(`could not refresh W3C credential, return status ${l.status}`);let d=await l.json();if(!d.body?.credential)throw new Error("no credential in CredentialIssuanceMessage response");return Er.fromJSON(d.body.credential)}};var bF=class extends Ni{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 at.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=ve.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=Ut();return{id:c,typ:"application/iden3comm-plain-json",type:at.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!==at.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||Lr(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=ve.parse(o.to),c=ta(i.mediaType,i.packerOptions,{senderDID:a,provingMethodAlg:i.packerOptions?.provingMethodAlg||await qc(r)});return this._packerMgr.pack(i.mediaType,ke.encode(JSON.stringify(s)),c)}};function tDe(n,e,t){let r=Ut();return{id:r,thid:r,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PROPOSAL_REQUEST_MESSAGE_TYPE,body:{credentials:t.credentials,did_doc:t.did_doc},created_time:Lt(new Date),expires_time:t?.expires_time?Lt(t.expires_time):void 0,attachments:t.attachments}}function nDe(n,e,t,r){let i=Ut();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PROPOSAL_MESSAGE_TYPE,body:{proposals:t||[]},created_time:Lt(new Date),expires_time:r?.expires_time?Lt(r.expires_time):void 0}}var EF=class extends Ni{constructor(t,r,i){super();this._packerMgr=t;this._identityWallet=r;this._params=i}async handle(t,r){switch(t.type){case at.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!==at.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=[];if(!r?.forceCredentialReissue){try{c=await this._identityWallet.credentialWallet.findByQuery({credentialSubject:{id:{$eq:t.from}},type:a.type,context:a.context,allowedIssuers:[t.to]})}catch(l){if(l.message!=="no credential satisfied query")throw l}if(c=c.filter(l=>!l.expirationDate||new Date(l.expirationDate)>new Date),c.length){let l=Ut();i||(i={id:l,typ:this._params.packerParams.mediaType,type:at.CREDENTIAL_OFFER_MESSAGE_TYPE,thid:t.thid??l,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 u=await this._params.proposalResolverFn(a.context,a.type,{msg:t});if(!u)throw new Error(`can't resolve Proposal for type: ${a.type}, context: ${a.context}`);if(!o){let l=Ut();o={id:l,typ:this._params.packerParams.mediaType,type:at.PROPOSAL_MESSAGE_TYPE,thid:t.thid??l,body:{proposals:[]},from:t.to,to:t.from}}o.body?.proposals.push(u)}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||Lr(i);let o=ve.parse(i.from),s=await this.handleProposalRequestMessage(i),a=ke.encode(JSON.stringify(s)),c=ta(this._params.packerParams.mediaType,this._params.packerParams.packerOptions,{provingMethodAlg:await qc(t),senderDID:o});return this._packerMgr.pack(this._params.packerParams.mediaType,a,c)}async handleProposal(t,r){if(r?.allowExpiredMessages||Lr(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 Cte(n,e,t,r,i){let o=Ut();return{id:o,thid:o,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PAYMENT_REQUEST_MESSAGE_TYPE,body:{agent:t,payments:r},created_time:Lt(new Date),expires_time:i?.expires_time?Lt(i.expires_time):void 0}}function Lte(n,e,t,r){let i=Ut();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PAYMENT_MESSAGE_TYPE,body:{payments:t},created_time:Lt(new Date),expires_time:r?.expires_time?Lt(r.expires_time):void 0}}var IF=class extends Ni{constructor(t,r){super();this._packerMgr=t;this._params=r}async handle(t,r){switch(t.type){case at.PAYMENT_REQUEST_MESSAGE_TYPE:return await this.handlePaymentRequestMessage(t,r);case at.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!==at.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=ve.parse(t.to),o=ve.parse(t.from),s=[];for(let m=0;m<t.body.payments.length;m++){let{data:w}=t.body.payments[m],b=Array.isArray(w)?w.find(S=>S.type==="Iden3PaymentRequestCryptoV1"?S.id===r.nonce:S.nonce===r.nonce):w;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=Lte(i,o,s),c=r?.mediaType||this._params.packerParams.mediaType||"application/iden3-zkp-json",u=ta(c,r?.packerOptions||this._params.packerParams,{senderDID:i,provingMethodAlg:r.messageProvingMethodAlg}),l=await this.packMessage(a,i,c,u),h=await(await fetch(t.body.agent,{method:"POST",body:l.buffer,headers:{...r.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||Lr(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=ve.parse(i.to);r.packerOptions=ta(o,r.packerOptions,{provingMethodAlg:await qc(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||Lr(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(u=>Array.isArray(u.data)?u.data:[u.data]).flat().find(u=>u.type==="Iden3PaymentRequestCryptoV1"?u.id===s:u.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 u=0;u<s.length;u++){let{credentials:l,description:d}=s[u],h=[];for(let f=0;f<s[u].options.length;f++){let{nonce:m,amount:w,chainId:b,optionId:S,expirationDate:R}=s[u].options[f],G=this._params.multiChainPaymentConfig?.find(z=>z.chainId===b);if(!G)throw new Error(`failed request. no config for chain ${b}`);let{recipient:U,paymentRails:H,options:M}=G,A=M.find(z=>z.id===S);if(!A)throw new Error(`failed request. no option for id ${S}`);if((A.type==="Iden3PaymentRailsERC20RequestV1"||A.type==="Iden3PaymentRailsSolanaSPLRequestV1")&&!A.contractAddress)throw new Error(`failed request. no token address for option id ${S}`);let T=R??new Date(new Date().setHours(new Date().getHours()+1));if(A.type==="Iden3PaymentRailsSolanaRequestV1"||A.type==="Iden3PaymentRailsSolanaSPLRequestV1"){if(!a?.solSigner)throw new Error(`please provide solana signer in context for ${A.type} payment type`);let z=await OB(a.solSigner,A,b,H,U,BigInt(w),T,m);h.push(z)}else{let z=await FB(o,A,b,H,U,BigInt(w),T,m);h.push(z)}}c.push({data:h,credentials:l,description:d})}return Cte(t,r,i,c)}async packMessage(t,r,i,o){let s=ke.encode(JSON.stringify(t)),a=i==="application/iden3comm-signed-json"?o:{provingMethodAlg:o?.provingMethodAlg||Jc};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 gS(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 mS(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 mS(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 gS(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 rDe(n,e){let t=Ut();return{id:t,thid:t,typ:"application/iden3comm-plain-json",type:at.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE,body:{queries:n},from:e?.from,to:e?.to,created_time:Lt(new Date),expires_time:e?.expires_time}}function Rte(n,e){let t=Ut();return{id:t,typ:"application/iden3comm-plain-json",thid:t,type:at.DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE,body:{disclosures:n},from:e?.from,to:e?.to,created_time:Lt(new Date),expires_time:e?.expires_time}}var AF=class extends Ni{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 at.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:return await this.handleDiscoveryQuery(t,r);default:return super.handle(t,r)}}async handleDiscoveryQuery(t,r){r?.allowExpiredMessages||Lr(t);let i=[];for(let o of t.body.queries)i.push(...this.handleQuery(o));return Promise.resolve(Rte(i,{to:t.from,from:t.to,expires_time:r?.disclosureExpiresDate?Lt(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 Dte(n,e){return{id:Ut(),pthid:e?.pthid,typ:"application/iden3comm-plain-json",type:at.PROBLEM_REPORT_MESSAGE_TYPE,ack:e?.ack,body:{code:n,comment:e?.comment,args:e?.args,escalate_to:e?.escalate_to},from:e?.from,to:e?.to}}function iDe(n,e,t){return Dte(e,{pthid:n,...t})}var Tte=new TextEncoder,Z0=new TextDecoder,E8=2**32;function Ss(...n){let e=n.reduce((i,{length:o})=>i+o,0),t=new Uint8Array(e),r=0;for(let i of n)t.set(i,r),r+=i.length;return t}function xF(n,e,t){if(e<0||e>=E8)throw new RangeError(`value must be >= 0 and <= ${E8-1}. Received ${e}`);n.set([e>>>24,e>>>16,e>>>8,e&255],t)}function I8(n){let e=Math.floor(n/E8),t=n%E8,r=new Uint8Array(8);return xF(r,e,0),xF(r,t,4),r}function A8(n){let e=new Uint8Array(4);return xF(e,n),e}function Ja(n){let e=new Uint8Array(n.length);for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r>127)throw new TypeError("non-ASCII string encountered in encode()");e[t]=r}return e}function Bte(n){if(Uint8Array.prototype.toBase64)return n.toBase64();let e=32768,t=[];for(let r=0;r<n.length;r+=e)t.push(String.fromCharCode.apply(null,n.subarray(r,r+e)));return btoa(t.join(""))}function Pte(n){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(n);let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Zr(n){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof n=="string"?n:Z0.decode(n),{alphabet:"base64url"});let e=n;e instanceof Uint8Array&&(e=Z0.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Pte(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Xr(n){let e=n;return typeof e=="string"&&(e=Tte.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Bte(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var _y=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var mI=class extends _y{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Xt=class extends _y{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Ih=class extends _y{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}},Ve=class extends _y{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"};function vF(n){switch(n){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new Xt(`Unsupported JWE Algorithm: ${n}`)}}var kte=n=>crypto.getRandomValues(new Uint8Array(vF(n)>>3));function x8(n,e){if(e.length<<3!==vF(n))throw new Ve("Invalid Initialization Vector length")}function $y(n,e){let t=n.byteLength<<3;if(t!==e)throw new Ve(`Invalid Content Encryption Key length. Expected ${e} bits, got ${t} bits`)}var Ah=(n,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${n}`),v8=(n,e)=>n.name===e;function oDe(n){return parseInt(n.name.slice(4),10)}function sDe(n,e){if(e&&!n.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Cs(n,e,t){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!v8(n.algorithm,"AES-GCM"))throw Ah("AES-GCM");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw Ah(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!v8(n.algorithm,"AES-KW"))throw Ah("AES-KW");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw Ah(r,"algorithm.length");break}case"ECDH":{switch(n.algorithm.name){case"ECDH":case"X25519":break;default:throw Ah("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!v8(n.algorithm,"PBKDF2"))throw Ah("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!v8(n.algorithm,"RSA-OAEP"))throw Ah("RSA-OAEP");let r=parseInt(e.slice(9),10)||1;if(oDe(n.algorithm.hash)!==r)throw Ah(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}sDe(n,t)}function Mte(n,e,...t){if(t=t.filter(Boolean),t.length>2){let r=t.pop();n+=`one of type ${t.join(", ")}, or ${r}.`}else t.length===2?n+=`one of type ${t[0]} or ${t[1]}.`:n+=`of type ${t[0]}.`;return e==null?n+=` Received ${e}`:typeof e=="function"&&e.name?n+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(n+=` Received an instance of ${e.constructor.name}`),n}var xh=(n,...e)=>Mte("Key must be ",n,...e),SF=(n,e,...t)=>Mte(`Key for the ${n} algorithm must be `,e,...t);function X0(n){if(!Vu(n))throw new Error("CryptoKey instance expected")}var Vu=n=>{if(n?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return n instanceof CryptoKey}catch{return!1}},gI=n=>n?.[Symbol.toStringTag]==="KeyObject",CF=n=>Vu(n)||gI(n);async function aDe(n,e){if(!(n instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let t={name:"HMAC",hash:"SHA-256"},r=await crypto.subtle.generateKey(t,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(t,r,n)),o=new Uint8Array(await crypto.subtle.sign(t,r,e)),s=0,a=-1;for(;++a<32;)s|=i[a]^o[a];return s===0}async function cDe(n,e,t,r,i,o){if(!(e instanceof Uint8Array))throw new TypeError(xh(e,"Uint8Array"));let s=parseInt(n.slice(1,4),10),a=await crypto.subtle.importKey("raw",e.subarray(s>>3),"AES-CBC",!1,["decrypt"]),c=await crypto.subtle.importKey("raw",e.subarray(0,s>>3),{hash:`SHA-${s<<1}`,name:"HMAC"},!1,["sign"]),u=Ss(o,r,t,I8(o.length<<3)),l=new Uint8Array((await crypto.subtle.sign("HMAC",c,u)).slice(0,s>>3)),d;try{d=await aDe(i,l)}catch{}if(!d)throw new Ih;let h;try{h=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:"AES-CBC"},a,t))}catch{}if(!h)throw new Ih;return h}async function uDe(n,e,t,r,i,o){let s;e instanceof Uint8Array?s=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):(Cs(e,n,"decrypt"),s=e);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:r,name:"AES-GCM",tagLength:128},s,Ss(t,i)))}catch{throw new Ih}}async function S8(n,e,t,r,i,o){if(!Vu(e)&&!(e instanceof Uint8Array))throw new TypeError(xh(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!r)throw new Ve("JWE Initialization Vector missing");if(!i)throw new Ve("JWE Authentication Tag missing");switch(x8(n,r),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&$y(e,parseInt(n.slice(-3),10)),cDe(n,e,t,r,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&$y(e,parseInt(n.slice(1,4),10)),uDe(n,e,t,r,i,o);default:throw new Xt("Unsupported JWE Content Encryption Algorithm")}}function ew(...n){let e=n.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(let r of e){let i=Object.keys(r);if(!t||t.size===0){t=new Set(i);continue}for(let o of i){if(t.has(o))return!1;t.add(o)}}return!0}var lDe=n=>typeof n=="object"&&n!==null;function Zo(n){if(!lDe(n)||Object.prototype.toString.call(n)!=="[object Object]")return!1;if(Object.getPrototypeOf(n)===null)return!0;let e=n;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(n)===e}function Ote(n,e){if(n.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function Fte(n,e,t){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"AES-KW",!0,[t]):(Cs(n,e,t),n)}async function yI(n,e,t){let r=await Fte(e,n,"wrapKey");Ote(r,n);let i=await crypto.subtle.importKey("raw",t,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,r,"AES-KW"))}async function wI(n,e,t){let r=await Fte(e,n,"unwrapKey");Ote(r,n);let i=await crypto.subtle.unwrapKey("raw",t,r,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}async function Nte(n,e){let t=`SHA-${n.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(t,e))}function RF(n){return Ss(A8(n.length),n)}async function dDe(n,e,t){let r=e>>3,i=32,o=Math.ceil(r/i),s=new Uint8Array(o*i);for(let a=1;a<=o;a++){let c=new Uint8Array(4+n.length+t.length);c.set(A8(a),0),c.set(n,4),c.set(t,4+n.length);let u=await Nte("sha256",c);s.set(u,(a-1)*i)}return s.slice(0,r)}async function C8(n,e,t,r,i=new Uint8Array,o=new Uint8Array){Cs(n,"ECDH"),Cs(e,"ECDH","deriveBits");let s=RF(Ja(t)),a=RF(i),c=RF(o),u=A8(r),l=new Uint8Array,d=Ss(s,a,c,u,l),h=new Uint8Array(await crypto.subtle.deriveBits({name:n.algorithm.name,public:n},e,fDe(n)));return dDe(h,r,d)}function fDe(n){return n.algorithm.name==="X25519"?256:Math.ceil(parseInt(n.algorithm.namedCurve.slice(-3),10)/8)<<3}function L8(n){switch(n.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return n.algorithm.name==="X25519"}}function hDe(n,e){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits"]):(Cs(n,e,"deriveBits"),n)}var pDe=(n,e)=>Ss(Ja(n),Uint8Array.of(0),e);async function Gte(n,e,t,r){if(!(n instanceof Uint8Array)||n.length<8)throw new Ve("PBES2 Salt Input must be 8 or more octets");let i=pDe(e,n),o=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:t,name:"PBKDF2",salt:i},a=await hDe(r,e);return new Uint8Array(await crypto.subtle.deriveBits(s,a,o))}async function Hte(n,e,t,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let o=await Gte(i,n,r,e);return{encryptedKey:await yI(n.slice(-6),o,t),p2c:r,p2s:Xr(i)}}async function Kte(n,e,t,r,i){let o=await Gte(i,n,r,e);return wI(n.slice(-6),o,t)}function DF(n,e){if(n.startsWith("RS")||n.startsWith("PS")){let{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${n} requires key modulusLength to be 2048 bits or larger`)}}var qte=n=>{switch(n){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Xt(`alg ${n} is not supported either by JOSE or your javascript runtime`)}};async function Vte(n,e,t){return Cs(e,n,"encrypt"),DF(n,e),new Uint8Array(await crypto.subtle.encrypt(qte(n),e,t))}async function Qte(n,e,t){return Cs(e,n,"decrypt"),DF(n,e),new Uint8Array(await crypto.subtle.decrypt(qte(n),e,t))}function bI(n){switch(n){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new Xt(`Unsupported JWE Algorithm: ${n}`)}}var Qu=n=>crypto.getRandomValues(new Uint8Array(bI(n)>>3));function mDe(n){let e,t;switch(n.kty){case"AKP":{switch(n.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:n.alg},t=n.priv?["sign"]:["verify"];break;default:throw new Xt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(n.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${n.alg.slice(-3)}`},t=n.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.alg.slice(-3)}`},t=n.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(n.alg.slice(-3),10)||1}`},t=n.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Xt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(n.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=n.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=n.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=n.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:n.crv},t=n.d?["deriveBits"]:[];break;default:throw new Xt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(n.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},t=n.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:n.crv},t=n.d?["deriveBits"]:[];break;default:throw new Xt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new Xt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}async function tw(n){if(!n.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:t}=mDe(n),r={...n};return r.kty!=="AKP"&&delete r.alg,delete r.use,crypto.subtle.importKey("jwk",r,e,n.ext??!(n.d||n.priv),n.key_ops??t)}async function Yte(n,e,t){if(!Zo(n))throw new TypeError("JWK must be an object");let r;switch(e??=n.alg,r??=t?.extractable??n.ext,n.kty){case"oct":if(typeof n.k!="string"||!n.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Zr(n.k);case"RSA":if("oth"in n&&n.oth!==void 0)throw new Xt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return tw({...n,alg:e,ext:r});case"AKP":{if(typeof n.alg!="string"||!n.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==n.alg)throw new TypeError("JWK alg and alg option value mismatch");return tw({...n,ext:r})}case"EC":case"OKP":return tw({...n,alg:e,ext:r});default:throw new Xt('Unsupported "kty" (Key Type) Parameter value')}}async function gDe(n,e,t,r,i){if(!(t instanceof Uint8Array))throw new TypeError(xh(t,"Uint8Array"));let o=parseInt(n.slice(1,4),10),s=await crypto.subtle.importKey("raw",t.subarray(o>>3),"AES-CBC",!1,["encrypt"]),a=await crypto.subtle.importKey("raw",t.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:"AES-CBC"},s,e)),u=Ss(i,r,c,I8(i.length<<3)),l=new Uint8Array((await crypto.subtle.sign("HMAC",a,u)).slice(0,o>>3));return{ciphertext:c,tag:l,iv:r}}async function yDe(n,e,t,r,i){let o;t instanceof Uint8Array?o=await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt"]):(Cs(t,n,"encrypt"),o=t);let s=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:"AES-GCM",tagLength:128},o,e)),a=s.slice(-16);return{ciphertext:s.slice(0,-16),tag:a,iv:r}}async function R8(n,e,t,r,i){if(!Vu(t)&&!(t instanceof Uint8Array))throw new TypeError(xh(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(r?x8(n,r):r=kte(n),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&$y(t,parseInt(n.slice(-3),10)),gDe(n,e,t,r,i);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&$y(t,parseInt(n.slice(1,4),10)),yDe(n,e,t,r,i);default:throw new Xt("Unsupported JWE Content Encryption Algorithm")}}async function jte(n,e,t,r){let i=n.slice(0,7),o=await R8(i,t,e,r,new Uint8Array);return{encryptedKey:o.ciphertext,iv:Xr(o.iv),tag:Xr(o.tag)}}async function Wte(n,e,t,r,i){let o=n.slice(0,7);return S8(o,e,t,r,i,new Uint8Array)}async function Zte(n,e,t,r,i){switch(n){case"dir":{if(t!==void 0)throw new Ve("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(t!==void 0)throw new Ve("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Zo(r.epk))throw new Ve('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(X0(e),!L8(e))throw new Xt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await Yte(r.epk,n);X0(o);let s,a;if(r.apu!==void 0){if(typeof r.apu!="string")throw new Ve('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{s=Zr(r.apu)}catch{throw new Ve("Failed to base64url decode the apu")}}if(r.apv!==void 0){if(typeof r.apv!="string")throw new Ve('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{a=Zr(r.apv)}catch{throw new Ve("Failed to base64url decode the apv")}}let c=await C8(o,e,n==="ECDH-ES"?r.enc:n,n==="ECDH-ES"?bI(r.enc):parseInt(n.slice(-5,-2),10),s,a);if(n==="ECDH-ES")return c;if(t===void 0)throw new Ve("JWE Encrypted Key missing");return wI(n.slice(-6),c,t)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");return X0(e),Qte(n,e,t)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");if(typeof r.p2c!="number")throw new Ve('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(r.p2c>o)throw new Ve('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof r.p2s!="string")throw new Ve('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let s;try{s=Zr(r.p2s)}catch{throw new Ve("Failed to base64url decode the p2s")}return Kte(n,e,t,r.p2c,s)}case"A128KW":case"A192KW":case"A256KW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");return wI(n,e,t)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");if(typeof r.iv!="string")throw new Ve('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof r.tag!="string")throw new Ve('JOSE Header "tag" (Authentication Tag) missing or invalid');let o;try{o=Zr(r.iv)}catch{throw new Ve("Failed to base64url decode the iv")}let s;try{s=Zr(r.tag)}catch{throw new Ve("Failed to base64url decode the tag")}return Wte(n,e,t,o,s)}default:throw new Xt('Invalid or unsupported "alg" (JWE Algorithm) header value')}}function nw(n,e,t,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new n('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(s=>typeof s!="string"||s.length===0))throw new n('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;t!==void 0?o=new Map([...Object.entries(t),...e.entries()]):o=e;for(let s of r.crit){if(!o.has(s))throw new Xt(`Extension Header Parameter "${s}" is not recognized`);if(i[s]===void 0)throw new n(`Extension Header Parameter "${s}" is missing`);if(o.get(s)&&r[s]===void 0)throw new n(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(r.crit)}function TF(n,e){if(e!==void 0&&(!Array.isArray(e)||e.some(t=>typeof t!="string")))throw new TypeError(`"${n}" option must be an array of strings`);if(e)return new Set(e)}var EI=n=>Zo(n)&&typeof n.kty=="string",Xte=n=>n.kty!=="oct"&&(n.kty==="AKP"&&typeof n.priv=="string"||typeof n.d=="string"),_te=n=>n.kty!=="oct"&&n.d===void 0&&n.priv===void 0,$te=n=>n.kty==="oct"&&typeof n.k=="string";var rw,ene=async(n,e,t,r=!1)=>{rw||=new WeakMap;let i=rw.get(n);if(i?.[t])return i[t];let o=await tw({...e,alg:t});return r&&Object.freeze(n),i?i[t]=o:rw.set(n,{[t]:o}),o},bDe=(n,e)=>{rw||=new WeakMap;let t=rw.get(n);if(t?.[e])return t[e];let r=n.type==="public",i=!!r,o;if(n.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}o=n.toCryptoKey(n.asymmetricKeyType,i,r?[]:["deriveBits"])}if(n.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=n.toCryptoKey(n.asymmetricKeyType,i,[r?"verify":"sign"])}switch(n.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==n.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=n.toCryptoKey(n.asymmetricKeyType,i,[r?"verify":"sign"])}}if(n.asymmetricKeyType==="rsa"){let s;switch(e){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(e.startsWith("RSA-OAEP"))return n.toCryptoKey({name:"RSA-OAEP",hash:s},i,r?["encrypt"]:["decrypt"]);o=n.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},i,[r?"verify":"sign"])}if(n.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(n.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError("given KeyObject instance cannot be used for this algorithm");e==="ES256"&&a==="P-256"&&(o=n.toCryptoKey({name:"ECDSA",namedCurve:a},i,[r?"verify":"sign"])),e==="ES384"&&a==="P-384"&&(o=n.toCryptoKey({name:"ECDSA",namedCurve:a},i,[r?"verify":"sign"])),e==="ES512"&&a==="P-521"&&(o=n.toCryptoKey({name:"ECDSA",namedCurve:a},i,[r?"verify":"sign"])),e.startsWith("ECDH-ES")&&(o=n.toCryptoKey({name:"ECDH",namedCurve:a},i,r?[]:["deriveBits"]))}if(!o)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return t?t[e]=o:rw.set(n,{[e]:o}),o};async function vh(n,e){if(n instanceof Uint8Array||Vu(n))return n;if(gI(n)){if(n.type==="secret")return n.export();if("toCryptoKey"in n&&typeof n.toCryptoKey=="function")try{return bDe(n,e)}catch(r){if(r instanceof TypeError)throw r}let t=n.export({format:"jwk"});return ene(n,t,e)}if(EI(n))return n.k?Zr(n.k):ene(n,n,e,!0);throw new Error("unreachable")}var iw=n=>n?.[Symbol.toStringTag],BF=(n,e,t)=>{if(e.use!==void 0){let r;switch(t){case"sign":case"verify":r="sig";break;case"encrypt":case"decrypt":r="enc";break}if(e.use!==r)throw new TypeError(`Invalid key for this operation, its "use" must be "${r}" when present`)}if(e.alg!==void 0&&e.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(e.key_ops)){let r;switch(!0){case(t==="sign"||t==="verify"):case n==="dir":case n.includes("CBC-HS"):r=t;break;case n.startsWith("PBES2"):r="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(n):!n.includes("GCM")&&n.endsWith("KW")?r=t==="encrypt"?"wrapKey":"unwrapKey":r=t;break;case(t==="encrypt"&&n.startsWith("RSA")):r="wrapKey";break;case t==="decrypt":r=n.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(r&&e.key_ops?.includes?.(r)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},EDe=(n,e,t)=>{if(!(e instanceof Uint8Array)){if(EI(e)){if($te(e)&&BF(n,e,t))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!CF(e))throw new TypeError(SF(n,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${iw(e)} instances for symmetric algorithms must be of type "secret"`)}},IDe=(n,e,t)=>{if(EI(e))switch(t){case"decrypt":case"sign":if(Xte(e)&&BF(n,e,t))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(_te(e)&&BF(n,e,t))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!CF(e))throw new TypeError(SF(n,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${iw(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(t){case"sign":throw new TypeError(`${iw(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${iw(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(t){case"verify":throw new TypeError(`${iw(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${iw(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function ow(n,e,t){switch(n.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":EDe(n,e,t);break;default:IDe(n,e,t)}}async function II(n,e,t){if(!Zo(n))throw new Ve("Flattened JWE must be an object");if(n.protected===void 0&&n.header===void 0&&n.unprotected===void 0)throw new Ve("JOSE Header missing");if(n.iv!==void 0&&typeof n.iv!="string")throw new Ve("JWE Initialization Vector incorrect type");if(typeof n.ciphertext!="string")throw new Ve("JWE Ciphertext missing or incorrect type");if(n.tag!==void 0&&typeof n.tag!="string")throw new Ve("JWE Authentication Tag incorrect type");if(n.protected!==void 0&&typeof n.protected!="string")throw new Ve("JWE Protected Header incorrect type");if(n.encrypted_key!==void 0&&typeof n.encrypted_key!="string")throw new Ve("JWE Encrypted Key incorrect type");if(n.aad!==void 0&&typeof n.aad!="string")throw new Ve("JWE AAD incorrect type");if(n.header!==void 0&&!Zo(n.header))throw new Ve("JWE Shared Unprotected Header incorrect type");if(n.unprotected!==void 0&&!Zo(n.unprotected))throw new Ve("JWE Per-Recipient Unprotected Header incorrect type");let r;if(n.protected)try{let U=Zr(n.protected);r=JSON.parse(Z0.decode(U))}catch{throw new Ve("JWE Protected Header is invalid")}if(!ew(r,n.header,n.unprotected))throw new Ve("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...r,...n.header,...n.unprotected};if(nw(Ve,new Map,t?.crit,r,i),i.zip!==void 0)throw new Xt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:o,enc:s}=i;if(typeof o!="string"||!o)throw new Ve("missing JWE Algorithm (alg) in JWE Header");if(typeof s!="string"||!s)throw new Ve("missing JWE Encryption Algorithm (enc) in JWE Header");let a=t&&TF("keyManagementAlgorithms",t.keyManagementAlgorithms),c=t&&TF("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms);if(a&&!a.has(o)||!a&&o.startsWith("PBES2"))throw new mI('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(s))throw new mI('"enc" (Encryption Algorithm) Header Parameter value not allowed');let u;if(n.encrypted_key!==void 0)try{u=Zr(n.encrypted_key)}catch{throw new Ve("Failed to base64url decode the encrypted_key")}let l=!1;typeof e=="function"&&(e=await e(r,n),l=!0),ow(o==="dir"?s:o,e,"decrypt");let d=await vh(e,o),h;try{h=await Zte(o,d,u,i,t)}catch(U){if(U instanceof TypeError||U instanceof Ve||U instanceof Xt)throw U;h=Qu(s)}let f,m;if(n.iv!==void 0)try{f=Zr(n.iv)}catch{throw new Ve("Failed to base64url decode the iv")}if(n.tag!==void 0)try{m=Zr(n.tag)}catch{throw new Ve("Failed to base64url decode the tag")}let w=n.protected!==void 0?Ja(n.protected):new Uint8Array,b;n.aad!==void 0?b=Ss(w,Ja("."),Ja(n.aad)):b=w;let S;try{S=Zr(n.ciphertext)}catch{throw new Ve("Failed to base64url decode the ciphertext")}let G={plaintext:await S8(s,h,S,f,m,b)};if(n.protected!==void 0&&(G.protectedHeader=r),n.aad!==void 0)try{G.additionalAuthenticatedData=Zr(n.aad)}catch{throw new Ve("Failed to base64url decode the aad")}return n.unprotected!==void 0&&(G.sharedUnprotectedHeader=n.unprotected),n.header!==void 0&&(G.unprotectedHeader=n.header),l?{...G,key:d}:G}async function PF(n,e,t){if(!Zo(n))throw new Ve("General JWE must be an object");if(!Array.isArray(n.recipients)||!n.recipients.every(Zo))throw new Ve("JWE Recipients missing or incorrect type");if(!n.recipients.length)throw new Ve("JWE Recipients has no members");for(let r of n.recipients)try{return await II({aad:n.aad,ciphertext:n.ciphertext,encrypted_key:r.encrypted_key,header:r.header,iv:n.iv,protected:n.protected,tag:n.tag,unprotected:n.unprotected},e,t)}catch{}throw new Ih}var D8=Symbol();async function tne(n){if(gI(n))if(n.type==="secret")n=n.export();else return n.export({format:"jwk"});if(n instanceof Uint8Array)return{kty:"oct",k:Xr(n)};if(!Vu(n))throw new TypeError(xh(n,"CryptoKey","KeyObject","Uint8Array"));if(!n.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:t,alg:r,use:i,...o}=await crypto.subtle.exportKey("jwk",n);return o.kty==="AKP"&&(o.alg=r),o}async function nne(n){return tne(n)}async function T8(n,e,t,r,i={}){let o,s,a;switch(n){case"dir":{a=t;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(X0(t),!L8(t))throw new Xt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:u}=i,l;i.epk?l=await vh(i.epk,n):l=(await crypto.subtle.generateKey(t.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:h,crv:f,kty:m}=await nne(l),w=await C8(t,l,n==="ECDH-ES"?e:n,n==="ECDH-ES"?bI(e):parseInt(n.slice(-5,-2),10),c,u);if(s={epk:{x:d,crv:f,kty:m}},m==="EC"&&(s.epk.y=h),c&&(s.apu=Xr(c)),u&&(s.apv=Xr(u)),n==="ECDH-ES"){a=w;break}a=r||Qu(e);let b=n.slice(-6);o=await yI(b,w,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=r||Qu(e),X0(t),o=await Vte(n,t,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=r||Qu(e);let{p2c:c,p2s:u}=i;({encryptedKey:o,...s}=await Hte(n,t,a,c,u));break}case"A128KW":case"A192KW":case"A256KW":{a=r||Qu(e),o=await yI(n,t,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=r||Qu(e);let{iv:c}=i;({encryptedKey:o,...s}=await jte(n,t,a,c));break}default:throw new Xt('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:a,encryptedKey:o,parameters:s}}var AI=class{#e;#t;#n;#r;#i;#o;#s;#a;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){if(this.#a)throw new TypeError("setKeyManagementParameters can only be called once");return this.#a=e,this}setProtectedHeader(e){if(this.#t)throw new TypeError("setProtectedHeader can only be called once");return this.#t=e,this}setSharedUnprotectedHeader(e){if(this.#n)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this.#n=e,this}setUnprotectedHeader(e){if(this.#r)throw new TypeError("setUnprotectedHeader can only be called once");return this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){if(this.#o)throw new TypeError("setContentEncryptionKey can only be called once");return this.#o=e,this}setInitializationVector(e){if(this.#s)throw new TypeError("setInitializationVector can only be called once");return this.#s=e,this}async encrypt(e,t){if(!this.#t&&!this.#r&&!this.#n)throw new Ve("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!ew(this.#t,this.#r,this.#n))throw new Ve("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let r={...this.#t,...this.#r,...this.#n};if(nw(Ve,new Map,t?.crit,this.#t,r),r.zip!==void 0)throw new Xt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:i,enc:o}=r;if(typeof i!="string"||!i)throw new Ve('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof o!="string"||!o)throw new Ve('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let s;if(this.#o&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);ow(i==="dir"?o:i,e,"encrypt");let a;{let b,S=await vh(e,i);({cek:a,encryptedKey:s,parameters:b}=await T8(i,o,S,this.#o,this.#a)),b&&(t&&D8 in t?this.#r?this.#r={...this.#r,...b}:this.setUnprotectedHeader(b):this.#t?this.#t={...this.#t,...b}:this.setProtectedHeader(b))}let c,u,l,d;if(this.#t?(u=Xr(JSON.stringify(this.#t)),l=Ja(u)):(u="",l=new Uint8Array),this.#i){d=Xr(this.#i);let b=Ja(d);c=Ss(l,Ja("."),b)}else c=l;let{ciphertext:h,tag:f,iv:m}=await R8(o,this.#e,a,this.#s,c),w={ciphertext:Xr(h)};return m&&(w.iv=Xr(m)),f&&(w.tag=Xr(f)),s&&(w.encrypted_key=Xr(s)),d&&(w.aad=d),this.#t&&(w.protected=u),this.#n&&(w.unprotected=this.#n),this.#r&&(w.header=this.#r),w}};var kF=class{#e;unprotectedHeader;keyManagementParameters;key;options;constructor(e,t,r){this.#e=e,this.key=t,this.options=r}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}setKeyManagementParameters(e){if(this.keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this.keyManagementParameters=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},xI=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let r=new kF(this,e,{crit:t?.crit});return this.#t.push(r),r}setProtectedHeader(e){if(this.#n)throw new TypeError("setProtectedHeader can only be called once");return this.#n=e,this}setSharedUnprotectedHeader(e){if(this.#r)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}async encrypt(){if(!this.#t.length)throw new Ve("at least one recipient must be added");if(this.#t.length===1){let[i]=this.#t,o=await new AI(this.#e).setAdditionalAuthenticatedData(this.#i).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(i.unprotectedHeader).encrypt(i.key,{...i.options}),s={ciphertext:o.ciphertext,iv:o.iv,recipients:[{}],tag:o.tag};return o.aad&&(s.aad=o.aad),o.protected&&(s.protected=o.protected),o.unprotected&&(s.unprotected=o.unprotected),o.encrypted_key&&(s.recipients[0].encrypted_key=o.encrypted_key),o.header&&(s.recipients[0].header=o.header),s}let e;for(let i=0;i<this.#t.length;i++){let o=this.#t[i];if(!ew(this.#n,this.#r,o.unprotectedHeader))throw new Ve("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let s={...this.#n,...this.#r,...o.unprotectedHeader},{alg:a}=s;if(typeof a!="string"||!a)throw new Ve('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(a==="dir"||a==="ECDH-ES")throw new Ve('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof s.enc!="string"||!s.enc)throw new Ve('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!e)e=s.enc;else if(e!==s.enc)throw new Ve('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(nw(Ve,new Map,o.options.crit,this.#n,s),s.zip!==void 0)throw new Xt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.')}let t=Qu(e),r={ciphertext:"",recipients:[]};for(let i=0;i<this.#t.length;i++){let o=this.#t[i],s={};if(r.recipients.push(s),i===0){let d=await new AI(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(o.unprotectedHeader).setKeyManagementParameters(o.keyManagementParameters).encrypt(o.key,{...o.options,[D8]:!0});r.ciphertext=d.ciphertext,r.iv=d.iv,r.tag=d.tag,d.aad&&(r.aad=d.aad),d.protected&&(r.protected=d.protected),d.unprotected&&(r.unprotected=d.unprotected),s.encrypted_key=d.encrypted_key,d.header&&(s.header=d.header);continue}let a=o.unprotectedHeader?.alg||this.#n?.alg||this.#r?.alg;ow(a==="dir"?e:a,o.key,"encrypt");let c=await vh(o.key,a),{encryptedKey:u,parameters:l}=await T8(a,e,c,t,o.keyManagementParameters);s.encrypted_key=Xr(u),(o.unprotectedHeader||l)&&(s.header={...o.unprotectedHeader,...l})}return r}};function MF(n){let e;if(typeof n=="string"){let t=n.split(".");(t.length===3||t.length===5)&&([e]=t)}else if(typeof n=="object"&&n)if("protected"in n)e=n.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let t=JSON.parse(Z0.decode(Zr(e)));if(!Zo(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var B8=class{constructor(e){this.resolvePrivateKeyByKid=e}async encrypt(e,t){let{enc:r,typ:i,recipients:o}=t,s=new xI(e).setProtectedHeader({enc:r,typ:i});return o.forEach(({recipientJWK:c,alg:u,kid:l})=>{s.addRecipient(c).setUnprotectedHeader({alg:u,kid:l})}),await s.encrypt()}async decrypt(e){let t=(r,i)=>{let o=i.header?.kid||r&&r.kid;if(!o)throw new Error("kid is required");return this.resolvePrivateKeyByKid(o)};if(Object.prototype.hasOwnProperty.call(e,"encrypted_key")){let r=e;return r.header=this.removeDuplicates(MF(r),r.header||{}),II(e,t)}return PF(e,t)}removeDuplicates=(e,t)=>{let r={...t};for(let[i,o]of Object.entries(e))r[i]===o&&delete r[i];return r}};var P8=class{constructor(e){this.kms=e}resolvePrivateKeyByKid=async e=>{let[,t]=e.split("#");if(!t)throw new Error("Missing key identifier");let[r]=t.split(":");if(!r)throw new Error("Missing key type in alias for default key resolver");let i=await this.kms.getKeyProvider(r)?.getPkStore();if(!i)throw new Error(`Key provider not found for ${r}`);try{return JSON.parse(await i.get({alias:t}))}catch{throw new Error(`Key not found for ${t}`)}}};var FF={};Rr(FF,{DeviceNotificationStatus:()=>one,NotificationServiceType:()=>rne,NotificationStatus:()=>ine,PushNotifier:()=>OF});var rne=(e=>(e.Push="push-notification",e))(rne||{}),ine=(t=>(t.Success="success",t.Failed="failed",t))(ine||{});var one=(r=>(r.Success="success",r.Rejected="rejected",r.Failed="failed",r))(one||{}),ADe={type:"push-notification",send:async({url:n,pushService:e,message:t})=>{try{let r=new Request(n,{method:"POST",body:JSON.stringify({metadata:e.metadata,message:t})}),i=await fetch(r);if(i.status!==200)throw new Error(`could not send push notification, return status ${i.status}`);let o=await i.json();return{status:"success",devices:o}}catch(r){return{status:"failed",error:r.toString()}}}},OF=class{constructor(e=ADe){this._publisher=e;if(e.type!=="push-notification")throw new Error(`PushNotifier: publisher type ${e.type} is not supported`)}async notify(e,t){let r=(t.didDocument.service??[]).find(s=>s.type==="push-notification");if(!r)throw new Error("no push service in did document");if(!r.metadata?.devices?.length)throw new Error("no devices in push service");let o=[r.serviceEndpoint??[]].flat().reduce((s,a)=>typeof a=="string"?[...s,a]:typeof a.uri=="string"?[...s,a.uri]:s,[]).map(async s=>this._publisher.send({url:s,pushService:r,message:e}));return await Promise.all(o)}};var xd={url:"http://localhost:8545",defaultGasLimit:6e5,minGasPrice:"0",maxGasPrice:"100000000000",confirmationBlockCount:5,confirmationTimeout:6e5,contractAddress:"",receiptTimeout:6e5,rpcResponseTimeout:5e3,waitReceiptCycleTime:3e4,waitBlockCycleTime:3e3},sne={state:0n,replacedByState:0n,createdAtTimestamp:0n,replacedAtTimestamp:0n,createdAtBlock:0n,replacedAtBlock:0n},dI=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,uM,this.provider),this._transactionService=new Xs(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??jr.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??lg},this._stateCacheOptions={notReplacedTtl:t?.stateCacheOptions?.notReplacedTtl??jr.DEFAULT_PROOF_VERIFY_DELAY/2,replacedTtl:t?.stateCacheOptions?.replacedTtl??jr.DEFAULT_PROOF_VERIFY_DELAY,maxSize:t?.stateCacheOptions?.maxSize??lg},this._rootCacheOptions={replacedTtl:t?.rootCacheOptions?.replacedTtl??jr.DEFAULT_AUTH_VERIFY_DELAY,notReplacedTtl:t?.rootCacheOptions?.notReplacedTtl??jr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.rootCacheOptions?.maxSize??lg},this._gistProofCacheOptions={ttl:jr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??lg},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??fh({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??fh({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??fh({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??fh({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){if(s.state===0n&&s.createdAtTimestamp===0n)throw new Error(Ue.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR);return s}}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=[];try{i=await r.getStateInfoById(e)}catch(s){throw z0(s)&&!this._disableCache&&await this._latestStateResolveCache?.set(t,{id:e,...sne},this._latestStateCacheOptions.ttl),s}let 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 a=await this._stateResolveCache?.get(r);if(a)return a}let{stateContract:i}=this.getStateContractAndProviderForId(e),o;try{let a=await i.getStateInfoByIdAndState(e,t);o={id:BigInt(a[0]),state:BigInt(a[1]),replacedByState:BigInt(a[2]),createdAtTimestamp:BigInt(a[3]),replacedAtTimestamp:BigInt(a[4]),createdAtBlock:BigInt(a[5]),replacedAtBlock:BigInt(a[6])}}catch(a){if(!cF(a))throw a;if(!Cx(Xe.fromBigInt(e),t))throw new Error(`State ${t} for identity ${e} is not genesis and not registered in the smart contract`);o={id:e,...sne,state:t}}let s=o.replacedAtTimestamp===0n?this._stateCacheOptions.notReplacedTtl:this._stateCacheOptions.replacedTtl;return!this._disableCache&&await this._stateResolveCache?.set(r,o,s),o}async publishState(e,t){let r=new f1;r.pubSignalsUnmarshal(ke.encode(JSON.stringify(e.pub_signals)));let{userId:i,oldUserState:o,newUserState:s,isOldStateGenesis:a}=r,{stateContract:c,provider:u}=this.getStateContractAndProviderForId(i.bigInt()),l=c.connect(t),d=dh(e.proof),h=[i.bigInt().toString(),o.bigInt().toString(),s.bigInt().toString(),a,d.a,d.b,d.c],f=await u.getFeeData(),m=xd.maxFeePerGas?BigInt(xd.maxFeePerGas):f.maxFeePerGas,w=xd.maxPriorityFeePerGas?BigInt(xd.maxPriorityFeePerGas):f.maxPriorityFeePerGas,b=await l.transitState.estimateGas(...h),S=await l.transitState.populateTransaction(...h),R={to:S.to,data:S.data,gasLimit:b,maxFeePerGas:m,maxPriorityFeePerGas:w},{txnHash:G}=await this._transactionService.sendTransactionRequest(t,R);return await this._latestStateResolveCache?.delete(this.getLatestStateCacheKey(i.bigInt())),G}async publishStateGeneric(e,t){let{userId:r,oldUserState:i,newUserState:o,isOldStateGenesis:s,methodId:a,methodParams:c}=t,{stateContract:u,provider:l}=this.getStateContractAndProviderForId(r.bigInt()),d=u.connect(e),h=await l.getFeeData(),f=xd.maxFeePerGas?BigInt(xd.maxFeePerGas):h.maxFeePerGas,m=xd.maxPriorityFeePerGas?BigInt(xd.maxPriorityFeePerGas):h.maxPriorityFeePerGas,w=[r.bigInt().toString(),i.bigInt().toString(),o.bigInt().toString(),s,a,c],b=await d.transitStateGeneric.estimateGas(...w),S=await d.transitStateGeneric.populateTransaction(...w),R={to:S.to,data:S.data,gasLimit:b,maxFeePerGas:f,maxPriorityFeePerGas:m},{txnHash:G}=await this._transactionService.sendTransactionRequest(e,R);return await this._latestStateResolveCache?.delete(this.getLatestStateCacheKey(r.bigInt())),G}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=Xe.fromBigInt(t),i=tm(ve.blockchainFromId(r),ve.networkIdFromId(r)),o=this.getRootCacheKey(i,e);if(!this._disableCache){let l=await this._rootResolveCache?.get(o);if(l)return l}let{stateContract:s}=this.getStateContractAndProviderForId(t),a=await s.getGISTRootInfo(e),c={root:BigInt(a.root.toString()),replacedByRoot:BigInt(a.replacedByRoot.toString()),createdAtTimestamp:BigInt(a.createdAtTimestamp.toString()),replacedAtTimestamp:BigInt(a.replacedAtTimestamp.toString()),createdAtBlock:BigInt(a.createdAtBlock.toString()),replacedAtBlock:BigInt(a.replacedAtBlock.toString())},u=c.replacedAtTimestamp==0n?this._rootCacheOptions.notReplacedTtl:this._rootCacheOptions.replacedTtl;return!this._disableCache&&await this._rootResolveCache?.set(o,c,u),c}getRpcProvider(){return this.provider}enableCache(){this._disableCache=!1}disableCache(){this._disableCache=!0}getStateContractAndProviderForId(e){let t=Xe.fromBigInt(e),r=tm(ve.blockchainFromId(t),ve.networkIdFromId(t)),i=this.networkByChainId(r),o=new jt(i.url);return{stateContract:new Ln(i.contractAddress,uM,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-state:${e.toString()}`}getStateCacheKey(e,t){return`state:${e.toString()}-${t.toString()}`}getRootCacheKey(e,t){return`root:${e.toString()}-${t.toString()}`}};var NF=[{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 UF=[{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 GF=10000000n,ane=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(ane||{}),cne=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]},HF=class n{constructor(e,t){this._configs=e;this._opts=t}static _supportedCircuits=["authV2","authV3","authV3-8-32","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","credentialAtomicQueryV3OnChain"];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=dh(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,u=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,l=new Ln(t.contract_address,NF);for(let d of r){let h=await this.prepareTxArgsSubmitV1(t,d),f=await l.submitZKPResponse.populateTransaction(...h),m={to:t.contract_address,data:f.data,maxFeePerGas:c,maxPriorityFeePerGas:u},w;try{w=await e.estimateGas(m)}catch{w=GF}m.gasLimit=w;let b=new Xs(o),{txnHash:S}=await b.sendTransactionRequest(e,m);s.set(S,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,u=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,d=await new Ln(t.contract_address,NF).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:c,maxPriorityFeePerGas:u},f;try{f=await e.estimateGas(h)}catch{f=GF}h.gasLimit=f;let m=new Xs(o),{txnHash:w}=await m.sendTransactionRequest(e,h);return new Map().set(w,r)}async submitResponse(e,t,r,i){let o=this._configs.find(S=>S.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(),u=o.maxFeePerGas?BigInt(o.maxFeePerGas):c.maxFeePerGas,l=o.maxPriorityFeePerGas?BigInt(o.maxPriorityFeePerGas):c.maxPriorityFeePerGas,h=await new Ln(t.contract_address,UF).submitResponse.populateTransaction(...a.txDataArgs),f={to:t.contract_address,data:h.data,maxFeePerGas:u,maxPriorityFeePerGas:l},m;try{m=await e.estimateGas(f)}catch{m=GF}f.gasLimit=m;let w=new Xs(s),{txnHash:b}=await w.sendTransactionRequest(e,f);return new Map().set(b,{authProof:a.result.authProof.raw,crossChainProof:a.result.crossChainProof.raw,responses:a.result.proofs.map(S=>S.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",u="";switch(i.authMethod){case"authV2":case"authV3":case"authV3-8-32":{let f=dh(i.zkp.proof);u=DE(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{u=une(i.userDid);break}case"embeddedAuth":{u="0x";break}default:throw new Error("auth proof must use method authV2, authV3, authV3-8-32 or ethIdentity")}for(let f of r){this.checkSupportedCircuit(f.circuitId);let{requestId:m,zkProofEncoded:w,metadata:b}=uI(f);a.push({proof:f,requestId:m,encoded:w,metadata:b})}let l=r.map(f=>({circuitId:f.circuitId,pub_signals:f.pub_signals}));["authV2","authV3","authV3-8-32"].includes(i.authMethod)&&l.push({circuitId:i.zkp.circuitId,pub_signals:i.zkp.pub_signals});for(let f of l){let{gistUpdateResolutions:m,stateUpdateResolutions:w}=this.getUpdateResolutions(e,t.chain_id,f.circuitId,f.pub_signals);m.length>0&&o.push(...await Promise.all(m)),w.length>0&&s.push(...await Promise.all(w))}let d=o.length||s.length?this.packCrossChainProofs(o,s):c,h={authProof:{raw:i,encoded:u},proofs:a,crossChainProof:{raw:{globalStateProofs:o||[],identityStateProofs:s||[]},encoded:d}};return{result:h,txDataArgs:cne(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(!R6(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=Xe.fromString(a.id),u=dw(ve.parseFromId(c));if(t===u)return o;let l=this.resolveDidDocumentEip712MessageAndSignature(ve.parseFromId(Xe.fromString(a.id)),i,{[r]:be.fromString(a[r])});return[...o,l]},[])}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 u of r){this.checkSupportedCircuit(u.circuitId);let{requestId:l,zkProofEncoded:d,metadata:h}=uI(u);s.push({requestId:l,zkProof:d,data:h});let{gistUpdateResolutions:f,stateUpdateResolutions:m}=this.getUpdateResolutions(e,t.chain_id,u.circuitId,u.pub_signals);f.length>0&&i.push(...await Promise.all(f)),m.length>0&&o.push(...await Promise.all(m))}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 mn.AbiCoder().encode(["tuple(string proofType,bytes proof)[]"],[r])}static packGlobalStateMsg(e){return new mn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,bytes2 idType,uint256 root,uint256 replacedAtTimestamp) globalStateMsg,bytes signature,)"],[e])}static packIdentityStateMsg(e){return new mn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,uint256 id,uint256 state,uint256 replacedAtTimestamp) idStateMsg,bytes signature,)"],[e])}static getOnChainGistRootStatePubSignals(e,t){let r=T6(e);if(!r||!r.unmarshaller)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=r.unmarshaller,o=new i(r.opts),s=ke.encode(JSON.stringify(t)),a=o.pubSignalsUnmarshal(s);if(a.getStatesInfo===void 0)throw new Error(`Public signals unmarshaller for circuit ${e} does not support getStatesInfo method`);return a.getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await bp(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}}},une=n=>`0x${Br(It.intToBytes(ve.idFromDID(n).bigInt()))}`;var KF=[{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 JF=[{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"}],sw=class{static abi=JF;static createInterface(){return new hc(JF)}static connect(e,t){return new Ln(e,JF,t)}};var vI=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=mn.getAddress(mn.hexlify(Xe.ethAddressFromId(ve.idFromDID(t)))),this._contract=sw.connect(this._contractAddress,new mn.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 Ir().unMarshalJson(JSON.stringify(t.map(u=>u.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=Er.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 u of i){let l=await Or.newTypeFromContext(o,`${r}.${u.key}`,this._merklizationOptions);switch(l){case"http://www.w3.org/2001/XMLSchema#boolean":{switch(u.rawValue.toString()){case"18586133768512220936620570745912940619677854269274689475585506675881198879027":s[u.key]=!0;break;case"19014214495641488759237505126948346942972912379615652741039992445865937985820":s[u.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[u.key]=u.value.toString();break}case"http://www.w3.org/2001/XMLSchema#integer":{s[u.key]=Number(u.value);break}case"http://www.w3.org/2001/XMLSchema#string":{this.validateSourceValue(l,u.value,u.rawValue),s[u.key]=u.rawValue;break}case"http://www.w3.org/2001/XMLSchema#dateTime":{let d=BigInt(u.rawValue),h=ia(Number(d)).toISOString();this.validateSourceValue(l,u.value,h),s[u.key]=h;break}case"http://www.w3.org/2001/XMLSchema#double":{let d=Number(u.rawValue);this.validateSourceValue(l,u.value,d),s[u.key]=d;break}default:throw new Error(`Unsupported data type ${l}`)}}s.type=r;let a=e.getId(),c=ve.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 kt({siblings:t.siblings.map(u=>be.fromBigInt(u)),existence:t.existence,nodeAux:t.auxExistence?{key:be.fromBigInt(t.auxIndex),value:be.fromBigInt(t.auxValue)}:void 0});return new yc({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:c,coreClaim:e})}async validateSourceValue(e,t,r){if(await Pu.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 qF=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 vI(o,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});await a.isInterfaceSupported();let{credentialData:c,coreClaimBigInts:u,credentialSubjectFields:l}=await a.getCredential(ve.idFromDID(t),r);return await a.convertOnChainInfoToW3CCredential(c,u,l)}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 vI(i,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});return await s.isInterfaceSupported(),await s.getUserCredentialsIds(ve.idFromDID(t))}default:throw new Error(`Unsupported adapter version ${o}`)}}getContractConnection(e){let t=ve.idFromDID(e),r=dw(e),i=mn.getAddress(mn.hexlify(Xe.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,KF,new mn.JsonRpcProvider(o.url)),connection:o}}};var VF=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 bp(ve.parseFromId(Xe.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 bp(ve.parseFromId(Xe.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 bp(ve.parseFromId(Xe.fromBigInt(e)),this.resolverUrl,r),{info:o,published:s}=this.getIden3StateInfo2023(i);if(!o&&!s)throw new Error(Ue.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 lne=[{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 dne=[{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 BDe(n,e,t,r,i,o){let s=new Ln(e,lne,n),a=await s.nonces(await n.getAddress()),[c,u]=await Promise.all([s.name(),s.version?.().catch(()=>"1")??Promise.resolve("1")]),l={name:c,version:u,chainId:o,verifyingContract:e},d={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},h={owner:await n.getAddress(),spender:t,value:r,nonce:a,deadline:i};return n.signTypedData(l,d,h)}async function PDe(n,e){return new Ln(n,dne,e).decimals()}var yne=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(yne||{}),wne=(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))(wne||{}),QF=[!0,1,"true"],zF=[!1,0,"false"],fne=(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,QF.includes(n)&&QF.includes(e)||zF.includes(n)&&zF.includes(e)?!0:n===e),hne=(n,e)=>Ene(n,e,(r,i)=>{switch(Ine(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}}),pne=(n,e)=>Ene(n,e,(r,i)=>{switch(Ine(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}}),kDe=(n,e)=>!!(QF.includes(e)&&typeof n<"u"||zF.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),mne=(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,gne=(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))},qa={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>kDe(n,e),$eq:(n,e)=>fne(n,e),$in:(n,e)=>mne(n,e),$nin:(n,e)=>!mne(n,e),$gt:(n,e)=>hne(n,e),$lt:(n,e)=>!pne(n,e),$ne:(n,e)=>!fne(n,e),$gte:(n,e)=>pne(n,e),$lte:(n,e)=>!hne(n,e),$between:(n,e)=>gne(n,e),$nonbetween:(n,e)=>!gne(n,e)},bne=(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},na=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=bne(e,this.path);return t==null&&this.operatorFunc!==qa.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},YF=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new na("id",qa.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new na("issuer",qa.$in,r));case"type":return e.concat(new na("type",qa.$in,r,!0));case"context":return e.concat(new na("@context",qa.$in,r,!0));case"credentialSubjectId":return e.concat(new na("credentialSubject.id",qa.$eq,r));case"schema":return e.concat(new na("credentialSchema.id",qa.$eq,r));case"credentialSubject":case"credentialStatus":{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 na(`${t}.${s}`,qa.$noop,null)]);let c=Object.keys(a).map(u=>{let l=a[u],d=`${t}.${s}`;return new na(d,qa[u],l)});return o.concat(c)},[]);return e.concat(i)}case"expirationDate":case"issuanceDate":{if(Object.keys(r).length===0)return e.concat([new na(t,qa.$noop,null)]);let i=Object.keys(r).map(o=>{let s=r[o],a=typeof s=="number"||typeof s=="string"&&/^\d+$/.test(s)?new Date(Number(s)*1e3).toISOString():s;return new na(t,qa[o],a)});return e.concat(i)}case"proofType":case"groupId":case"skipClaimRevocationCheck":return e;default:throw new Error(`${t} : not defined query key`)}},[]),Ene=(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),MDe=/^[+-]?\d+$/,ODe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,FDe=/^([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]))$/,NDe=/^(true)|(false)$/,UDe=/^\d{4}-\d{2}-\d{2}$/,Ine=n=>MDe.test(n)?0:ODe.test(n)?2:FDe.test(n)||UDe.test(n)?3:NDe.test(n)?1:4;var jF=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 WF=class n{constructor(e){this._mtDepth=e}static storageKeyMeta="merkle-tree-meta";async createIdentityMerkleTrees(e){e||(e=`${Ut()}`);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=ky(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify([...i,...a])),[...i,...a]}let r=ky(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 bw(_c(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 bw(_c(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 ZF=class{constructor(e){this._storageKey=e;this._store=Fd(`${e}-db`,e)}_store;async save(e,t,r="id"){return Nd(e,t,this._store)}async get(e,t="id"){return Zc(e,this._store)}async load(){return $N(this._store)}async delete(e,t="id"){return jI(e,this._store)}};var XF=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=Fd(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=Fd(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Ut()}`),await Zc(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=ky(e);return await Nd(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await Zc(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 Zc(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(_c(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await Zc(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(_c(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await Zc(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 jI(e,this._merkleTreeMetaStore),await Nd(t,i,this._merkleTreeMetaStore),await Nd(e,t,this._bindingStore)}};var _F=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 $F=class{constructor(e){this._dataSource=e}static storageKey="credentials";async listCredentials(){return(await this._dataSource.load()).filter(t=>t!==void 0).map(t=>t&&Er.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&&Er.fromJSON(t)}async findCredentialsByQuery(e){let t=YF(e);return(await this._dataSource.load()).filter(o=>t.every(s=>s.execute(o))).filter(o=>o!==void 0).map(o=>Er.fromJSON(o))}};var eN=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 tN=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,t){let r=t?.mode??"full",i={wasm:r==="proving"||r==="full"?this.loadCircuitFile(e,this._wasmFilePath):Promise.resolve(null),provingKey:r==="proving"||r==="full"?this.loadCircuitFile(e,this._provingKeyPath):Promise.resolve(null),verificationKey:r==="verification"||r==="full"?this.loadCircuitFile(e,this._verificationKeyPath):Promise.resolve(null)},[o,s,a]=await Promise.all([i.wasm,i.provingKey,i.verificationKey]);return{circuitId:e,wasm:o,provingKey:s,verificationKey:a}}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 zu=n=>{if(!n){let e=On.hash(new Array(3).fill(0n));return{proof:new kt,treeState:{state:be.fromBigInt(e),claimsRoot:Ne,revocationRoot:Ne,rootOfRoots:Ne}}}return{proof:n.mtp,treeState:x6(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},aw=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 kt({siblings:r,nodeAux:t,existence:e});return{root:be.fromBigInt(n.root),proof:i}},k8=new Set(["credentialStatus.revocationNonce","credentialStatus.id"]),rN=n=>{let e=[];if(n.credentialSubject){let t=nN(n.credentialSubject,"credentialSubject");e.push(...vd(t))}if(n.expirationDate){let t=vd({expirationDate:n.expirationDate});e.push(...t)}if(n.issuanceDate){let t=vd({issuanceDate:n.issuanceDate});e.push(...t)}if(n.credentialStatus&&Object.keys(n.credentialStatus).length>0){let t=nN(n.credentialStatus,"credentialStatus"),r=Object.fromEntries(Object.entries(t).filter(([i])=>k8.has(i)));if(!Object.keys(r).length)throw new Error(`credentialStatus query contains no allowed fields \u2014 permitted: ${[...k8].join(", ")}`);e.push(...vd(r))}return e.length===0?[{operator:Zt.$noop,fieldName:""}]:e},nN=(n,e)=>{let t={};for(let[r,i]of Object.entries(n))i!==void 0&&(t[`${e}.${r}`]=i);return t},M8=(n,e)=>{if(!e)return[{operator:Zt.$noop,fieldName:""}];let t=nN(e,n);return vd(t)},vd=n=>{if(!n)return[{operator:Zt.$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:Zt.$sd,fieldName:r});continue}for(let[a,c]of o){if(!Object.hasOwn(Zt,a))throw new Error("operator is not supported by lib");let u=Zt[a];e.push({operator:u,fieldName:r,operatorValue:c})}}return e},GDe=n=>vd(n),SI=async(n,e,t,r)=>{let i=n.fieldName,[o]=i.split("."),s=i;switch(o){case"credentialStatus":s=i.replace("credentialStatus.",""),e=Ue.JSONLD_SCHEMA.IDEN3_PROOFS_DEFINITION_DOCUMENT;break;case"credentialSubject":s=i.replace("credentialSubject.","");break;case"":break;case"expirationDate":case"issuanceDate":e=Ue.JSONLD_SCHEMA.W3C_VC_DOCUMENT_2018,t=Ue.CREDENTIAL_TYPE.W3C_VERIFIABLE_CREDENTIAL;break}let a={...n,fieldName:s,slotIndex:0,merklizedSchema:!1,datatype:"",claimPathKey:BigInt(0),values:[],path:new Or};if(!s&&n.operator!==0)throw new Error("query must have a field name if operator is not $noop");if(s&&(a.datatype=await Or.newTypeFromContext(e,`${t}.${s}`,r)),await z2(JSON.parse(e),r,t)||(a.merklizedSchema=!0),!a.merklizedSchema)a.slotIndex=await Q2(s,t,ke.encode(e));else if(!r.legacyNoopOperator&&a.operator===0)a.claimPathKey=BigInt(0),a.path=new Or;else try{let u=await B6(e,t,s,r);i==="credentialStatus.id"&&u.parts[u.parts.length-1]==="@id"&&u.parts.pop(),a.claimPathKey=await u.mtEntry(),a.path=u}catch(u){throw new Error(`field does not exist in the schema ${u.message}`)}if(n.operatorValue!==void 0){if(!S6(a.datatype,n.operator))throw new Error(`operator ${n.operator} is not supported for datatype ${a.datatype}`);if((n.operator===0||n.operator===16)&&n.operatorValue)throw new Error(`operator value should be undefined for ${n.operator} operator`);let u;switch(n.operator){case 0:case 16:u=[];break;case 11:u=KDe(n.operatorValue);break;default:u=await O8(n.operatorValue,a.datatype)}a.values=u}return a.fieldName=i,a},CI=async(n,e,t,r,i)=>{let o=[];if(t.credentialSubject!==void 0&&o.push(...M8("credentialSubject",t.credentialSubject)),t.expirationDate&&o.push(...vd({expirationDate:t.expirationDate})),t.issuanceDate&&o.push(...vd({issuanceDate:t.issuanceDate})),t.credentialStatus!==void 0&&Object.keys(t.credentialStatus).length>0){let s=M8("credentialStatus",t.credentialStatus).filter(a=>k8.has(a.fieldName));if(!s.length)throw new Error(`credentialStatus query contains no allowed fields \u2014 permitted: ${[...k8].join(", ")}`);o.push(...s)}return o.length===0&&o.push({operator:Zt.$noop,fieldName:""}),Promise.all(o.map(s=>{let a=n;if(s.fieldName.startsWith("credentialStatus.")){let c=i?.verifiableCredential?.credentialStatus?.type;if(!c)throw new Error("credentialStatus.type is required to verify a credentialStatus query: include verifiableCredential.credentialStatus.type in the verifiablePresentation");a=c}return SI(s,e,a,r)}))},HDe=async(n,e,t,r)=>{let i=M8("credentialSubject",t);return Promise.all(i.map(o=>SI(o,e,n,r)))},O8=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await Pu.hashValue(e,n[r]);else t[0]=await Pu.hashValue(e,n);return t},KDe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")},F8=n=>["authV2","authV3","authV3-8-32"].includes(n);async function sN(n,e){e=e||{};let t;try{t=await WebAssembly.compile(n)}catch(l){throw new Error(l)}let r="",i="",o=await WebAssembly.instantiate(t,{runtime:{exceptionHandler:function(l){let d;throw l==1?d=`Signal not found.
423
+ `);for(let d=0;d<u.length;d++){let h=DLe(BigInt(u[d])%this.prime,this.n32);for(let f=0;f<this.n32;f++)this.instance.exports.writeSharedRWMemory(f,h[this.n32-1-f]);try{this.instance.exports.setInputSignal(a,c,d),i++}catch(f){throw new Error(f)}}}),i<this.instance.exports.getInputSize())throw new Error(`Not all inputs have been set. Only ${i} out of ${this.instance.exports.getInputSize()}`)}async calculateWitness(e,t){let r=[];await this._doCalculateWitness(e,t);for(let i=0;i<this.witnessSize;i++){this.instance.exports.getWitness(i);let o=new Uint32Array(this.n32);for(let s=0;s<this.n32;s++)o[this.n32-1-s]=this.instance.exports.readSharedRWMemory(s);r.push(AO(o))}return r}async calculateBinWitness(e,t){let r=new Uint32Array(this.witnessSize*this.n32),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t);for(let o=0;o<this.witnessSize;o++){this.instance.exports.getWitness(o);let s=o*this.n32;for(let a=0;a<this.n32;a++)r[s+a]=this.instance.exports.readSharedRWMemory(a)}return i}async calculateWTNSBin(e,t){let r=new Uint32Array(this.witnessSize*this.n32+this.n32+11),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t),i[0]=119,i[1]=116,i[2]=110,i[3]=115,r[1]=2,r[2]=2,r[3]=1;let o=this.n32*4,a=(8+o).toString(16);r[4]=parseInt(a.slice(0,8),16),r[5]=parseInt(a.slice(8,16),16),r[6]=o,this.instance.exports.getRawPrime();let c=7;for(let d=0;d<this.n32;d++)r[c+d]=this.instance.exports.readSharedRWMemory(d);c+=this.n32,r[c]=this.witnessSize,c++,r[c]=2,c++;let l=(o*this.witnessSize).toString(16);r[c]=parseInt(l.slice(0,8),16),r[c+1]=parseInt(l.slice(8,16),16),c+=2;for(let d=0;d<this.witnessSize;d++){this.instance.exports.getWitness(d);for(let h=0;h<this.n32;h++)r[c+h]=this.instance.exports.readSharedRWMemory(h);c+=this.n32}return i}};function DLe(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 AO(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 TLe(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 BLe(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 Vy=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function $E(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function xO(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Kc(n,...e){if(!$E(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 Fee(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");xO(n.outputLen),xO(n.blockLen)}function $C(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 PLe(n,e){Kc(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function e8(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function dO(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Ju(n,e){return n<<32-e|n>>>e}var Nee=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kLe=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function zy(n){if(Kc(n),Nee)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=kLe[n[t]];return e}var wd={_0:48,_9:57,A:65,F:70,a:97,f:102};function mee(n){if(n>=wd._0&&n<=wd._9)return n-wd._0;if(n>=wd.A&&n<=wd.F)return n-(wd.A-10);if(n>=wd.a&&n<=wd.f)return n-(wd.a-10)}function t8(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(Nee)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=mee(n.charCodeAt(o)),a=mee(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 eI(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function KO(n){return typeof n=="string"&&(n=eI(n)),Kc(n),n}function Fi(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];Kc(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 n8=class{};function MLe(n){let e=r=>n().update(KO(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function JO(n=32){if(Vy&&typeof Vy.getRandomValues=="function")return Vy.getRandomValues(new Uint8Array(n));if(Vy&&typeof Vy.randomBytes=="function")return Uint8Array.from(Vy.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function OLe(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,u=r?0:4;n.setUint32(e+c,s,r),n.setUint32(e+u,a,r)}function FLe(n,e,t){return n&e^~n&t}function NLe(n,e,t){return n&e^n&t^e&t}var vO=class extends n8{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=dO(this.buffer)}update(e){$C(this),e=KO(e),Kc(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=dO(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){$C(this),PLe(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,e8(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;OLe(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=dO(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,l[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()}},yh=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ULe=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]),wh=new Uint32Array(64),SO=class extends vO{constructor(e=32){super(64,e,8,!1),this.A=yh[0]|0,this.B=yh[1]|0,this.C=yh[2]|0,this.D=yh[3]|0,this.E=yh[4]|0,this.F=yh[5]|0,this.G=yh[6]|0,this.H=yh[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)wh[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=wh[d-15],f=wh[d-2],m=Ju(h,7)^Ju(h,18)^h>>>3,w=Ju(f,17)^Ju(f,19)^f>>>10;wh[d]=w+wh[d-7]+m+wh[d-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:u,H:l}=this;for(let d=0;d<64;d++){let h=Ju(a,6)^Ju(a,11)^Ju(a,25),f=l+h+FLe(a,c,u)+ULe[d]+wh[d]|0,w=(Ju(r,2)^Ju(r,13)^Ju(r,22))+NLe(r,i,o)|0;l=u,u=c,c=a,a=s+f|0,s=o,o=i,i=r,r=f+w|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,u=u+this.G|0,l=l+this.H|0,this.set(r,i,o,s,a,c,u,l)}roundClean(){e8(wh)}destroy(){this.set(0,0,0,0,0,0,0,0),e8(this.buffer)}},Uee=MLe(()=>new SO);var qO=BigInt(0),r8=BigInt(1);function i8(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function K0(n,e,t=""){let r=$E(n),i=n?.length,o=e!==void 0;if(!r||o&&i!==e){let s=t&&`"${t}" `,a=o?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof n}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return n}function jC(n){let e=n.toString(16);return e.length&1?"0"+e:e}function Gee(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?qO:BigInt("0x"+n)}function tI(n){return Gee(zy(n))}function Hee(n){return Kc(n),Gee(zy(Uint8Array.from(n).reverse()))}function VO(n,e){return t8(n.toString(16).padStart(e*2,"0"))}function Kee(n,e){return VO(n,e).reverse()}function ao(n,e,t){let r;if(typeof e=="string")try{r=t8(e)}catch(i){throw new Error(n+" must be hex string or Uint8Array, cause: "+i)}else if($E(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");return r}var fO=n=>typeof n=="bigint"&&qO<=n;function Jee(n,e,t){return fO(n)&&fO(e)&&fO(t)&&e<=n&&n<t}function GLe(n,e,t,r){if(!Jee(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function WE(n){let e;for(e=0;n>qO;n>>=r8,e+=1);return e}function HLe(n,e){return n>>BigInt(e)&r8}var nI=n=>(r8<<BigInt(n))-r8;function KLe(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},u=(...f)=>t(s,o,...f),l=(f=r(0))=>{s=u(i(0),f),o=u(),f.length!==0&&(s=u(i(1),f),o=u())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,m=[];for(;f<e;){o=u();let w=o.slice();m.push(w),f+=o.length}return Fi(...m)};return(f,m)=>{c(),l(f);let w;for(;!(w=m(d()));)l();return c(),w}}function JLe(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function u8(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 ui=()=>{throw new Error("not implemented")};function CO(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 ea=BigInt(0),Wo=BigInt(1),J0=BigInt(2),qee=BigInt(3),Vee=BigInt(4),Qee=BigInt(5),qLe=BigInt(7),zee=BigInt(8),VLe=BigInt(9),Yee=BigInt(16);function Ha(n,e){let t=n%e;return t>=ea?t:e+t}function gee(n,e){if(n===ea)throw new Error("invert: expected non-zero number");if(e<=ea)throw new Error("invert: expected positive modulus, got "+e);let t=Ha(n,e),r=e,i=ea,o=Wo;for(;t!==ea;){let a=r/t,c=r%t,u=i-o*a;r=t,t=c,i=o,o=u}if(r!==Wo)throw new Error("invert: does not exist");return Ha(i,e)}function QO(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function jee(n,e){let t=(n.ORDER+Wo)/Vee,r=n.pow(e,t);return QO(n,r,e),r}function QLe(n,e){let t=(n.ORDER-Qee)/zee,r=n.mul(e,J0),i=n.pow(r,t),o=n.mul(e,i),s=n.mul(n.mul(o,J0),i),a=n.mul(o,n.sub(s,n.ONE));return QO(n,a,e),a}function zLe(n){let e=jy(n),t=Wee(n),r=t(e,e.neg(e.ONE)),i=t(e,r),o=t(e,e.neg(r)),s=(n+qLe)/Yee;return(a,c)=>{let u=a.pow(c,s),l=a.mul(u,r),d=a.mul(u,i),h=a.mul(u,o),f=a.eql(a.sqr(l),c),m=a.eql(a.sqr(d),c);u=a.cmov(u,l,f),l=a.cmov(h,d,m);let w=a.eql(a.sqr(l),c),b=a.cmov(u,l,w);return QO(a,b,c),b}}function Wee(n){if(n<qee)throw new Error("sqrt is not defined for small field");let e=n-Wo,t=0;for(;e%J0===ea;)e/=J0,t++;let r=J0,i=jy(n);for(;o8(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return jee;let o=i.pow(r,e),s=(e+Wo)/J0;return function(c,u){if(c.is0(u))return u;if(o8(c,u)!==1)throw new Error("Cannot find square root");let l=t,d=c.mul(c.ONE,o),h=c.pow(u,e),f=c.pow(u,s);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let m=1,w=c.sqr(h);for(;!c.eql(w,c.ONE);)if(m++,w=c.sqr(w),m===l)throw new Error("Cannot find square root");let b=Wo<<BigInt(l-m-1),S=c.pow(d,b);l=m,d=c.sqr(S),h=c.mul(h,d),f=c.mul(f,S)}return f}}function YLe(n){return n%Vee===qee?jee:n%zee===Qee?QLe:n%Yee===VLe?zLe(n):Wee(n)}var jLe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function WLe(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=jLe.reduce((r,i)=>(r[i]="function",r),e);return u8(n,t),n}function l8(n,e,t){if(t<ea)throw new Error("invalid exponent, negatives unsupported");if(t===ea)return n.ONE;if(t===Wo)return e;let r=n.ONE,i=e;for(;t>ea;)t&Wo&&(r=n.mul(r,i)),i=n.sqr(i),t>>=Wo;return r}function rI(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 o8(n,e){let t=(n.ORDER-Wo)/J0,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 Zee(n,e){e!==void 0&&xO(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function jy(n,e,t=!1,r={}){if(n<=ea)throw new Error("invalid field: expected ORDER > 0, got "+n);let i,o,s=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||t)throw new Error("cannot specify opts in two arguments");let h=e;h.BITS&&(i=h.BITS),h.sqrt&&(o=h.sqrt),typeof h.isLE=="boolean"&&(t=h.isLE),typeof h.modFromBytes=="boolean"&&(s=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(o=r.sqrt);let{nBitLength:c,nByteLength:u}=Zee(n,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l,d=Object.freeze({ORDER:n,isLE:t,BITS:c,BYTES:u,MASK:nI(c),ZERO:ea,ONE:Wo,allowedLengths:a,create:h=>Ha(h,n),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return ea<=h&&h<n},is0:h=>h===ea,isValidNot0:h=>!d.is0(h)&&d.isValid(h),isOdd:h=>(h&Wo)===Wo,neg:h=>Ha(-h,n),eql:(h,f)=>h===f,sqr:h=>Ha(h*h,n),add:(h,f)=>Ha(h+f,n),sub:(h,f)=>Ha(h-f,n),mul:(h,f)=>Ha(h*f,n),pow:(h,f)=>l8(d,h,f),div:(h,f)=>Ha(h*gee(f,n),n),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>gee(h,n),sqrt:o||(h=>(l||(l=YLe(n)),l(d,h))),toBytes:h=>t?Kee(h,u):VO(h,u),fromBytes:(h,f=!0)=>{if(a){if(!a.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);let w=new Uint8Array(u);w.set(h,t?0:w.length-h.length),h=w}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let m=t?Hee(h):tI(h);if(s&&(m=Ha(m,n)),!f&&!d.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:h=>rI(d,h),cmov:(h,f,m)=>m?f:h});return Object.freeze(d)}function Xee(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 zO(n){let e=Xee(n);return e+Math.ceil(e/2)}function _ee(n,e,t=!1){let r=n.length,i=Xee(e),o=zO(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?Hee(n):tI(n),a=Ha(s,e-Wo)+Wo;return t?Kee(a,i):VO(a,i)}var Yy=BigInt(0),q0=BigInt(1);function s8(n,e){let t=e.negate();return n?t:e}function jE(n,e){let t=rI(n.Fp,e.map(r=>r.Z));return e.map((r,i)=>n.fromAffine(r.toAffine(t[i])))}function $ee(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function hO(n,e){$ee(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=nI(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function yee(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+=q0);let u=e*r,l=u+Math.abs(a)-1,d=a===0,h=a<0,f=e%2!==0;return{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:f,offsetF:u}}function ZLe(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 XLe(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 pO=new WeakMap,ete=new WeakMap;function mO(n){return ete.get(n)||1}function wee(n){if(n!==Yy)throw new Error("invalid wNAF")}var LO=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let i=e;for(;t>Yy;)t&q0&&(r=r.add(i)),i=i.double(),t>>=q0;return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=hO(t,this.bits),o=[],s=e,a=s;for(let c=0;c<r;c++){a=s,o.push(a);for(let u=1;u<i;u++)a=a.add(s),o.push(a);s=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=hO(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:h,offsetF:f}=yee(r,a,s);r=c,l?o=o.add(s8(h,t[f])):i=i.add(s8(d,t[u]))}return wee(r),{p:i,f:o}}wNAFUnsafe(e,t,r,i=this.ZERO){let o=hO(e,this.bits);for(let s=0;s<o.windows&&r!==Yy;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=yee(r,s,o);if(r=a,!u){let d=t[c];i=i.add(l?d.negate():d)}}return wee(r),i}getPrecomputes(e,t,r){let i=pO.get(t);return i||(i=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(i=r(i)),pO.set(t,i))),i}cached(e,t,r){let i=mO(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let o=mO(e);return o===1?this._unsafeLadder(e,t,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,i)}createCache(e,t){$ee(t,this.bits),ete.set(e,t),pO.delete(e)}hasCache(e){return mO(e)!==1}};function _Le(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Yy||r>Yy;)t&q0&&(o=o.add(i)),r&q0&&(s=s.add(i)),i=i.double(),t>>=q0,r>>=q0;return{p1:o,p2:s}}function $Le(n,e,t,r){ZLe(t,n),XLe(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=WE(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=nI(c),l=new Array(Number(u)+1).fill(s),d=Math.floor((e.BITS-1)/c)*c,h=s;for(let f=d;f>=0;f-=c){l.fill(s);for(let w=0;w<o;w++){let b=r[w],S=Number(b>>BigInt(f)&u);l[S]=l[S].add(t[w])}let m=s;for(let w=l.length-1,b=s;w>0;w--)b=b.add(l[w]),m=m.add(b);if(h=h.add(m),f!==0)for(let w=0;w<c;w++)h=h.double()}return h}function bee(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return WLe(e),e}else return jy(n,{isLE:t})}function eRe(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>Yy))throw new Error(`CURVE.${c} must be positive bigint`)}let i=bee(e.p,t.Fp,r),o=bee(e.n,t.Fn,r),a=["Gx","Gy","a","b"];for(let c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}var tRe=tI;function bh(n,e){if(ZE(n),ZE(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 nRe(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 ZE(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function tte(n){if(!$E(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or string");return typeof n=="string"?eI(n):n}function rRe(n,e,t,r){Kc(n),ZE(t),e=tte(e),e.length>255&&(e=r(Fi(eI("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=Fi(e,bh(e.length,1)),c=bh(0,o),u=bh(t,2),l=new Array(s),d=r(Fi(c,n,u,bh(0,1),a));l[0]=r(Fi(d,bh(1,1),a));for(let f=1;f<=s;f++){let m=[nRe(d,l[f-1]),bh(f+1,1),a];l[f]=r(Fi(...m))}return Fi(...l).slice(0,t)}function iRe(n,e,t,r,i){if(Kc(n),ZE(t),e=tte(e),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update(eI("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(bh(t,2)).update(e).update(bh(e.length,1)).digest()}function gO(n,e,t){u8(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:c}=t;if(!JLe(t.hash))throw new Error("expected valid hash");Kc(n),ZE(e);let u=r.toString(2).length,l=Math.ceil((u+i)/8),d=e*o*l,h;if(a==="xmd")h=rRe(n,c,d,s);else if(a==="xof")h=iRe(n,c,d,i,s);else if(a==="_internal_pass")h=n;else throw new Error('expand must be "xmd" or "xof"');let f=new Array(e);for(let m=0;m<e;m++){let w=new Array(o);for(let b=0;b<o;b++){let S=l*(b+m*o),R=h.subarray(S,S+l);w[b]=Ha(tRe(R),r)}f[m]=w}return f}var oRe=eI("HashToScalar-");function Eee(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=Object.assign({},t,s),c=gO(o,2,a),u=r(c[0]),l=r(c[1]);return i(u.add(l))},encodeToCurve(o,s){let a=t.encodeDST?{DST:t.encodeDST}:{},c=Object.assign({},t,a,s),u=gO(o,1,c),l=r(u[0]);return i(l)},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))},hashToScalar(o,s){let a=n.Fn.ORDER,c=Object.assign({},t,{p:a,m:1,DST:oRe},s);return gO(o,1,c)[0][0]}}}var a8=class extends n8{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Fee(e);let r=KO(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),e8(o)}update(e){return $C(this),this.iHash.update(e),this}digestInto(e){$C(this),Kc(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()}},nte=(n,e,t)=>new a8(n,e).update(t).digest();nte.create=(n,e)=>new a8(n,e);var Iee=(n,e)=>(n+(n>=0?e:-e)/rte)/e;function sRe(n,e,t){let[[r,i],[o,s]]=e,a=Iee(s*n,t),c=Iee(-i*n,t),u=n-a*r-c*o,l=-a*i-c*s,d=u<Ed,h=l<Ed;d&&(u=-u),h&&(l=-l);let f=nI(Math.ceil(WE(t)/2))+V0;if(u<Ed||u>=f||l<Ed||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:d,k1:u,k2neg:h,k2:l}}function RO(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function yO(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return i8(t.lowS,"lowS"),i8(t.prehash,"prehash"),t.format!==void 0&&RO(t.format),t}var DO=class extends Error{constructor(e=""){super(e)}},bd={Err:DO,_tlv:{encode:(n,e)=>{let{Err:t}=bd;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=jC(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?jC(i.length/2|128):"";return jC(n)+o+i+e},decode(n,e){let{Err:t}=bd,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 u=e.subarray(r,r+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)s=s<<8|l;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}=bd;if(n<Ed)throw new e("integer: negative integers are not allowed");let t=jC(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}=bd;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 tI(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=bd,i=ao("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:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(n){let{_tlv:e,_int:t}=bd,r=e.encode(2,t.encode(n.r)),i=e.encode(2,t.encode(n.s)),o=r+i;return e.encode(48,o)}},Ed=BigInt(0),V0=BigInt(1),rte=BigInt(2),WC=BigInt(3),aRe=BigInt(4);function Id(n,e){let{BYTES:t}=n,r;if(typeof e=="bigint")r=e;else{let i=ao("private key",e);try{r=n.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!n.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function ite(n,e={}){let t=eRe("weierstrass",n,e),{Fp:r,Fn:i}=t,o=t.CURVE,{h:s,n:a}=o;u8(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!r.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=ste(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(Q,v,p){let{x,y}=v.toAffine(),I=r.toBytes(x);if(i8(p,"isCompressed"),p){l();let C=!r.isOdd(y);return Fi(ote(C),I)}else return Fi(Uint8Array.of(4),I,r.toBytes(y))}function h(Q){K0(Q,void 0,"Point");let{publicKey:v,publicKeyUncompressed:p}=u,x=Q.length,y=Q[0],I=Q.subarray(1);if(x===v&&(y===2||y===3)){let C=r.fromBytes(I);if(!r.isValid(C))throw new Error("bad point: is not on curve, wrong x");let F=w(C),N;try{N=r.sqrt(F)}catch(q){let _=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+_)}l();let O=r.isOdd(N);return(y&1)===1!==O&&(N=r.neg(N)),{x:C,y:N}}else if(x===p&&y===4){let C=r.BYTES,F=r.fromBytes(I.subarray(0,C)),N=r.fromBytes(I.subarray(C,C*2));if(!b(F,N))throw new Error("bad point: is not on curve");return{x:F,y:N}}else throw new Error(`bad point: got length ${x}, expected compressed=${v} or uncompressed=${p}`)}let f=e.toBytes||d,m=e.fromBytes||h;function w(Q){let v=r.sqr(Q),p=r.mul(v,Q);return r.add(r.add(p,r.mul(Q,o.a)),o.b)}function b(Q,v){let p=r.sqr(v),x=w(Q);return r.eql(p,x)}if(!b(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=r.mul(r.pow(o.a,WC),aRe),R=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(S,R)))throw new Error("bad curve params: a or b");function G(Q,v,p=!1){if(!r.isValid(v)||p&&r.is0(v))throw new Error(`bad point coordinate ${Q}`);return v}function U(Q){if(!(Q instanceof z))throw new Error("ProjectivePoint expected")}function H(Q){if(!c||!c.basises)throw new Error("no endo");return sRe(Q,c.basises,i.ORDER)}let M=CO((Q,v)=>{let{X:p,Y:x,Z:y}=Q;if(r.eql(y,r.ONE))return{x:p,y:x};let I=Q.is0();v==null&&(v=I?r.ONE:r.inv(y));let C=r.mul(p,v),F=r.mul(x,v),N=r.mul(y,v);if(I)return{x:r.ZERO,y:r.ZERO};if(!r.eql(N,r.ONE))throw new Error("invZ was invalid");return{x:C,y:F}}),A=CO(Q=>{if(Q.is0()){if(e.allowInfinityPoint&&!r.is0(Q.Y))return;throw new Error("bad point: ZERO")}let{x:v,y:p}=Q.toAffine();if(!r.isValid(v)||!r.isValid(p))throw new Error("bad point: x or y not field elements");if(!b(v,p))throw new Error("bad point: equation left != right");if(!Q.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function T(Q,v,p,x,y){return p=new z(r.mul(p.X,Q),p.Y,p.Z),v=s8(x,v),p=s8(y,p),v.add(p)}class z{constructor(v,p,x){this.X=G("x",v),this.Y=G("y",p,!0),this.Z=G("z",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(v){let{x:p,y:x}=v||{};if(!v||!r.isValid(p)||!r.isValid(x))throw new Error("invalid affine point");if(v instanceof z)throw new Error("projective point not allowed");return r.is0(p)&&r.is0(x)?z.ZERO:new z(p,x,r.ONE)}static fromBytes(v){let p=z.fromAffine(m(K0(v,void 0,"point")));return p.assertValidity(),p}static fromHex(v){return z.fromBytes(ao("pointHex",v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,p=!0){return Y.createCache(this,v),p||this.multiply(WC),this}assertValidity(){A(this)}hasEvenY(){let{y:v}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(v)}equals(v){U(v);let{X:p,Y:x,Z:y}=this,{X:I,Y:C,Z:F}=v,N=r.eql(r.mul(p,F),r.mul(I,y)),O=r.eql(r.mul(x,F),r.mul(C,y));return N&&O}negate(){return new z(this.X,r.neg(this.Y),this.Z)}double(){let{a:v,b:p}=o,x=r.mul(p,WC),{X:y,Y:I,Z:C}=this,F=r.ZERO,N=r.ZERO,O=r.ZERO,D=r.mul(y,y),q=r.mul(I,I),_=r.mul(C,C),L=r.mul(y,I);return L=r.add(L,L),O=r.mul(y,C),O=r.add(O,O),F=r.mul(v,O),N=r.mul(x,_),N=r.add(F,N),F=r.sub(q,N),N=r.add(q,N),N=r.mul(F,N),F=r.mul(L,F),O=r.mul(x,O),_=r.mul(v,_),L=r.sub(D,_),L=r.mul(v,L),L=r.add(L,O),O=r.add(D,D),D=r.add(O,D),D=r.add(D,_),D=r.mul(D,L),N=r.add(N,D),_=r.mul(I,C),_=r.add(_,_),D=r.mul(_,L),F=r.sub(F,D),O=r.mul(_,q),O=r.add(O,O),O=r.add(O,O),new z(F,N,O)}add(v){U(v);let{X:p,Y:x,Z:y}=this,{X:I,Y:C,Z:F}=v,N=r.ZERO,O=r.ZERO,D=r.ZERO,q=o.a,_=r.mul(o.b,WC),L=r.mul(p,I),g=r.mul(x,C),K=r.mul(y,F),E=r.add(p,x),V=r.add(I,C);E=r.mul(E,V),V=r.add(L,g),E=r.sub(E,V),V=r.add(p,y);let J=r.add(I,F);return V=r.mul(V,J),J=r.add(L,K),V=r.sub(V,J),J=r.add(x,y),N=r.add(C,F),J=r.mul(J,N),N=r.add(g,K),J=r.sub(J,N),D=r.mul(q,V),N=r.mul(_,K),D=r.add(N,D),N=r.sub(g,D),D=r.add(g,D),O=r.mul(N,D),g=r.add(L,L),g=r.add(g,L),K=r.mul(q,K),V=r.mul(_,V),g=r.add(g,K),K=r.sub(L,K),K=r.mul(q,K),V=r.add(V,K),L=r.mul(g,V),O=r.add(O,L),L=r.mul(J,V),N=r.mul(E,N),N=r.sub(N,L),L=r.mul(E,g),D=r.mul(J,D),D=r.add(D,L),new z(N,O,D)}subtract(v){return this.add(v.negate())}is0(){return this.equals(z.ZERO)}multiply(v){let{endo:p}=e;if(!i.isValidNot0(v))throw new Error("invalid scalar: out of range");let x,y,I=C=>Y.cached(this,C,F=>jE(z,F));if(p){let{k1neg:C,k1:F,k2neg:N,k2:O}=H(v),{p:D,f:q}=I(F),{p:_,f:L}=I(O);y=q.add(L),x=T(p.beta,D,_,C,N)}else{let{p:C,f:F}=I(v);x=C,y=F}return jE(z,[x,y])[0]}multiplyUnsafe(v){let{endo:p}=e,x=this;if(!i.isValid(v))throw new Error("invalid scalar: out of range");if(v===Ed||x.is0())return z.ZERO;if(v===V0)return x;if(Y.hasCache(this))return this.multiply(v);if(p){let{k1neg:y,k1:I,k2neg:C,k2:F}=H(v),{p1:N,p2:O}=_Le(z,x,I,F);return T(p.beta,N,O,y,C)}else return Y.unsafe(x,v)}multiplyAndAddUnsafe(v,p,x){let y=this.multiplyUnsafe(p).add(v.multiplyUnsafe(x));return y.is0()?void 0:y}toAffine(v){return M(this,v)}isTorsionFree(){let{isTorsionFree:v}=e;return s===V0?!0:v?v(z,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:v}=e;return s===V0?this:v?v(z,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(v=!0){return i8(v,"isCompressed"),this.assertValidity(),f(z,this,v)}toHex(v=!0){return zy(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(v=!0){return this.toBytes(v)}_setWindowSize(v){this.precompute(v)}static normalizeZ(v){return jE(z,v)}static msm(v,p){return $Le(z,i,v,p)}static fromPrivateKey(v){return z.BASE.multiply(Id(i,v))}}z.BASE=new z(o.Gx,o.Gy,r.ONE),z.ZERO=new z(r.ZERO,r.ONE,r.ZERO),z.Fp=r,z.Fn=i;let j=i.BITS,Y=new LO(z,e.endo?Math.ceil(j/2):j);return z.BASE.precompute(8),z}function ote(n){return Uint8Array.of(n?2:3)}function ste(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function cRe(n,e={}){let{Fn:t}=n,r=e.randomBytes||JO,i=Object.assign(ste(n.Fp,t),{seed:zO(t.ORDER)});function o(f){try{return!!Id(t,f)}catch{return!1}}function s(f,m){let{publicKey:w,publicKeyUncompressed:b}=i;try{let S=f.length;return m===!0&&S!==w||m===!1&&S!==b?!1:!!n.fromBytes(f)}catch{return!1}}function a(f=r(i.seed)){return _ee(K0(f,i.seed,"seed"),t.ORDER)}function c(f,m=!0){return n.BASE.multiply(Id(t,f)).toBytes(m)}function u(f){let m=a(f);return{secretKey:m,publicKey:c(m)}}function l(f){if(typeof f=="bigint")return!1;if(f instanceof n)return!0;let{secretKey:m,publicKey:w,publicKeyUncompressed:b}=i;if(t.allowedLengths||m===w)return;let S=ao("key",f).length;return S===w||S===b}function d(f,m,w=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let b=Id(t,f);return n.fromHex(m).multiply(b).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:u,Point:n,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:f=>Id(t,f),precompute(f=8,m=n.BASE){return m.precompute(f,!1)}},lengths:i})}function uRe(n,e,t={}){Fee(e),u8(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=t.randomBytes||JO,i=t.hmac||((p,...x)=>nte(e,p,Fi(...x))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f}=cRe(n,t),m={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function b(p){let x=a>>V0;return p>x}function S(p,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${p}: out of range 1..Point.Fn.ORDER`);return x}function R(p,x){RO(x);let y=f.signature,I=x==="compact"?y:x==="recovered"?y+1:void 0;return K0(p,I,`${x} signature`)}class G{constructor(x,y,I){this.r=S("r",x),this.s=S("s",y),I!=null&&(this.recovery=I),Object.freeze(this)}static fromBytes(x,y=w){R(x,y);let I;if(y==="der"){let{r:O,s:D}=bd.toSig(K0(x));return new G(O,D)}y==="recovered"&&(I=x[0],y="compact",x=x.subarray(1));let C=s.BYTES,F=x.subarray(0,C),N=x.subarray(C,C*2);return new G(s.fromBytes(F),s.fromBytes(N),I)}static fromHex(x,y){return this.fromBytes(t8(x),y)}addRecoveryBit(x){return new G(this.r,this.s,x)}recoverPublicKey(x){let y=o.ORDER,{r:I,s:C,recovery:F}=this;if(F==null||![0,1,2,3].includes(F))throw new Error("recovery id invalid");if(a*rte<y&&F>1)throw new Error("recovery id is ambiguous for h>1 curve");let O=F===2||F===3?I+a:I;if(!o.isValid(O))throw new Error("recovery id 2 or 3 invalid");let D=o.toBytes(O),q=n.fromBytes(Fi(ote((F&1)===0),D)),_=s.inv(O),L=H(ao("msgHash",x)),g=s.create(-L*_),K=s.create(C*_),E=n.BASE.multiplyUnsafe(g).add(q.multiplyUnsafe(K));if(E.is0())throw new Error("point at infinify");return E.assertValidity(),E}hasHighS(){return b(this.s)}toBytes(x=w){if(RO(x),x==="der")return t8(bd.hexFromSig(this));let y=s.toBytes(this.r),I=s.toBytes(this.s);if(x==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Fi(Uint8Array.of(this.recovery),y,I)}return Fi(y,I)}toHex(x){return zy(this.toBytes(x))}assertValidity(){}static fromCompact(x){return G.fromBytes(ao("sig",x),"compact")}static fromDER(x){return G.fromBytes(ao("sig",x),"der")}normalizeS(){return this.hasHighS()?new G(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return zy(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return zy(this.toBytes("compact"))}}let U=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let y=tI(x),I=x.length*8-c;return I>0?y>>BigInt(I):y},H=t.bits2int_modN||function(x){return s.create(U(x))},M=nI(c);function A(p){return GLe("num < 2^"+c,p,Ed,M),s.toBytes(p)}function T(p,x){return K0(p,void 0,"message"),x?K0(e(p),void 0,"prehashed message"):p}function z(p,x,y){if(["recovered","canonical"].some(g=>g in y))throw new Error("sign() legacy options not supported");let{lowS:I,prehash:C,extraEntropy:F}=yO(y,m);p=T(p,C);let N=H(p),O=Id(s,x),D=[A(O),A(N)];if(F!=null&&F!==!1){let g=F===!0?r(f.secretKey):F;D.push(ao("extraEntropy",g))}let q=Fi(...D),_=N;function L(g){let K=U(g);if(!s.isValidNot0(K))return;let E=s.inv(K),V=n.BASE.multiply(K).toAffine(),J=s.create(V.x);if(J===Ed)return;let B=s.create(E*s.create(_+J*O));if(B===Ed)return;let X=(V.x===J?0:2)|Number(V.y&V0),ce=B;return I&&b(B)&&(ce=s.neg(B),X^=1),new G(J,ce,X)}return{seed:q,k2sig:L}}function j(p,x,y={}){p=ao("message",p);let{seed:I,k2sig:C}=z(p,x,y);return KLe(e.outputLen,s.BYTES,i)(I,C)}function Y(p){let x,y=typeof p=="string"||$E(p),I=!y&&p!==null&&typeof p=="object"&&typeof p.r=="bigint"&&typeof p.s=="bigint";if(!y&&!I)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(I)x=new G(p.r,p.s);else if(y){try{x=G.fromBytes(ao("sig",p),"der")}catch(C){if(!(C instanceof bd.Err))throw C}if(!x)try{x=G.fromBytes(ao("sig",p),"compact")}catch{return!1}}return x||!1}function Q(p,x,y,I={}){let{lowS:C,prehash:F,format:N}=yO(I,m);if(y=ao("publicKey",y),x=T(ao("message",x),F),"strict"in I)throw new Error("options.strict was renamed to lowS");let O=N===void 0?Y(p):G.fromBytes(ao("sig",p),N);if(O===!1)return!1;try{let D=n.fromBytes(y);if(C&&O.hasHighS())return!1;let{r:q,s:_}=O,L=H(x),g=s.inv(_),K=s.create(L*g),E=s.create(q*g),V=n.BASE.multiplyUnsafe(K).add(D.multiplyUnsafe(E));return V.is0()?!1:s.create(V.x)===q}catch{return!1}}function v(p,x,y={}){let{prehash:I}=yO(y,m);return x=T(x,I),G.fromBytes(p,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f,Point:n,sign:j,verify:Q,recoverPublicKey:v,Signature:G,hash:e})}function Aee(n){let{CURVE:e,curveOpts:t}=ate(n),r=ite(e,t);return fRe(n,r)}function ate(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=n.allowedPrivateKeyLengths?Array.from(new Set(n.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,i=jy(e.n,{BITS:n.nBitLength,allowedLengths:r,modFromBytes:n.wrapPrivateKey}),o={Fp:t,Fn:i,allowInfinityPoint:n.allowInfinityPoint,endo:n.endo,isTorsionFree:n.isTorsionFree,clearCofactor:n.clearCofactor,fromBytes:n.fromBytes,toBytes:n.toBytes};return{CURVE:e,curveOpts:o}}function lRe(n){let{CURVE:e,curveOpts:t}=ate(n),r={hmac:n.hmac,randomBytes:n.randomBytes,lowS:n.lowS,bits2int:n.bits2int,bits2int_modN:n.bits2int_modN};return{CURVE:e,curveOpts:t,hash:n.hash,ecdsaOpts:r}}function dRe(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 fRe(n,e){let{Fp:t,Fn:r}=e;function i(s){return Jee(s,V0,r.ORDER)}let o=dRe(t,n.a,n.b);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s=>Id(r,s),weierstrassEquation:o,isWithinCurveOrder:i})}function hRe(n,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},n,Zee(t.Fn.ORDER,t.Fn.BITS))})}function pRe(n){let{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:i}=lRe(n),o=ite(e,t),s=uRe(o,r,i);return hRe(n,s)}var mRe=BigInt(0),ZC=BigInt(1),xee=BigInt(2),Qy=BigInt(3);function gRe(n){let e=[];for(;n>ZC;n>>=ZC)(n&ZC)===mRe?e.unshift(0):(n&Qy)===Qy?(e.unshift(-1),n+=ZC):e.unshift(1);return e}function wO(n){if(!Array.isArray(n)||n.length===0)throw new Error("expected non-empty array")}function yRe(n,e,t,r){let{Fp2:i,Fp12:o}=n,{twistType:s,ateLoopSize:a,xNegative:c,postPrecompute:u}=r,l;if(s==="multiplicative")l=(G,U,H,M,A,T)=>o.mul014(M,G,i.mul(U,A),i.mul(H,T));else if(s==="divisive")l=(G,U,H,M,A,T)=>o.mul034(M,i.mul(H,T),i.mul(U,A),G);else throw new Error("bls: unknown twist type");let d=i.div(i.ONE,i.mul(i.ONE,xee));function h(G,U,H,M){let A=i.sqr(H),T=i.sqr(M),z=i.mulByB(i.mul(T,Qy)),j=i.mul(z,Qy),Y=i.sub(i.sub(i.sqr(i.add(H,M)),T),A),Q=i.sub(z,A),v=i.mul(i.sqr(U),Qy),p=i.neg(Y);return G.push([Q,v,p]),U=i.mul(i.mul(i.mul(i.sub(A,j),U),H),d),H=i.sub(i.sqr(i.mul(i.add(A,j),d)),i.mul(i.sqr(z),Qy)),M=i.mul(A,Y),{Rx:U,Ry:H,Rz:M}}function f(G,U,H,M,A,T){let z=i.sub(H,i.mul(T,M)),j=i.sub(U,i.mul(A,M)),Y=i.sub(i.mul(z,A),i.mul(j,T)),Q=i.neg(z),v=j;G.push([Y,Q,v]);let p=i.sqr(j),x=i.mul(p,j),y=i.mul(p,U),I=i.add(i.sub(x,i.mul(y,xee)),i.mul(i.sqr(z),M));return U=i.mul(j,I),H=i.sub(i.mul(i.sub(y,I),z),i.mul(x,H)),M=i.mul(M,x),{Rx:U,Ry:H,Rz:M}}let m=gRe(a),w=CO(G=>{let U=G,{x:H,y:M}=U.toAffine(),A=H,T=M,z=i.neg(M),j=A,Y=T,Q=i.ONE,v=[];for(let p of m){let x=[];({Rx:j,Ry:Y,Rz:Q}=h(x,j,Y,Q)),p&&({Rx:j,Ry:Y,Rz:Q}=f(x,j,Y,Q,A,p===-1?z:T)),v.push(x)}if(u){let p=v[v.length-1];u(j,Y,Q,A,T,f.bind(null,p))}return v});function b(G,U=!1){let H=o.ONE;if(G.length){let M=G[0][0].length;for(let A=0;A<M;A++){H=o.sqr(H);for(let[T,z,j]of G)for(let[Y,Q,v]of T[A])H=l(Y,Q,v,H,z,j)}}return c&&(H=o.conjugate(H)),U?o.finalExponentiate(H):H}function S(G,U=!0){let H=[];jE(e,G.map(({g1:M})=>M)),jE(t,G.map(({g2:M})=>M));for(let{g1:M,g2:A}of G){if(M.is0()||A.is0())throw new Error("pairing is not available for ZERO point");M.assertValidity(),A.assertValidity();let T=M.toAffine();H.push([w(A),T.x,T.y])}return b(H,U)}function R(G,U,H=!0){return S([{g1:G,g2:U}],H)}return{Fp12:o,millerLoopBatch:b,pairing:R,pairingBatch:S,calcPairingPrecomputes:w}}function vee(n,e,t,r,i){let{Fp12:o,pairingBatch:s}=n;function a(d){return d instanceof e.Point?d:e.Point.fromHex(d)}function c(d){return d instanceof t.Point?d:t.Point.fromHex(d)}function u(d){if(!(d instanceof t.Point))throw new Error(`expected valid message hashed to ${i?"G1":"G2"} curve`);return d}let l=i?(d,h)=>({g1:h,g2:d}):(d,h)=>({g1:d,g2:h});return{getPublicKey(d){let h=Id(e.Point.Fn,d);return e.Point.BASE.multiply(h)},sign(d,h,f){if(f!=null)throw new Error("sign() expects 2 arguments");let m=Id(e.Point.Fn,h);return u(d).assertValidity(),d.multiply(m)},verify(d,h,f,m){if(m!=null)throw new Error("verify() expects 3 arguments");d=c(d),f=a(f);let w=f.negate(),b=e.Point.BASE,S=u(h),R=d,G=s([l(w,S),l(b,R)]);return o.eql(G,o.ONE)},verifyBatch(d,h,f){if(wO(h),f.length!==h.length)throw new Error("amount of public keys and messages should be equal");let m=c(d),w=h,b=f.map(a),S=new Map;for(let U=0;U<b.length;U++){let H=b[U],M=w[U],A=S.get(M);A===void 0&&(A=[],S.set(M,A)),A.push(H)}let R=[],G=e.Point.BASE;try{for(let[U,H]of S){let M=H.reduce((A,T)=>A.add(T));R.push(l(M,U))}return R.push(l(G.negate(),m)),o.eql(s(R),o.ONE)}catch{return!1}},aggregatePublicKeys(d){wO(d),d=d.map(f=>a(f));let h=d.reduce((f,m)=>f.add(m),e.Point.ZERO);return h.assertValidity(),h},aggregateSignatures(d){wO(d),d=d.map(f=>c(f));let h=d.reduce((f,m)=>f.add(m),t.Point.ZERO);return h.assertValidity(),h},hash(d,h){Kc(d);let f=h?{DST:h}:void 0;return t.hashToCurve(d,f)},Signature:r}}function wRe(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=Aee(n.G1),a=Object.assign(s,Eee(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),c=Aee(n.G2),u=Object.assign(c,Eee(c.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),l=yRe(n.fields,a.Point,u.Point,{...n.params,postPrecompute:n.postPrecompute}),{millerLoopBatch:d,pairing:h,pairingBatch:f,calcPairingPrecomputes:m}=l,w=vee(l,a,u,n.G2.Signature,!1),b=vee(l,u,a,n.G1.ShortSignature,!0),S=n.randomBytes||JO,R=()=>{let C=zO(t.ORDER);return _ee(S(C),t.ORDER)},G={randomSecretKey:R,randomPrivateKey:R,calcPairingPrecomputes:m},{ShortSignature:U}=n.G1,{Signature:H}=n.G2;function M(C,F){return C instanceof a.Point?C:b.hash(ao("point",C),F?.DST)}function A(C,F){return C instanceof u.Point?C:w.hash(ao("point",C),F?.DST)}function T(C){return w.getPublicKey(C).toBytes(!0)}function z(C){return b.getPublicKey(C).toBytes(!0)}function j(C,F,N){let O=A(C,N),D=w.sign(O,F);return C instanceof u.Point?D:H.toBytes(D)}function Y(C,F,N){let O=M(C,N),D=b.sign(O,F);return C instanceof a.Point?D:U.toBytes(D)}function Q(C,F,N,O){let D=A(F,O);return w.verify(C,D,N)}function v(C,F,N,O){let D=M(F,O);return b.verify(C,D,N)}function p(C){let F=w.aggregatePublicKeys(C);return C[0]instanceof a.Point?F:F.toBytes(!0)}function x(C){let F=w.aggregateSignatures(C);return C[0]instanceof u.Point?F:H.toBytes(F)}function y(C){let F=b.aggregateSignatures(C);return C[0]instanceof a.Point?F:U.toBytes(F)}function I(C,F,N,O){let D=F.map(q=>A(q,O));return w.verifyBatch(C,D,N)}return a.Point.BASE.precompute(4),{longSignatures:w,shortSignatures:b,millerLoopBatch:d,pairing:h,pairingBatch:f,verifyBatch:I,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:T,getPublicKeyForShortSignatures:z,sign:j,signShortSignature:Y,verify:Q,verifyShortSignature:v,aggregatePublicKeys:p,aggregateSignatures:x,aggregateShortSignatures:y,G1:a,G2:u,Signature:H,ShortSignature:U}}var See=BigInt(0),Ad=BigInt(1),jo=BigInt(2),Cee=BigInt(3);function YO(n,e,t,r,i=1,o){let s=BigInt(o===void 0?r:o),a=t**BigInt(r),c=[];for(let u=0;u<i;u++){let l=BigInt(u+1),d=[];for(let h=0,f=Ad;h<r;h++){let m=(l*f-l)/s%a;d.push(n.pow(e,m)),f*=t}c.push(d)}return c}function bRe(n,e,t){let r=e.pow(t,(n.ORDER-Ad)/Cee),i=e.pow(t,(n.ORDER-Ad)/jo);function o(h,f){let m=e.mul(e.frobeniusMap(h,1),r),w=e.mul(e.frobeniusMap(f,1),i);return[m,w]}let s=e.pow(t,(n.ORDER**jo-Ad)/Cee),a=e.pow(t,(n.ORDER**jo-Ad)/jo);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 u=h=>(f,m)=>{let w=m.toAffine(),b=h(w.x,w.y);return f.fromAffine({x:b[0],y:b[1]})},l=u(o),d=u(c);return{psi:o,psi2:c,G2psi:l,G2psi2:d,PSI_X:r,PSI_Y:i,PSI2_X:s,PSI2_Y:a}}var Lee=(n,e)=>{if(e.length!==2)throw new Error("invalid tuple");let t=e.map(r=>n.create(r));return{c0:t[0],c1:t[1]}},TO=class{constructor(e,t={}){this.MASK=Ad;let r=e.ORDER,i=r*r;this.Fp=e,this.ORDER=i,this.BITS=WE(i),this.BYTES=Math.ceil(WE(i)/8),this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO},this.Fp_NONRESIDUE=e.create(t.NONRESIDUE||BigInt(-1)),this.Fp_div2=e.div(e.ONE,jo),this.NONRESIDUE=Lee(e,t.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=YO(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=t.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return Lee(this.Fp,e)}create(e){return e}isValid({c0:e,c1:t}){function r(i,o){return typeof i=="bigint"&&See<=i&&i<o}return r(e,this.ORDER)&&r(t,this.ORDER)}is0({c0:e,c1:t}){return this.Fp.is0(e)&&this.Fp.is0(t)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}eql({c0:e,c1:t},{c0:r,c1:i}){return this.Fp.eql(e,r)&&this.Fp.eql(t,i)}neg({c0:e,c1:t}){return{c0:this.Fp.neg(e),c1:this.Fp.neg(t)}}pow(e,t){return l8(this,e,t)}invertBatch(e){return rI(this,e)}add(e,t){let{c0:r,c1:i}=e,{c0:o,c1:s}=t;return{c0:this.Fp.add(r,o),c1:this.Fp.add(i,s)}}sub({c0:e,c1:t},{c0:r,c1:i}){return{c0:this.Fp.sub(e,r),c1:this.Fp.sub(t,i)}}mul({c0:e,c1:t},r){let{Fp:i}=this;if(typeof r=="bigint")return{c0:i.mul(e,r),c1:i.mul(t,r)};let{c0:o,c1:s}=r,a=i.mul(e,o),c=i.mul(t,s),u=i.sub(a,c),l=i.sub(i.mul(i.add(e,t),i.add(o,s)),i.add(a,c));return{c0:u,c1:l}}sqr({c0:e,c1:t}){let{Fp:r}=this,i=r.add(e,t),o=r.sub(e,t),s=r.add(e,e);return{c0:r.mul(i,o),c1:r.mul(s,t)}}addN(e,t){return this.add(e,t)}subN(e,t){return this.sub(e,t)}mulN(e,t){return this.mul(e,t)}sqrN(e){return this.sqr(e)}div(e,t){let{Fp:r}=this;return this.mul(e,typeof t=="bigint"?r.inv(r.create(t)):this.inv(t))}inv({c0:e,c1:t}){let{Fp:r}=this,i=r.inv(r.create(e*e+t*t));return{c0:r.mul(i,r.create(e)),c1:r.mul(i,r.create(-t))}}sqrt(e){let{Fp:t}=this,r=this,{c0:i,c1:o}=e;if(t.is0(o))return o8(t,i)===1?r.create({c0:t.sqrt(i),c1:t.ZERO}):r.create({c0:t.ZERO,c1:t.sqrt(t.div(i,this.Fp_NONRESIDUE))});let s=t.sqrt(t.sub(t.sqr(i),t.mul(t.sqr(o),this.Fp_NONRESIDUE))),a=t.mul(t.add(s,i),this.Fp_div2);o8(t,a)===-1&&(a=t.sub(a,s));let u=t.sqrt(a),l=r.create({c0:u,c1:t.div(t.mul(o,this.Fp_div2),u)});if(!r.eql(r.sqr(l),e))throw new Error("Cannot find square root");let d=l,h=r.neg(d),{re:f,im:m}=r.reim(d),{re:w,im:b}=r.reim(h);return m>b||m===b&&f>w?d:h}isOdd(e){let{re:t,im:r}=this.reim(e),i=t%jo,o=t===See,s=r%jo;return BigInt(i||o&&s)==Ad}fromBytes(e){let{Fp:t}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);return{c0:t.fromBytes(e.subarray(0,t.BYTES)),c1:t.fromBytes(e.subarray(t.BYTES))}}toBytes({c0:e,c1:t}){return Fi(this.Fp.toBytes(e),this.Fp.toBytes(t))}cmov({c0:e,c1:t},{c0:r,c1:i},o){return{c0:this.Fp.cmov(e,r,o),c1:this.Fp.cmov(t,i,o)}}reim({c0:e,c1:t}){return{re:e,im:t}}Fp4Square(e,t){let r=this,i=r.sqr(e),o=r.sqr(t);return{first:r.add(r.mulByNonresidue(o),i),second:r.sub(r.sub(r.sqr(r.add(e,t)),i),o)}}mulByNonresidue({c0:e,c1:t}){return this.mul({c0:e,c1:t},this.NONRESIDUE)}frobeniusMap({c0:e,c1:t},r){return{c0:e,c1:this.Fp.mul(t,this.FROBENIUS_COEFFICIENTS[r%2])}}},BO=class{constructor(e){this.MASK=Ad,this.Fp2=e,this.ORDER=e.ORDER,this.BITS=3*e.BITS,this.BYTES=3*e.BYTES,this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO,c2:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO,c2:e.ZERO};let{Fp:t}=e,r=YO(e,e.NONRESIDUE,t.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=r[0],this.FROBENIUS_COEFFICIENTS_2=r[1],Object.seal(this)}add({c0:e,c1:t,c2:r},{c0:i,c1:o,c2:s}){let{Fp2:a}=this;return{c0:a.add(e,i),c1:a.add(t,o),c2:a.add(r,s)}}sub({c0:e,c1:t,c2:r},{c0:i,c1:o,c2:s}){let{Fp2:a}=this;return{c0:a.sub(e,i),c1:a.sub(t,o),c2:a.sub(r,s)}}mul({c0:e,c1:t,c2:r},i){let{Fp2:o}=this;if(typeof i=="bigint")return{c0:o.mul(e,i),c1:o.mul(t,i),c2:o.mul(r,i)};let{c0:s,c1:a,c2:c}=i,u=o.mul(e,s),l=o.mul(t,a),d=o.mul(r,c);return{c0:o.add(u,o.mulByNonresidue(o.sub(o.mul(o.add(t,r),o.add(a,c)),o.add(l,d)))),c1:o.add(o.sub(o.mul(o.add(e,t),o.add(s,a)),o.add(u,l)),o.mulByNonresidue(d)),c2:o.sub(o.add(l,o.mul(o.add(e,r),o.add(s,c))),o.add(u,d))}}sqr({c0:e,c1:t,c2:r}){let{Fp2:i}=this,o=i.sqr(e),s=i.mul(i.mul(e,t),jo),a=i.mul(i.mul(t,r),jo),c=i.sqr(r);return{c0:i.add(i.mulByNonresidue(a),o),c1:i.add(i.mulByNonresidue(c),s),c2:i.sub(i.sub(i.add(i.add(s,i.sqr(i.add(i.sub(e,t),r))),a),o),c)}}addN(e,t){return this.add(e,t)}subN(e,t){return this.sub(e,t)}mulN(e,t){return this.mul(e,t)}sqrN(e){return this.sqr(e)}create(e){return e}isValid({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return i.isValid(e)&&i.isValid(t)&&i.isValid(r)}is0({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return i.is0(e)&&i.is0(t)&&i.is0(r)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return{c0:i.neg(e),c1:i.neg(t),c2:i.neg(r)}}eql({c0:e,c1:t,c2:r},{c0:i,c1:o,c2:s}){let{Fp2:a}=this;return a.eql(e,i)&&a.eql(t,o)&&a.eql(r,s)}sqrt(e){return ui()}div(e,t){let{Fp2:r}=this,{Fp:i}=r;return this.mul(e,typeof t=="bigint"?i.inv(i.create(t)):this.inv(t))}pow(e,t){return l8(this,e,t)}invertBatch(e){return rI(this,e)}inv({c0:e,c1:t,c2:r}){let{Fp2:i}=this,o=i.sub(i.sqr(e),i.mulByNonresidue(i.mul(r,t))),s=i.sub(i.mulByNonresidue(i.sqr(r)),i.mul(e,t)),a=i.sub(i.sqr(t),i.mul(e,r)),c=i.inv(i.add(i.mulByNonresidue(i.add(i.mul(r,s),i.mul(t,a))),i.mul(e,o)));return{c0:i.mul(c,o),c1:i.mul(c,s),c2:i.mul(c,a)}}fromBytes(e){let{Fp2:t}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);let r=t.BYTES;return{c0:t.fromBytes(e.subarray(0,r)),c1:t.fromBytes(e.subarray(r,r*2)),c2:t.fromBytes(e.subarray(2*r))}}toBytes({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return Fi(i.toBytes(e),i.toBytes(t),i.toBytes(r))}cmov({c0:e,c1:t,c2:r},{c0:i,c1:o,c2:s},a){let{Fp2:c}=this;return{c0:c.cmov(e,i,a),c1:c.cmov(t,o,a),c2:c.cmov(r,s,a)}}fromBigSix(e){let{Fp2:t}=this;if(!Array.isArray(e)||e.length!==6)throw new Error("invalid Fp6 usage");return{c0:t.fromBigTuple(e.slice(0,2)),c1:t.fromBigTuple(e.slice(2,4)),c2:t.fromBigTuple(e.slice(4,6))}}frobeniusMap({c0:e,c1:t,c2:r},i){let{Fp2:o}=this;return{c0:o.frobeniusMap(e,i),c1:o.mul(o.frobeniusMap(t,i),this.FROBENIUS_COEFFICIENTS_1[i%6]),c2:o.mul(o.frobeniusMap(r,i),this.FROBENIUS_COEFFICIENTS_2[i%6])}}mulByFp2({c0:e,c1:t,c2:r},i){let{Fp2:o}=this;return{c0:o.mul(e,i),c1:o.mul(t,i),c2:o.mul(r,i)}}mulByNonresidue({c0:e,c1:t,c2:r}){let{Fp2:i}=this;return{c0:i.mulByNonresidue(r),c1:e,c2:t}}mul1({c0:e,c1:t,c2:r},i){let{Fp2:o}=this;return{c0:o.mulByNonresidue(o.mul(r,i)),c1:o.mul(e,i),c2:o.mul(t,i)}}mul01({c0:e,c1:t,c2:r},i,o){let{Fp2:s}=this,a=s.mul(e,i),c=s.mul(t,o);return{c0:s.add(s.mulByNonresidue(s.sub(s.mul(s.add(t,r),o),c)),a),c1:s.sub(s.sub(s.mul(s.add(i,o),s.add(e,t)),a),c),c2:s.add(s.sub(s.mul(s.add(e,r),i),a),c)}}},PO=class{constructor(e,t){this.MASK=Ad;let{Fp2:r}=e,{Fp:i}=r;this.Fp6=e,this.ORDER=r.ORDER,this.BITS=2*e.BITS,this.BYTES=2*e.BYTES,this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO},this.FROBENIUS_COEFFICIENTS=YO(r,r.NONRESIDUE,i.ORDER,12,1,6)[0],this.X_LEN=t.X_LEN,this.finalExponentiate=t.Fp12finalExponentiate}create(e){return e}isValid({c0:e,c1:t}){let{Fp6:r}=this;return r.isValid(e)&&r.isValid(t)}is0({c0:e,c1:t}){let{Fp6:r}=this;return r.is0(e)&&r.is0(t)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:t}){let{Fp6:r}=this;return{c0:r.neg(e),c1:r.neg(t)}}eql({c0:e,c1:t},{c0:r,c1:i}){let{Fp6:o}=this;return o.eql(e,r)&&o.eql(t,i)}sqrt(e){ui()}inv({c0:e,c1:t}){let{Fp6:r}=this,i=r.inv(r.sub(r.sqr(e),r.mulByNonresidue(r.sqr(t))));return{c0:r.mul(e,i),c1:r.neg(r.mul(t,i))}}div(e,t){let{Fp6:r}=this,{Fp2:i}=r,{Fp:o}=i;return this.mul(e,typeof t=="bigint"?o.inv(o.create(t)):this.inv(t))}pow(e,t){return l8(this,e,t)}invertBatch(e){return rI(this,e)}add({c0:e,c1:t},{c0:r,c1:i}){let{Fp6:o}=this;return{c0:o.add(e,r),c1:o.add(t,i)}}sub({c0:e,c1:t},{c0:r,c1:i}){let{Fp6:o}=this;return{c0:o.sub(e,r),c1:o.sub(t,i)}}mul({c0:e,c1:t},r){let{Fp6:i}=this;if(typeof r=="bigint")return{c0:i.mul(e,r),c1:i.mul(t,r)};let{c0:o,c1:s}=r,a=i.mul(e,o),c=i.mul(t,s);return{c0:i.add(a,i.mulByNonresidue(c)),c1:i.sub(i.mul(i.add(e,t),i.add(o,s)),i.add(a,c))}}sqr({c0:e,c1:t}){let{Fp6:r}=this,i=r.mul(e,t);return{c0:r.sub(r.sub(r.mul(r.add(r.mulByNonresidue(t),e),r.add(e,t)),i),r.mulByNonresidue(i)),c1:r.add(i,i)}}addN(e,t){return this.add(e,t)}subN(e,t){return this.sub(e,t)}mulN(e,t){return this.mul(e,t)}sqrN(e){return this.sqr(e)}fromBytes(e){let{Fp6:t}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);return{c0:t.fromBytes(e.subarray(0,t.BYTES)),c1:t.fromBytes(e.subarray(t.BYTES))}}toBytes({c0:e,c1:t}){let{Fp6:r}=this;return Fi(r.toBytes(e),r.toBytes(t))}cmov({c0:e,c1:t},{c0:r,c1:i},o){let{Fp6:s}=this;return{c0:s.cmov(e,r,o),c1:s.cmov(t,i,o)}}fromBigTwelve(e){let{Fp6:t}=this;return{c0:t.fromBigSix(e.slice(0,6)),c1:t.fromBigSix(e.slice(6,12))}}frobeniusMap(e,t){let{Fp6:r}=this,{Fp2:i}=r,{c0:o,c1:s,c2:a}=r.frobeniusMap(e.c1,t),c=this.FROBENIUS_COEFFICIENTS[t%12];return{c0:r.frobeniusMap(e.c0,t),c1:r.create({c0:i.mul(o,c),c1:i.mul(s,c),c2:i.mul(a,c)})}}mulByFp2({c0:e,c1:t},r){let{Fp6:i}=this;return{c0:i.mulByFp2(e,r),c1:i.mulByFp2(t,r)}}conjugate({c0:e,c1:t}){return{c0:e,c1:this.Fp6.neg(t)}}mul014({c0:e,c1:t},r,i,o){let{Fp6:s}=this,{Fp2:a}=s,c=s.mul01(e,r,i),u=s.mul1(t,o);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(s.sub(s.mul01(s.add(t,e),r,a.add(i,o)),c),u)}}mul034({c0:e,c1:t},r,i,o){let{Fp6:s}=this,{Fp2:a}=s,c=s.create({c0:a.mul(e.c0,r),c1:a.mul(e.c1,r),c2:a.mul(e.c2,r)}),u=s.mul01(t,i,o),l=s.mul01(s.add(e,t),a.add(r,i),o);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(l,s.add(c,u))}}_cyclotomicSquare({c0:e,c1:t}){let{Fp6:r}=this,{Fp2:i}=r,{c0:o,c1:s,c2:a}=e,{c0:c,c1:u,c2:l}=t,{first:d,second:h}=i.Fp4Square(o,u),{first:f,second:m}=i.Fp4Square(c,a),{first:w,second:b}=i.Fp4Square(s,l),S=i.mulByNonresidue(b);return{c0:r.create({c0:i.add(i.mul(i.sub(d,o),jo),d),c1:i.add(i.mul(i.sub(f,s),jo),f),c2:i.add(i.mul(i.sub(w,a),jo),w)}),c1:r.create({c0:i.add(i.mul(i.add(S,c),jo),S),c1:i.add(i.mul(i.add(h,u),jo),h),c2:i.add(i.mul(i.add(m,l),jo),m)})}}_cyclotomicExp(e,t){let r=this.ONE;for(let i=this.X_LEN-1;i>=0;i--)r=this._cyclotomicSquare(r),HLe(t,i)&&(r=this.mul(r,e));return r}};function ERe(n){let e=jy(n.ORDER),t=new TO(e,n),r=new BO(t),i=new PO(r,n);return{Fp:e,Fp2:t,Fp6:r,Fp12:i}}var IRe=BigInt(0),kO=BigInt(1),cte=BigInt(2),ARe=BigInt(3),ute=BigInt(6),d8=BigInt("4965661367192848881"),xRe=WE(d8),vRe=ute*d8**cte,f8={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:kO,a:IRe,b:ARe,Gx:kO,Gy:BigInt(2)},Ree=jy(f8.n),lte={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:XE,Fp2:qu,Fp6:SRe,Fp12:zn}=ERe({ORDER:f8.p,X_LEN:xRe,FP2_NONRESIDUE:[BigInt(9),kO],Fp2mulByB:n=>qu.mul(n,lte),Fp12finalExponentiate:n=>{let e=l=>zn.conjugate(zn._cyclotomicExp(l,d8)),t=zn.mul(zn.conjugate(n),zn.inv(n)),r=zn.mul(zn.frobeniusMap(t,2),t),i=zn._cyclotomicSquare(e(r)),o=zn.mul(zn._cyclotomicSquare(i),i),s=e(o),a=e(zn._cyclotomicSquare(s)),c=zn.mul(zn.mul(zn.conjugate(a),s),zn.conjugate(o)),u=zn.mul(c,i);return zn.mul(zn.frobeniusMap(zn.mul(zn.conjugate(r),u),3),zn.mul(zn.frobeniusMap(c,2),zn.mul(zn.frobeniusMap(u,1),zn.mul(zn.mul(c,s),r))))}}),{G2psi:CRe,psi:Dee}=bRe(XE,qu,qu.NONRESIDUE),bO=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:XE.ORDER,m:2,k:128,expand:"xmd",hash:Uee}),LRe=(n,e,t,r,i,o)=>{let s=Dee(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=Dee(s[0],s[1]);o(n,e,t,a[0],qu.neg(a[1]))},RRe={p:qu.ORDER,n:f8.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:qu.ZERO,b:lte,Gx:qu.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:qu.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},Q0=wRe({fields:{Fp:XE,Fp2:qu,Fp6:SRe,Fp12:zn,Fr:Ree},G1:{...f8,Fp:XE,htfDefaults:{...bO,m:1,DST:"BN254G2_XMD:SHA-256_SVDW_RO_"},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:ui,fromBytes:ui,toBytes:ui,ShortSignature:{fromBytes:ui,fromHex:ui,toBytes:ui,toRawBytes:ui,toHex:ui}},G2:{...RRe,Fp:qu,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...bO},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(vRe).equals(CRe(n,e)),mapToCurve:ui,fromBytes:ui,toBytes:ui,Signature:{fromBytes:ui,fromHex:ui,toBytes:ui,toRawBytes:ui,toHex:ui}},params:{ateLoopSize:d8*ute+cte,r:Ree.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:bO,postPrecompute:LRe});pRe({a:BigInt(0),b:BigInt(3),Fp:XE,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:Uee});var h8="groth16",DRe="auth",TRe="authV2",BRe="authV3",PRe="authV3-8-32",kRe=new TextDecoder,Tee=BigInt(0),Bee=Q0.fields.Fp2,Pee=Q0.fields.Fp12;async function jO(n,e,t){let r=await RLe(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:c}=await YC.prove(e,s);return{proof:a,pub_signals:c}}var[MO,MRe]=[Q0.G1.ProjectivePoint,Q0.G2.ProjectivePoint],XC=([n,e])=>MO.fromAffine({x:BigInt(n),y:BigInt(e)}),_C=([[n,e],[t,r]])=>MRe.fromAffine({x:Bee.fromBigTuple([BigInt(n),BigInt(e)]),y:Bee.fromBigTuple([BigInt(t),BigInt(r)])});async function WO(n,e,t,r){if(r(e.pub_signals).challenge!==zI(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(kRe.decode(t));return ZO(e,o)}function ZO(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=MO.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<Tee||BigInt(r[s])>=Q0.G1.CURVE.n)throw new Error(`Input value is not in the field ${Q0.G1.CURVE.n}`);if(BigInt(r[s])!==Tee){let[a,c]=e.IC[s+1].map(BigInt);i=i.add(MO.fromAffine({x:a,y:c}).multiply(BigInt(r[s])))}}i=i.add(XC(e.IC[0]));let o=Q0.pairingBatch([{g1:XC(t.pi_a).negate(),g2:_C(t.pi_b)},{g1:i,g2:_C(e.vk_gamma_2)},{g1:XC(t.pi_c),g2:_C(e.vk_delta_2)},{g1:XC(e.vk_alpha_1),g2:_C(e.vk_beta_2)}]);return Pee.eql(o,Pee.ONE)}var OO=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=Xe.fromBigInt(BigInt(e[2])),t}async verify(e,t,r){return WO(e,t,r,this.unmarshall)}prove(e,t,r){return jO(e,t,r)}},FO=new OO(new Hc(h8,DRe)),NO=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 WO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await jO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await VE(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:Xe.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},UO=new NO(new Hc(h8,TRe)),c8=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 WO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await jO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await VE(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:Xe.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},GO=new c8(new Hc(h8,BRe)),HO=new c8(new Hc(h8,PRe));_E(FO.methodAlg,()=>FO);_E(UO.methodAlg,()=>UO);_E(GO.methodAlg,()=>GO);_E(HO.methodAlg,()=>HO);var Wy={registerProvingMethod:_E,getProvingMethod:Oee,provingMethodGroth16AuthInstance:FO,provingMethodGroth16AuthV2Instance:UO,provingMethodGroth16AuthV3Instance:GO,provingMethodGroth16AuthV3_8_32Instance:HO};var Jc=Wy.provingMethodGroth16AuthV2Instance.methodAlg;function ORe(n){return Object.values(Oy).includes(n)}function FRe(n){return Object.values(_s).includes(n)}function NRe(n){return Object.values(IC).includes(n)}function URe(n){return Object.values(Fy).includes(n)}function GRe(n){return Object.values(AC).includes(n)}var dte=n=>{let[e,t]=n.toString().split(":");return`iden3comm/v1;env=application/iden3-zkp-json;circuitId=${t};alg=${e}`},fte=(n,e)=>{let[t,r]=e.toString().split(":");for(let i of n){let{env:o,circuits:s,alg:a}=vs(i);if(o==="application/iden3-zkp-json"&&s?.includes(r)&&(!a||a?.includes(t)))return!0}return!1};function HRe(n){return Object.values(xC).includes(n)}var KRe=n=>{let e=[];for(let t of n){let r=`${t.protocolVersion};env=${t.env}`;t.circuits?.length&&(r+=`;circuitId=${t.circuits.join(",")}`),t.alg?.length&&(r+=`;alg=${t.alg.join(",")}`),e.push(r)}return e},vs=n=>{let e=n.split(";");if(e.length<2)throw new Error("Invalid accept profile");let t=e[0].trim();if(!ORe(t))throw new Error(`Protocol version '${t}' not supported`);if(e[1].split("=").length!==2)throw new Error("Invalid accept profile 'env' parameter");let i=e[1].split("=")[1].trim();if(!FRe(i))throw new Error(`Envelop '${i}' not supported`);let o=e.findIndex(l=>l.includes("circuitId="));if(i!=="application/iden3-zkp-json"&&o>0)throw new Error(`Circuits not supported for env '${i}'`);let s;o>0&&(s=e[o].split("=")[1].split(",").map(l=>l.trim()).map(l=>{if(!NRe(l))throw new Error(`Circuit '${l}' not supported`);return l}));let a=e.findIndex(l=>l.includes("alg="));if(a===-1)return{protocolVersion:t,env:i,circuits:s,alg:void 0};let c=e[a].split("=")[1].split(",").map(l=>l.trim()),u=[];switch(i){case"application/iden3-zkp-json":u=c.map(l=>{if(!GRe(l))throw new Error(`Algorithm '${l}' not supported for '${i}'`);return l});break;case"application/iden3comm-signed-json":u=c.map(l=>{if(!URe(l))throw new Error(`Algorithm '${l}' not supported for '${i}'`);return l});break;case"application/iden3comm-encrypted-json":u=c.map(l=>{if(!HRe(l))throw new Error(`Algorithm '${l}' not supported for '${i}'`);return l});break;default:throw new Error(`Algorithms not supported for '${i}'`)}return{protocolVersion:t,env:i,circuits:s,alg:u}},XO=(n,e,t)=>{if(!t?.length)return Jc;let r=[Wy.provingMethodGroth16AuthV3_8_32Instance.methodAlg,Wy.provingMethodGroth16AuthV3Instance.methodAlg];if(e){let i=r.indexOf(e);i!==-1&&r.splice(i,1),r.unshift(e)}for(let i of r)if(n.isProfileSupported("application/iden3-zkp-json",dte(i))&&fte(t,i))return i;return Jc};var p8="https://www.w3.org/ns/did/v1",m8="https://w3id.org/security/suites/jws-2020/v1",iI=class{constructor(e,t=p8){this._did=e;let r=[t].flat();this._context=r.includes(p8)?r:[p8,...r]}_verificationMethods=[];_keyAgreements=[];_context;async addVerificationMethod(e,t){let r=await e.build(this._did);return this._verificationMethods.push(r),this._keyAgreements.push(r.id),t&&(this._context=[...new Set([...this._context,...Array.isArray(t)?t:[t]])]),this}build(){return{"@context":this._context,id:this._did,keyAgreement:this._keyAgreements,verificationMethod:this._verificationMethods}}},oI=class{constructor(e,t){this._keyProvider=e;this._alias=t?.alias}_alias;async build(e){let t=this._alias?{type:this._keyProvider.keyType,id:this._alias}:await this._keyProvider.newPrivateKey(),r=await this._keyProvider.publicKey(t),i=this._alias??t.id;return{id:`${e}#${i}`,type:"JsonWebKey2020",controller:e,publicKeyJwk:EM(r,t.type)}}};var _O=(n,e)=>Promise.all(n.map(async t=>{if(!t.did)throw new Error("Missing recipient DID");let r=t.didDocument??(await e.resolve(t.did.string()))?.didDocument;if(!r)throw new Error("Recipient DID document not found");let i=Ny(r);if(!i.length)throw new Error(`No verification methods defined in the DID document of ${r.id}`);let o=t.keyType??"JsonWebKey2020",s=t.alg??"RSA-OAEP-256",a=i.find(u=>u.controller===t.did.string()&&u.type===o&&u.publicKeyJwk?.alg===s);if(!a)throw new Error(`No key found with id ${t.did.string()} and type ${o} in DID document of ${r.id}`);let c=JRe(a);if(!c)throw new Error("No public key found");if(c instanceof Uint8Array)throw new Error("Public key is not a JWK");return{did:t.did.string(),keyType:o,kid:a.id,alg:s,recipientJWK:c}})),JRe=n=>n.publicKeyBase58?mw(n.publicKeyBase58):n.publicKeyBase64?Xu(n.publicKeyBase64):n.publicKeyHex?di(n.publicKeyHex):n.publicKeyJwk?n.publicKeyJwk:null;var $O=class{constructor(e,t){this._joseService=e;this._documentResolver=t}_supportedProtocolVersions=["iden3comm/v1"];_supportedAlgorithms=["RSA-OAEP-256","ECDH-ES+A256KW"];packMessage(e,t){return this.packInternal(e,t)}getSupportedAlgorithms(){return this._supportedAlgorithms}registerSupportedAlgorithm(e){this._supportedAlgorithms=[...new Set([...this._supportedAlgorithms,e])]}async pack(e,t){let r=JSON.parse(lt.decode(e));return this.packInternal(r,t)}async unpack(e){let{plaintext:t}=await this._joseService.decrypt(JSON.parse(lt.decode(e)));return JSON.parse(lt.decode(t))}mediaType(){return"application/iden3comm-encrypted-json"}getSupportedProfiles(){return this._supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this._supportedAlgorithms.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=vs(e);if(!this._supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);return!!o?.some(s=>this._supportedAlgorithms.includes(s))}async packInternal(e,t){let{enc:r,recipients:i}=t;if(!r)throw new Error("Missing encryption algorithm");if(!i.length)throw new Error("Missing recipients");if(!e.to)throw new Error("Missing recipient DID");let o=await _O(i,this._documentResolver),s=ke.encode(JSON.stringify(e)),a=await this._joseService.encrypt(s,{enc:r,typ:"application/iden3comm-encrypted-json",recipients:o});return ke.encode(JSON.stringify(a))}};var eF=class{constructor(e,t){this._kms=e;this._documentResolver=t}supportedAlgorithms=["ES256K","ES256K-R"];supportedProtocolVersions=["iden3comm/v1"];packMessage(e,t){return this.packInternal(e,t)}async pack(e,t){let r=JSON.parse(lt.decode(e));return this.packInternal(r,t)}async unpack(e){let t=lt.decode(e),[r,i]=t.split("."),o=JSON.parse(XI(r)),s=JSON.parse(XI(i)),a=Jj(o.kid)?.did;if(a&&a!==s.from)throw new Error(`Sender does not match DID in message with kid ${o?.kid}`);let c=await this.resolveDidDoc(s.from),u=Ny(c);if(!u?.length)throw new Error(`No verification methods defined in the DID document of ${c.id}`);if(o.kid){let d=u.find(h=>h.id===o.kid);if(!d)throw new Error(`verification method with specified kid ${o.kid} is not found in the DID Document`);u=[d]}if(!aW(t,u))throw new Error("JWS verification failed");return s}mediaType(){return"application/iden3comm-signed-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=vs(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);return!o?.length||o.some(a=>this.supportedAlgorithms.includes(a))}async resolveDidDoc(e){let t;try{let r=await this._documentResolver.resolve(e);if(!r?.didDocument?.id)throw new Error(`did document for ${e} is not found in resolution result`);t=r.didDocument}catch(r){throw new Error(`did document for ${e} is not resolved: ${r.message}`)}return t}async packInternal(e,t){if(!t.alg)throw new Error("Missing algorithm");let r=e.from??"";if(!r)throw new Error("Missing sender DID");if(!My[t.alg]?.length)throw new Error(`No supported verification methods for algorithm ${t.alg}`);let o=t.didDocument??await this.resolveDidDoc(r),s=Ny(o);if(!s.length)throw new Error(`No verification methods defined in the DID document of ${o.id}`);let a=t.kid?s.find(S=>S.id===t.kid):s[0];if(!a)throw new Error(`No key found with id ${t.kid} in DID document of ${o.id}`);let{publicKeyBytes:c,kmsKeyType:u}=bM(a);if(!c&&!u&&(a.blockchainAccountId||a.ethereumAddress)&&!t.signer)throw new Error(`No signer provided for ${a.blockchainAccountId||a.ethereumAddress}`);let l=a.id,d={alg:t.alg,kid:l,typ:"application/iden3comm-signed-json"},h=ZI(JSON.stringify(d)),f=ZI(JSON.stringify(e)),m=`${h}.${f}`,w=ke.encode(m),b;if(t.signer){let S=await t.signer(a,w);b=Lh(S)}else{if(!c)throw new Error("No public key found");if(!u)throw new Error("No KMS key type found");let S=await this._kms.sign({type:u,id:fo(u,Br(c))},w,{alg:t.alg});b=Lh(S)}return ke.encode(`${m}.${b}`)}};var tF=class{supportedProtocolVersions=["iden3comm/v1"];packMessage(e){return e.typ="application/iden3comm-plain-json",Promise.resolve(ke.encode(JSON.stringify(e)))}async pack(e){let t=JSON.parse(lt.decode(e));return t.typ="application/iden3comm-plain-json",Promise.resolve(ke.encode(JSON.stringify(t)))}async unpack(e){return JSON.parse(lt.decode(e))}mediaType(){return"application/iden3comm-plain-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=vs(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);if(o)throw new Error(`Algorithms are not supported for ${r} media type`);return!0}};var hte="unknown circuit ID. can't verify msg sender",g8="sender of message is not used for jwz token creation",pte="message was packed with unsupported circuit",mte="message proof is invalid",gte="message state verification failed",yte="unknown proving method algorithm";var{getProvingMethod:qRe}=Wy,sI=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},aI=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},cI=class{constructor(e,t,r={acceptedStateTransitionDelay:gM}){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(ke.encode(JSON.stringify(e)),t)}async pack(e,t){let r=await qRe(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(yte);let o=new Eh(r,lt.decode(e),(a,c)=>i?.dataPreparer?.prepare(a,t.senderDID,c));o.setHeader(Ka.Type,"application/iden3-zkp-json");let s=await o.prove(i.provingKey,i.wasm);return ke.encode(s)}async unpackMessage(e,t){let r=this.verificationParamsMap.get(t.toString());if(!r?.key)throw new Error(pte);if(!await e.verify(r?.key))throw new Error(mte);if(!await r?.verificationFn?.verify(e.circuitId,e.zkProof.pub_signals,this._opts))throw new Error(gte);let s=JSON.parse(e.getPayload());return await VRe(e,s),s}parseToken(e){return Eh.parse(lt.decode(e))}async unpack(e){let t=await this.parseToken(e),r=new Hc(t.alg,t.circuitId);return this.unpackMessage(t,r)}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}=vs(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;let s=this.supportedCircuitIds,a=!i?.length||i.some(l=>s.includes(l)),c=this.supportedAlgorithms;return(!o?.length||o.some(l=>c.includes(l)))&&a}},VRe=async(n,e)=>{switch(n.circuitId){case"authV2":case"authV3-8-32":case"authV3":{if(!e.from)throw new Error(g8);let t=(n.circuitId==="authV2"?new Ws:new ku).pubSignalsUnmarshal(ke.encode(JSON.stringify(n.zkProof.pub_signals))),r=ve.parseFromId(t.userID),i=await n.getMessageHash();if(It.bytesToInt(i.reverse())!==t.challenge)throw new Error(g8);if(e.from!==r.string())throw new Error(g8)}break;default:throw new Error(hte)}};var nF=class extends cI{constructor(t,r,i){super(new Map,new Map,{...i});this.circuitStorage=t;this.proofService=r;this.supportedCircuitIds=["authV2","authV3","authV3-8-32"]}async pack(t,r){let i=r.provingMethodAlg,o=i.circuitId,s=i.toString();if(!this.provingParamsMap.has(s)){let{provingKey:a,wasm:c}=await this.circuitStorage.loadCircuitData(o,{mode:"proving"});if(!a||!c)throw new Error(`circuit data not found for circuit id: ${o}`);this.provingParamsMap.set(s,{provingKey:a,wasm:c,dataPreparer:new sI(this.proofService.generateAuthInputs.bind(this.proofService))})}return super.pack(t,r)}async unpack(t){let r=await this.parseToken(t),i=r.circuitId,o=new Hc(r.alg,i);if(!this.verificationParamsMap.has(o.toString())){let{verificationKey:s}=await this.circuitStorage.loadCircuitData(i,{mode:"verification"});if(!s)throw new Error(`verification key not found for circuit id: ${i}`);this.verificationParamsMap.set(o.toString(),{key:s,verificationFn:new aI(this.proofService.verifyState.bind(this.proofService))})}return super.unpackMessage(r,o)}};var wte=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(wte||{});var rF=(o=>(o.AUTHV2="authV2",o.AUTHV3="authV3",o.AUTHV3_8_32="authV3-8-32",o.ETH_IDENTITY="ethIdentity",o.EMBEDDED_AUTH="embeddedAuth",o))(rF||{});var bte=(e=>(e.FeatureType="feature-type",e))(bte||{}),Ete=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(Ete||{});var Ni=class{nextMessageHandler;setNext(e){return this.nextMessageHandler=e,e}async handle(e,t){return t.allowExpiredMessages||Lr(e),this.nextMessageHandler?this.nextMessageHandler.handle(e,t):Promise.reject("Message handler not provided or message not supported")}},iF=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 qc(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 qc(e)},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};async function qc(n){try{let e=lt.decode(n);return(await Eh.parse(e)).method.methodAlg}catch{return Jc}}var Ite=n=>n.reduce((e,t)=>{let r=t.query;if(!r)return e;let i=r.groupId;if(!i)return e;let o=e.get(i);if(!o){let a=zc(12),u=new DataView(a.buffer).getUint32(0);return e.set(i,{query:r,linkNonce:u}),e}let s=R4(o.query.credentialSubject,r.credentialSubject);return e.set(i,{...o,query:{skipClaimRevocationCheck:o.query.skipClaimRevocationCheck||r.skipClaimRevocationCheck,...o.query,credentialSubject:s}}),e},new Map),Zy=async(n,e,t,r,i)=>{let o=e??[],s=Ite(o),a=new Map,c=[];for(let u of o){let l;try{if(!i.supportedCircuits.includes(u.circuitId)){if(u.optional){console.log(`Circuit ${u.circuitId} is not supported, skipping optional proof request`);continue}throw new Error(`Circuit ${u.circuitId} is not allowed`)}let h=u.query,f=i.credentials?.get(u.id.toString());if(f){l=await r.generateProof(u,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h?.skipClaimRevocationCheck,credential:f.credential,linkNonce:f.linkNonce,bypassCache:i.bypassProofsCache,allowExpiredCredentials:i.allowExpiredCredentials}),c.push(l);continue}let m=h?.groupId,w=s.get(m);if(m){if(!w)throw new Error(`Invalid group id ${h?.groupId}`);let S=w.query;if(!a.has(m)){let R=await r.findCredentialByProofQuery(n,w.query);if(!R.cred){if(u.optional){console.log("No credential found for optional proof request, skipping");continue}throw new Error(Ue.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(S)}`)}a.set(m,R)}}let b=a.get(m);l=await r.generateProof(u,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h?.skipClaimRevocationCheck,credential:b?.cred,credentialRevocationStatus:b?.revStatus,linkNonce:w?.linkNonce?BigInt(w.linkNonce):void 0,bypassCache:i.bypassProofsCache,allowExpiredCredentials:i.allowExpiredCredentials})}catch(d){let h=[Ue.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,Ue.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,Ue.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED,Ue.ERRORS.PROOF_SERVICE_CREDENTIAL_IS_EXPIRED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(Ue.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY))&&u.optional){console.log(`Error in optional proof request: ${d.message}, skipping`);continue}throw d}c.push(l)}return c},oF=async(n,e,t)=>{switch(t.acceptProfile||(t.acceptProfile=vC),t.acceptProfile.env){case"application/iden3comm-plain-json":return{authProof:{authMethod:"embeddedAuth"}};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=Ate(t.senderAddress,t.zkpResponses),o=await e.generateAuthProof(r,n,{challenge:i});return{authProof:{authMethod:r,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")}},uI=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=dh(n.proof),o=DE(t,i.a,i.b,i.c),s=mn.AbiCoder.defaultAbiCoder().encode(["string"],[n.circuitId]);return{requestId:e,zkProofEncoded:o,metadata:s}},Ate=(n,e)=>{let t=e.map(r=>{let i=uI(r);return{requestId:i.requestId,proof:i.zkProofEncoded,metadata:i.metadata}});return BigInt(mn.keccak256(new mn.AbiCoder().encode(["address","(uint256 requestId,bytes proof,bytes metadata)[]"],[n,t])))&BigInt("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")},QRe=n=>new mn.AbiCoder().encode(["tuple(string key,bytes value)[]"],[n]),Lr=n=>{if(n?.expires_time&&n.expires_time<Lt(new Date))throw new Error("Message expired")},ta=(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||Jc,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}`)},sF=(n,e,t)=>{if(t?.length)for(let r of t){let i=vs(r),o=Number(n.split("/").at(-2));if(!(i.protocolVersion!=="iden3comm/v1"||i.protocolVersion==="iden3comm/v1"&&(o<1||o>=2))&&e.isProfileSupported(i.env,r))return i}return vC};function zRe(n,e,t,r){return xte(n,"",e,t,r)}function xte(n,e,t,r,i){let o=Ut();return{id:o,thid:o,from:t,typ:"application/iden3comm-plain-json",type:at.AUTHORIZATION_REQUEST_MESSAGE_TYPE,body:{accept:i?.accept,reason:n,message:e,callbackUrl:r,scope:i?.scope??[]},created_time:Lt(new Date),expires_time:i?.expires_time?Lt(i.expires_time):void 0,attachments:i?.attachments}}var aF=class extends Ni{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=Object.values(Lc);handle(t,r){switch(t.type){case at.AUTHORIZATION_REQUEST_MESSAGE_TYPE:return this.handleAuthRequest(t,r);case at.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!==at.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!==at.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for authorization request");let i=t.to?ve.parse(t.to):r.senderDid,o=Ut();if(!t.from)throw new Error("auth request should contain from field");let s=at.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,a=this.getSupportedMediaTypeByProfile(r,t.body.accept),c=ve.parse(t.from),u=await Zy(i,t?.body.scope,c,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits,bypassProofsCache:r.bypassProofsCache,allowExpiredCredentials:r.allowExpiredCredentials,credentials:r.credentials});return{id:o,typ:a,type:s,thid:t.thid??o,body:{message:t?.body?.message,scope:u},created_time:Lt(new Date),from:i.string(),to:t.from}}async handleAuthorizationRequest(t,r,i){let o=await this.parseAuthorizationRequest(r);i?.allowExpiredMessages||Lr(o),i||(i={mediaType:"application/iden3-zkp-json"});let s=o.to?ve.parse(o.to):t,a=await this.handleAuthRequest(o,{senderDid:s,mediaType:i.mediaType,bypassProofsCache:i.bypassProofsCache,allowExpiredCredentials:i.allowExpiredCredentials}),c=ke.encode(JSON.stringify(a)),u=ta(i.mediaType,i.packerOptions,{provingMethodAlg:XO(this._packerMgr,i.preferredAuthProvingMethod,o.body.accept),senderDID:s}),l=lt.decode(await this._packerMgr.pack(i.mediaType,c,u));return{authRequest:o,authResponse:a,token:l}}async handleAuthResponse(t,r){let i=r.request;if(t.type!==at.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 u=c.query?.groupId,l=s.find(w=>w.id.toString()===c.id.toString());if(!l){if(c.optional)continue;throw new Error(`proof is not given for requestId ${c.id}`)}let d=D6(c.circuitId);if(!d.includes(l.circuitId))throw new Error(`proof is not given for requested circuit expected: ${d.join(", ")}, given ${l.circuitId} `);let h=c.params??{};h.verifierDid=ve.parse(i.from);let f=[r.acceptedProofGenerationDelay,r.acceptedStateTransitionDelay].some(w=>w!==void 0)?{acceptedProofGenerationDelay:r.acceptedProofGenerationDelay,acceptedStateTransitionDelay:r.acceptedStateTransitionDelay}:void 0,{linkID:m}=await this._proofService.verifyZKPResponse(l,{query:c.query,sender:t.from,params:h,opts:f});m&&u&&a.set(u,[...a.get(u)??[],{linkID:m.toString(),requestId:l.id}])}for(let[c,u]of a.entries())if(u.some(l=>l.linkID!==u[0].linkID))throw new Error(`Link id validation failed for group ${c}, request linkID to requestIds info: ${JSON.stringify(u)}`);return t}async handleAuthorizationResponse(t,r,i){i?.allowExpiredMessages||Lr(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;if(!s)continue;let a=s.groupId;if(a){let c=r[a]??[];for(let u of c){let l=u.query;if(!l)continue;if(l.type!==s?.type)throw new Error("all requests in the group should have the same type");if(l.context!==s?.context)throw new Error("all requests in the group should have the same context");let d=s?.allowedIssuers,h=l.allowedIssuers;if(!(d.includes("*")||d.every(f=>h.includes(f))))throw new Error("all requests in the group should have the same issuer")}r[a]=[...r[a]??[],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}=vs(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}};var vte=[{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 lI=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new jt(e.url);let i=new Ln(t,vte,this._provider);this._signer&&(this._signer=this._signer.connect(this._provider),i=i.connect(this._signer)),this._contract=i,this._transactionService=new Xs(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()}),kt.fromJSON({existence:e.existence,node_aux:t,siblings:r})}};function jRe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function WRe(n){return(jRe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function Xy(n,e){return WRe(n).includes(e)}function z0(n){return Xy(n,Ue.ERRORS.IDENTITY_DOES_NOT_EXIST)||Xy(n,Ue.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function cF(n){return Xy(n,Ue.ERRORS.STATE_DOES_NOT_EXIST)||Xy(n,Ue.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function uF(n){return Xy(n,Ue.ERRORS.ROOT_DOES_NOT_EXIST)||Xy(n,Ue.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var lF=class{constructor(e,t){this._configs=e;this._stateStorage=new dI(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=ve.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(!z0(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(!mf(t,f))throw new Error(`latest state not found and state parameter ${s} is not genesis state`);c=f}let u=ve.idFromDID(t);return await this._getOnChainRevocationStorageForIssuer(i,r).getRevocationStatusByIdAndState(u.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],u=r.searchParams.get("revocationNonce")||e.revocationNonce;if(u==null)throw new Error("revocationNonce not found in credentialStatus id field");let l=typeof u=="number"?u:parseInt(u,10);return{contractAddress:c,chainId:a,revocationNonce:l,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 lI(r,t)}};var Y0=class{async resolve(e){let r=await(await fetch(e.id)).json();return y8(r)}},y8=({issuer:n,mtp:e})=>({mtp:kt.fromJSON(e),issuer:n});var j0=class n{constructor(e=Ne,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 dF=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 Y0().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=ve.idFromDID(t),s;try{let l=await this._state.getLatestStateById(o.bigInt());if(!l.state)throw new Error("state contract returned empty state");s=l.state}catch(l){if(!z0(l))throw l;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=be.fromHex(d).bigInt(),f=wp(t);if(!f&&!mf(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)),u=be.fromBigInt(s);return await this.getRevocationStatusFromRHS(c,u,a)}getRevocationStatusFromIssuerData(e,t,r){if(r&&mf(e,r.value.bigInt()))return{mtp:new kt,issuer:{state:r.value.hex(),revocationTreeRoot:r.revocationTreeRoot.hex(),rootOfRoots:r.rootOfRoots.hex(),claimsTreeRoot:r.claimsTreeRoot.hex()}};if(t&&mf(e,t.state.value))return{mtp:new kt,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,u]=o.children,l=be.fromHex(c);return{mtp:await this.rhsGenerateProof(l,e,`${r}/node`),issuer:{state:s,claimsTreeRoot:a,revocationTreeRoot:c,rootOfRoots:u}}}async rhsGenerateProof(e,t,r){let i=!1,o=[],s,a=()=>new kt({siblings:o,existence:i,nodeAux:s}),c=e;for(let u=0;u<t.bytes.length*8;u++){if(c.bytes.every(f=>f===0))return a();let d=(await(await fetch(`${r}/${c.hex()}`)).json())?.node,h=j0.fromHex(d);switch(h.nodeType()){case 2:return t.bytes.every((f,m)=>f===h.children[0].bytes[m])?(i=!0,a()):(s={key:h.children[0],value:h.children[1]},a());case 1:Iw(t.bytes,u)?(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 ZRe(n,e){let t=ve.parse(n),r=ve.idFromDID(t),{method:i,blockchain:o,networkId:s}=ve.decodePartsFromId(r),a=It.hexToBytes(e),c=It.bytesToInt(a),u=Wc(i,o,s);return Ste(ve.idFromDID(t).bigInt(),c,u)}function Ste(n,e,t){let r=Xe.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var fI=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var hI=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=XRe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return y8(a.body)}};function XRe(n,e,t){return{id:Ut(),typ:"application/iden3comm-plain-json",type:at.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE,body:{revocation_nonce:t},thid:Ut(),from:n,to:e}}var pI=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)}},fF=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=pb.getInstance();r.then(s=>o.publish(NR.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},W0=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 hF=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 pF=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new fI,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new Y0),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new hI))}getCredentialStatusResolverRegistry(){return this._credentialStatusResolverRegistry}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:Ue.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ue.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(Ue.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:Ue.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ue.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=ve.parse(e.issuer),s=Xl(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(Ue.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(Ue.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:${Ut()}`,i.issuanceDate=i.issuanceDate?i.issuanceDate*1e3:Date.now(),Er.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(Ue.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function w8(n,e,t,r){let i=await b8(r,e,n);await new W0().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function b8(n,e,t){let r=new mF;return n&&await $Re(r,e,n),await _Re(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new j0(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function _Re(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function $Re(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var mF=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 Xc(o,s),c=await eDe(i,a);for(let u of c)this.seen.get(u.hash.hex())||(this.nodes.push(u),this.seen.set(u.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 eDe(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 j0;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=Iw(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=Rh([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var gF=class n extends Ni{constructor(t,r){super();this._packerMgr=t;this.opts=r}async handle(t,r){switch(t.type){case at.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 at.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:return this.handleFetchRequest(t);case at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:return this.handleIssuanceResponseMsg(t);case at.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}case at.ENCRYPTED_CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:return await this.handleEncryptedIssuanceResponseMessage(t),null;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=ve.parse(t.from),s=ve.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=Ut(),a={id:s,typ:r.mediaType,type:at.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE,thid:t.thid??s,body:{id:o.id},from:t.to,to:t.from},c=ke.encode(JSON.stringify(a)),u=ve.parse(t.to),l=ta(r.mediaType,r.packerOptions,{senderDID:u}),d=lt.decode(await this._packerMgr.pack(r.mediaType,c,l));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":pM[r.mediaType],...r.headers},body:d})).arrayBuffer();if(!f.byteLength)throw new Error(`could not fetch , ${o?.id}, response is empty`);let{unpackedMessage:m}=await this._packerMgr.unpack(new Uint8Array(f));if(m.type===at.ENCRYPTED_CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE)return await this.handleEncryptedIssuanceResponseMessage(m),[];if(m.type!==at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE)return m;i.push(Er.fromJSON(m.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,at.CREDENTIAL_OFFER_MESSAGE_TYPE);r?.allowExpiredMessages||Lr(i);let o=r?.mediaType||"application/iden3-zkp-json",s=ta(o,r?.packerOptions,{provingMethodAlg:r?.messageProvingMethodAlg||await qc(t),senderDID:ve.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,at.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=ve.parse(t.to),i=ve.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(Xl(r,s).string()!==i.string())throw new Error("credential subject is not a sender DID");return{id:Ut(),type:at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE,typ:t.typ??"application/iden3comm-plain-json",thid:t.thid??Ut(),body:{credential:s},from:t.to,to:t.from}}async handleCredentialFetchRequest(t,r){let i=await n.unpackMessage(this._packerMgr,t,at.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);r?.allowExpiredMessages||Lr(i);let o=await this.handleFetchRequest(i);return this._packerMgr.pack("application/iden3comm-plain-json",ke.encode(JSON.stringify(o)),{})}async handleEncryptedIssuanceResponseMessage(t){if(!this.opts?.joseService)throw new Error("JoseService is not initialized. Encrypted issuance response cannot be handled");let{plaintext:r}=await this.opts.joseService.decrypt(t.body.data),i=Er.fromJSON({...JSON.parse(lt.decode(r)),proof:t.body.proof});if(!this.opts?.credentialWallet)throw new Error("please provide credential wallet in options for encrypted issuance response handling");if(!this.opts?.didResolverUrl)throw new Error("please provide resolver URL in options for encrypted issuance response handling");if(!this.opts?.merklizeOptions)throw new Error("please provide merklize options for encrypted issuance response handling");let o=this.opts.credentialWallet.getCredentialStatusResolverRegistry();if(!o)throw new Error("credential status resolver registry is not available in credential wallet");if(!await i.verifyProofs(this.opts.didResolverUrl,{credStatusResolverRegistry:o,merklizeOptions:this.opts.merklizeOptions}))throw new Error("credential proof verification failed");return await this.opts?.credentialWallet?.save(i),null}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");let r=t.body.credential;if(!(r instanceof Er)){if(typeof r!="object"||r===null)throw new Error("credential object is not properly unmarshaled");r=Er.fromJSON(r)}return await this.opts.credentialWallet.save(r),null}async handleIssuanceResponseMessage(t,r){let i=await n.unpackMessage(this._packerMgr,t,at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);return r?.allowExpiredMessages||Lr(i),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 yF=class extends Ni{constructor(t,r,i){super();this._packerMgr=t;this._proofService=r;this._zkpVerifier=i}_supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","credentialAtomicQueryV3OnChain","authV2","authV3","authV3-8-32","linkedMultiQuery10-beta.1","credentialAtomicQueryV3","linkedMultiQuery"];async handle(t,r){switch(t.type){case at.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!==at.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 u=t.from?ve.parse(t.from):void 0,{scope:l=[]}=t.body,d=await Zy(i,l,u,this._proofService,{ethSigner:o,challenge:s??It.bytesToInt(di(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),m=new Map;for(let[w,b]of f)m.set(w,{responses:b});return t.body.transaction_data.txHash=f.keys().next().value,m}case"b68967e2":{let f=await this._zkpVerifier.submitZKPResponse(o,t.body.transaction_data,d),m=new Map;for(let[w,b]of f)m.set(w,{responses:[b]});return t.body.transaction_data.txHash=f.keys().next().value,m}case"06c86a91":{if(!t.to)throw new Error("failed message. empty 'to' field");let f=sF(at.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE,this._packerMgr,t.body.accept),m=ve.parse(t.to),{authProof:w}=await oF(m,this._proofService,{supportedCircuits:this._supportedCircuits,acceptProfile:f,senderAddress:await o.getAddress(),zkpResponses:d}),b=await this._zkpVerifier.submitResponse(o,t.body.transaction_data,d,w);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.'")}}async parseContractInvokeRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==at.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:at.CONTRACT_INVOKE_RESPONSE_MESSAGE_TYPE,from:t.to,to:t.from,body:{transaction_data:t.body.transaction_data,scope:[]},created_time:Lt(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||Lr(o),o.body.transaction_data.method_id!=="b68967e2")throw new Error("please use handle method to work with other method ids");if(o.type!==at.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 l=o.from?ve.parse(o.from):void 0,d=await Zy(t,o?.body?.scope,l,this._proofService,{ethSigner:s,challenge:a,supportedCircuits:this._supportedCircuits});return this._zkpVerifier.submitZKPResponse(s,o.body.transaction_data,d)}};var wF=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=ve.parse(r),o=t?.mediaType||"application/iden3-zkp-json",s=t?.packerOptions??{senderDID:i,provingMethodAlg:Jc},a={id:Ut(),typ:"application/iden3-zkp-json",type:at.CREDENTIAL_REFRESH_MESSAGE_TYPE,thid:Ut(),body:{id:e.id,reason:t?.reason??"credential is expired"},from:r,to:e.issuer},c=ke.encode(JSON.stringify(a)),u=await this._options.packageManager.pack(o,c,s),l=await fetch(e.refreshService.id,{method:"post",headers:{"Content-Type":"application/json"},body:u.buffer});if(l.status!==200)throw new Error(`could not refresh W3C credential, return status ${l.status}`);let d=await l.json();if(!d.body?.credential)throw new Error("no credential in CredentialIssuanceMessage response");return Er.fromJSON(d.body.credential)}};var bF=class extends Ni{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 at.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=ve.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=Ut();return{id:c,typ:"application/iden3comm-plain-json",type:at.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!==at.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||Lr(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=ve.parse(o.to),c=ta(i.mediaType,i.packerOptions,{senderDID:a,provingMethodAlg:i.packerOptions?.provingMethodAlg||await qc(r)});return this._packerMgr.pack(i.mediaType,ke.encode(JSON.stringify(s)),c)}};function tDe(n,e,t){let r=Ut();return{id:r,thid:r,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PROPOSAL_REQUEST_MESSAGE_TYPE,body:{credentials:t.credentials,did_doc:t.did_doc},created_time:Lt(new Date),expires_time:t?.expires_time?Lt(t.expires_time):void 0,attachments:t.attachments}}function nDe(n,e,t,r){let i=Ut();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PROPOSAL_MESSAGE_TYPE,body:{proposals:t||[]},created_time:Lt(new Date),expires_time:r?.expires_time?Lt(r.expires_time):void 0}}var EF=class extends Ni{constructor(t,r,i){super();this._packerMgr=t;this._identityWallet=r;this._params=i}async handle(t,r){switch(t.type){case at.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!==at.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=[];if(!r?.forceCredentialReissue){try{c=await this._identityWallet.credentialWallet.findByQuery({credentialSubject:{id:{$eq:t.from}},type:a.type,context:a.context,allowedIssuers:[t.to]})}catch(l){if(l.message!=="no credential satisfied query")throw l}if(c=c.filter(l=>!l.expirationDate||new Date(l.expirationDate)>new Date),c.length){let l=Ut();i||(i={id:l,typ:this._params.packerParams.mediaType,type:at.CREDENTIAL_OFFER_MESSAGE_TYPE,thid:t.thid??l,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 u=await this._params.proposalResolverFn(a.context,a.type,{msg:t});if(!u)throw new Error(`can't resolve Proposal for type: ${a.type}, context: ${a.context}`);if(!o){let l=Ut();o={id:l,typ:this._params.packerParams.mediaType,type:at.PROPOSAL_MESSAGE_TYPE,thid:t.thid??l,body:{proposals:[]},from:t.to,to:t.from}}o.body?.proposals.push(u)}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||Lr(i);let o=ve.parse(i.from),s=await this.handleProposalRequestMessage(i),a=ke.encode(JSON.stringify(s)),c=ta(this._params.packerParams.mediaType,this._params.packerParams.packerOptions,{provingMethodAlg:await qc(t),senderDID:o});return this._packerMgr.pack(this._params.packerParams.mediaType,a,c)}async handleProposal(t,r){if(r?.allowExpiredMessages||Lr(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 Cte(n,e,t,r,i){let o=Ut();return{id:o,thid:o,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PAYMENT_REQUEST_MESSAGE_TYPE,body:{agent:t,payments:r},created_time:Lt(new Date),expires_time:i?.expires_time?Lt(i.expires_time):void 0}}function Lte(n,e,t,r){let i=Ut();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PAYMENT_MESSAGE_TYPE,body:{payments:t},created_time:Lt(new Date),expires_time:r?.expires_time?Lt(r.expires_time):void 0}}var IF=class extends Ni{constructor(t,r){super();this._packerMgr=t;this._params=r}async handle(t,r){switch(t.type){case at.PAYMENT_REQUEST_MESSAGE_TYPE:return await this.handlePaymentRequestMessage(t,r);case at.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!==at.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=ve.parse(t.to),o=ve.parse(t.from),s=[];for(let m=0;m<t.body.payments.length;m++){let{data:w}=t.body.payments[m],b=Array.isArray(w)?w.find(S=>S.type==="Iden3PaymentRequestCryptoV1"?S.id===r.nonce:S.nonce===r.nonce):w;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=Lte(i,o,s),c=r?.mediaType||this._params.packerParams.mediaType||"application/iden3-zkp-json",u=ta(c,r?.packerOptions||this._params.packerParams,{senderDID:i,provingMethodAlg:r.messageProvingMethodAlg}),l=await this.packMessage(a,i,c,u),h=await(await fetch(t.body.agent,{method:"POST",body:l.buffer,headers:{...r.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||Lr(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=ve.parse(i.to);r.packerOptions=ta(o,r.packerOptions,{provingMethodAlg:await qc(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||Lr(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(u=>Array.isArray(u.data)?u.data:[u.data]).flat().find(u=>u.type==="Iden3PaymentRequestCryptoV1"?u.id===s:u.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 u=0;u<s.length;u++){let{credentials:l,description:d}=s[u],h=[];for(let f=0;f<s[u].options.length;f++){let{nonce:m,amount:w,chainId:b,optionId:S,expirationDate:R}=s[u].options[f],G=this._params.multiChainPaymentConfig?.find(z=>z.chainId===b);if(!G)throw new Error(`failed request. no config for chain ${b}`);let{recipient:U,paymentRails:H,options:M}=G,A=M.find(z=>z.id===S);if(!A)throw new Error(`failed request. no option for id ${S}`);if((A.type==="Iden3PaymentRailsERC20RequestV1"||A.type==="Iden3PaymentRailsSolanaSPLRequestV1")&&!A.contractAddress)throw new Error(`failed request. no token address for option id ${S}`);let T=R??new Date(new Date().setHours(new Date().getHours()+1));if(A.type==="Iden3PaymentRailsSolanaRequestV1"||A.type==="Iden3PaymentRailsSolanaSPLRequestV1"){if(!a?.solSigner)throw new Error(`please provide solana signer in context for ${A.type} payment type`);let z=await OB(a.solSigner,A,b,H,U,BigInt(w),T,m);h.push(z)}else{let z=await FB(o,A,b,H,U,BigInt(w),T,m);h.push(z)}}c.push({data:h,credentials:l,description:d})}return Cte(t,r,i,c)}async packMessage(t,r,i,o){let s=ke.encode(JSON.stringify(t)),a=i==="application/iden3comm-signed-json"?o:{provingMethodAlg:o?.provingMethodAlg||Jc};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 gS(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 mS(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 mS(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 gS(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 rDe(n,e){let t=Ut();return{id:t,thid:t,typ:"application/iden3comm-plain-json",type:at.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE,body:{queries:n},from:e?.from,to:e?.to,created_time:Lt(new Date),expires_time:e?.expires_time}}function Rte(n,e){let t=Ut();return{id:t,typ:"application/iden3comm-plain-json",thid:t,type:at.DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE,body:{disclosures:n},from:e?.from,to:e?.to,created_time:Lt(new Date),expires_time:e?.expires_time}}var AF=class extends Ni{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 at.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:return await this.handleDiscoveryQuery(t,r);default:return super.handle(t,r)}}async handleDiscoveryQuery(t,r){r?.allowExpiredMessages||Lr(t);let i=[];for(let o of t.body.queries)i.push(...this.handleQuery(o));return Promise.resolve(Rte(i,{to:t.from,from:t.to,expires_time:r?.disclosureExpiresDate?Lt(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 Dte(n,e){return{id:Ut(),pthid:e?.pthid,typ:"application/iden3comm-plain-json",type:at.PROBLEM_REPORT_MESSAGE_TYPE,ack:e?.ack,body:{code:n,comment:e?.comment,args:e?.args,escalate_to:e?.escalate_to},from:e?.from,to:e?.to}}function iDe(n,e,t){return Dte(e,{pthid:n,...t})}var Tte=new TextEncoder,Z0=new TextDecoder,E8=2**32;function Ss(...n){let e=n.reduce((i,{length:o})=>i+o,0),t=new Uint8Array(e),r=0;for(let i of n)t.set(i,r),r+=i.length;return t}function xF(n,e,t){if(e<0||e>=E8)throw new RangeError(`value must be >= 0 and <= ${E8-1}. Received ${e}`);n.set([e>>>24,e>>>16,e>>>8,e&255],t)}function I8(n){let e=Math.floor(n/E8),t=n%E8,r=new Uint8Array(8);return xF(r,e,0),xF(r,t,4),r}function A8(n){let e=new Uint8Array(4);return xF(e,n),e}function Ja(n){let e=new Uint8Array(n.length);for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r>127)throw new TypeError("non-ASCII string encountered in encode()");e[t]=r}return e}function Bte(n){if(Uint8Array.prototype.toBase64)return n.toBase64();let e=32768,t=[];for(let r=0;r<n.length;r+=e)t.push(String.fromCharCode.apply(null,n.subarray(r,r+e)));return btoa(t.join(""))}function Pte(n){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(n);let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Zr(n){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof n=="string"?n:Z0.decode(n),{alphabet:"base64url"});let e=n;e instanceof Uint8Array&&(e=Z0.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Pte(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Xr(n){let e=n;return typeof e=="string"&&(e=Tte.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Bte(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var _y=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var mI=class extends _y{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Xt=class extends _y{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Ih=class extends _y{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}},Ve=class extends _y{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"};function vF(n){switch(n){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new Xt(`Unsupported JWE Algorithm: ${n}`)}}var kte=n=>crypto.getRandomValues(new Uint8Array(vF(n)>>3));function x8(n,e){if(e.length<<3!==vF(n))throw new Ve("Invalid Initialization Vector length")}function $y(n,e){let t=n.byteLength<<3;if(t!==e)throw new Ve(`Invalid Content Encryption Key length. Expected ${e} bits, got ${t} bits`)}var Ah=(n,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${n}`),v8=(n,e)=>n.name===e;function oDe(n){return parseInt(n.name.slice(4),10)}function sDe(n,e){if(e&&!n.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Cs(n,e,t){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!v8(n.algorithm,"AES-GCM"))throw Ah("AES-GCM");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw Ah(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!v8(n.algorithm,"AES-KW"))throw Ah("AES-KW");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw Ah(r,"algorithm.length");break}case"ECDH":{switch(n.algorithm.name){case"ECDH":case"X25519":break;default:throw Ah("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!v8(n.algorithm,"PBKDF2"))throw Ah("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!v8(n.algorithm,"RSA-OAEP"))throw Ah("RSA-OAEP");let r=parseInt(e.slice(9),10)||1;if(oDe(n.algorithm.hash)!==r)throw Ah(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}sDe(n,t)}function Mte(n,e,...t){if(t=t.filter(Boolean),t.length>2){let r=t.pop();n+=`one of type ${t.join(", ")}, or ${r}.`}else t.length===2?n+=`one of type ${t[0]} or ${t[1]}.`:n+=`of type ${t[0]}.`;return e==null?n+=` Received ${e}`:typeof e=="function"&&e.name?n+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(n+=` Received an instance of ${e.constructor.name}`),n}var xh=(n,...e)=>Mte("Key must be ",n,...e),SF=(n,e,...t)=>Mte(`Key for the ${n} algorithm must be `,e,...t);function X0(n){if(!Vu(n))throw new Error("CryptoKey instance expected")}var Vu=n=>{if(n?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return n instanceof CryptoKey}catch{return!1}},gI=n=>n?.[Symbol.toStringTag]==="KeyObject",CF=n=>Vu(n)||gI(n);async function aDe(n,e){if(!(n instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let t={name:"HMAC",hash:"SHA-256"},r=await crypto.subtle.generateKey(t,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(t,r,n)),o=new Uint8Array(await crypto.subtle.sign(t,r,e)),s=0,a=-1;for(;++a<32;)s|=i[a]^o[a];return s===0}async function cDe(n,e,t,r,i,o){if(!(e instanceof Uint8Array))throw new TypeError(xh(e,"Uint8Array"));let s=parseInt(n.slice(1,4),10),a=await crypto.subtle.importKey("raw",e.subarray(s>>3),"AES-CBC",!1,["decrypt"]),c=await crypto.subtle.importKey("raw",e.subarray(0,s>>3),{hash:`SHA-${s<<1}`,name:"HMAC"},!1,["sign"]),u=Ss(o,r,t,I8(o.length<<3)),l=new Uint8Array((await crypto.subtle.sign("HMAC",c,u)).slice(0,s>>3)),d;try{d=await aDe(i,l)}catch{}if(!d)throw new Ih;let h;try{h=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:"AES-CBC"},a,t))}catch{}if(!h)throw new Ih;return h}async function uDe(n,e,t,r,i,o){let s;e instanceof Uint8Array?s=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):(Cs(e,n,"decrypt"),s=e);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:r,name:"AES-GCM",tagLength:128},s,Ss(t,i)))}catch{throw new Ih}}async function S8(n,e,t,r,i,o){if(!Vu(e)&&!(e instanceof Uint8Array))throw new TypeError(xh(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!r)throw new Ve("JWE Initialization Vector missing");if(!i)throw new Ve("JWE Authentication Tag missing");switch(x8(n,r),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&$y(e,parseInt(n.slice(-3),10)),cDe(n,e,t,r,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&$y(e,parseInt(n.slice(1,4),10)),uDe(n,e,t,r,i,o);default:throw new Xt("Unsupported JWE Content Encryption Algorithm")}}function ew(...n){let e=n.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(let r of e){let i=Object.keys(r);if(!t||t.size===0){t=new Set(i);continue}for(let o of i){if(t.has(o))return!1;t.add(o)}}return!0}var lDe=n=>typeof n=="object"&&n!==null;function Zo(n){if(!lDe(n)||Object.prototype.toString.call(n)!=="[object Object]")return!1;if(Object.getPrototypeOf(n)===null)return!0;let e=n;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(n)===e}function Ote(n,e){if(n.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function Fte(n,e,t){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"AES-KW",!0,[t]):(Cs(n,e,t),n)}async function yI(n,e,t){let r=await Fte(e,n,"wrapKey");Ote(r,n);let i=await crypto.subtle.importKey("raw",t,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,r,"AES-KW"))}async function wI(n,e,t){let r=await Fte(e,n,"unwrapKey");Ote(r,n);let i=await crypto.subtle.unwrapKey("raw",t,r,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}async function Nte(n,e){let t=`SHA-${n.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(t,e))}function RF(n){return Ss(A8(n.length),n)}async function dDe(n,e,t){let r=e>>3,i=32,o=Math.ceil(r/i),s=new Uint8Array(o*i);for(let a=1;a<=o;a++){let c=new Uint8Array(4+n.length+t.length);c.set(A8(a),0),c.set(n,4),c.set(t,4+n.length);let u=await Nte("sha256",c);s.set(u,(a-1)*i)}return s.slice(0,r)}async function C8(n,e,t,r,i=new Uint8Array,o=new Uint8Array){Cs(n,"ECDH"),Cs(e,"ECDH","deriveBits");let s=RF(Ja(t)),a=RF(i),c=RF(o),u=A8(r),l=new Uint8Array,d=Ss(s,a,c,u,l),h=new Uint8Array(await crypto.subtle.deriveBits({name:n.algorithm.name,public:n},e,fDe(n)));return dDe(h,r,d)}function fDe(n){return n.algorithm.name==="X25519"?256:Math.ceil(parseInt(n.algorithm.namedCurve.slice(-3),10)/8)<<3}function L8(n){switch(n.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return n.algorithm.name==="X25519"}}function hDe(n,e){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits"]):(Cs(n,e,"deriveBits"),n)}var pDe=(n,e)=>Ss(Ja(n),Uint8Array.of(0),e);async function Gte(n,e,t,r){if(!(n instanceof Uint8Array)||n.length<8)throw new Ve("PBES2 Salt Input must be 8 or more octets");let i=pDe(e,n),o=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:t,name:"PBKDF2",salt:i},a=await hDe(r,e);return new Uint8Array(await crypto.subtle.deriveBits(s,a,o))}async function Hte(n,e,t,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let o=await Gte(i,n,r,e);return{encryptedKey:await yI(n.slice(-6),o,t),p2c:r,p2s:Xr(i)}}async function Kte(n,e,t,r,i){let o=await Gte(i,n,r,e);return wI(n.slice(-6),o,t)}function DF(n,e){if(n.startsWith("RS")||n.startsWith("PS")){let{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${n} requires key modulusLength to be 2048 bits or larger`)}}var qte=n=>{switch(n){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Xt(`alg ${n} is not supported either by JOSE or your javascript runtime`)}};async function Vte(n,e,t){return Cs(e,n,"encrypt"),DF(n,e),new Uint8Array(await crypto.subtle.encrypt(qte(n),e,t))}async function Qte(n,e,t){return Cs(e,n,"decrypt"),DF(n,e),new Uint8Array(await crypto.subtle.decrypt(qte(n),e,t))}function bI(n){switch(n){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new Xt(`Unsupported JWE Algorithm: ${n}`)}}var Qu=n=>crypto.getRandomValues(new Uint8Array(bI(n)>>3));function mDe(n){let e,t;switch(n.kty){case"AKP":{switch(n.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:n.alg},t=n.priv?["sign"]:["verify"];break;default:throw new Xt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(n.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${n.alg.slice(-3)}`},t=n.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.alg.slice(-3)}`},t=n.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(n.alg.slice(-3),10)||1}`},t=n.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Xt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(n.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=n.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=n.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=n.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:n.crv},t=n.d?["deriveBits"]:[];break;default:throw new Xt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(n.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},t=n.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:n.crv},t=n.d?["deriveBits"]:[];break;default:throw new Xt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new Xt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}async function tw(n){if(!n.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:t}=mDe(n),r={...n};return r.kty!=="AKP"&&delete r.alg,delete r.use,crypto.subtle.importKey("jwk",r,e,n.ext??!(n.d||n.priv),n.key_ops??t)}async function Yte(n,e,t){if(!Zo(n))throw new TypeError("JWK must be an object");let r;switch(e??=n.alg,r??=t?.extractable??n.ext,n.kty){case"oct":if(typeof n.k!="string"||!n.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Zr(n.k);case"RSA":if("oth"in n&&n.oth!==void 0)throw new Xt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return tw({...n,alg:e,ext:r});case"AKP":{if(typeof n.alg!="string"||!n.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==n.alg)throw new TypeError("JWK alg and alg option value mismatch");return tw({...n,ext:r})}case"EC":case"OKP":return tw({...n,alg:e,ext:r});default:throw new Xt('Unsupported "kty" (Key Type) Parameter value')}}async function gDe(n,e,t,r,i){if(!(t instanceof Uint8Array))throw new TypeError(xh(t,"Uint8Array"));let o=parseInt(n.slice(1,4),10),s=await crypto.subtle.importKey("raw",t.subarray(o>>3),"AES-CBC",!1,["encrypt"]),a=await crypto.subtle.importKey("raw",t.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:"AES-CBC"},s,e)),u=Ss(i,r,c,I8(i.length<<3)),l=new Uint8Array((await crypto.subtle.sign("HMAC",a,u)).slice(0,o>>3));return{ciphertext:c,tag:l,iv:r}}async function yDe(n,e,t,r,i){let o;t instanceof Uint8Array?o=await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt"]):(Cs(t,n,"encrypt"),o=t);let s=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:"AES-GCM",tagLength:128},o,e)),a=s.slice(-16);return{ciphertext:s.slice(0,-16),tag:a,iv:r}}async function R8(n,e,t,r,i){if(!Vu(t)&&!(t instanceof Uint8Array))throw new TypeError(xh(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(r?x8(n,r):r=kte(n),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&$y(t,parseInt(n.slice(-3),10)),gDe(n,e,t,r,i);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&$y(t,parseInt(n.slice(1,4),10)),yDe(n,e,t,r,i);default:throw new Xt("Unsupported JWE Content Encryption Algorithm")}}async function jte(n,e,t,r){let i=n.slice(0,7),o=await R8(i,t,e,r,new Uint8Array);return{encryptedKey:o.ciphertext,iv:Xr(o.iv),tag:Xr(o.tag)}}async function Wte(n,e,t,r,i){let o=n.slice(0,7);return S8(o,e,t,r,i,new Uint8Array)}async function Zte(n,e,t,r,i){switch(n){case"dir":{if(t!==void 0)throw new Ve("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(t!==void 0)throw new Ve("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Zo(r.epk))throw new Ve('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(X0(e),!L8(e))throw new Xt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await Yte(r.epk,n);X0(o);let s,a;if(r.apu!==void 0){if(typeof r.apu!="string")throw new Ve('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{s=Zr(r.apu)}catch{throw new Ve("Failed to base64url decode the apu")}}if(r.apv!==void 0){if(typeof r.apv!="string")throw new Ve('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{a=Zr(r.apv)}catch{throw new Ve("Failed to base64url decode the apv")}}let c=await C8(o,e,n==="ECDH-ES"?r.enc:n,n==="ECDH-ES"?bI(r.enc):parseInt(n.slice(-5,-2),10),s,a);if(n==="ECDH-ES")return c;if(t===void 0)throw new Ve("JWE Encrypted Key missing");return wI(n.slice(-6),c,t)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");return X0(e),Qte(n,e,t)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");if(typeof r.p2c!="number")throw new Ve('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(r.p2c>o)throw new Ve('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof r.p2s!="string")throw new Ve('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let s;try{s=Zr(r.p2s)}catch{throw new Ve("Failed to base64url decode the p2s")}return Kte(n,e,t,r.p2c,s)}case"A128KW":case"A192KW":case"A256KW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");return wI(n,e,t)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");if(typeof r.iv!="string")throw new Ve('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof r.tag!="string")throw new Ve('JOSE Header "tag" (Authentication Tag) missing or invalid');let o;try{o=Zr(r.iv)}catch{throw new Ve("Failed to base64url decode the iv")}let s;try{s=Zr(r.tag)}catch{throw new Ve("Failed to base64url decode the tag")}return Wte(n,e,t,o,s)}default:throw new Xt('Invalid or unsupported "alg" (JWE Algorithm) header value')}}function nw(n,e,t,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new n('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(s=>typeof s!="string"||s.length===0))throw new n('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;t!==void 0?o=new Map([...Object.entries(t),...e.entries()]):o=e;for(let s of r.crit){if(!o.has(s))throw new Xt(`Extension Header Parameter "${s}" is not recognized`);if(i[s]===void 0)throw new n(`Extension Header Parameter "${s}" is missing`);if(o.get(s)&&r[s]===void 0)throw new n(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(r.crit)}function TF(n,e){if(e!==void 0&&(!Array.isArray(e)||e.some(t=>typeof t!="string")))throw new TypeError(`"${n}" option must be an array of strings`);if(e)return new Set(e)}var EI=n=>Zo(n)&&typeof n.kty=="string",Xte=n=>n.kty!=="oct"&&(n.kty==="AKP"&&typeof n.priv=="string"||typeof n.d=="string"),_te=n=>n.kty!=="oct"&&n.d===void 0&&n.priv===void 0,$te=n=>n.kty==="oct"&&typeof n.k=="string";var rw,ene=async(n,e,t,r=!1)=>{rw||=new WeakMap;let i=rw.get(n);if(i?.[t])return i[t];let o=await tw({...e,alg:t});return r&&Object.freeze(n),i?i[t]=o:rw.set(n,{[t]:o}),o},bDe=(n,e)=>{rw||=new WeakMap;let t=rw.get(n);if(t?.[e])return t[e];let r=n.type==="public",i=!!r,o;if(n.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}o=n.toCryptoKey(n.asymmetricKeyType,i,r?[]:["deriveBits"])}if(n.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=n.toCryptoKey(n.asymmetricKeyType,i,[r?"verify":"sign"])}switch(n.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==n.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=n.toCryptoKey(n.asymmetricKeyType,i,[r?"verify":"sign"])}}if(n.asymmetricKeyType==="rsa"){let s;switch(e){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(e.startsWith("RSA-OAEP"))return n.toCryptoKey({name:"RSA-OAEP",hash:s},i,r?["encrypt"]:["decrypt"]);o=n.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},i,[r?"verify":"sign"])}if(n.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(n.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError("given KeyObject instance cannot be used for this algorithm");e==="ES256"&&a==="P-256"&&(o=n.toCryptoKey({name:"ECDSA",namedCurve:a},i,[r?"verify":"sign"])),e==="ES384"&&a==="P-384"&&(o=n.toCryptoKey({name:"ECDSA",namedCurve:a},i,[r?"verify":"sign"])),e==="ES512"&&a==="P-521"&&(o=n.toCryptoKey({name:"ECDSA",namedCurve:a},i,[r?"verify":"sign"])),e.startsWith("ECDH-ES")&&(o=n.toCryptoKey({name:"ECDH",namedCurve:a},i,r?[]:["deriveBits"]))}if(!o)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return t?t[e]=o:rw.set(n,{[e]:o}),o};async function vh(n,e){if(n instanceof Uint8Array||Vu(n))return n;if(gI(n)){if(n.type==="secret")return n.export();if("toCryptoKey"in n&&typeof n.toCryptoKey=="function")try{return bDe(n,e)}catch(r){if(r instanceof TypeError)throw r}let t=n.export({format:"jwk"});return ene(n,t,e)}if(EI(n))return n.k?Zr(n.k):ene(n,n,e,!0);throw new Error("unreachable")}var iw=n=>n?.[Symbol.toStringTag],BF=(n,e,t)=>{if(e.use!==void 0){let r;switch(t){case"sign":case"verify":r="sig";break;case"encrypt":case"decrypt":r="enc";break}if(e.use!==r)throw new TypeError(`Invalid key for this operation, its "use" must be "${r}" when present`)}if(e.alg!==void 0&&e.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(e.key_ops)){let r;switch(!0){case(t==="sign"||t==="verify"):case n==="dir":case n.includes("CBC-HS"):r=t;break;case n.startsWith("PBES2"):r="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(n):!n.includes("GCM")&&n.endsWith("KW")?r=t==="encrypt"?"wrapKey":"unwrapKey":r=t;break;case(t==="encrypt"&&n.startsWith("RSA")):r="wrapKey";break;case t==="decrypt":r=n.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(r&&e.key_ops?.includes?.(r)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},EDe=(n,e,t)=>{if(!(e instanceof Uint8Array)){if(EI(e)){if($te(e)&&BF(n,e,t))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!CF(e))throw new TypeError(SF(n,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${iw(e)} instances for symmetric algorithms must be of type "secret"`)}},IDe=(n,e,t)=>{if(EI(e))switch(t){case"decrypt":case"sign":if(Xte(e)&&BF(n,e,t))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(_te(e)&&BF(n,e,t))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!CF(e))throw new TypeError(SF(n,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${iw(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(t){case"sign":throw new TypeError(`${iw(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${iw(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(t){case"verify":throw new TypeError(`${iw(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${iw(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function ow(n,e,t){switch(n.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":EDe(n,e,t);break;default:IDe(n,e,t)}}async function II(n,e,t){if(!Zo(n))throw new Ve("Flattened JWE must be an object");if(n.protected===void 0&&n.header===void 0&&n.unprotected===void 0)throw new Ve("JOSE Header missing");if(n.iv!==void 0&&typeof n.iv!="string")throw new Ve("JWE Initialization Vector incorrect type");if(typeof n.ciphertext!="string")throw new Ve("JWE Ciphertext missing or incorrect type");if(n.tag!==void 0&&typeof n.tag!="string")throw new Ve("JWE Authentication Tag incorrect type");if(n.protected!==void 0&&typeof n.protected!="string")throw new Ve("JWE Protected Header incorrect type");if(n.encrypted_key!==void 0&&typeof n.encrypted_key!="string")throw new Ve("JWE Encrypted Key incorrect type");if(n.aad!==void 0&&typeof n.aad!="string")throw new Ve("JWE AAD incorrect type");if(n.header!==void 0&&!Zo(n.header))throw new Ve("JWE Shared Unprotected Header incorrect type");if(n.unprotected!==void 0&&!Zo(n.unprotected))throw new Ve("JWE Per-Recipient Unprotected Header incorrect type");let r;if(n.protected)try{let U=Zr(n.protected);r=JSON.parse(Z0.decode(U))}catch{throw new Ve("JWE Protected Header is invalid")}if(!ew(r,n.header,n.unprotected))throw new Ve("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...r,...n.header,...n.unprotected};if(nw(Ve,new Map,t?.crit,r,i),i.zip!==void 0)throw new Xt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:o,enc:s}=i;if(typeof o!="string"||!o)throw new Ve("missing JWE Algorithm (alg) in JWE Header");if(typeof s!="string"||!s)throw new Ve("missing JWE Encryption Algorithm (enc) in JWE Header");let a=t&&TF("keyManagementAlgorithms",t.keyManagementAlgorithms),c=t&&TF("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms);if(a&&!a.has(o)||!a&&o.startsWith("PBES2"))throw new mI('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(s))throw new mI('"enc" (Encryption Algorithm) Header Parameter value not allowed');let u;if(n.encrypted_key!==void 0)try{u=Zr(n.encrypted_key)}catch{throw new Ve("Failed to base64url decode the encrypted_key")}let l=!1;typeof e=="function"&&(e=await e(r,n),l=!0),ow(o==="dir"?s:o,e,"decrypt");let d=await vh(e,o),h;try{h=await Zte(o,d,u,i,t)}catch(U){if(U instanceof TypeError||U instanceof Ve||U instanceof Xt)throw U;h=Qu(s)}let f,m;if(n.iv!==void 0)try{f=Zr(n.iv)}catch{throw new Ve("Failed to base64url decode the iv")}if(n.tag!==void 0)try{m=Zr(n.tag)}catch{throw new Ve("Failed to base64url decode the tag")}let w=n.protected!==void 0?Ja(n.protected):new Uint8Array,b;n.aad!==void 0?b=Ss(w,Ja("."),Ja(n.aad)):b=w;let S;try{S=Zr(n.ciphertext)}catch{throw new Ve("Failed to base64url decode the ciphertext")}let G={plaintext:await S8(s,h,S,f,m,b)};if(n.protected!==void 0&&(G.protectedHeader=r),n.aad!==void 0)try{G.additionalAuthenticatedData=Zr(n.aad)}catch{throw new Ve("Failed to base64url decode the aad")}return n.unprotected!==void 0&&(G.sharedUnprotectedHeader=n.unprotected),n.header!==void 0&&(G.unprotectedHeader=n.header),l?{...G,key:d}:G}async function PF(n,e,t){if(!Zo(n))throw new Ve("General JWE must be an object");if(!Array.isArray(n.recipients)||!n.recipients.every(Zo))throw new Ve("JWE Recipients missing or incorrect type");if(!n.recipients.length)throw new Ve("JWE Recipients has no members");for(let r of n.recipients)try{return await II({aad:n.aad,ciphertext:n.ciphertext,encrypted_key:r.encrypted_key,header:r.header,iv:n.iv,protected:n.protected,tag:n.tag,unprotected:n.unprotected},e,t)}catch{}throw new Ih}var D8=Symbol();async function tne(n){if(gI(n))if(n.type==="secret")n=n.export();else return n.export({format:"jwk"});if(n instanceof Uint8Array)return{kty:"oct",k:Xr(n)};if(!Vu(n))throw new TypeError(xh(n,"CryptoKey","KeyObject","Uint8Array"));if(!n.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:t,alg:r,use:i,...o}=await crypto.subtle.exportKey("jwk",n);return o.kty==="AKP"&&(o.alg=r),o}async function nne(n){return tne(n)}async function T8(n,e,t,r,i={}){let o,s,a;switch(n){case"dir":{a=t;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(X0(t),!L8(t))throw new Xt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:u}=i,l;i.epk?l=await vh(i.epk,n):l=(await crypto.subtle.generateKey(t.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:h,crv:f,kty:m}=await nne(l),w=await C8(t,l,n==="ECDH-ES"?e:n,n==="ECDH-ES"?bI(e):parseInt(n.slice(-5,-2),10),c,u);if(s={epk:{x:d,crv:f,kty:m}},m==="EC"&&(s.epk.y=h),c&&(s.apu=Xr(c)),u&&(s.apv=Xr(u)),n==="ECDH-ES"){a=w;break}a=r||Qu(e);let b=n.slice(-6);o=await yI(b,w,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=r||Qu(e),X0(t),o=await Vte(n,t,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=r||Qu(e);let{p2c:c,p2s:u}=i;({encryptedKey:o,...s}=await Hte(n,t,a,c,u));break}case"A128KW":case"A192KW":case"A256KW":{a=r||Qu(e),o=await yI(n,t,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=r||Qu(e);let{iv:c}=i;({encryptedKey:o,...s}=await jte(n,t,a,c));break}default:throw new Xt('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:a,encryptedKey:o,parameters:s}}var AI=class{#e;#t;#n;#r;#i;#o;#s;#a;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){if(this.#a)throw new TypeError("setKeyManagementParameters can only be called once");return this.#a=e,this}setProtectedHeader(e){if(this.#t)throw new TypeError("setProtectedHeader can only be called once");return this.#t=e,this}setSharedUnprotectedHeader(e){if(this.#n)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this.#n=e,this}setUnprotectedHeader(e){if(this.#r)throw new TypeError("setUnprotectedHeader can only be called once");return this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){if(this.#o)throw new TypeError("setContentEncryptionKey can only be called once");return this.#o=e,this}setInitializationVector(e){if(this.#s)throw new TypeError("setInitializationVector can only be called once");return this.#s=e,this}async encrypt(e,t){if(!this.#t&&!this.#r&&!this.#n)throw new Ve("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!ew(this.#t,this.#r,this.#n))throw new Ve("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let r={...this.#t,...this.#r,...this.#n};if(nw(Ve,new Map,t?.crit,this.#t,r),r.zip!==void 0)throw new Xt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:i,enc:o}=r;if(typeof i!="string"||!i)throw new Ve('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof o!="string"||!o)throw new Ve('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let s;if(this.#o&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);ow(i==="dir"?o:i,e,"encrypt");let a;{let b,S=await vh(e,i);({cek:a,encryptedKey:s,parameters:b}=await T8(i,o,S,this.#o,this.#a)),b&&(t&&D8 in t?this.#r?this.#r={...this.#r,...b}:this.setUnprotectedHeader(b):this.#t?this.#t={...this.#t,...b}:this.setProtectedHeader(b))}let c,u,l,d;if(this.#t?(u=Xr(JSON.stringify(this.#t)),l=Ja(u)):(u="",l=new Uint8Array),this.#i){d=Xr(this.#i);let b=Ja(d);c=Ss(l,Ja("."),b)}else c=l;let{ciphertext:h,tag:f,iv:m}=await R8(o,this.#e,a,this.#s,c),w={ciphertext:Xr(h)};return m&&(w.iv=Xr(m)),f&&(w.tag=Xr(f)),s&&(w.encrypted_key=Xr(s)),d&&(w.aad=d),this.#t&&(w.protected=u),this.#n&&(w.unprotected=this.#n),this.#r&&(w.header=this.#r),w}};var kF=class{#e;unprotectedHeader;keyManagementParameters;key;options;constructor(e,t,r){this.#e=e,this.key=t,this.options=r}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}setKeyManagementParameters(e){if(this.keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this.keyManagementParameters=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},xI=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let r=new kF(this,e,{crit:t?.crit});return this.#t.push(r),r}setProtectedHeader(e){if(this.#n)throw new TypeError("setProtectedHeader can only be called once");return this.#n=e,this}setSharedUnprotectedHeader(e){if(this.#r)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}async encrypt(){if(!this.#t.length)throw new Ve("at least one recipient must be added");if(this.#t.length===1){let[i]=this.#t,o=await new AI(this.#e).setAdditionalAuthenticatedData(this.#i).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(i.unprotectedHeader).encrypt(i.key,{...i.options}),s={ciphertext:o.ciphertext,iv:o.iv,recipients:[{}],tag:o.tag};return o.aad&&(s.aad=o.aad),o.protected&&(s.protected=o.protected),o.unprotected&&(s.unprotected=o.unprotected),o.encrypted_key&&(s.recipients[0].encrypted_key=o.encrypted_key),o.header&&(s.recipients[0].header=o.header),s}let e;for(let i=0;i<this.#t.length;i++){let o=this.#t[i];if(!ew(this.#n,this.#r,o.unprotectedHeader))throw new Ve("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let s={...this.#n,...this.#r,...o.unprotectedHeader},{alg:a}=s;if(typeof a!="string"||!a)throw new Ve('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(a==="dir"||a==="ECDH-ES")throw new Ve('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof s.enc!="string"||!s.enc)throw new Ve('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!e)e=s.enc;else if(e!==s.enc)throw new Ve('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(nw(Ve,new Map,o.options.crit,this.#n,s),s.zip!==void 0)throw new Xt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.')}let t=Qu(e),r={ciphertext:"",recipients:[]};for(let i=0;i<this.#t.length;i++){let o=this.#t[i],s={};if(r.recipients.push(s),i===0){let d=await new AI(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(o.unprotectedHeader).setKeyManagementParameters(o.keyManagementParameters).encrypt(o.key,{...o.options,[D8]:!0});r.ciphertext=d.ciphertext,r.iv=d.iv,r.tag=d.tag,d.aad&&(r.aad=d.aad),d.protected&&(r.protected=d.protected),d.unprotected&&(r.unprotected=d.unprotected),s.encrypted_key=d.encrypted_key,d.header&&(s.header=d.header);continue}let a=o.unprotectedHeader?.alg||this.#n?.alg||this.#r?.alg;ow(a==="dir"?e:a,o.key,"encrypt");let c=await vh(o.key,a),{encryptedKey:u,parameters:l}=await T8(a,e,c,t,o.keyManagementParameters);s.encrypted_key=Xr(u),(o.unprotectedHeader||l)&&(s.header={...o.unprotectedHeader,...l})}return r}};function MF(n){let e;if(typeof n=="string"){let t=n.split(".");(t.length===3||t.length===5)&&([e]=t)}else if(typeof n=="object"&&n)if("protected"in n)e=n.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let t=JSON.parse(Z0.decode(Zr(e)));if(!Zo(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var B8=class{constructor(e){this.resolvePrivateKeyByKid=e}async encrypt(e,t){let{enc:r,typ:i,recipients:o}=t,s=new xI(e).setProtectedHeader({enc:r,typ:i});return o.forEach(({recipientJWK:c,alg:u,kid:l})=>{s.addRecipient(c).setUnprotectedHeader({alg:u,kid:l})}),await s.encrypt()}async decrypt(e){let t=(r,i)=>{let o=i.header?.kid||r&&r.kid;if(!o)throw new Error("kid is required");return this.resolvePrivateKeyByKid(o)};if(Object.prototype.hasOwnProperty.call(e,"encrypted_key")){let r=e;return r.header=this.removeDuplicates(MF(r),r.header||{}),II(e,t)}return PF(e,t)}removeDuplicates=(e,t)=>{let r={...t};for(let[i,o]of Object.entries(e))r[i]===o&&delete r[i];return r}};var P8=class{constructor(e){this.kms=e}resolvePrivateKeyByKid=async e=>{let[,t]=e.split("#");if(!t)throw new Error("Missing key identifier");let[r]=t.split(":");if(!r)throw new Error("Missing key type in alias for default key resolver");let i=await this.kms.getKeyProvider(r)?.getPkStore();if(!i)throw new Error(`Key provider not found for ${r}`);try{return JSON.parse(await i.get({alias:t}))}catch{throw new Error(`Key not found for ${t}`)}}};var FF={};Rr(FF,{DeviceNotificationStatus:()=>one,NotificationServiceType:()=>rne,NotificationStatus:()=>ine,PushNotifier:()=>OF});var rne=(e=>(e.Push="push-notification",e))(rne||{}),ine=(t=>(t.Success="success",t.Failed="failed",t))(ine||{});var one=(r=>(r.Success="success",r.Rejected="rejected",r.Failed="failed",r))(one||{}),ADe={type:"push-notification",send:async({url:n,pushService:e,message:t})=>{try{let r=new Request(n,{method:"POST",body:JSON.stringify({metadata:e.metadata,message:t})}),i=await fetch(r);if(i.status!==200)throw new Error(`could not send push notification, return status ${i.status}`);let o=await i.json();return{status:"success",devices:o}}catch(r){return{status:"failed",error:r.toString()}}}},OF=class{constructor(e=ADe){this._publisher=e;if(e.type!=="push-notification")throw new Error(`PushNotifier: publisher type ${e.type} is not supported`)}async notify(e,t){let r=(t.didDocument.service??[]).find(s=>s.type==="push-notification");if(!r)throw new Error("no push service in did document");if(!r.metadata?.devices?.length)throw new Error("no devices in push service");let o=[r.serviceEndpoint??[]].flat().reduce((s,a)=>typeof a=="string"?[...s,a]:typeof a.uri=="string"?[...s,a.uri]:s,[]).map(async s=>this._publisher.send({url:s,pushService:r,message:e}));return await Promise.all(o)}};var xd={url:"http://localhost:8545",defaultGasLimit:6e5,minGasPrice:"0",maxGasPrice:"100000000000",confirmationBlockCount:5,confirmationTimeout:6e5,contractAddress:"",receiptTimeout:6e5,rpcResponseTimeout:5e3,waitReceiptCycleTime:3e4,waitBlockCycleTime:3e3},sne={state:0n,replacedByState:0n,createdAtTimestamp:0n,replacedAtTimestamp:0n,createdAtBlock:0n,replacedAtBlock:0n},dI=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,uM,this.provider),this._transactionService=new Xs(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??jr.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??lg},this._stateCacheOptions={notReplacedTtl:t?.stateCacheOptions?.notReplacedTtl??jr.DEFAULT_PROOF_VERIFY_DELAY/2,replacedTtl:t?.stateCacheOptions?.replacedTtl??jr.DEFAULT_PROOF_VERIFY_DELAY,maxSize:t?.stateCacheOptions?.maxSize??lg},this._rootCacheOptions={replacedTtl:t?.rootCacheOptions?.replacedTtl??jr.DEFAULT_AUTH_VERIFY_DELAY,notReplacedTtl:t?.rootCacheOptions?.notReplacedTtl??jr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.rootCacheOptions?.maxSize??lg},this._gistProofCacheOptions={ttl:jr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??lg},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??fh({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??fh({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??fh({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??fh({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){if(s.state===0n&&s.createdAtTimestamp===0n)throw new Error(Ue.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR);return s}}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=[];try{i=await r.getStateInfoById(e)}catch(s){throw z0(s)&&!this._disableCache&&await this._latestStateResolveCache?.set(t,{id:e,...sne},this._latestStateCacheOptions.ttl),s}let 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 a=await this._stateResolveCache?.get(r);if(a)return a}let{stateContract:i}=this.getStateContractAndProviderForId(e),o;try{let a=await i.getStateInfoByIdAndState(e,t);o={id:BigInt(a[0]),state:BigInt(a[1]),replacedByState:BigInt(a[2]),createdAtTimestamp:BigInt(a[3]),replacedAtTimestamp:BigInt(a[4]),createdAtBlock:BigInt(a[5]),replacedAtBlock:BigInt(a[6])}}catch(a){if(!cF(a))throw a;if(!Cx(Xe.fromBigInt(e),t))throw new Error(`State ${t} for identity ${e} is not genesis and not registered in the smart contract`);o={id:e,...sne,state:t}}let s=o.replacedAtTimestamp===0n?this._stateCacheOptions.notReplacedTtl:this._stateCacheOptions.replacedTtl;return!this._disableCache&&await this._stateResolveCache?.set(r,o,s),o}async publishState(e,t){let r=new f1;r.pubSignalsUnmarshal(ke.encode(JSON.stringify(e.pub_signals)));let{userId:i,oldUserState:o,newUserState:s,isOldStateGenesis:a}=r,{stateContract:c,provider:u}=this.getStateContractAndProviderForId(i.bigInt()),l=c.connect(t),d=dh(e.proof),h=[i.bigInt().toString(),o.bigInt().toString(),s.bigInt().toString(),a,d.a,d.b,d.c],f=await u.getFeeData(),m=xd.maxFeePerGas?BigInt(xd.maxFeePerGas):f.maxFeePerGas,w=xd.maxPriorityFeePerGas?BigInt(xd.maxPriorityFeePerGas):f.maxPriorityFeePerGas,b=await l.transitState.estimateGas(...h),S=await l.transitState.populateTransaction(...h),R={to:S.to,data:S.data,gasLimit:b,maxFeePerGas:m,maxPriorityFeePerGas:w},{txnHash:G}=await this._transactionService.sendTransactionRequest(t,R);return await this._latestStateResolveCache?.delete(this.getLatestStateCacheKey(i.bigInt())),G}async publishStateGeneric(e,t){let{userId:r,oldUserState:i,newUserState:o,isOldStateGenesis:s,methodId:a,methodParams:c}=t,{stateContract:u,provider:l}=this.getStateContractAndProviderForId(r.bigInt()),d=u.connect(e),h=await l.getFeeData(),f=xd.maxFeePerGas?BigInt(xd.maxFeePerGas):h.maxFeePerGas,m=xd.maxPriorityFeePerGas?BigInt(xd.maxPriorityFeePerGas):h.maxPriorityFeePerGas,w=[r.bigInt().toString(),i.bigInt().toString(),o.bigInt().toString(),s,a,c],b=await d.transitStateGeneric.estimateGas(...w),S=await d.transitStateGeneric.populateTransaction(...w),R={to:S.to,data:S.data,gasLimit:b,maxFeePerGas:f,maxPriorityFeePerGas:m},{txnHash:G}=await this._transactionService.sendTransactionRequest(e,R);return await this._latestStateResolveCache?.delete(this.getLatestStateCacheKey(r.bigInt())),G}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=Xe.fromBigInt(t),i=tm(ve.blockchainFromId(r),ve.networkIdFromId(r)),o=this.getRootCacheKey(i,e);if(!this._disableCache){let l=await this._rootResolveCache?.get(o);if(l)return l}let{stateContract:s}=this.getStateContractAndProviderForId(t),a=await s.getGISTRootInfo(e),c={root:BigInt(a.root.toString()),replacedByRoot:BigInt(a.replacedByRoot.toString()),createdAtTimestamp:BigInt(a.createdAtTimestamp.toString()),replacedAtTimestamp:BigInt(a.replacedAtTimestamp.toString()),createdAtBlock:BigInt(a.createdAtBlock.toString()),replacedAtBlock:BigInt(a.replacedAtBlock.toString())},u=c.replacedAtTimestamp==0n?this._rootCacheOptions.notReplacedTtl:this._rootCacheOptions.replacedTtl;return!this._disableCache&&await this._rootResolveCache?.set(o,c,u),c}getRpcProvider(){return this.provider}enableCache(){this._disableCache=!1}disableCache(){this._disableCache=!0}getStateContractAndProviderForId(e){let t=Xe.fromBigInt(e),r=tm(ve.blockchainFromId(t),ve.networkIdFromId(t)),i=this.networkByChainId(r),o=new jt(i.url);return{stateContract:new Ln(i.contractAddress,uM,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-state:${e.toString()}`}getStateCacheKey(e,t){return`state:${e.toString()}-${t.toString()}`}getRootCacheKey(e,t){return`root:${e.toString()}-${t.toString()}`}};var NF=[{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 UF=[{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 GF=10000000n,ane=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(ane||{}),cne=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]},HF=class n{constructor(e,t){this._configs=e;this._opts=t}static _supportedCircuits=["authV2","authV3","authV3-8-32","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","credentialAtomicQueryV3OnChain"];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=dh(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,u=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,l=new Ln(t.contract_address,NF);for(let d of r){let h=await this.prepareTxArgsSubmitV1(t,d),f=await l.submitZKPResponse.populateTransaction(...h),m={to:t.contract_address,data:f.data,maxFeePerGas:c,maxPriorityFeePerGas:u},w;try{w=await e.estimateGas(m)}catch{w=GF}m.gasLimit=w;let b=new Xs(o),{txnHash:S}=await b.sendTransactionRequest(e,m);s.set(S,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,u=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,d=await new Ln(t.contract_address,NF).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:c,maxPriorityFeePerGas:u},f;try{f=await e.estimateGas(h)}catch{f=GF}h.gasLimit=f;let m=new Xs(o),{txnHash:w}=await m.sendTransactionRequest(e,h);return new Map().set(w,r)}async submitResponse(e,t,r,i){let o=this._configs.find(S=>S.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(),u=o.maxFeePerGas?BigInt(o.maxFeePerGas):c.maxFeePerGas,l=o.maxPriorityFeePerGas?BigInt(o.maxPriorityFeePerGas):c.maxPriorityFeePerGas,h=await new Ln(t.contract_address,UF).submitResponse.populateTransaction(...a.txDataArgs),f={to:t.contract_address,data:h.data,maxFeePerGas:u,maxPriorityFeePerGas:l},m;try{m=await e.estimateGas(f)}catch{m=GF}f.gasLimit=m;let w=new Xs(s),{txnHash:b}=await w.sendTransactionRequest(e,f);return new Map().set(b,{authProof:a.result.authProof.raw,crossChainProof:a.result.crossChainProof.raw,responses:a.result.proofs.map(S=>S.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",u="";switch(i.authMethod){case"authV2":case"authV3":case"authV3-8-32":{let f=dh(i.zkp.proof);u=DE(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{u=une(i.userDid);break}case"embeddedAuth":{u="0x";break}default:throw new Error("auth proof must use method authV2, authV3, authV3-8-32 or ethIdentity")}for(let f of r){this.checkSupportedCircuit(f.circuitId);let{requestId:m,zkProofEncoded:w,metadata:b}=uI(f);a.push({proof:f,requestId:m,encoded:w,metadata:b})}let l=r.map(f=>({circuitId:f.circuitId,pub_signals:f.pub_signals}));["authV2","authV3","authV3-8-32"].includes(i.authMethod)&&l.push({circuitId:i.zkp.circuitId,pub_signals:i.zkp.pub_signals});for(let f of l){let{gistUpdateResolutions:m,stateUpdateResolutions:w}=this.getUpdateResolutions(e,t.chain_id,f.circuitId,f.pub_signals);m.length>0&&o.push(...await Promise.all(m)),w.length>0&&s.push(...await Promise.all(w))}let d=o.length||s.length?this.packCrossChainProofs(o,s):c,h={authProof:{raw:i,encoded:u},proofs:a,crossChainProof:{raw:{globalStateProofs:o||[],identityStateProofs:s||[]},encoded:d}};return{result:h,txDataArgs:cne(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(!R6(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=Xe.fromString(a.id),u=dw(ve.parseFromId(c));if(t===u)return o;let l=this.resolveDidDocumentEip712MessageAndSignature(ve.parseFromId(Xe.fromString(a.id)),i,{[r]:be.fromString(a[r])});return[...o,l]},[])}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 u of r){this.checkSupportedCircuit(u.circuitId);let{requestId:l,zkProofEncoded:d,metadata:h}=uI(u);s.push({requestId:l,zkProof:d,data:h});let{gistUpdateResolutions:f,stateUpdateResolutions:m}=this.getUpdateResolutions(e,t.chain_id,u.circuitId,u.pub_signals);f.length>0&&i.push(...await Promise.all(f)),m.length>0&&o.push(...await Promise.all(m))}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 mn.AbiCoder().encode(["tuple(string proofType,bytes proof)[]"],[r])}static packGlobalStateMsg(e){return new mn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,bytes2 idType,uint256 root,uint256 replacedAtTimestamp) globalStateMsg,bytes signature,)"],[e])}static packIdentityStateMsg(e){return new mn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,uint256 id,uint256 state,uint256 replacedAtTimestamp) idStateMsg,bytes signature,)"],[e])}static getOnChainGistRootStatePubSignals(e,t){let r=T6(e);if(!r||!r.unmarshaller)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=r.unmarshaller,o=new i(r.opts),s=ke.encode(JSON.stringify(t)),a=o.pubSignalsUnmarshal(s);if(a.getStatesInfo===void 0)throw new Error(`Public signals unmarshaller for circuit ${e} does not support getStatesInfo method`);return a.getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await bp(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}}},une=n=>`0x${Br(It.intToBytes(ve.idFromDID(n).bigInt()))}`;var KF=[{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 JF=[{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"}],sw=class{static abi=JF;static createInterface(){return new hc(JF)}static connect(e,t){return new Ln(e,JF,t)}};var vI=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=mn.getAddress(mn.hexlify(Xe.ethAddressFromId(ve.idFromDID(t)))),this._contract=sw.connect(this._contractAddress,new mn.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 Ir().unMarshalJson(JSON.stringify(t.map(u=>u.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=Er.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 u of i){let l=await Or.newTypeFromContext(o,`${r}.${u.key}`,this._merklizationOptions);switch(l){case"http://www.w3.org/2001/XMLSchema#boolean":{switch(u.rawValue.toString()){case"18586133768512220936620570745912940619677854269274689475585506675881198879027":s[u.key]=!0;break;case"19014214495641488759237505126948346942972912379615652741039992445865937985820":s[u.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[u.key]=u.value.toString();break}case"http://www.w3.org/2001/XMLSchema#integer":{s[u.key]=Number(u.value);break}case"http://www.w3.org/2001/XMLSchema#string":{this.validateSourceValue(l,u.value,u.rawValue),s[u.key]=u.rawValue;break}case"http://www.w3.org/2001/XMLSchema#dateTime":{let d=BigInt(u.rawValue),h=ia(Number(d)).toISOString();this.validateSourceValue(l,u.value,h),s[u.key]=h;break}case"http://www.w3.org/2001/XMLSchema#double":{let d=Number(u.rawValue);this.validateSourceValue(l,u.value,d),s[u.key]=d;break}default:throw new Error(`Unsupported data type ${l}`)}}s.type=r;let a=e.getId(),c=ve.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 kt({siblings:t.siblings.map(u=>be.fromBigInt(u)),existence:t.existence,nodeAux:t.auxExistence?{key:be.fromBigInt(t.auxIndex),value:be.fromBigInt(t.auxValue)}:void 0});return new yc({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:c,coreClaim:e})}async validateSourceValue(e,t,r){if(await Pu.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 qF=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 vI(o,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});await a.isInterfaceSupported();let{credentialData:c,coreClaimBigInts:u,credentialSubjectFields:l}=await a.getCredential(ve.idFromDID(t),r);return await a.convertOnChainInfoToW3CCredential(c,u,l)}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 vI(i,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});return await s.isInterfaceSupported(),await s.getUserCredentialsIds(ve.idFromDID(t))}default:throw new Error(`Unsupported adapter version ${o}`)}}getContractConnection(e){let t=ve.idFromDID(e),r=dw(e),i=mn.getAddress(mn.hexlify(Xe.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,KF,new mn.JsonRpcProvider(o.url)),connection:o}}};var VF=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 bp(ve.parseFromId(Xe.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 bp(ve.parseFromId(Xe.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 bp(ve.parseFromId(Xe.fromBigInt(e)),this.resolverUrl,r),{info:o,published:s}=this.getIden3StateInfo2023(i);if(!o&&!s)throw new Error(Ue.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 lne=[{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 dne=[{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 BDe(n,e,t,r,i,o){let s=new Ln(e,lne,n),a=await s.nonces(await n.getAddress()),[c,u]=await Promise.all([s.name(),s.version?.().catch(()=>"1")??Promise.resolve("1")]),l={name:c,version:u,chainId:o,verifyingContract:e},d={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},h={owner:await n.getAddress(),spender:t,value:r,nonce:a,deadline:i};return n.signTypedData(l,d,h)}async function PDe(n,e){return new Ln(n,dne,e).decimals()}var yne=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(yne||{}),wne=(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))(wne||{}),QF=[!0,1,"true"],zF=[!1,0,"false"],fne=(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,QF.includes(n)&&QF.includes(e)||zF.includes(n)&&zF.includes(e)?!0:n===e),hne=(n,e)=>Ene(n,e,(r,i)=>{switch(Ine(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}}),pne=(n,e)=>Ene(n,e,(r,i)=>{switch(Ine(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}}),kDe=(n,e)=>!!(QF.includes(e)&&typeof n<"u"||zF.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),mne=(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,gne=(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))},qa={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>kDe(n,e),$eq:(n,e)=>fne(n,e),$in:(n,e)=>mne(n,e),$nin:(n,e)=>!mne(n,e),$gt:(n,e)=>hne(n,e),$lt:(n,e)=>!pne(n,e),$ne:(n,e)=>!fne(n,e),$gte:(n,e)=>pne(n,e),$lte:(n,e)=>!hne(n,e),$between:(n,e)=>gne(n,e),$nonbetween:(n,e)=>!gne(n,e)},bne=(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},na=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=bne(e,this.path);return t==null&&this.operatorFunc!==qa.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},YF=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new na("id",qa.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new na("issuer",qa.$in,r));case"type":return e.concat(new na("type",qa.$in,r,!0));case"context":return e.concat(new na("@context",qa.$in,r,!0));case"credentialSubjectId":return e.concat(new na("credentialSubject.id",qa.$eq,r));case"schema":return e.concat(new na("credentialSchema.id",qa.$eq,r));case"credentialSubject":case"credentialStatus":{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 na(`${t}.${s}`,qa.$noop,null)]);let c=Object.keys(a).map(u=>{let l=a[u],d=`${t}.${s}`;return new na(d,qa[u],l)});return o.concat(c)},[]);return e.concat(i)}case"expirationDate":case"issuanceDate":{if(Object.keys(r).length===0)return e.concat([new na(t,qa.$noop,null)]);let i=Object.keys(r).map(o=>{let s=r[o],a=typeof s=="number"||typeof s=="string"&&/^\d+$/.test(s)?new Date(Number(s)*1e3).toISOString():s;return new na(t,qa[o],a)});return e.concat(i)}case"proofType":case"groupId":case"skipClaimRevocationCheck":return e;default:throw new Error(`${t} : not defined query key`)}},[]),Ene=(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),MDe=/^[+-]?\d+$/,ODe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,FDe=/^([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]))$/,NDe=/^(true)|(false)$/,UDe=/^\d{4}-\d{2}-\d{2}$/,Ine=n=>MDe.test(n)?0:ODe.test(n)?2:FDe.test(n)||UDe.test(n)?3:NDe.test(n)?1:4;var jF=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 WF=class n{constructor(e){this._mtDepth=e}static storageKeyMeta="merkle-tree-meta";async createIdentityMerkleTrees(e){e||(e=`${Ut()}`);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=ky(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify([...i,...a])),[...i,...a]}let r=ky(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 bw(_c(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 bw(_c(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 ZF=class{constructor(e){this._storageKey=e;this._store=Fd(`${e}-db`,e)}_store;async save(e,t,r="id"){return Nd(e,t,this._store)}async get(e,t="id"){return Zc(e,this._store)}async load(){return $N(this._store)}async delete(e,t="id"){return jI(e,this._store)}};var XF=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=Fd(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=Fd(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Ut()}`),await Zc(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=ky(e);return await Nd(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await Zc(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 Zc(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(_c(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await Zc(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(_c(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await Zc(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 jI(e,this._merkleTreeMetaStore),await Nd(t,i,this._merkleTreeMetaStore),await Nd(e,t,this._bindingStore)}};var _F=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 $F=class{constructor(e){this._dataSource=e}static storageKey="credentials";async listCredentials(){return(await this._dataSource.load()).filter(t=>t!==void 0).map(t=>t&&Er.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&&Er.fromJSON(t)}async findCredentialsByQuery(e){let t=YF(e);return(await this._dataSource.load()).filter(o=>t.every(s=>s.execute(o))).filter(o=>o!==void 0).map(o=>Er.fromJSON(o))}};var eN=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 tN=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,t){let r=t?.mode??"full",i={wasm:r==="proving"||r==="full"?this.loadCircuitFile(e,this._wasmFilePath):Promise.resolve(null),provingKey:r==="proving"||r==="full"?this.loadCircuitFile(e,this._provingKeyPath):Promise.resolve(null),verificationKey:r==="verification"||r==="full"?this.loadCircuitFile(e,this._verificationKeyPath):Promise.resolve(null)},[o,s,a]=await Promise.all([i.wasm,i.provingKey,i.verificationKey]);return{circuitId:e,wasm:o,provingKey:s,verificationKey:a}}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 zu=n=>{if(!n){let e=On.hash(new Array(3).fill(0n));return{proof:new kt,treeState:{state:be.fromBigInt(e),claimsRoot:Ne,revocationRoot:Ne,rootOfRoots:Ne}}}return{proof:n.mtp,treeState:x6(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},aw=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 kt({siblings:r,nodeAux:t,existence:e});return{root:be.fromBigInt(n.root),proof:i}},k8=new Set(["credentialStatus.revocationNonce","credentialStatus.id"]),rN=n=>{let e=[];if(n.credentialSubject){let t=nN(n.credentialSubject,"credentialSubject");e.push(...vd(t))}if(n.expirationDate){let t=vd({expirationDate:n.expirationDate});e.push(...t)}if(n.issuanceDate){let t=vd({issuanceDate:n.issuanceDate});e.push(...t)}if(n.credentialStatus&&Object.keys(n.credentialStatus).length>0){let t=nN(n.credentialStatus,"credentialStatus"),r=Object.fromEntries(Object.entries(t).filter(([i])=>k8.has(i)));if(!Object.keys(r).length)throw new Error(`credentialStatus query contains no allowed fields \u2014 permitted: ${[...k8].join(", ")}`);e.push(...vd(r))}return e.length===0?[{operator:Zt.$noop,fieldName:""}]:e},nN=(n,e)=>{let t={};for(let[r,i]of Object.entries(n))i!==void 0&&(t[`${e}.${r}`]=i);return t},M8=(n,e)=>{if(!e)return[{operator:Zt.$noop,fieldName:""}];let t=nN(e,n);return vd(t)},vd=n=>{if(!n)return[{operator:Zt.$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:Zt.$sd,fieldName:r});continue}for(let[a,c]of o){if(!Object.hasOwn(Zt,a))throw new Error("operator is not supported by lib");let u=Zt[a];e.push({operator:u,fieldName:r,operatorValue:c})}}return e},GDe=n=>vd(n),SI=async(n,e,t,r)=>{let i=n.fieldName,[o]=i.split("."),s=i;switch(o){case"credentialStatus":s=i.replace("credentialStatus.",""),e=Ue.JSONLD_SCHEMA.IDEN3_PROOFS_DEFINITION_DOCUMENT;break;case"credentialSubject":s=i.replace("credentialSubject.","");break;case"":break;case"expirationDate":case"issuanceDate":e=Ue.JSONLD_SCHEMA.W3C_VC_DOCUMENT_2018,t=Ue.CREDENTIAL_TYPE.W3C_VERIFIABLE_CREDENTIAL;break}let a={...n,fieldName:s,slotIndex:0,merklizedSchema:!1,datatype:"",claimPathKey:BigInt(0),values:[],path:new Or};if(!s&&n.operator!==0)throw new Error("query must have a field name if operator is not $noop");if(s&&(a.datatype=await Or.newTypeFromContext(e,`${t}.${s}`,r)),await z2(JSON.parse(e),r,t)||(a.merklizedSchema=!0),!a.merklizedSchema)a.slotIndex=await Q2(s,t,ke.encode(e));else if(!r.legacyNoopOperator&&a.operator===0)a.claimPathKey=BigInt(0),a.path=new Or;else try{let u=await B6(e,t,s,r);i==="credentialStatus.id"&&u.parts[u.parts.length-1]==="@id"&&u.parts.pop(),a.claimPathKey=await u.mtEntry(),a.path=u}catch(u){throw new Error(`field does not exist in the schema ${u.message}`)}if(n.operatorValue!==void 0){if(!S6(a.datatype,n.operator))throw new Error(`operator ${n.operator} is not supported for datatype ${a.datatype}`);if((n.operator===0||n.operator===16)&&n.operatorValue)throw new Error(`operator value should be undefined for ${n.operator} operator`);let u;switch(n.operator){case 0:case 16:u=[];break;case 11:u=KDe(n.operatorValue);break;default:u=await O8(n.operatorValue,a.datatype)}a.values=u}return a.fieldName=i,a},CI=async(n,e,t,r,i)=>{let o=[];if(t.credentialSubject!==void 0&&o.push(...M8("credentialSubject",t.credentialSubject)),t.expirationDate&&o.push(...vd({expirationDate:t.expirationDate})),t.issuanceDate&&o.push(...vd({issuanceDate:t.issuanceDate})),t.credentialStatus!==void 0&&Object.keys(t.credentialStatus).length>0){let s=M8("credentialStatus",t.credentialStatus).filter(a=>k8.has(a.fieldName));if(!s.length)throw new Error(`credentialStatus query contains no allowed fields \u2014 permitted: ${[...k8].join(", ")}`);o.push(...s)}return o.length===0&&o.push({operator:Zt.$noop,fieldName:""}),Promise.all(o.map(s=>{let a=n;if(s.fieldName.startsWith("credentialStatus.")){let c=i?.verifiableCredential?.credentialStatus?.type;if(!c)throw new Error("credentialStatus.type is required to verify a credentialStatus query: include verifiableCredential.credentialStatus.type in the verifiablePresentation");a=c}return SI(s,e,a,r)}))},HDe=async(n,e,t,r)=>{let i=M8("credentialSubject",t);return Promise.all(i.map(o=>SI(o,e,n,r)))},O8=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await Pu.hashValue(e,n[r]);else t[0]=await Pu.hashValue(e,n);return t},KDe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")},F8=n=>["authV2","authV3","authV3-8-32"].includes(n);async function sN(n,e){e=e||{};let t;try{t=await WebAssembly.compile(n)}catch(l){throw new Error(l)}let r="",i="",o=await WebAssembly.instantiate(t,{runtime:{exceptionHandler:function(l){let d;throw l==1?d=`Signal not found.
424
424
  `:l==2?d=`Too many signals set.
425
425
  `:l==3?d=`Signal already set.
426
426
  `:l==4?d=`Assert Failed.