@0xpolygonid/js-sdk 1.40.1 → 1.40.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/esm/index.js +2 -1
- package/dist/browser/esm/index.js.map +1 -1
- package/dist/browser/umd/index.global.js +1 -1
- package/dist/browser/umd/index.global.js.map +1 -1
- package/dist/node/cjs/index.cjs +2 -1
- package/dist/node/cjs/index.cjs.map +1 -1
- package/dist/node/esm/index.js +2 -1
- package/dist/node/esm/index.js.map +1 -1
- package/dist/types/iden3comm/handlers/common.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/iden3comm/handlers/common.ts +3 -2
|
@@ -420,7 +420,7 @@ if (cid) {
|
|
|
420
420
|
`?i="":(i!==""&&(i+=" "),i+=l)},showSharedRWMemory:function(){u()}}}),s=e;return new AO(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+=xO(d).toString()}}var AO=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=xO(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=DLe(o),a=parseInt(s.slice(0,8),16),c=parseInt(s.slice(8,16),16),u=RLe(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=LLe(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(xO(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 LLe(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 xO(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 RLe(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 DLe(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 zy=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 vO(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Uc(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 Dee(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");vO(n.outputLen),vO(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 TLe(n,e){Uc(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function $C(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function fO(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Hu(n,e){return n<<32-e|n>>>e}var Tee=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",BLe=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function jy(n){if(Uc(n),Tee)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=BLe[n[t]];return e}var wd={_0:48,_9:57,A:65,F:70,a:97,f:102};function cee(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 e8(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(Tee)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=cee(n.charCodeAt(o)),a=cee(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 $E(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function JO(n){return typeof n=="string"&&(n=$E(n)),Uc(n),n}function Mi(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];Uc(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 t8=class{};function PLe(n){let e=r=>n().update(JO(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function qO(n=32){if(zy&&typeof zy.getRandomValues=="function")return zy.getRandomValues(new Uint8Array(n));if(zy&&typeof zy.randomBytes=="function")return Uint8Array.from(zy.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function kLe(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 MLe(n,e,t){return n&e^~n&t}function OLe(n,e,t){return n&e^n&t^e&t}var SO=class extends t8{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=fO(this.buffer)}update(e){_C(this),e=JO(e),Uc(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=fO(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),TLe(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,$C(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;kLe(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=fO(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()}},mh=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),FLe=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]),gh=new Uint32Array(64),CO=class extends SO{constructor(e=32){super(64,e,8,!1),this.A=mh[0]|0,this.B=mh[1]|0,this.C=mh[2]|0,this.D=mh[3]|0,this.E=mh[4]|0,this.F=mh[5]|0,this.G=mh[6]|0,this.H=mh[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)gh[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=gh[d-15],f=gh[d-2],m=Hu(h,7)^Hu(h,18)^h>>>3,w=Hu(f,17)^Hu(f,19)^f>>>10;gh[d]=w+gh[d-7]+m+gh[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=Hu(a,6)^Hu(a,11)^Hu(a,25),f=l+h+MLe(a,c,u)+FLe[d]+gh[d]|0,w=(Hu(r,2)^Hu(r,13)^Hu(r,22))+OLe(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(){$C(gh)}destroy(){this.set(0,0,0,0,0,0,0,0),$C(this.buffer)}},Bee=PLe(()=>new CO);var VO=BigInt(0),n8=BigInt(1);function r8(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function J0(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 YC(n){let e=n.toString(16);return e.length&1?"0"+e:e}function Pee(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?VO:BigInt("0x"+n)}function eI(n){return Pee(jy(n))}function kee(n){return Uc(n),Pee(jy(Uint8Array.from(n).reverse()))}function QO(n,e){return e8(n.toString(16).padStart(e*2,"0"))}function Mee(n,e){return QO(n,e).reverse()}function so(n,e,t){let r;if(typeof e=="string")try{r=e8(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 hO=n=>typeof n=="bigint"&&VO<=n;function Oee(n,e,t){return hO(n)&&hO(e)&&hO(t)&&e<=n&&n<t}function NLe(n,e,t,r){if(!Oee(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function jE(n){let e;for(e=0;n>VO;n>>=n8,e+=1);return e}function ULe(n,e){return n>>BigInt(e)&n8}var tI=n=>(n8<<BigInt(n))-n8;function GLe(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 Mi(...m)};return(f,m)=>{c(),l(f);let w;for(;!(w=m(d()));)l();return c(),w}}function HLe(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function c8(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 ci=()=>{throw new Error("not implemented")};function LO(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),jo=BigInt(1),q0=BigInt(2),Fee=BigInt(3),Nee=BigInt(4),Uee=BigInt(5),KLe=BigInt(7),Gee=BigInt(8),JLe=BigInt(9),Hee=BigInt(16);function Ga(n,e){let t=n%e;return t>=ea?t:e+t}function uee(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=Ga(n,e),r=e,i=ea,o=jo;for(;t!==ea;){let a=r/t,c=r%t,u=i-o*a;r=t,t=c,i=o,o=u}if(r!==jo)throw new Error("invert: does not exist");return Ga(i,e)}function zO(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Kee(n,e){let t=(n.ORDER+jo)/Nee,r=n.pow(e,t);return zO(n,r,e),r}function qLe(n,e){let t=(n.ORDER-Uee)/Gee,r=n.mul(e,q0),i=n.pow(r,t),o=n.mul(e,i),s=n.mul(n.mul(o,q0),i),a=n.mul(o,n.sub(s,n.ONE));return zO(n,a,e),a}function VLe(n){let e=Zy(n),t=Jee(n),r=t(e,e.neg(e.ONE)),i=t(e,r),o=t(e,e.neg(r)),s=(n+KLe)/Hee;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 zO(a,b,c),b}}function Jee(n){if(n<Fee)throw new Error("sqrt is not defined for small field");let e=n-jo,t=0;for(;e%q0===ea;)e/=q0,t++;let r=q0,i=Zy(n);for(;i8(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Kee;let o=i.pow(r,e),s=(e+jo)/q0;return function(c,u){if(c.is0(u))return u;if(i8(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=jo<<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 QLe(n){return n%Nee===Fee?Kee:n%Gee===Uee?qLe:n%Hee===JLe?VLe(n):Jee(n)}var zLe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function YLe(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=zLe.reduce((r,i)=>(r[i]="function",r),e);return c8(n,t),n}function u8(n,e,t){if(t<ea)throw new Error("invalid exponent, negatives unsupported");if(t===ea)return n.ONE;if(t===jo)return e;let r=n.ONE,i=e;for(;t>ea;)t&jo&&(r=n.mul(r,i)),i=n.sqr(i),t>>=jo;return r}function nI(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 i8(n,e){let t=(n.ORDER-jo)/q0,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 qee(n,e){e!==void 0&&vO(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Zy(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}=qee(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:tI(c),ZERO:ea,ONE:jo,allowedLengths:a,create:h=>Ga(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&jo)===jo,neg:h=>Ga(-h,n),eql:(h,f)=>h===f,sqr:h=>Ga(h*h,n),add:(h,f)=>Ga(h+f,n),sub:(h,f)=>Ga(h-f,n),mul:(h,f)=>Ga(h*f,n),pow:(h,f)=>u8(d,h,f),div:(h,f)=>Ga(h*uee(f,n),n),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>uee(h,n),sqrt:o||(h=>(l||(l=QLe(n)),l(d,h))),toBytes:h=>t?Mee(h,u):QO(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?kee(h):eI(h);if(s&&(m=Ga(m,n)),!f&&!d.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:h=>nI(d,h),cmov:(h,f,m)=>m?f:h});return Object.freeze(d)}function Vee(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 YO(n){let e=Vee(n);return e+Math.ceil(e/2)}function Qee(n,e,t=!1){let r=n.length,i=Vee(e),o=YO(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?kee(n):eI(n),a=Ga(s,e-jo)+jo;return t?Mee(a,i):QO(a,i)}var Wy=BigInt(0),V0=BigInt(1);function o8(n,e){let t=e.negate();return n?t:e}function YE(n,e){let t=nI(n.Fp,e.map(r=>r.Z));return e.map((r,i)=>n.fromAffine(r.toAffine(t[i])))}function zee(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function pO(n,e){zee(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=tI(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function lee(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+=V0);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 jLe(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 WLe(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 mO=new WeakMap,Yee=new WeakMap;function gO(n){return Yee.get(n)||1}function dee(n){if(n!==Wy)throw new Error("invalid wNAF")}var RO=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>Wy;)t&V0&&(r=r.add(i)),i=i.double(),t>>=V0;return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=pO(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=pO(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:h,offsetF:f}=lee(r,a,s);r=c,l?o=o.add(o8(h,t[f])):i=i.add(o8(d,t[u]))}return dee(r),{p:i,f:o}}wNAFUnsafe(e,t,r,i=this.ZERO){let o=pO(e,this.bits);for(let s=0;s<o.windows&&r!==Wy;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=lee(r,s,o);if(r=a,!u){let d=t[c];i=i.add(l?d.negate():d)}}return dee(r),i}getPrecomputes(e,t,r){let i=mO.get(t);return i||(i=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(i=r(i)),mO.set(t,i))),i}cached(e,t,r){let i=gO(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let o=gO(e);return o===1?this._unsafeLadder(e,t,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,i)}createCache(e,t){zee(t,this.bits),Yee.set(e,t),mO.delete(e)}hasCache(e){return gO(e)!==1}};function ZLe(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Wy||r>Wy;)t&V0&&(o=o.add(i)),r&V0&&(s=s.add(i)),i=i.double(),t>>=V0,r>>=V0;return{p1:o,p2:s}}function XLe(n,e,t,r){jLe(t,n),WLe(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=jE(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=tI(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 fee(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return YLe(e),e}else return Zy(n,{isLE:t})}function _Le(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>Wy))throw new Error(`CURVE.${c} must be positive bigint`)}let i=fee(e.p,t.Fp,r),o=fee(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 $Le=eI;function yh(n,e){if(WE(n),WE(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 eRe(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 WE(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function jee(n){if(!_E(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or string");return typeof n=="string"?$E(n):n}function tRe(n,e,t,r){Uc(n),WE(t),e=jee(e),e.length>255&&(e=r(Mi($E("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=Mi(e,yh(e.length,1)),c=yh(0,o),u=yh(t,2),l=new Array(s),d=r(Mi(c,n,u,yh(0,1),a));l[0]=r(Mi(d,yh(1,1),a));for(let f=1;f<=s;f++){let m=[eRe(d,l[f-1]),yh(f+1,1),a];l[f]=r(Mi(...m))}return Mi(...l).slice(0,t)}function nRe(n,e,t,r,i){if(Uc(n),WE(t),e=jee(e),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update($E("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(yh(t,2)).update(e).update(yh(e.length,1)).digest()}function yO(n,e,t){c8(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:c}=t;if(!HLe(t.hash))throw new Error("expected valid hash");Uc(n),WE(e);let u=r.toString(2).length,l=Math.ceil((u+i)/8),d=e*o*l,h;if(a==="xmd")h=tRe(n,c,d,s);else if(a==="xof")h=nRe(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),T=h.subarray(S,S+l);w[b]=Ga($Le(T),r)}f[m]=w}return f}var rRe=$E("HashToScalar-");function hee(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=yO(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=yO(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:rRe},s);return yO(o,1,c)[0][0]}}}var s8=class extends t8{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Dee(e);let r=JO(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),$C(o)}update(e){return _C(this),this.iHash.update(e),this}digestInto(e){_C(this),Uc(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()}},Wee=(n,e,t)=>new s8(n,e).update(t).digest();Wee.create=(n,e)=>new s8(n,e);var pee=(n,e)=>(n+(n>=0?e:-e)/Zee)/e;function iRe(n,e,t){let[[r,i],[o,s]]=e,a=pee(s*n,t),c=pee(-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=tI(Math.ceil(jE(t)/2))+Q0;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 DO(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function wO(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return r8(t.lowS,"lowS"),r8(t.prehash,"prehash"),t.format!==void 0&&DO(t.format),t}var TO=class extends Error{constructor(e=""){super(e)}},bd={Err:TO,_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=YC(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?YC(i.length/2|128):"";return YC(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=YC(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 eI(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=bd,i=so("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),Q0=BigInt(1),Zee=BigInt(2),jC=BigInt(3),oRe=BigInt(4);function Id(n,e){let{BYTES:t}=n,r;if(typeof e=="bigint")r=e;else{let i=so("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 Xee(n,e={}){let t=_Le("weierstrass",n,e),{Fp:r,Fn:i}=t,o=t.CURVE,{h:s,n:a}=o;c8(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=$ee(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(r8(p,"isCompressed"),p){l();let C=!r.isOdd(y);return Mi(_ee(C),I)}else return Mi(Uint8Array.of(4),I,r.toBytes(y))}function h(Q){J0(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,jC),oRe),T=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(S,T)))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 iRe(Q,c.basises,i.ORDER)}let M=LO((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=LO(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 D(Q,v,p,x,y){return p=new z(r.mul(p.X,Q),p.Y,p.Z),v=o8(x,v),p=o8(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(J0(v,void 0,"point")));return p.assertValidity(),p}static fromHex(v){return z.fromBytes(so("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(jC),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,jC),{X:y,Y:I,Z:C}=this,F=r.ZERO,N=r.ZERO,O=r.ZERO,R=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(R,_),L=r.mul(v,L),L=r.add(L,O),O=r.add(R,R),R=r.add(O,R),R=r.add(R,_),R=r.mul(R,L),N=r.add(N,R),_=r.mul(I,C),_=r.add(_,_),R=r.mul(_,L),F=r.sub(F,R),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,R=r.ZERO,q=o.a,_=r.mul(o.b,jC),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),R=r.mul(q,V),N=r.mul(_,K),R=r.add(N,R),N=r.sub(g,R),R=r.add(g,R),O=r.mul(N,R),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),R=r.mul(J,R),R=r.add(R,L),new z(N,O,R)}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=>YE(z,F));if(p){let{k1neg:C,k1:F,k2neg:N,k2:O}=H(v),{p:R,f:q}=I(F),{p:_,f:L}=I(O);y=q.add(L),x=D(p.beta,R,_,C,N)}else{let{p:C,f:F}=I(v);x=C,y=F}return YE(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===Q0)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}=ZLe(z,x,I,F);return D(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===Q0?!0:v?v(z,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:v}=e;return s===Q0?this:v?v(z,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(v=!0){return r8(v,"isCompressed"),this.assertValidity(),f(z,this,v)}toHex(v=!0){return jy(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 YE(z,v)}static msm(v,p){return XLe(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 RO(z,e.endo?Math.ceil(j/2):j);return z.BASE.precompute(8),z}function _ee(n){return Uint8Array.of(n?2:3)}function $ee(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function sRe(n,e={}){let{Fn:t}=n,r=e.randomBytes||qO,i=Object.assign($ee(n.Fp,t),{seed:YO(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 Qee(J0(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=so("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 aRe(n,e,t={}){Dee(e),c8(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=t.randomBytes||qO,i=t.hmac||((p,...x)=>Wee(e,p,Mi(...x))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f}=sRe(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>>Q0;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 T(p,x){DO(x);let y=f.signature,I=x==="compact"?y:x==="recovered"?y+1:void 0;return J0(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){T(x,y);let I;if(y==="der"){let{r:O,s:R}=bd.toSig(J0(x));return new G(O,R)}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(e8(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*Zee<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 R=o.toBytes(O),q=n.fromBytes(Mi(_ee((F&1)===0),R)),_=s.inv(O),L=H(so("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(DO(x),x==="der")return e8(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 Mi(Uint8Array.of(this.recovery),y,I)}return Mi(y,I)}toHex(x){return jy(this.toBytes(x))}assertValidity(){}static fromCompact(x){return G.fromBytes(so("sig",x),"compact")}static fromDER(x){return G.fromBytes(so("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 jy(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return jy(this.toBytes("compact"))}}let U=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let y=eI(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=tI(c);function A(p){return NLe("num < 2^"+c,p,Ed,M),s.toBytes(p)}function D(p,x){return J0(p,void 0,"message"),x?J0(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}=wO(y,m);p=D(p,C);let N=H(p),O=Id(s,x),R=[A(O),A(N)];if(F!=null&&F!==!1){let g=F===!0?r(f.secretKey):F;R.push(so("extraEntropy",g))}let q=Mi(...R),_=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&Q0),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=so("message",p);let{seed:I,k2sig:C}=z(p,x,y);return GLe(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(so("sig",p),"der")}catch(C){if(!(C instanceof bd.Err))throw C}if(!x)try{x=G.fromBytes(so("sig",p),"compact")}catch{return!1}}return x||!1}function Q(p,x,y,I={}){let{lowS:C,prehash:F,format:N}=wO(I,m);if(y=so("publicKey",y),x=D(so("message",x),F),"strict"in I)throw new Error("options.strict was renamed to lowS");let O=N===void 0?Y(p):G.fromBytes(so("sig",p),N);if(O===!1)return!1;try{let R=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(R.multiplyUnsafe(E));return V.is0()?!1:s.create(V.x)===q}catch{return!1}}function v(p,x,y={}){let{prehash:I}=wO(y,m);return x=D(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 mee(n){let{CURVE:e,curveOpts:t}=ete(n),r=Xee(e,t);return lRe(n,r)}function ete(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=Zy(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 cRe(n){let{CURVE:e,curveOpts:t}=ete(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 uRe(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 lRe(n,e){let{Fp:t,Fn:r}=e;function i(s){return Oee(s,Q0,r.ORDER)}let o=uRe(t,n.a,n.b);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s=>Id(r,s),weierstrassEquation:o,isWithinCurveOrder:i})}function dRe(n,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},n,qee(t.Fn.ORDER,t.Fn.BITS))})}function fRe(n){let{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:i}=cRe(n),o=Xee(e,t),s=aRe(o,r,i);return dRe(n,s)}var hRe=BigInt(0),WC=BigInt(1),gee=BigInt(2),Yy=BigInt(3);function pRe(n){let e=[];for(;n>WC;n>>=WC)(n&WC)===hRe?e.unshift(0):(n&Yy)===Yy?(e.unshift(-1),n+=WC):e.unshift(1);return e}function bO(n){if(!Array.isArray(n)||n.length===0)throw new Error("expected non-empty array")}function mRe(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,D)=>o.mul014(M,G,i.mul(U,A),i.mul(H,D));else if(s==="divisive")l=(G,U,H,M,A,D)=>o.mul034(M,i.mul(H,D),i.mul(U,A),G);else throw new Error("bls: unknown twist type");let d=i.div(i.ONE,i.mul(i.ONE,gee));function h(G,U,H,M){let A=i.sqr(H),D=i.sqr(M),z=i.mulByB(i.mul(D,Yy)),j=i.mul(z,Yy),Y=i.sub(i.sub(i.sqr(i.add(H,M)),D),A),Q=i.sub(z,A),v=i.mul(i.sqr(U),Yy),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),Yy)),M=i.mul(A,Y),{Rx:U,Ry:H,Rz:M}}function f(G,U,H,M,A,D){let z=i.sub(H,i.mul(D,M)),j=i.sub(U,i.mul(A,M)),Y=i.sub(i.mul(z,A),i.mul(j,D)),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,gee)),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=pRe(a),w=LO(G=>{let U=G,{x:H,y:M}=U.toAffine(),A=H,D=M,z=i.neg(M),j=A,Y=D,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:D)),v.push(x)}if(u){let p=v[v.length-1];u(j,Y,Q,A,D,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[D,z,j]of G)for(let[Y,Q,v]of D[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=[];YE(e,G.map(({g1:M})=>M)),YE(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 D=M.toAffine();H.push([w(A),D.x,D.y])}return b(H,U)}function T(G,U,H=!0){return S([{g1:G,g2:U}],H)}return{Fp12:o,millerLoopBatch:b,pairing:T,pairingBatch:S,calcPairingPrecomputes:w}}function yee(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),T=d,G=s([l(w,S),l(b,T)]);return o.eql(G,o.ONE)},verifyBatch(d,h,f){if(bO(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 T=[],G=e.Point.BASE;try{for(let[U,H]of S){let M=H.reduce((A,D)=>A.add(D));T.push(l(M,U))}return T.push(l(G.negate(),m)),o.eql(s(T),o.ONE)}catch{return!1}},aggregatePublicKeys(d){bO(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){bO(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){Uc(d);let f=h?{DST:h}:void 0;return t.hashToCurve(d,f)},Signature:r}}function gRe(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=mee(n.G1),a=Object.assign(s,hee(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),c=mee(n.G2),u=Object.assign(c,hee(c.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),l=mRe(n.fields,a.Point,u.Point,{...n.params,postPrecompute:n.postPrecompute}),{millerLoopBatch:d,pairing:h,pairingBatch:f,calcPairingPrecomputes:m}=l,w=yee(l,a,u,n.G2.Signature,!1),b=yee(l,u,a,n.G1.ShortSignature,!0),S=n.randomBytes||qO,T=()=>{let C=YO(t.ORDER);return Qee(S(C),t.ORDER)},G={randomSecretKey:T,randomPrivateKey:T,calcPairingPrecomputes:m},{ShortSignature:U}=n.G1,{Signature:H}=n.G2;function M(C,F){return C instanceof a.Point?C:b.hash(so("point",C),F?.DST)}function A(C,F){return C instanceof u.Point?C:w.hash(so("point",C),F?.DST)}function D(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),R=w.sign(O,F);return C instanceof u.Point?R:H.toBytes(R)}function Y(C,F,N){let O=M(C,N),R=b.sign(O,F);return C instanceof a.Point?R:U.toBytes(R)}function Q(C,F,N,O){let R=A(F,O);return w.verify(C,R,N)}function v(C,F,N,O){let R=M(F,O);return b.verify(C,R,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 R=F.map(q=>A(q,O));return w.verifyBatch(C,R,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:D,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 wee=BigInt(0),Ad=BigInt(1),Yo=BigInt(2),bee=BigInt(3);function jO(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 yRe(n,e,t){let r=e.pow(t,(n.ORDER-Ad)/bee),i=e.pow(t,(n.ORDER-Ad)/Yo);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**Yo-Ad)/bee),a=e.pow(t,(n.ORDER**Yo-Ad)/Yo);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 Eee=(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]}},BO=class{constructor(e,t={}){this.MASK=Ad;let r=e.ORDER,i=r*r;this.Fp=e,this.ORDER=i,this.BITS=jE(i),this.BYTES=Math.ceil(jE(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,Yo),this.NONRESIDUE=Eee(e,t.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=jO(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=t.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return Eee(this.Fp,e)}create(e){return e}isValid({c0:e,c1:t}){function r(i,o){return typeof i=="bigint"&&wee<=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 u8(this,e,t)}invertBatch(e){return nI(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 i8(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);i8(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%Yo,o=t===wee,s=r%Yo;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 Mi(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])}}},PO=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=jO(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),Yo),a=i.mul(i.mul(t,r),Yo),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 ci()}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 u8(this,e,t)}invertBatch(e){return nI(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 Mi(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)}}},kO=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=jO(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){ci()}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 u8(this,e,t)}invertBatch(e){return nI(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 Mi(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),Yo),d),c1:i.add(i.mul(i.sub(f,s),Yo),f),c2:i.add(i.mul(i.sub(w,a),Yo),w)}),c1:r.create({c0:i.add(i.mul(i.add(S,c),Yo),S),c1:i.add(i.mul(i.add(h,u),Yo),h),c2:i.add(i.mul(i.add(m,l),Yo),m)})}}_cyclotomicExp(e,t){let r=this.ONE;for(let i=this.X_LEN-1;i>=0;i--)r=this._cyclotomicSquare(r),ULe(t,i)&&(r=this.mul(r,e));return r}};function wRe(n){let e=Zy(n.ORDER),t=new BO(e,n),r=new PO(t),i=new kO(r,n);return{Fp:e,Fp2:t,Fp6:r,Fp12:i}}var bRe=BigInt(0),MO=BigInt(1),tte=BigInt(2),ERe=BigInt(3),nte=BigInt(6),l8=BigInt("4965661367192848881"),IRe=jE(l8),ARe=nte*l8**tte,d8={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:MO,a:bRe,b:ERe,Gx:MO,Gy:BigInt(2)},Iee=Zy(d8.n),rte={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:ZE,Fp2:Ku,Fp6:xRe,Fp12:zn}=wRe({ORDER:d8.p,X_LEN:IRe,FP2_NONRESIDUE:[BigInt(9),MO],Fp2mulByB:n=>Ku.mul(n,rte),Fp12finalExponentiate:n=>{let e=l=>zn.conjugate(zn._cyclotomicExp(l,l8)),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:vRe,psi:Aee}=yRe(ZE,Ku,Ku.NONRESIDUE),EO=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:ZE.ORDER,m:2,k:128,expand:"xmd",hash:Bee}),SRe=(n,e,t,r,i,o)=>{let s=Aee(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=Aee(s[0],s[1]);o(n,e,t,a[0],Ku.neg(a[1]))},CRe={p:Ku.ORDER,n:d8.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:Ku.ZERO,b:rte,Gx:Ku.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:Ku.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},z0=gRe({fields:{Fp:ZE,Fp2:Ku,Fp6:xRe,Fp12:zn,Fr:Iee},G1:{...d8,Fp:ZE,htfDefaults:{...EO,m:1,DST:"BN254G2_XMD:SHA-256_SVDW_RO_"},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:ci,fromBytes:ci,toBytes:ci,ShortSignature:{fromBytes:ci,fromHex:ci,toBytes:ci,toRawBytes:ci,toHex:ci}},G2:{...CRe,Fp:Ku,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...EO},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(ARe).equals(vRe(n,e)),mapToCurve:ci,fromBytes:ci,toBytes:ci,Signature:{fromBytes:ci,fromHex:ci,toBytes:ci,toRawBytes:ci,toHex:ci}},params:{ateLoopSize:l8*nte+tte,r:Iee.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:EO,postPrecompute:SRe});fRe({a:BigInt(0),b:BigInt(3),Fp:ZE,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:Bee});var f8="groth16",LRe="auth",RRe="authV2",DRe="authV3",TRe="authV3-8-32",BRe=new TextDecoder,xee=BigInt(0),vee=z0.fields.Fp2,See=z0.fields.Fp12;async function WO(n,e,t){let r=await CLe(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:c}=await zC.prove(e,s);return{proof:a,pub_signals:c}}var[OO,PRe]=[z0.G1.ProjectivePoint,z0.G2.ProjectivePoint],ZC=([n,e])=>OO.fromAffine({x:BigInt(n),y:BigInt(e)}),XC=([[n,e],[t,r]])=>PRe.fromAffine({x:vee.fromBigTuple([BigInt(n),BigInt(e)]),y:vee.fromBigTuple([BigInt(t),BigInt(r)])});async function ZO(n,e,t,r){if(r(e.pub_signals).challenge!==JI(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(BRe.decode(t));return XO(e,o)}function XO(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=OO.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<xee||BigInt(r[s])>=z0.G1.CURVE.n)throw new Error(`Input value is not in the field ${z0.G1.CURVE.n}`);if(BigInt(r[s])!==xee){let[a,c]=e.IC[s+1].map(BigInt);i=i.add(OO.fromAffine({x:a,y:c}).multiply(BigInt(r[s])))}}i=i.add(ZC(e.IC[0]));let o=z0.pairingBatch([{g1:ZC(t.pi_a).negate(),g2:XC(t.pi_b)},{g1:i,g2:XC(e.vk_gamma_2)},{g1:ZC(t.pi_c),g2:XC(e.vk_delta_2)},{g1:ZC(e.vk_alpha_1),g2:XC(e.vk_beta_2)}]);return See.eql(o,See.ONE)}var FO=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 ZO(e,t,r,this.unmarshall)}prove(e,t,r){return WO(e,t,r)}},NO=new FO(new Nc(f8,LRe)),UO=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 ZO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await WO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await qE(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 UO(new Nc(f8,RRe)),a8=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 ZO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await WO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await qE(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])}}},HO=new a8(new Nc(f8,DRe)),KO=new a8(new Nc(f8,TRe));XE(NO.methodAlg,()=>NO);XE(GO.methodAlg,()=>GO);XE(HO.methodAlg,()=>HO);XE(KO.methodAlg,()=>KO);var Y0={registerProvingMethod:XE,getProvingMethod:Ree,provingMethodGroth16AuthInstance:NO,provingMethodGroth16AuthV2Instance:GO,provingMethodGroth16AuthV3Instance:HO,provingMethodGroth16AuthV3_8_32Instance:KO};var ite="unknown circuit ID. can't verify msg sender",h8="sender of message is not used for jwz token creation",ote="message was packed with unsupported circuit",ste="message proof is invalid",ate="message state verification failed",cte="unknown proving method algorithm";var{getProvingMethod:kRe}=Y0,rI=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},iI=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},oI=class{constructor(e,t,r={acceptedStateTransitionDelay:dM}){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 kRe(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(cte);let o=new wh(r,lt.decode(e),(a,c)=>i?.dataPreparer?.prepare(a,t.senderDID,c));o.setHeader(Ha.Type,"application/iden3-zkp-json");let s=await o.prove(i.provingKey,i.wasm);return ke.encode(s)}async unpackMessage(e,t){let r=this.verificationParamsMap.get(t.toString());if(!r?.key)throw new Error(ote);if(!await e.verify(r?.key))throw new Error(ste);if(!await r?.verificationFn?.verify(e.circuitId,e.zkProof.pub_signals,this._opts))throw new Error(ate);let s=JSON.parse(e.getPayload());return await MRe(e,s),s}parseToken(e){return wh.parse(lt.decode(e))}async unpack(e){let t=await this.parseToken(e),r=new Nc(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}=xs(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}},MRe=async(n,e)=>{switch(n.circuitId){case"authV2":case"authV3-8-32":case"authV3":{if(!e.from)throw new Error(h8);let t=(n.circuitId==="authV2"?new Zs:new Uu).pubSignalsUnmarshal(ke.encode(JSON.stringify(n.zkProof.pub_signals))),r=ve.parseFromId(t.userID),i=await n.getMessageHash();if(Ct.bytesToInt(i.reverse())!==t.challenge)throw new Error(h8);if(e.from!==r.string())throw new Error(h8)}break;default:throw new Error(ite)}};var _O=class extends oI{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 rI(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 Nc(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 iI(this.proofService.verifyState.bind(this.proofService))})}return super.unpackMessage(r,o)}};var ute=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(ute||{});var $O=(t=>(t.AUTHV2="authV2",t.ETH_IDENTITY="ethIdentity",t))($O||{});var lte=(e=>(e.FeatureType="feature-type",e))(lte||{}),dte=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(dte||{});var Hc=Y0.provingMethodGroth16AuthV2Instance.methodAlg,Oi=class{nextMessageHandler;setNext(e){return this.nextMessageHandler=e,e}async handle(e,t){return t.allowExpiredMessages||vr(e),this.nextMessageHandler?this.nextMessageHandler.handle(e,t):Promise.reject("Message handler not provided or message not supported")}},eF=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 Gc(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 Gc(e)},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};async function Gc(n){try{let e=lt.decode(n);return(await wh.parse(e)).method.methodAlg}catch{return Hc}}var ORe=n=>n.reduce((e,t)=>{let r=t.query.groupId;if(!r)return e;let i=e.get(r);if(!i){let s=Vc(12),c=new DataView(s.buffer).getUint32(0);return e.set(r,{query:t.query,linkNonce:c}),e}let o=v4(i.query.credentialSubject,t.query.credentialSubject);return e.set(r,{...i,query:{skipClaimRevocationCheck:i.query.skipClaimRevocationCheck||t.query.skipClaimRevocationCheck,...i.query,credentialSubject:o}}),e},new Map),Xy=async(n,e,t,r,i)=>{let o=e??[],s=ORe(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=h.groupId,m=s.get(f);if(f){if(!m)throw new Error(`Invalid group id ${h.groupId}`);let b=m.query;if(!a.has(f)){let S=await r.findCredentialByProofQuery(n,m.query);if(!S.cred){if(u.optional){console.log("No credential found for optional proof request, skipping");continue}throw new Error(Ge.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(b)}`)}a.set(f,S)}}let w=a.get(f);l=await r.generateProof(u,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h.skipClaimRevocationCheck,credential:w?.cred,credentialRevocationStatus:w?.revStatus,linkNonce:m?.linkNonce?BigInt(m.linkNonce):void 0,bypassCache:i.bypassProofsCache,allowExpiredCredentials:i.allowExpiredCredentials})}catch(d){let h=[Ge.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,Ge.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,Ge.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(Ge.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},tF=async(n,e,t)=>{switch(t.acceptProfile||(t.acceptProfile=DE),t.acceptProfile.env){case"application/iden3-zkp-json":if(!t.acceptProfile.circuits)throw new Error("Circuit not specified in accept profile");for(let r of t.acceptProfile.circuits){if(!t.supportedCircuits.includes(r))throw new Error(`Circuit ${r} is not supported`);if(!t.senderAddress)throw new Error("Sender address is not provided");let i=fte(t.senderAddress,t.zkpResponses),o=await e.generateAuthProof(r,n,{challenge:i});return{authProof:{authMethod:"authV2",zkp:o}}}throw new Error("Auth method is not supported");case"application/iden3comm-signed-json":if(!t.acceptProfile.alg||t.acceptProfile.alg.length===0)throw new Error("Algorithm not specified");if(t.acceptProfile.alg[0]==="ES256K-R")return{authProof:{authMethod:"ethIdentity",userDid:n}};throw new Error(`Algorithm ${t.acceptProfile.alg[0]} not supported`);default:throw new Error("Accept env not supported")}},sI=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=F0(n.proof),o=yC(t,i.a,i.b,i.c);return{requestId:e,zkProofEncoded:o,metadata:r}},fte=(n,e)=>{let t=e.map(r=>{let i=sI(r);return{requestId:i.requestId,proof:i.zkProofEncoded,metadata:i.metadata}});return BigInt(xn.keccak256(new xn.AbiCoder().encode(["address","(uint256 requestId,bytes proof,bytes metadata)[]"],[n,t])))&BigInt("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")},FRe=n=>new xn.AbiCoder().encode(["tuple(string key,bytes value)[]"],[n]),vr=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||Hc,senderDID:e?.senderDID||t?.senderDID};if(!r.senderDID)throw new Error("senderDID is required for ZKPMessage");return r}throw new Error(`unsupported media type ${n}`)};function NRe(n,e,t,r){return hte(n,"",e,t,r)}function hte(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 nF=class extends Oi{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=["credentialAtomicQueryV3-beta.1","credentialAtomicQuerySigV2","credentialAtomicQueryMTPV2","credentialAtomicQueryV3","linkedMultiQuery10-beta.1","linkedMultiQuery"];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 Xy(i,t?.body.scope,c,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits,bypassProofsCache:r.bypassProofsCache,allowExpiredCredentials:r.allowExpiredCredentials});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||vr(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:this.getDefaultProvingMethodAlg(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=rM(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||vr(t);let o=await this.handleAuthResponse(t,{request:r,acceptedStateTransitionDelay:i?.acceptedStateTransitionDelay,acceptedProofGenerationDelay:i?.acceptedProofGenerationDelay});return{request:r,response:o}}verifyAuthRequest(t){let r={},i=t.body.scope||[];for(let o of i){let s=o.query.groupId;if(s){let a=r[s]??[];for(let c of a){if(c.query.type!==o.query.type)throw new Error("all requests in the group should have the same type");if(c.query.context!==o.query.context)throw new Error("all requests in the group should have the same context");let u=o.query.allowedIssuers,l=c.query.allowedIssuers;if(!(u.includes("*")||u.every(d=>l.includes(d))))throw new Error("all requests in the group should have the same issuer")}r[s]=[...r[s]??[],o]}}}getSupportedMediaTypeByProfile(t,r){let i;if(!r?.length)return t.mediaType||"application/iden3-zkp-json";let o=[];for(let s of r){let{env:a}=xs(s);this._packerMgr.isProfileSupported(a,s)&&o.push(a)}if(!o.length)throw new Error("no packer with profile which meets `accept` header requirements");return i=o.includes("application/iden3-zkp-json")?"application/iden3-zkp-json":o[0],t.mediaType&&o.includes(t.mediaType)&&(i=t.mediaType),i}getDefaultProvingMethodAlg(t,r){if(!r?.length)return Hc;let i=[Y0.provingMethodGroth16AuthV3_8_32Instance.methodAlg,Y0.provingMethodGroth16AuthV3Instance.methodAlg];if(t){let o=i.indexOf(t);o!==-1&&i.splice(o,1),i.unshift(t)}for(let o of i)if(this._packerMgr.isProfileSupported("application/iden3-zkp-json",gM(o))&&yM(r,o))return o;return Hc}};var pte=[{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 aI=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new jt(e.url);let i=new Ln(t,pte,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 GRe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function HRe(n){return(GRe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function _y(n,e){return HRe(n).includes(e)}function j0(n){return _y(n,Ge.ERRORS.IDENTITY_DOES_NOT_EXIST)||_y(n,Ge.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function rF(n){return _y(n,Ge.ERRORS.STATE_DOES_NOT_EXIST)||_y(n,Ge.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function iF(n){return _y(n,Ge.ERRORS.ROOT_DOES_NOT_EXIST)||_y(n,Ge.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var oF=class{constructor(e,t){this._configs=e;this._stateStorage=new cI(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(!j0(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(!pf(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 aI(r,t)}};var W0=class{async resolve(e){let r=await(await fetch(e.id)).json();return p8(r)}},p8=({issuer:n,mtp:e})=>({mtp:kt.fromJSON(e),issuer:n});var Z0=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 sF=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 W0().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(!j0(l))throw l;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=be.fromHex(d).bigInt(),f=yp(t);if(!f&&!pf(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&&pf(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&&pf(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=Z0.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 KRe(n,e){let t=ve.parse(n),r=ve.idFromDID(t),{method:i,blockchain:o,networkId:s}=ve.decodePartsFromId(r),a=Ct.hexToBytes(e),c=Ct.bytesToInt(a),u=Yc(i,o,s);return mte(ve.idFromDID(t).bigInt(),c,u)}function mte(n,e,t){let r=Xe.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var uI=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var lI=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=JRe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return p8(a.body)}};function JRe(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 dI=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)}},aF=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=hb.getInstance();r.then(s=>o.publish(kR.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},X0=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 cF=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 uF=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new uI,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new W0),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new lI))}getCredentialStatusResolverRegistry(){return this._credentialStatusResolverRegistry}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:Ge.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ge.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(Ge.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:Ge.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ge.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=Zl(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(Ge.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(Ge.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(),Pr.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(Ge.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function m8(n,e,t,r){let i=await g8(r,e,n);await new X0().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function g8(n,e,t){let r=new lF;return n&&await VRe(r,e,n),await qRe(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new Z0(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function qRe(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function VRe(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var lF=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 Wc(o,s),c=await QRe(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 QRe(n,e){if(e.type!==oa)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 Z0;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=Lh([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var dF=class n extends Oi{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":uM[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(Pr.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||vr(i);let o=r?.mediaType||"application/iden3-zkp-json",s=ta(o,r?.packerOptions,{provingMethodAlg:r?.messageProvingMethodAlg||await Gc(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(Zl(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||vr(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=Pr.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");if(!(t.body.credential instanceof Pr))throw new Error("credential object is not properly unmarshaled");return await this.opts.credentialWallet.save(t.body.credential),null}async handleIssuanceResponseMessage(t,r){let i=await n.unpackMessage(this._packerMgr,t,at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);return r?.allowExpiredMessages||vr(i),i.body.credential=Pr.fromJSON(i.body.credential),await this.handleIssuanceResponseMsg(i),Uint8Array.from([])}static async unpackMessage(t,r,i){let{unpackedMessage:o}=await t.unpack(r),s=o;if(o.type!==i)throw new Error("Invalid message type");return s}};var fF=class extends Oi{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(na).find(f=>na[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 Xy(i,l,u,this._proofService,{ethSigner:o,challenge:s??Ct.bytesToInt(Ni(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=this.getFirstSupportedProfile(at.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE,t.body.accept),m=ve.parse(t.to),{authProof:w}=await tF(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.'")}}getFirstSupportedProfile(t,r){if(r?.length)for(let i of r){let o=xs(i),s=Number(t.split("/").at(-2));if(!(o.protocolVersion!=="iden3comm/v1"||o.protocolVersion==="iden3comm/v1"&&(s<1||s>=2))&&this._packerMgr.isProfileSupported(o.env,i))return o}return DE}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||vr(o),o.body.transaction_data.method_id!=="b68967e2")throw new Error("please use handle method to work with other method ids");if(o.type!==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(na).find(h=>na[h]===c))throw new Error(`Invalid chain id ${c}`);let l=o.from?ve.parse(o.from):void 0,d=await Xy(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 hF=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:Hc},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 Pr.fromJSON(d.body.credential)}};var pF=class extends Oi{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||vr(o);let s=await this.handleRevocationStatusRequestMessage(o,{senderDid:t,mediaType:i.mediaType,packerOptions:i.packerOptions,treeState:i.treeState});if(!o.to)throw new Error("failed request. empty 'to' field");let a=ve.parse(o.to),c=ta(i.mediaType,i.packerOptions,{senderDID:a,provingMethodAlg:i.packerOptions?.provingMethodAlg||await Gc(r)});return this._packerMgr.pack(i.mediaType,ke.encode(JSON.stringify(s)),c)}};function zRe(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 YRe(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 mF=class extends Oi{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=[];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.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||vr(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 Gc(t),senderDID:o});return this._packerMgr.pack(this._params.packerParams.mediaType,a,c)}async handleProposal(t,r){if(r?.allowExpiredMessages||vr(t),r?.proposalRequest&&r.proposalRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.proposalRequest.from}, given ${t.to}`);return{proposal:t}}};function gte(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 yte(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 gF=class extends Oi{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=yte(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||vr(i);let o=r.mediaType||this._params.packerParams.mediaType||"application/iden3-zkp-json";r.packerOptions||(r.packerOptions=this._params.packerParams.packerOptions),r.mediaType=o;let s=ve.parse(i.to);r.packerOptions=ta(o,r.packerOptions,{provingMethodAlg:await Gc(t),senderDID:s});let a=await this.handlePaymentRequestMessage(i,r);return a?this.packMessage(a,s,r.mediaType||"application/iden3-zkp-json",r.packerOptions):null}async handlePayment(t,r){if(r?.allowExpiredMessages||vr(t),r.paymentRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.paymentRequest.from}, given ${t.to}`);if(!t.body.payments.length)throw new Error("failed request. empty 'payments' field in body");if(!r.paymentValidationHandler)throw new Error("please provide payment validation handler in options");for(let i=0;i<t.body.payments.length;i++){let o=t.body.payments[i],s=o.type==="Iden3PaymentCryptoV1"?o.id:o.nonce,c=r.paymentRequest.body.payments.map(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:T}=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 D=T??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 xB(a.solSigner,A,b,H,U,BigInt(w),D,m);h.push(z)}else{let z=await vB(o,A,b,H,U,BigInt(w),D,m);h.push(z)}}c.push({data:h,credentials:l,description:d})}return gte(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||Hc};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 sS(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 oS(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 oS(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 sS(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 jRe(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 wte(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 yF=class extends Oi{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||vr(t);let i=[];for(let o of t.body.queries)i.push(...this.handleQuery(o));return Promise.resolve(wte(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 bte(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 WRe(n,e,t){return bte(e,{pthid:n,...t})}var Ete=new TextEncoder,_0=new TextDecoder,y8=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 wF(n,e,t){if(e<0||e>=y8)throw new RangeError(`value must be >= 0 and <= ${y8-1}. Received ${e}`);n.set([e>>>24,e>>>16,e>>>8,e&255],t)}function w8(n){let e=Math.floor(n/y8),t=n%y8,r=new Uint8Array(8);return wF(r,e,0),wF(r,t,4),r}function b8(n){let e=new Uint8Array(4);return wF(e,n),e}function Ka(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 Ite(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 Ate(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 Wr(n){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof n=="string"?n:_0.decode(n),{alphabet:"base64url"});let e=n;e instanceof Uint8Array&&(e=_0.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Ate(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Zr(n){let e=n;return typeof e=="string"&&(e=Ete.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Ite(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 fI=class extends $y{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Zt=class extends $y{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},bh=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 bF(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 Zt(`Unsupported JWE Algorithm: ${n}`)}}var xte=n=>crypto.getRandomValues(new Uint8Array(bF(n)>>3));function E8(n,e){if(e.length<<3!==bF(n))throw new Ve("Invalid Initialization Vector length")}function ew(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 Eh=(n,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${n}`),I8=(n,e)=>n.name===e;function ZRe(n){return parseInt(n.name.slice(4),10)}function XRe(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(!I8(n.algorithm,"AES-GCM"))throw Eh("AES-GCM");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw Eh(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!I8(n.algorithm,"AES-KW"))throw Eh("AES-KW");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw Eh(r,"algorithm.length");break}case"ECDH":{switch(n.algorithm.name){case"ECDH":case"X25519":break;default:throw Eh("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!I8(n.algorithm,"PBKDF2"))throw Eh("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!I8(n.algorithm,"RSA-OAEP"))throw Eh("RSA-OAEP");let r=parseInt(e.slice(9),10)||1;if(ZRe(n.algorithm.hash)!==r)throw Eh(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}XRe(n,t)}function vte(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 Ih=(n,...e)=>vte("Key must be ",n,...e),EF=(n,e,...t)=>vte(`Key for the ${n} algorithm must be `,e,...t);function $0(n){if(!Ju(n))throw new Error("CryptoKey instance expected")}var Ju=n=>{if(n?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return n instanceof CryptoKey}catch{return!1}},hI=n=>n?.[Symbol.toStringTag]==="KeyObject",IF=n=>Ju(n)||hI(n);async function _Re(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 $Re(n,e,t,r,i,o){if(!(e instanceof Uint8Array))throw new TypeError(Ih(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,w8(o.length<<3)),l=new Uint8Array((await crypto.subtle.sign("HMAC",c,u)).slice(0,s>>3)),d;try{d=await _Re(i,l)}catch{}if(!d)throw new bh;let h;try{h=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:"AES-CBC"},a,t))}catch{}if(!h)throw new bh;return h}async function eDe(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 bh}}async function A8(n,e,t,r,i,o){if(!Ju(e)&&!(e instanceof Uint8Array))throw new TypeError(Ih(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(E8(n,r),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&ew(e,parseInt(n.slice(-3),10)),$Re(n,e,t,r,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&ew(e,parseInt(n.slice(1,4),10)),eDe(n,e,t,r,i,o);default:throw new Zt("Unsupported JWE Content Encryption Algorithm")}}function tw(...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 tDe=n=>typeof n=="object"&&n!==null;function Wo(n){if(!tDe(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 Ste(n,e){if(n.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function Cte(n,e,t){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"AES-KW",!0,[t]):(Cs(n,e,t),n)}async function pI(n,e,t){let r=await Cte(e,n,"wrapKey");Ste(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 mI(n,e,t){let r=await Cte(e,n,"unwrapKey");Ste(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 Lte(n,e){let t=`SHA-${n.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(t,e))}function xF(n){return Ss(b8(n.length),n)}async function nDe(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(b8(a),0),c.set(n,4),c.set(t,4+n.length);let u=await Lte("sha256",c);s.set(u,(a-1)*i)}return s.slice(0,r)}async function x8(n,e,t,r,i=new Uint8Array,o=new Uint8Array){Cs(n,"ECDH"),Cs(e,"ECDH","deriveBits");let s=xF(Ka(t)),a=xF(i),c=xF(o),u=b8(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,rDe(n)));return nDe(h,r,d)}function rDe(n){return n.algorithm.name==="X25519"?256:Math.ceil(parseInt(n.algorithm.namedCurve.slice(-3),10)/8)<<3}function v8(n){switch(n.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return n.algorithm.name==="X25519"}}function iDe(n,e){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits"]):(Cs(n,e,"deriveBits"),n)}var oDe=(n,e)=>Ss(Ka(n),Uint8Array.of(0),e);async function Dte(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=oDe(e,n),o=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:t,name:"PBKDF2",salt:i},a=await iDe(r,e);return new Uint8Array(await crypto.subtle.deriveBits(s,a,o))}async function Tte(n,e,t,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let o=await Dte(i,n,r,e);return{encryptedKey:await pI(n.slice(-6),o,t),p2c:r,p2s:Zr(i)}}async function Bte(n,e,t,r,i){let o=await Dte(i,n,r,e);return mI(n.slice(-6),o,t)}function vF(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 kte=n=>{switch(n){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Zt(`alg ${n} is not supported either by JOSE or your javascript runtime`)}};async function Mte(n,e,t){return Cs(e,n,"encrypt"),vF(n,e),new Uint8Array(await crypto.subtle.encrypt(kte(n),e,t))}async function Ote(n,e,t){return Cs(e,n,"decrypt"),vF(n,e),new Uint8Array(await crypto.subtle.decrypt(kte(n),e,t))}function gI(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 Zt(`Unsupported JWE Algorithm: ${n}`)}}var qu=n=>crypto.getRandomValues(new Uint8Array(gI(n)>>3));function sDe(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 Zt('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 Zt('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 Zt('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 Zt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new Zt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}async function nw(n){if(!n.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:t}=sDe(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 Nte(n,e,t){if(!Wo(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 Wr(n.k);case"RSA":if("oth"in n&&n.oth!==void 0)throw new Zt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return nw({...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 nw({...n,ext:r})}case"EC":case"OKP":return nw({...n,alg:e,ext:r});default:throw new Zt('Unsupported "kty" (Key Type) Parameter value')}}async function aDe(n,e,t,r,i){if(!(t instanceof Uint8Array))throw new TypeError(Ih(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,w8(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 cDe(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 S8(n,e,t,r,i){if(!Ju(t)&&!(t instanceof Uint8Array))throw new TypeError(Ih(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(r?E8(n,r):r=xte(n),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ew(t,parseInt(n.slice(-3),10)),aDe(n,e,t,r,i);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ew(t,parseInt(n.slice(1,4),10)),cDe(n,e,t,r,i);default:throw new Zt("Unsupported JWE Content Encryption Algorithm")}}async function Ute(n,e,t,r){let i=n.slice(0,7),o=await S8(i,t,e,r,new Uint8Array);return{encryptedKey:o.ciphertext,iv:Zr(o.iv),tag:Zr(o.tag)}}async function Gte(n,e,t,r,i){let o=n.slice(0,7);return A8(o,e,t,r,i,new Uint8Array)}async function Hte(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(!Wo(r.epk))throw new Ve('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if($0(e),!v8(e))throw new Zt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await Nte(r.epk,n);$0(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=Wr(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=Wr(r.apv)}catch{throw new Ve("Failed to base64url decode the apv")}}let c=await x8(o,e,n==="ECDH-ES"?r.enc:n,n==="ECDH-ES"?gI(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 mI(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 $0(e),Ote(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=Wr(r.p2s)}catch{throw new Ve("Failed to base64url decode the p2s")}return Bte(n,e,t,r.p2c,s)}case"A128KW":case"A192KW":case"A256KW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");return mI(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=Wr(r.iv)}catch{throw new Ve("Failed to base64url decode the iv")}let s;try{s=Wr(r.tag)}catch{throw new Ve("Failed to base64url decode the tag")}return Gte(n,e,t,o,s)}default:throw new Zt('Invalid or unsupported "alg" (JWE Algorithm) header value')}}function rw(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 Zt(`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 SF(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 yI=n=>Wo(n)&&typeof n.kty=="string",Kte=n=>n.kty!=="oct"&&(n.kty==="AKP"&&typeof n.priv=="string"||typeof n.d=="string"),Jte=n=>n.kty!=="oct"&&n.d===void 0&&n.priv===void 0,qte=n=>n.kty==="oct"&&typeof n.k=="string";var iw,Vte=async(n,e,t,r=!1)=>{iw||=new WeakMap;let i=iw.get(n);if(i?.[t])return i[t];let o=await nw({...e,alg:t});return r&&Object.freeze(n),i?i[t]=o:iw.set(n,{[t]:o}),o},lDe=(n,e)=>{iw||=new WeakMap;let t=iw.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:iw.set(n,{[e]:o}),o};async function Ah(n,e){if(n instanceof Uint8Array||Ju(n))return n;if(hI(n)){if(n.type==="secret")return n.export();if("toCryptoKey"in n&&typeof n.toCryptoKey=="function")try{return lDe(n,e)}catch(r){if(r instanceof TypeError)throw r}let t=n.export({format:"jwk"});return Vte(n,t,e)}if(yI(n))return n.k?Wr(n.k):Vte(n,n,e,!0);throw new Error("unreachable")}var ow=n=>n?.[Symbol.toStringTag],CF=(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},dDe=(n,e,t)=>{if(!(e instanceof Uint8Array)){if(yI(e)){if(qte(e)&&CF(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(!IF(e))throw new TypeError(EF(n,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${ow(e)} instances for symmetric algorithms must be of type "secret"`)}},fDe=(n,e,t)=>{if(yI(e))switch(t){case"decrypt":case"sign":if(Kte(e)&&CF(n,e,t))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Jte(e)&&CF(n,e,t))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!IF(e))throw new TypeError(EF(n,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${ow(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(t){case"sign":throw new TypeError(`${ow(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ow(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(t){case"verify":throw new TypeError(`${ow(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ow(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function sw(n,e,t){switch(n.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":dDe(n,e,t);break;default:fDe(n,e,t)}}async function wI(n,e,t){if(!Wo(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&&!Wo(n.header))throw new Ve("JWE Shared Unprotected Header incorrect type");if(n.unprotected!==void 0&&!Wo(n.unprotected))throw new Ve("JWE Per-Recipient Unprotected Header incorrect type");let r;if(n.protected)try{let U=Wr(n.protected);r=JSON.parse(_0.decode(U))}catch{throw new Ve("JWE Protected Header is invalid")}if(!tw(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(rw(Ve,new Map,t?.crit,r,i),i.zip!==void 0)throw new Zt('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&&SF("keyManagementAlgorithms",t.keyManagementAlgorithms),c=t&&SF("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms);if(a&&!a.has(o)||!a&&o.startsWith("PBES2"))throw new fI('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(s))throw new fI('"enc" (Encryption Algorithm) Header Parameter value not allowed');let u;if(n.encrypted_key!==void 0)try{u=Wr(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),sw(o==="dir"?s:o,e,"decrypt");let d=await Ah(e,o),h;try{h=await Hte(o,d,u,i,t)}catch(U){if(U instanceof TypeError||U instanceof Ve||U instanceof Zt)throw U;h=qu(s)}let f,m;if(n.iv!==void 0)try{f=Wr(n.iv)}catch{throw new Ve("Failed to base64url decode the iv")}if(n.tag!==void 0)try{m=Wr(n.tag)}catch{throw new Ve("Failed to base64url decode the tag")}let w=n.protected!==void 0?Ka(n.protected):new Uint8Array,b;n.aad!==void 0?b=Ss(w,Ka("."),Ka(n.aad)):b=w;let S;try{S=Wr(n.ciphertext)}catch{throw new Ve("Failed to base64url decode the ciphertext")}let G={plaintext:await A8(s,h,S,f,m,b)};if(n.protected!==void 0&&(G.protectedHeader=r),n.aad!==void 0)try{G.additionalAuthenticatedData=Wr(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 LF(n,e,t){if(!Wo(n))throw new Ve("General JWE must be an object");if(!Array.isArray(n.recipients)||!n.recipients.every(Wo))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 wI({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 bh}var C8=Symbol();async function Qte(n){if(hI(n))if(n.type==="secret")n=n.export();else return n.export({format:"jwk"});if(n instanceof Uint8Array)return{kty:"oct",k:Zr(n)};if(!Ju(n))throw new TypeError(Ih(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 zte(n){return Qte(n)}async function L8(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($0(t),!v8(t))throw new Zt("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 Ah(i.epk,n):l=(await crypto.subtle.generateKey(t.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:h,crv:f,kty:m}=await zte(l),w=await x8(t,l,n==="ECDH-ES"?e:n,n==="ECDH-ES"?gI(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=Zr(c)),u&&(s.apv=Zr(u)),n==="ECDH-ES"){a=w;break}a=r||qu(e);let b=n.slice(-6);o=await pI(b,w,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=r||qu(e),$0(t),o=await Mte(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 Tte(n,t,a,c,u));break}case"A128KW":case"A192KW":case"A256KW":{a=r||qu(e),o=await pI(n,t,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=r||qu(e);let{iv:c}=i;({encryptedKey:o,...s}=await Ute(n,t,a,c));break}default:throw new Zt('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:a,encryptedKey:o,parameters:s}}var bI=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(!tw(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(rw(Ve,new Map,t?.crit,this.#t,r),r.zip!==void 0)throw new Zt('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}`);sw(i==="dir"?o:i,e,"encrypt");let a;{let b,S=await Ah(e,i);({cek:a,encryptedKey:s,parameters:b}=await L8(i,o,S,this.#o,this.#a)),b&&(t&&C8 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=Zr(JSON.stringify(this.#t)),l=Ka(u)):(u="",l=new Uint8Array),this.#i){d=Zr(this.#i);let b=Ka(d);c=Ss(l,Ka("."),b)}else c=l;let{ciphertext:h,tag:f,iv:m}=await S8(o,this.#e,a,this.#s,c),w={ciphertext:Zr(h)};return m&&(w.iv=Zr(m)),f&&(w.tag=Zr(f)),s&&(w.encrypted_key=Zr(s)),d&&(w.aad=d),this.#t&&(w.protected=u),this.#n&&(w.unprotected=this.#n),this.#r&&(w.header=this.#r),w}};var RF=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}},EI=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let r=new RF(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 bI(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(!tw(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(rw(Ve,new Map,o.options.crit,this.#n,s),s.zip!==void 0)throw new Zt('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 bI(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(o.unprotectedHeader).setKeyManagementParameters(o.keyManagementParameters).encrypt(o.key,{...o.options,[C8]:!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;sw(a==="dir"?e:a,o.key,"encrypt");let c=await Ah(o.key,a),{encryptedKey:u,parameters:l}=await L8(a,e,c,t,o.keyManagementParameters);s.encrypted_key=Zr(u),(o.unprotectedHeader||l)&&(s.header={...o.unprotectedHeader,...l})}return r}};function DF(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(_0.decode(Wr(e)));if(!Wo(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var R8=class{constructor(e){this.resolvePrivateKeyByKid=e}async encrypt(e,t){let{enc:r,typ:i,recipients:o}=t,s=new EI(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(DF(r),r.header||{}),wI(e,t)}return LF(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 D8=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 BF={};Sr(BF,{DeviceNotificationStatus:()=>Wte,NotificationServiceType:()=>Yte,NotificationStatus:()=>jte,PushNotifier:()=>TF});var Yte=(e=>(e.Push="push-notification",e))(Yte||{}),jte=(t=>(t.Success="success",t.Failed="failed",t))(jte||{});var Wte=(r=>(r.Success="success",r.Rejected="rejected",r.Failed="failed",r))(Wte||{}),hDe={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()}}}},TF=class{constructor(e=hDe){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},Zte={state:0n,replacedByState:0n,createdAtTimestamp:0n,replacedAtTimestamp:0n,createdAtBlock:0n,replacedAtBlock:0n},cI=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,iM,this.provider),this._transactionService=new Xs(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??Yr.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??fg},this._stateCacheOptions={notReplacedTtl:t?.stateCacheOptions?.notReplacedTtl??Yr.DEFAULT_PROOF_VERIFY_DELAY/2,replacedTtl:t?.stateCacheOptions?.replacedTtl??Yr.DEFAULT_PROOF_VERIFY_DELAY,maxSize:t?.stateCacheOptions?.maxSize??fg},this._rootCacheOptions={replacedTtl:t?.rootCacheOptions?.replacedTtl??Yr.DEFAULT_AUTH_VERIFY_DELAY,notReplacedTtl:t?.rootCacheOptions?.notReplacedTtl??Yr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.rootCacheOptions?.maxSize??fg},this._gistProofCacheOptions={ttl:Yr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??fg},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??lh({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??lh({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??lh({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??lh({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(Ge.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 j0(s)&&!this._disableCache&&await this._latestStateResolveCache?.set(t,{id:e,...Zte},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(!rF(a))throw a;if(!Ax(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,...Zte,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 xE;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=F0(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),T={to:S.to,data:S.data,gasLimit:b,maxFeePerGas:m,maxPriorityFeePerGas:w},{txnHash:G}=await this._transactionService.sendTransactionRequest(t,T);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),T={to:S.to,data:S.data,gasLimit:b,maxFeePerGas:f,maxPriorityFeePerGas:m},{txnHash:G}=await this._transactionService.sendTransactionRequest(e,T);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=rm(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=rm(ve.blockchainFromId(t),ve.networkIdFromId(t)),i=this.networkByChainId(r),o=new jt(i.url);return{stateContract:new Ln(i.contractAddress,iM,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 PF=[{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 kF=[{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 MF=10000000n,Xte=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(Xte||{}),_te=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]},OF=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 _supportedCircuitsPubSignalsMap={credentialAtomicQueryMTPV2OnChain:{ctor:pE},credentialAtomicQuerySigV2OnChain:{ctor:IE},"credentialAtomicQueryV3OnChain-beta.1":{ctor:My},credentialAtomicQueryV3OnChain:{ctor:My},authV2:{ctor:Zs},authV3:{ctor:Uu},"authV3-8-32":{ctor:Uu,opts:{mtLevel:8,mtLevelClaim:32}}};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=F0(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,PF);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=MF}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,PF).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:c,maxPriorityFeePerGas:u},f;try{f=await e.estimateGas(h)}catch{f=MF}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,kF).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=MF}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":{let f=F0(i.zkp.proof);u=yC(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{u=$te(i.userDid);break}default:throw new Error("auth proof must use method AuthV2 or ethIdentity")}for(let f of r){this.checkSupportedCircuit(f.circuitId);let{requestId:m,zkProofEncoded:w,metadata:b}=sI(f);a.push({proof:f,requestId:m,encoded:w,metadata:b})}let l=r.map(f=>({circuitId:f.circuitId,pub_signals:f.pub_signals}));i.authMethod=="authV2"&&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:_te(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(!nM(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}=sI(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 xn.AbiCoder().encode(["tuple(string proofType,bytes proof)[]"],[r])}static packGlobalStateMsg(e){return new xn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,bytes2 idType,uint256 root,uint256 replacedAtTimestamp) globalStateMsg,bytes signature,)"],[e])}static packIdentityStateMsg(e){return new xn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,uint256 id,uint256 state,uint256 replacedAtTimestamp) idStateMsg,bytes signature,)"],[e])}static getOnChainGistRootStatePubSignals(e,t){let r=this._supportedCircuitsPubSignalsMap[e].ctor;if(!r)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=new r(this._supportedCircuitsPubSignalsMap[e].opts),o=ke.encode(JSON.stringify(t));return i.pubSignalsUnmarshal(o).getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await wp(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}}},$te=n=>`0x${Rr(Ct.intToBytes(ve.idFromDID(n).bigInt()))}`;var FF=[{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 NF=[{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"}],aw=class{static abi=NF;static createInterface(){return new dc(NF)}static connect(e,t){return new Ln(e,NF,t)}};var II=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=xn.getAddress(xn.hexlify(Xe.ethAddressFromId(ve.idFromDID(t)))),this._contract=aw.connect(this._contractAddress,new xn.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 Fr().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:ra(Number(e.issuanceDate)).getTime()},a=await this.existenceProof(i),c=Pr.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 Gr.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=ra(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 mc({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:c,coreClaim:e})}async validateSourceValue(e,t,r){if(await Tu.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 UF=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 II(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 II(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=xn.getAddress(xn.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,FF,new xn.JsonRpcProvider(o.url)),connection:o}}};var GF=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 wp(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 wp(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 wp(ve.parseFromId(Xe.fromBigInt(e)),this.resolverUrl,r),{info:o,published:s}=this.getIden3StateInfo2023(i);if(!o&&!s)throw new Error(Ge.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 ene=[{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 tne=[{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 ADe(n,e,t,r,i,o){let s=new Ln(e,ene,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 xDe(n,e){return new Ln(n,tne,e).decimals()}var ane=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(ane||{}),cne=(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))(cne||{}),HF=[!0,1,"true"],KF=[!1,0,"false"],nne=(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,HF.includes(n)&&HF.includes(e)||KF.includes(n)&&KF.includes(e)?!0:n===e),rne=(n,e)=>lne(n,e,(r,i)=>{switch(dne(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}}),ine=(n,e)=>lne(n,e,(r,i)=>{switch(dne(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}}),vDe=(n,e)=>!!(HF.includes(e)&&typeof n<"u"||KF.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),one=(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,sne=(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))},Vu={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>vDe(n,e),$eq:(n,e)=>nne(n,e),$in:(n,e)=>one(n,e),$nin:(n,e)=>!one(n,e),$gt:(n,e)=>rne(n,e),$lt:(n,e)=>!ine(n,e),$ne:(n,e)=>!nne(n,e),$gte:(n,e)=>ine(n,e),$lte:(n,e)=>!rne(n,e),$between:(n,e)=>sne(n,e),$nonbetween:(n,e)=>!sne(n,e)},une=(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},Kc=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=une(e,this.path);return t==null&&this.operatorFunc!==Vu.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},JF=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new Kc("id",Vu.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new Kc("issuer",Vu.$in,r));case"type":return e.concat(new Kc("type",Vu.$in,r,!0));case"context":return e.concat(new Kc("@context",Vu.$in,r,!0));case"credentialSubjectId":return e.concat(new Kc("credentialSubject.id",Vu.$eq,r));case"schema":return e.concat(new Kc("credentialSchema.id",Vu.$eq,r));case"credentialSubject":{let i=Object.keys(r).reduce((o,s)=>{let a=r[s];if(typeof a=="object"&&Object.keys(a).length===0)return o.concat([new Kc(`credentialSubject.${s}`,Vu.$noop,null)]);let c=Object.keys(a).map(u=>{let l=a[u],d=`credentialSubject.${s}`;return new Kc(d,Vu[u],l)});return o.concat(c)},[]);return e.concat(i)}case"proofType":case"groupId":case"skipClaimRevocationCheck":return e;default:throw new Error(`${t} : not defined query key`)}},[]),lne=(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),SDe=/^[+-]?\d+$/,CDe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,LDe=/^([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]))$/,RDe=/^(true)|(false)$/,DDe=/^\d{4}-\d{2}-\d{2}$/,dne=n=>SDe.test(n)?0:CDe.test(n)?2:LDe.test(n)||DDe.test(n)?3:RDe.test(n)?1:4;var qF=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 VF=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=Oy(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify([...i,...a])),[...i,...a]}let r=Oy(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 sa(new bw(Zc(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 sa(new bw(Zc(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 QF=class{constructor(e){this._storageKey=e;this._store=Od(`${e}-db`,e)}_store;async save(e,t,r="id"){return Fd(e,t,this._store)}async get(e,t="id"){return jc(e,this._store)}async load(){return zN(this._store)}async delete(e,t="id"){return VI(e,this._store)}};var zF=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=Od(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=Od(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Ut()}`),await jc(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=Oy(e);return await Fd(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await jc(e,this._merkleTreeMetaStore);if(t)return t;throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=await jc(e,this._merkleTreeMetaStore),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let o=r.find(s=>s.identifier===e&&s.type===t);if(!o)throw i;return new sa(new Ew(Zc(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await jc(e,this._merkleTreeMetaStore);if(!o)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=o.find(c=>c.identifier===e&&c.type===t);if(!s)throw new Error(`Merkle tree not found for identifier ${e} and type ${t}`);await new sa(new Ew(Zc(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await jc(e,this._merkleTreeMetaStore);if(!r||!r?.length)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=r.map(o=>({...o,identifier:t}));await VI(e,this._merkleTreeMetaStore),await Fd(t,i,this._merkleTreeMetaStore),await Fd(e,t,this._bindingStore)}};var YF=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 jF=class{constructor(e){this._dataSource=e}static storageKey="credentials";async listCredentials(){return(await this._dataSource.load()).filter(t=>t!==void 0).map(t=>t&&Pr.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&&Pr.fromJSON(t)}async findCredentialsByQuery(e){let t=JF(e);return(await this._dataSource.load()).filter(o=>t.every(s=>s.execute(o))).filter(o=>o!==void 0).map(o=>Pr.fromJSON(o))}};var WF=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 ZF=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 Qu=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:X5(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},xh=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}},T8=n=>{if(!n)return[{operator:dn.$noop,fieldName:""}];let e=[],t=Object.entries(n);if(!t.length)throw new Error("query must have at least 1 predicate");for(let[r,i]of t){let o=Object.entries(i);if(o.length===0){e.push({operator:dn.$sd,fieldName:r});continue}for(let[a,c]of o){if(!dn[a])throw new Error("operator is not supported by lib");let u=dn[a];e.push({operator:u,fieldName:r,operatorValue:c})}}return e},B8=async(n,e,t,r)=>{let i={...n,slotIndex:0,merklizedSchema:!1,datatype:"",claimPathKey:BigInt(0),values:[],path:new Gr};if(!n.fieldName&&n.operator!==0)throw new Error("query must have a field name if operator is not $noop");if(n.fieldName&&(i.datatype=await Gr.newTypeFromContext(e,`${t}.${n.fieldName}`,r)),await Q2(JSON.parse(e),r,t)||(i.merklizedSchema=!0),!i.merklizedSchema)i.slotIndex=await V2(n.fieldName,t,ke.encode(e));else try{let s=await b6(e,t,n.fieldName,r);i.claimPathKey=await s.mtEntry(),i.path=s}catch(s){throw new Error(`field does not exist in the schema ${s.message}`)}if(n.operatorValue!==void 0){if(!$5(i.datatype,n.operator))throw new Error(`operator ${n.operator} is not supported for datatype ${i.datatype}`);if((n.operator===0||n.operator===16)&&n.operatorValue)throw new Error(`operator value should be undefined for ${n.operator} operator`);let s;switch(n.operator){case 0:case 16:s=[];break;case 11:s=TDe(n.operatorValue);break;default:s=await P8(n.operatorValue,i.datatype)}i.values=s}return i},AI=async(n,e,t,r)=>{let i=T8(t);return Promise.all(i.map(o=>B8(o,e,n,r)))},P8=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await Tu.hashValue(e,n[r]);else t[0]=await Tu.hashValue(e,n);return t},TDe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")};async function $F(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=LLe(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(xO(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 LLe(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 xO(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 RLe(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 DLe(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 zy=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 vO(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Uc(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 Dee(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");vO(n.outputLen),vO(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 TLe(n,e){Uc(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function $C(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function fO(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Hu(n,e){return n<<32-e|n>>>e}var Tee=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",BLe=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function jy(n){if(Uc(n),Tee)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=BLe[n[t]];return e}var wd={_0:48,_9:57,A:65,F:70,a:97,f:102};function cee(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 e8(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(Tee)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=cee(n.charCodeAt(o)),a=cee(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 $E(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function JO(n){return typeof n=="string"&&(n=$E(n)),Uc(n),n}function Mi(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];Uc(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 t8=class{};function PLe(n){let e=r=>n().update(JO(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function qO(n=32){if(zy&&typeof zy.getRandomValues=="function")return zy.getRandomValues(new Uint8Array(n));if(zy&&typeof zy.randomBytes=="function")return Uint8Array.from(zy.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function kLe(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 MLe(n,e,t){return n&e^~n&t}function OLe(n,e,t){return n&e^n&t^e&t}var SO=class extends t8{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=fO(this.buffer)}update(e){_C(this),e=JO(e),Uc(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=fO(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),TLe(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,$C(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;kLe(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=fO(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()}},mh=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),FLe=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]),gh=new Uint32Array(64),CO=class extends SO{constructor(e=32){super(64,e,8,!1),this.A=mh[0]|0,this.B=mh[1]|0,this.C=mh[2]|0,this.D=mh[3]|0,this.E=mh[4]|0,this.F=mh[5]|0,this.G=mh[6]|0,this.H=mh[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)gh[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=gh[d-15],f=gh[d-2],m=Hu(h,7)^Hu(h,18)^h>>>3,w=Hu(f,17)^Hu(f,19)^f>>>10;gh[d]=w+gh[d-7]+m+gh[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=Hu(a,6)^Hu(a,11)^Hu(a,25),f=l+h+MLe(a,c,u)+FLe[d]+gh[d]|0,w=(Hu(r,2)^Hu(r,13)^Hu(r,22))+OLe(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(){$C(gh)}destroy(){this.set(0,0,0,0,0,0,0,0),$C(this.buffer)}},Bee=PLe(()=>new CO);var VO=BigInt(0),n8=BigInt(1);function r8(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function J0(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 YC(n){let e=n.toString(16);return e.length&1?"0"+e:e}function Pee(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?VO:BigInt("0x"+n)}function eI(n){return Pee(jy(n))}function kee(n){return Uc(n),Pee(jy(Uint8Array.from(n).reverse()))}function QO(n,e){return e8(n.toString(16).padStart(e*2,"0"))}function Mee(n,e){return QO(n,e).reverse()}function so(n,e,t){let r;if(typeof e=="string")try{r=e8(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 hO=n=>typeof n=="bigint"&&VO<=n;function Oee(n,e,t){return hO(n)&&hO(e)&&hO(t)&&e<=n&&n<t}function NLe(n,e,t,r){if(!Oee(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function jE(n){let e;for(e=0;n>VO;n>>=n8,e+=1);return e}function ULe(n,e){return n>>BigInt(e)&n8}var tI=n=>(n8<<BigInt(n))-n8;function GLe(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 Mi(...m)};return(f,m)=>{c(),l(f);let w;for(;!(w=m(d()));)l();return c(),w}}function HLe(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function c8(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 ci=()=>{throw new Error("not implemented")};function LO(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),jo=BigInt(1),q0=BigInt(2),Fee=BigInt(3),Nee=BigInt(4),Uee=BigInt(5),KLe=BigInt(7),Gee=BigInt(8),JLe=BigInt(9),Hee=BigInt(16);function Ga(n,e){let t=n%e;return t>=ea?t:e+t}function uee(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=Ga(n,e),r=e,i=ea,o=jo;for(;t!==ea;){let a=r/t,c=r%t,u=i-o*a;r=t,t=c,i=o,o=u}if(r!==jo)throw new Error("invert: does not exist");return Ga(i,e)}function zO(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Kee(n,e){let t=(n.ORDER+jo)/Nee,r=n.pow(e,t);return zO(n,r,e),r}function qLe(n,e){let t=(n.ORDER-Uee)/Gee,r=n.mul(e,q0),i=n.pow(r,t),o=n.mul(e,i),s=n.mul(n.mul(o,q0),i),a=n.mul(o,n.sub(s,n.ONE));return zO(n,a,e),a}function VLe(n){let e=Zy(n),t=Jee(n),r=t(e,e.neg(e.ONE)),i=t(e,r),o=t(e,e.neg(r)),s=(n+KLe)/Hee;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 zO(a,b,c),b}}function Jee(n){if(n<Fee)throw new Error("sqrt is not defined for small field");let e=n-jo,t=0;for(;e%q0===ea;)e/=q0,t++;let r=q0,i=Zy(n);for(;i8(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Kee;let o=i.pow(r,e),s=(e+jo)/q0;return function(c,u){if(c.is0(u))return u;if(i8(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=jo<<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 QLe(n){return n%Nee===Fee?Kee:n%Gee===Uee?qLe:n%Hee===JLe?VLe(n):Jee(n)}var zLe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function YLe(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=zLe.reduce((r,i)=>(r[i]="function",r),e);return c8(n,t),n}function u8(n,e,t){if(t<ea)throw new Error("invalid exponent, negatives unsupported");if(t===ea)return n.ONE;if(t===jo)return e;let r=n.ONE,i=e;for(;t>ea;)t&jo&&(r=n.mul(r,i)),i=n.sqr(i),t>>=jo;return r}function nI(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 i8(n,e){let t=(n.ORDER-jo)/q0,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 qee(n,e){e!==void 0&&vO(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Zy(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}=qee(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:tI(c),ZERO:ea,ONE:jo,allowedLengths:a,create:h=>Ga(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&jo)===jo,neg:h=>Ga(-h,n),eql:(h,f)=>h===f,sqr:h=>Ga(h*h,n),add:(h,f)=>Ga(h+f,n),sub:(h,f)=>Ga(h-f,n),mul:(h,f)=>Ga(h*f,n),pow:(h,f)=>u8(d,h,f),div:(h,f)=>Ga(h*uee(f,n),n),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>uee(h,n),sqrt:o||(h=>(l||(l=QLe(n)),l(d,h))),toBytes:h=>t?Mee(h,u):QO(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?kee(h):eI(h);if(s&&(m=Ga(m,n)),!f&&!d.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:h=>nI(d,h),cmov:(h,f,m)=>m?f:h});return Object.freeze(d)}function Vee(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 YO(n){let e=Vee(n);return e+Math.ceil(e/2)}function Qee(n,e,t=!1){let r=n.length,i=Vee(e),o=YO(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?kee(n):eI(n),a=Ga(s,e-jo)+jo;return t?Mee(a,i):QO(a,i)}var Wy=BigInt(0),V0=BigInt(1);function o8(n,e){let t=e.negate();return n?t:e}function YE(n,e){let t=nI(n.Fp,e.map(r=>r.Z));return e.map((r,i)=>n.fromAffine(r.toAffine(t[i])))}function zee(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function pO(n,e){zee(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=tI(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function lee(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+=V0);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 jLe(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 WLe(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 mO=new WeakMap,Yee=new WeakMap;function gO(n){return Yee.get(n)||1}function dee(n){if(n!==Wy)throw new Error("invalid wNAF")}var RO=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>Wy;)t&V0&&(r=r.add(i)),i=i.double(),t>>=V0;return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=pO(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=pO(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:h,offsetF:f}=lee(r,a,s);r=c,l?o=o.add(o8(h,t[f])):i=i.add(o8(d,t[u]))}return dee(r),{p:i,f:o}}wNAFUnsafe(e,t,r,i=this.ZERO){let o=pO(e,this.bits);for(let s=0;s<o.windows&&r!==Wy;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=lee(r,s,o);if(r=a,!u){let d=t[c];i=i.add(l?d.negate():d)}}return dee(r),i}getPrecomputes(e,t,r){let i=mO.get(t);return i||(i=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(i=r(i)),mO.set(t,i))),i}cached(e,t,r){let i=gO(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let o=gO(e);return o===1?this._unsafeLadder(e,t,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,i)}createCache(e,t){zee(t,this.bits),Yee.set(e,t),mO.delete(e)}hasCache(e){return gO(e)!==1}};function ZLe(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Wy||r>Wy;)t&V0&&(o=o.add(i)),r&V0&&(s=s.add(i)),i=i.double(),t>>=V0,r>>=V0;return{p1:o,p2:s}}function XLe(n,e,t,r){jLe(t,n),WLe(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=jE(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=tI(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 fee(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return YLe(e),e}else return Zy(n,{isLE:t})}function _Le(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>Wy))throw new Error(`CURVE.${c} must be positive bigint`)}let i=fee(e.p,t.Fp,r),o=fee(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 $Le=eI;function yh(n,e){if(WE(n),WE(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 eRe(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 WE(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function jee(n){if(!_E(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or string");return typeof n=="string"?$E(n):n}function tRe(n,e,t,r){Uc(n),WE(t),e=jee(e),e.length>255&&(e=r(Mi($E("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=Mi(e,yh(e.length,1)),c=yh(0,o),u=yh(t,2),l=new Array(s),d=r(Mi(c,n,u,yh(0,1),a));l[0]=r(Mi(d,yh(1,1),a));for(let f=1;f<=s;f++){let m=[eRe(d,l[f-1]),yh(f+1,1),a];l[f]=r(Mi(...m))}return Mi(...l).slice(0,t)}function nRe(n,e,t,r,i){if(Uc(n),WE(t),e=jee(e),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update($E("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(yh(t,2)).update(e).update(yh(e.length,1)).digest()}function yO(n,e,t){c8(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:c}=t;if(!HLe(t.hash))throw new Error("expected valid hash");Uc(n),WE(e);let u=r.toString(2).length,l=Math.ceil((u+i)/8),d=e*o*l,h;if(a==="xmd")h=tRe(n,c,d,s);else if(a==="xof")h=nRe(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),T=h.subarray(S,S+l);w[b]=Ga($Le(T),r)}f[m]=w}return f}var rRe=$E("HashToScalar-");function hee(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=yO(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=yO(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:rRe},s);return yO(o,1,c)[0][0]}}}var s8=class extends t8{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Dee(e);let r=JO(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),$C(o)}update(e){return _C(this),this.iHash.update(e),this}digestInto(e){_C(this),Uc(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()}},Wee=(n,e,t)=>new s8(n,e).update(t).digest();Wee.create=(n,e)=>new s8(n,e);var pee=(n,e)=>(n+(n>=0?e:-e)/Zee)/e;function iRe(n,e,t){let[[r,i],[o,s]]=e,a=pee(s*n,t),c=pee(-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=tI(Math.ceil(jE(t)/2))+Q0;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 DO(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function wO(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return r8(t.lowS,"lowS"),r8(t.prehash,"prehash"),t.format!==void 0&&DO(t.format),t}var TO=class extends Error{constructor(e=""){super(e)}},bd={Err:TO,_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=YC(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?YC(i.length/2|128):"";return YC(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=YC(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 eI(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=bd,i=so("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),Q0=BigInt(1),Zee=BigInt(2),jC=BigInt(3),oRe=BigInt(4);function Id(n,e){let{BYTES:t}=n,r;if(typeof e=="bigint")r=e;else{let i=so("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 Xee(n,e={}){let t=_Le("weierstrass",n,e),{Fp:r,Fn:i}=t,o=t.CURVE,{h:s,n:a}=o;c8(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=$ee(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(r8(p,"isCompressed"),p){l();let C=!r.isOdd(y);return Mi(_ee(C),I)}else return Mi(Uint8Array.of(4),I,r.toBytes(y))}function h(Q){J0(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,jC),oRe),T=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(S,T)))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 iRe(Q,c.basises,i.ORDER)}let M=LO((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=LO(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 D(Q,v,p,x,y){return p=new z(r.mul(p.X,Q),p.Y,p.Z),v=o8(x,v),p=o8(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(J0(v,void 0,"point")));return p.assertValidity(),p}static fromHex(v){return z.fromBytes(so("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(jC),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,jC),{X:y,Y:I,Z:C}=this,F=r.ZERO,N=r.ZERO,O=r.ZERO,R=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(R,_),L=r.mul(v,L),L=r.add(L,O),O=r.add(R,R),R=r.add(O,R),R=r.add(R,_),R=r.mul(R,L),N=r.add(N,R),_=r.mul(I,C),_=r.add(_,_),R=r.mul(_,L),F=r.sub(F,R),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,R=r.ZERO,q=o.a,_=r.mul(o.b,jC),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),R=r.mul(q,V),N=r.mul(_,K),R=r.add(N,R),N=r.sub(g,R),R=r.add(g,R),O=r.mul(N,R),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),R=r.mul(J,R),R=r.add(R,L),new z(N,O,R)}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=>YE(z,F));if(p){let{k1neg:C,k1:F,k2neg:N,k2:O}=H(v),{p:R,f:q}=I(F),{p:_,f:L}=I(O);y=q.add(L),x=D(p.beta,R,_,C,N)}else{let{p:C,f:F}=I(v);x=C,y=F}return YE(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===Q0)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}=ZLe(z,x,I,F);return D(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===Q0?!0:v?v(z,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:v}=e;return s===Q0?this:v?v(z,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(v=!0){return r8(v,"isCompressed"),this.assertValidity(),f(z,this,v)}toHex(v=!0){return jy(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 YE(z,v)}static msm(v,p){return XLe(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 RO(z,e.endo?Math.ceil(j/2):j);return z.BASE.precompute(8),z}function _ee(n){return Uint8Array.of(n?2:3)}function $ee(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function sRe(n,e={}){let{Fn:t}=n,r=e.randomBytes||qO,i=Object.assign($ee(n.Fp,t),{seed:YO(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 Qee(J0(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=so("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 aRe(n,e,t={}){Dee(e),c8(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=t.randomBytes||qO,i=t.hmac||((p,...x)=>Wee(e,p,Mi(...x))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f}=sRe(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>>Q0;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 T(p,x){DO(x);let y=f.signature,I=x==="compact"?y:x==="recovered"?y+1:void 0;return J0(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){T(x,y);let I;if(y==="der"){let{r:O,s:R}=bd.toSig(J0(x));return new G(O,R)}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(e8(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*Zee<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 R=o.toBytes(O),q=n.fromBytes(Mi(_ee((F&1)===0),R)),_=s.inv(O),L=H(so("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(DO(x),x==="der")return e8(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 Mi(Uint8Array.of(this.recovery),y,I)}return Mi(y,I)}toHex(x){return jy(this.toBytes(x))}assertValidity(){}static fromCompact(x){return G.fromBytes(so("sig",x),"compact")}static fromDER(x){return G.fromBytes(so("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 jy(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return jy(this.toBytes("compact"))}}let U=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let y=eI(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=tI(c);function A(p){return NLe("num < 2^"+c,p,Ed,M),s.toBytes(p)}function D(p,x){return J0(p,void 0,"message"),x?J0(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}=wO(y,m);p=D(p,C);let N=H(p),O=Id(s,x),R=[A(O),A(N)];if(F!=null&&F!==!1){let g=F===!0?r(f.secretKey):F;R.push(so("extraEntropy",g))}let q=Mi(...R),_=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&Q0),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=so("message",p);let{seed:I,k2sig:C}=z(p,x,y);return GLe(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(so("sig",p),"der")}catch(C){if(!(C instanceof bd.Err))throw C}if(!x)try{x=G.fromBytes(so("sig",p),"compact")}catch{return!1}}return x||!1}function Q(p,x,y,I={}){let{lowS:C,prehash:F,format:N}=wO(I,m);if(y=so("publicKey",y),x=D(so("message",x),F),"strict"in I)throw new Error("options.strict was renamed to lowS");let O=N===void 0?Y(p):G.fromBytes(so("sig",p),N);if(O===!1)return!1;try{let R=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(R.multiplyUnsafe(E));return V.is0()?!1:s.create(V.x)===q}catch{return!1}}function v(p,x,y={}){let{prehash:I}=wO(y,m);return x=D(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 mee(n){let{CURVE:e,curveOpts:t}=ete(n),r=Xee(e,t);return lRe(n,r)}function ete(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=Zy(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 cRe(n){let{CURVE:e,curveOpts:t}=ete(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 uRe(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 lRe(n,e){let{Fp:t,Fn:r}=e;function i(s){return Oee(s,Q0,r.ORDER)}let o=uRe(t,n.a,n.b);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s=>Id(r,s),weierstrassEquation:o,isWithinCurveOrder:i})}function dRe(n,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},n,qee(t.Fn.ORDER,t.Fn.BITS))})}function fRe(n){let{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:i}=cRe(n),o=Xee(e,t),s=aRe(o,r,i);return dRe(n,s)}var hRe=BigInt(0),WC=BigInt(1),gee=BigInt(2),Yy=BigInt(3);function pRe(n){let e=[];for(;n>WC;n>>=WC)(n&WC)===hRe?e.unshift(0):(n&Yy)===Yy?(e.unshift(-1),n+=WC):e.unshift(1);return e}function bO(n){if(!Array.isArray(n)||n.length===0)throw new Error("expected non-empty array")}function mRe(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,D)=>o.mul014(M,G,i.mul(U,A),i.mul(H,D));else if(s==="divisive")l=(G,U,H,M,A,D)=>o.mul034(M,i.mul(H,D),i.mul(U,A),G);else throw new Error("bls: unknown twist type");let d=i.div(i.ONE,i.mul(i.ONE,gee));function h(G,U,H,M){let A=i.sqr(H),D=i.sqr(M),z=i.mulByB(i.mul(D,Yy)),j=i.mul(z,Yy),Y=i.sub(i.sub(i.sqr(i.add(H,M)),D),A),Q=i.sub(z,A),v=i.mul(i.sqr(U),Yy),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),Yy)),M=i.mul(A,Y),{Rx:U,Ry:H,Rz:M}}function f(G,U,H,M,A,D){let z=i.sub(H,i.mul(D,M)),j=i.sub(U,i.mul(A,M)),Y=i.sub(i.mul(z,A),i.mul(j,D)),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,gee)),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=pRe(a),w=LO(G=>{let U=G,{x:H,y:M}=U.toAffine(),A=H,D=M,z=i.neg(M),j=A,Y=D,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:D)),v.push(x)}if(u){let p=v[v.length-1];u(j,Y,Q,A,D,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[D,z,j]of G)for(let[Y,Q,v]of D[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=[];YE(e,G.map(({g1:M})=>M)),YE(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 D=M.toAffine();H.push([w(A),D.x,D.y])}return b(H,U)}function T(G,U,H=!0){return S([{g1:G,g2:U}],H)}return{Fp12:o,millerLoopBatch:b,pairing:T,pairingBatch:S,calcPairingPrecomputes:w}}function yee(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),T=d,G=s([l(w,S),l(b,T)]);return o.eql(G,o.ONE)},verifyBatch(d,h,f){if(bO(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 T=[],G=e.Point.BASE;try{for(let[U,H]of S){let M=H.reduce((A,D)=>A.add(D));T.push(l(M,U))}return T.push(l(G.negate(),m)),o.eql(s(T),o.ONE)}catch{return!1}},aggregatePublicKeys(d){bO(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){bO(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){Uc(d);let f=h?{DST:h}:void 0;return t.hashToCurve(d,f)},Signature:r}}function gRe(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=mee(n.G1),a=Object.assign(s,hee(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),c=mee(n.G2),u=Object.assign(c,hee(c.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),l=mRe(n.fields,a.Point,u.Point,{...n.params,postPrecompute:n.postPrecompute}),{millerLoopBatch:d,pairing:h,pairingBatch:f,calcPairingPrecomputes:m}=l,w=yee(l,a,u,n.G2.Signature,!1),b=yee(l,u,a,n.G1.ShortSignature,!0),S=n.randomBytes||qO,T=()=>{let C=YO(t.ORDER);return Qee(S(C),t.ORDER)},G={randomSecretKey:T,randomPrivateKey:T,calcPairingPrecomputes:m},{ShortSignature:U}=n.G1,{Signature:H}=n.G2;function M(C,F){return C instanceof a.Point?C:b.hash(so("point",C),F?.DST)}function A(C,F){return C instanceof u.Point?C:w.hash(so("point",C),F?.DST)}function D(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),R=w.sign(O,F);return C instanceof u.Point?R:H.toBytes(R)}function Y(C,F,N){let O=M(C,N),R=b.sign(O,F);return C instanceof a.Point?R:U.toBytes(R)}function Q(C,F,N,O){let R=A(F,O);return w.verify(C,R,N)}function v(C,F,N,O){let R=M(F,O);return b.verify(C,R,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 R=F.map(q=>A(q,O));return w.verifyBatch(C,R,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:D,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 wee=BigInt(0),Ad=BigInt(1),Yo=BigInt(2),bee=BigInt(3);function jO(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 yRe(n,e,t){let r=e.pow(t,(n.ORDER-Ad)/bee),i=e.pow(t,(n.ORDER-Ad)/Yo);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**Yo-Ad)/bee),a=e.pow(t,(n.ORDER**Yo-Ad)/Yo);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 Eee=(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]}},BO=class{constructor(e,t={}){this.MASK=Ad;let r=e.ORDER,i=r*r;this.Fp=e,this.ORDER=i,this.BITS=jE(i),this.BYTES=Math.ceil(jE(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,Yo),this.NONRESIDUE=Eee(e,t.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=jO(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=t.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return Eee(this.Fp,e)}create(e){return e}isValid({c0:e,c1:t}){function r(i,o){return typeof i=="bigint"&&wee<=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 u8(this,e,t)}invertBatch(e){return nI(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 i8(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);i8(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%Yo,o=t===wee,s=r%Yo;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 Mi(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])}}},PO=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=jO(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),Yo),a=i.mul(i.mul(t,r),Yo),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 ci()}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 u8(this,e,t)}invertBatch(e){return nI(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 Mi(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)}}},kO=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=jO(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){ci()}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 u8(this,e,t)}invertBatch(e){return nI(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 Mi(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),Yo),d),c1:i.add(i.mul(i.sub(f,s),Yo),f),c2:i.add(i.mul(i.sub(w,a),Yo),w)}),c1:r.create({c0:i.add(i.mul(i.add(S,c),Yo),S),c1:i.add(i.mul(i.add(h,u),Yo),h),c2:i.add(i.mul(i.add(m,l),Yo),m)})}}_cyclotomicExp(e,t){let r=this.ONE;for(let i=this.X_LEN-1;i>=0;i--)r=this._cyclotomicSquare(r),ULe(t,i)&&(r=this.mul(r,e));return r}};function wRe(n){let e=Zy(n.ORDER),t=new BO(e,n),r=new PO(t),i=new kO(r,n);return{Fp:e,Fp2:t,Fp6:r,Fp12:i}}var bRe=BigInt(0),MO=BigInt(1),tte=BigInt(2),ERe=BigInt(3),nte=BigInt(6),l8=BigInt("4965661367192848881"),IRe=jE(l8),ARe=nte*l8**tte,d8={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:MO,a:bRe,b:ERe,Gx:MO,Gy:BigInt(2)},Iee=Zy(d8.n),rte={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:ZE,Fp2:Ku,Fp6:xRe,Fp12:zn}=wRe({ORDER:d8.p,X_LEN:IRe,FP2_NONRESIDUE:[BigInt(9),MO],Fp2mulByB:n=>Ku.mul(n,rte),Fp12finalExponentiate:n=>{let e=l=>zn.conjugate(zn._cyclotomicExp(l,l8)),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:vRe,psi:Aee}=yRe(ZE,Ku,Ku.NONRESIDUE),EO=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:ZE.ORDER,m:2,k:128,expand:"xmd",hash:Bee}),SRe=(n,e,t,r,i,o)=>{let s=Aee(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=Aee(s[0],s[1]);o(n,e,t,a[0],Ku.neg(a[1]))},CRe={p:Ku.ORDER,n:d8.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:Ku.ZERO,b:rte,Gx:Ku.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:Ku.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},z0=gRe({fields:{Fp:ZE,Fp2:Ku,Fp6:xRe,Fp12:zn,Fr:Iee},G1:{...d8,Fp:ZE,htfDefaults:{...EO,m:1,DST:"BN254G2_XMD:SHA-256_SVDW_RO_"},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:ci,fromBytes:ci,toBytes:ci,ShortSignature:{fromBytes:ci,fromHex:ci,toBytes:ci,toRawBytes:ci,toHex:ci}},G2:{...CRe,Fp:Ku,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...EO},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(ARe).equals(vRe(n,e)),mapToCurve:ci,fromBytes:ci,toBytes:ci,Signature:{fromBytes:ci,fromHex:ci,toBytes:ci,toRawBytes:ci,toHex:ci}},params:{ateLoopSize:l8*nte+tte,r:Iee.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:EO,postPrecompute:SRe});fRe({a:BigInt(0),b:BigInt(3),Fp:ZE,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:Bee});var f8="groth16",LRe="auth",RRe="authV2",DRe="authV3",TRe="authV3-8-32",BRe=new TextDecoder,xee=BigInt(0),vee=z0.fields.Fp2,See=z0.fields.Fp12;async function WO(n,e,t){let r=await CLe(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:c}=await zC.prove(e,s);return{proof:a,pub_signals:c}}var[OO,PRe]=[z0.G1.ProjectivePoint,z0.G2.ProjectivePoint],ZC=([n,e])=>OO.fromAffine({x:BigInt(n),y:BigInt(e)}),XC=([[n,e],[t,r]])=>PRe.fromAffine({x:vee.fromBigTuple([BigInt(n),BigInt(e)]),y:vee.fromBigTuple([BigInt(t),BigInt(r)])});async function ZO(n,e,t,r){if(r(e.pub_signals).challenge!==JI(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(BRe.decode(t));return XO(e,o)}function XO(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=OO.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<xee||BigInt(r[s])>=z0.G1.CURVE.n)throw new Error(`Input value is not in the field ${z0.G1.CURVE.n}`);if(BigInt(r[s])!==xee){let[a,c]=e.IC[s+1].map(BigInt);i=i.add(OO.fromAffine({x:a,y:c}).multiply(BigInt(r[s])))}}i=i.add(ZC(e.IC[0]));let o=z0.pairingBatch([{g1:ZC(t.pi_a).negate(),g2:XC(t.pi_b)},{g1:i,g2:XC(e.vk_gamma_2)},{g1:ZC(t.pi_c),g2:XC(e.vk_delta_2)},{g1:ZC(e.vk_alpha_1),g2:XC(e.vk_beta_2)}]);return See.eql(o,See.ONE)}var FO=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 ZO(e,t,r,this.unmarshall)}prove(e,t,r){return WO(e,t,r)}},NO=new FO(new Nc(f8,LRe)),UO=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 ZO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await WO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await qE(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 UO(new Nc(f8,RRe)),a8=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 ZO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await WO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await qE(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])}}},HO=new a8(new Nc(f8,DRe)),KO=new a8(new Nc(f8,TRe));XE(NO.methodAlg,()=>NO);XE(GO.methodAlg,()=>GO);XE(HO.methodAlg,()=>HO);XE(KO.methodAlg,()=>KO);var Y0={registerProvingMethod:XE,getProvingMethod:Ree,provingMethodGroth16AuthInstance:NO,provingMethodGroth16AuthV2Instance:GO,provingMethodGroth16AuthV3Instance:HO,provingMethodGroth16AuthV3_8_32Instance:KO};var ite="unknown circuit ID. can't verify msg sender",h8="sender of message is not used for jwz token creation",ote="message was packed with unsupported circuit",ste="message proof is invalid",ate="message state verification failed",cte="unknown proving method algorithm";var{getProvingMethod:kRe}=Y0,rI=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},iI=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},oI=class{constructor(e,t,r={acceptedStateTransitionDelay:dM}){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 kRe(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(cte);let o=new wh(r,lt.decode(e),(a,c)=>i?.dataPreparer?.prepare(a,t.senderDID,c));o.setHeader(Ha.Type,"application/iden3-zkp-json");let s=await o.prove(i.provingKey,i.wasm);return ke.encode(s)}async unpackMessage(e,t){let r=this.verificationParamsMap.get(t.toString());if(!r?.key)throw new Error(ote);if(!await e.verify(r?.key))throw new Error(ste);if(!await r?.verificationFn?.verify(e.circuitId,e.zkProof.pub_signals,this._opts))throw new Error(ate);let s=JSON.parse(e.getPayload());return await MRe(e,s),s}parseToken(e){return wh.parse(lt.decode(e))}async unpack(e){let t=await this.parseToken(e),r=new Nc(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}=xs(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}},MRe=async(n,e)=>{switch(n.circuitId){case"authV2":case"authV3-8-32":case"authV3":{if(!e.from)throw new Error(h8);let t=(n.circuitId==="authV2"?new Zs:new Uu).pubSignalsUnmarshal(ke.encode(JSON.stringify(n.zkProof.pub_signals))),r=ve.parseFromId(t.userID),i=await n.getMessageHash();if(Ct.bytesToInt(i.reverse())!==t.challenge)throw new Error(h8);if(e.from!==r.string())throw new Error(h8)}break;default:throw new Error(ite)}};var _O=class extends oI{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 rI(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 Nc(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 iI(this.proofService.verifyState.bind(this.proofService))})}return super.unpackMessage(r,o)}};var ute=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(ute||{});var $O=(t=>(t.AUTHV2="authV2",t.ETH_IDENTITY="ethIdentity",t))($O||{});var lte=(e=>(e.FeatureType="feature-type",e))(lte||{}),dte=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(dte||{});var Hc=Y0.provingMethodGroth16AuthV2Instance.methodAlg,Oi=class{nextMessageHandler;setNext(e){return this.nextMessageHandler=e,e}async handle(e,t){return t.allowExpiredMessages||vr(e),this.nextMessageHandler?this.nextMessageHandler.handle(e,t):Promise.reject("Message handler not provided or message not supported")}},eF=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 Gc(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 Gc(e)},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};async function Gc(n){try{let e=lt.decode(n);return(await wh.parse(e)).method.methodAlg}catch{return Hc}}var ORe=n=>n.reduce((e,t)=>{let r=t.query.groupId;if(!r)return e;let i=e.get(r);if(!i){let s=Vc(12),c=new DataView(s.buffer).getUint32(0);return e.set(r,{query:t.query,linkNonce:c}),e}let o=v4(i.query.credentialSubject,t.query.credentialSubject);return e.set(r,{...i,query:{skipClaimRevocationCheck:i.query.skipClaimRevocationCheck||t.query.skipClaimRevocationCheck,...i.query,credentialSubject:o}}),e},new Map),Xy=async(n,e,t,r,i)=>{let o=e??[],s=ORe(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=h.groupId,m=s.get(f);if(f){if(!m)throw new Error(`Invalid group id ${h.groupId}`);let b=m.query;if(!a.has(f)){let S=await r.findCredentialByProofQuery(n,m.query);if(!S.cred){if(u.optional){console.log("No credential found for optional proof request, skipping");continue}throw new Error(Ge.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(b)}`)}a.set(f,S)}}let w=a.get(f);l=await r.generateProof(u,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h.skipClaimRevocationCheck,credential:w?.cred,credentialRevocationStatus:w?.revStatus,linkNonce:m?.linkNonce?BigInt(m.linkNonce):void 0,bypassCache:i.bypassProofsCache,allowExpiredCredentials:i.allowExpiredCredentials})}catch(d){let h=[Ge.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,Ge.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,Ge.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED,Ge.ERRORS.PROOF_SERVICE_CREDENTIAL_IS_EXPIRED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(Ge.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},tF=async(n,e,t)=>{switch(t.acceptProfile||(t.acceptProfile=DE),t.acceptProfile.env){case"application/iden3-zkp-json":if(!t.acceptProfile.circuits)throw new Error("Circuit not specified in accept profile");for(let r of t.acceptProfile.circuits){if(!t.supportedCircuits.includes(r))throw new Error(`Circuit ${r} is not supported`);if(!t.senderAddress)throw new Error("Sender address is not provided");let i=fte(t.senderAddress,t.zkpResponses),o=await e.generateAuthProof(r,n,{challenge:i});return{authProof:{authMethod:"authV2",zkp:o}}}throw new Error("Auth method is not supported");case"application/iden3comm-signed-json":if(!t.acceptProfile.alg||t.acceptProfile.alg.length===0)throw new Error("Algorithm not specified");if(t.acceptProfile.alg[0]==="ES256K-R")return{authProof:{authMethod:"ethIdentity",userDid:n}};throw new Error(`Algorithm ${t.acceptProfile.alg[0]} not supported`);default:throw new Error("Accept env not supported")}},sI=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=F0(n.proof),o=yC(t,i.a,i.b,i.c);return{requestId:e,zkProofEncoded:o,metadata:r}},fte=(n,e)=>{let t=e.map(r=>{let i=sI(r);return{requestId:i.requestId,proof:i.zkProofEncoded,metadata:i.metadata}});return BigInt(xn.keccak256(new xn.AbiCoder().encode(["address","(uint256 requestId,bytes proof,bytes metadata)[]"],[n,t])))&BigInt("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")},FRe=n=>new xn.AbiCoder().encode(["tuple(string key,bytes value)[]"],[n]),vr=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||Hc,senderDID:e?.senderDID||t?.senderDID};if(!r.senderDID)throw new Error("senderDID is required for ZKPMessage");return r}throw new Error(`unsupported media type ${n}`)};function NRe(n,e,t,r){return hte(n,"",e,t,r)}function hte(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 nF=class extends Oi{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=["credentialAtomicQueryV3-beta.1","credentialAtomicQuerySigV2","credentialAtomicQueryMTPV2","credentialAtomicQueryV3","linkedMultiQuery10-beta.1","linkedMultiQuery"];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 Xy(i,t?.body.scope,c,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits,bypassProofsCache:r.bypassProofsCache,allowExpiredCredentials:r.allowExpiredCredentials});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||vr(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:this.getDefaultProvingMethodAlg(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=rM(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||vr(t);let o=await this.handleAuthResponse(t,{request:r,acceptedStateTransitionDelay:i?.acceptedStateTransitionDelay,acceptedProofGenerationDelay:i?.acceptedProofGenerationDelay});return{request:r,response:o}}verifyAuthRequest(t){let r={},i=t.body.scope||[];for(let o of i){let s=o.query.groupId;if(s){let a=r[s]??[];for(let c of a){if(c.query.type!==o.query.type)throw new Error("all requests in the group should have the same type");if(c.query.context!==o.query.context)throw new Error("all requests in the group should have the same context");let u=o.query.allowedIssuers,l=c.query.allowedIssuers;if(!(u.includes("*")||u.every(d=>l.includes(d))))throw new Error("all requests in the group should have the same issuer")}r[s]=[...r[s]??[],o]}}}getSupportedMediaTypeByProfile(t,r){let i;if(!r?.length)return t.mediaType||"application/iden3-zkp-json";let o=[];for(let s of r){let{env:a}=xs(s);this._packerMgr.isProfileSupported(a,s)&&o.push(a)}if(!o.length)throw new Error("no packer with profile which meets `accept` header requirements");return i=o.includes("application/iden3-zkp-json")?"application/iden3-zkp-json":o[0],t.mediaType&&o.includes(t.mediaType)&&(i=t.mediaType),i}getDefaultProvingMethodAlg(t,r){if(!r?.length)return Hc;let i=[Y0.provingMethodGroth16AuthV3_8_32Instance.methodAlg,Y0.provingMethodGroth16AuthV3Instance.methodAlg];if(t){let o=i.indexOf(t);o!==-1&&i.splice(o,1),i.unshift(t)}for(let o of i)if(this._packerMgr.isProfileSupported("application/iden3-zkp-json",gM(o))&&yM(r,o))return o;return Hc}};var pte=[{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 aI=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new jt(e.url);let i=new Ln(t,pte,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 GRe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function HRe(n){return(GRe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function _y(n,e){return HRe(n).includes(e)}function j0(n){return _y(n,Ge.ERRORS.IDENTITY_DOES_NOT_EXIST)||_y(n,Ge.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function rF(n){return _y(n,Ge.ERRORS.STATE_DOES_NOT_EXIST)||_y(n,Ge.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function iF(n){return _y(n,Ge.ERRORS.ROOT_DOES_NOT_EXIST)||_y(n,Ge.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var oF=class{constructor(e,t){this._configs=e;this._stateStorage=new cI(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(!j0(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(!pf(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 aI(r,t)}};var W0=class{async resolve(e){let r=await(await fetch(e.id)).json();return p8(r)}},p8=({issuer:n,mtp:e})=>({mtp:kt.fromJSON(e),issuer:n});var Z0=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 sF=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 W0().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(!j0(l))throw l;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=be.fromHex(d).bigInt(),f=yp(t);if(!f&&!pf(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&&pf(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&&pf(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=Z0.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 KRe(n,e){let t=ve.parse(n),r=ve.idFromDID(t),{method:i,blockchain:o,networkId:s}=ve.decodePartsFromId(r),a=Ct.hexToBytes(e),c=Ct.bytesToInt(a),u=Yc(i,o,s);return mte(ve.idFromDID(t).bigInt(),c,u)}function mte(n,e,t){let r=Xe.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var uI=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var lI=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=JRe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return p8(a.body)}};function JRe(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 dI=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)}},aF=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=hb.getInstance();r.then(s=>o.publish(kR.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},X0=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 cF=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 uF=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new uI,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new W0),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new lI))}getCredentialStatusResolverRegistry(){return this._credentialStatusResolverRegistry}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:Ge.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ge.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(Ge.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:Ge.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ge.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=Zl(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(Ge.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(Ge.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(),Pr.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(Ge.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function m8(n,e,t,r){let i=await g8(r,e,n);await new X0().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function g8(n,e,t){let r=new lF;return n&&await VRe(r,e,n),await qRe(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new Z0(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function qRe(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function VRe(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var lF=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 Wc(o,s),c=await QRe(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 QRe(n,e){if(e.type!==oa)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 Z0;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=Lh([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var dF=class n extends Oi{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":uM[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(Pr.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||vr(i);let o=r?.mediaType||"application/iden3-zkp-json",s=ta(o,r?.packerOptions,{provingMethodAlg:r?.messageProvingMethodAlg||await Gc(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(Zl(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||vr(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=Pr.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");if(!(t.body.credential instanceof Pr))throw new Error("credential object is not properly unmarshaled");return await this.opts.credentialWallet.save(t.body.credential),null}async handleIssuanceResponseMessage(t,r){let i=await n.unpackMessage(this._packerMgr,t,at.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);return r?.allowExpiredMessages||vr(i),i.body.credential=Pr.fromJSON(i.body.credential),await this.handleIssuanceResponseMsg(i),Uint8Array.from([])}static async unpackMessage(t,r,i){let{unpackedMessage:o}=await t.unpack(r),s=o;if(o.type!==i)throw new Error("Invalid message type");return s}};var fF=class extends Oi{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(na).find(f=>na[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 Xy(i,l,u,this._proofService,{ethSigner:o,challenge:s??Ct.bytesToInt(Ni(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=this.getFirstSupportedProfile(at.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE,t.body.accept),m=ve.parse(t.to),{authProof:w}=await tF(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.'")}}getFirstSupportedProfile(t,r){if(r?.length)for(let i of r){let o=xs(i),s=Number(t.split("/").at(-2));if(!(o.protocolVersion!=="iden3comm/v1"||o.protocolVersion==="iden3comm/v1"&&(s<1||s>=2))&&this._packerMgr.isProfileSupported(o.env,i))return o}return DE}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||vr(o),o.body.transaction_data.method_id!=="b68967e2")throw new Error("please use handle method to work with other method ids");if(o.type!==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(na).find(h=>na[h]===c))throw new Error(`Invalid chain id ${c}`);let l=o.from?ve.parse(o.from):void 0,d=await Xy(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 hF=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:Hc},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 Pr.fromJSON(d.body.credential)}};var pF=class extends Oi{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||vr(o);let s=await this.handleRevocationStatusRequestMessage(o,{senderDid:t,mediaType:i.mediaType,packerOptions:i.packerOptions,treeState:i.treeState});if(!o.to)throw new Error("failed request. empty 'to' field");let a=ve.parse(o.to),c=ta(i.mediaType,i.packerOptions,{senderDID:a,provingMethodAlg:i.packerOptions?.provingMethodAlg||await Gc(r)});return this._packerMgr.pack(i.mediaType,ke.encode(JSON.stringify(s)),c)}};function zRe(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 YRe(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 mF=class extends Oi{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=[];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.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||vr(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 Gc(t),senderDID:o});return this._packerMgr.pack(this._params.packerParams.mediaType,a,c)}async handleProposal(t,r){if(r?.allowExpiredMessages||vr(t),r?.proposalRequest&&r.proposalRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.proposalRequest.from}, given ${t.to}`);return{proposal:t}}};function gte(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 yte(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 gF=class extends Oi{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=yte(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||vr(i);let o=r.mediaType||this._params.packerParams.mediaType||"application/iden3-zkp-json";r.packerOptions||(r.packerOptions=this._params.packerParams.packerOptions),r.mediaType=o;let s=ve.parse(i.to);r.packerOptions=ta(o,r.packerOptions,{provingMethodAlg:await Gc(t),senderDID:s});let a=await this.handlePaymentRequestMessage(i,r);return a?this.packMessage(a,s,r.mediaType||"application/iden3-zkp-json",r.packerOptions):null}async handlePayment(t,r){if(r?.allowExpiredMessages||vr(t),r.paymentRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.paymentRequest.from}, given ${t.to}`);if(!t.body.payments.length)throw new Error("failed request. empty 'payments' field in body");if(!r.paymentValidationHandler)throw new Error("please provide payment validation handler in options");for(let i=0;i<t.body.payments.length;i++){let o=t.body.payments[i],s=o.type==="Iden3PaymentCryptoV1"?o.id:o.nonce,c=r.paymentRequest.body.payments.map(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:T}=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 D=T??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 xB(a.solSigner,A,b,H,U,BigInt(w),D,m);h.push(z)}else{let z=await vB(o,A,b,H,U,BigInt(w),D,m);h.push(z)}}c.push({data:h,credentials:l,description:d})}return gte(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||Hc};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 sS(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 oS(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 oS(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 sS(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 jRe(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 wte(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 yF=class extends Oi{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||vr(t);let i=[];for(let o of t.body.queries)i.push(...this.handleQuery(o));return Promise.resolve(wte(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 bte(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 WRe(n,e,t){return bte(e,{pthid:n,...t})}var Ete=new TextEncoder,_0=new TextDecoder,y8=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 wF(n,e,t){if(e<0||e>=y8)throw new RangeError(`value must be >= 0 and <= ${y8-1}. Received ${e}`);n.set([e>>>24,e>>>16,e>>>8,e&255],t)}function w8(n){let e=Math.floor(n/y8),t=n%y8,r=new Uint8Array(8);return wF(r,e,0),wF(r,t,4),r}function b8(n){let e=new Uint8Array(4);return wF(e,n),e}function Ka(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 Ite(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 Ate(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 Wr(n){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof n=="string"?n:_0.decode(n),{alphabet:"base64url"});let e=n;e instanceof Uint8Array&&(e=_0.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Ate(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Zr(n){let e=n;return typeof e=="string"&&(e=Ete.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Ite(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 fI=class extends $y{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Zt=class extends $y{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},bh=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 bF(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 Zt(`Unsupported JWE Algorithm: ${n}`)}}var xte=n=>crypto.getRandomValues(new Uint8Array(bF(n)>>3));function E8(n,e){if(e.length<<3!==bF(n))throw new Ve("Invalid Initialization Vector length")}function ew(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 Eh=(n,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${n}`),I8=(n,e)=>n.name===e;function ZRe(n){return parseInt(n.name.slice(4),10)}function XRe(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(!I8(n.algorithm,"AES-GCM"))throw Eh("AES-GCM");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw Eh(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!I8(n.algorithm,"AES-KW"))throw Eh("AES-KW");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw Eh(r,"algorithm.length");break}case"ECDH":{switch(n.algorithm.name){case"ECDH":case"X25519":break;default:throw Eh("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!I8(n.algorithm,"PBKDF2"))throw Eh("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!I8(n.algorithm,"RSA-OAEP"))throw Eh("RSA-OAEP");let r=parseInt(e.slice(9),10)||1;if(ZRe(n.algorithm.hash)!==r)throw Eh(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}XRe(n,t)}function vte(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 Ih=(n,...e)=>vte("Key must be ",n,...e),EF=(n,e,...t)=>vte(`Key for the ${n} algorithm must be `,e,...t);function $0(n){if(!Ju(n))throw new Error("CryptoKey instance expected")}var Ju=n=>{if(n?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return n instanceof CryptoKey}catch{return!1}},hI=n=>n?.[Symbol.toStringTag]==="KeyObject",IF=n=>Ju(n)||hI(n);async function _Re(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 $Re(n,e,t,r,i,o){if(!(e instanceof Uint8Array))throw new TypeError(Ih(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,w8(o.length<<3)),l=new Uint8Array((await crypto.subtle.sign("HMAC",c,u)).slice(0,s>>3)),d;try{d=await _Re(i,l)}catch{}if(!d)throw new bh;let h;try{h=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:"AES-CBC"},a,t))}catch{}if(!h)throw new bh;return h}async function eDe(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 bh}}async function A8(n,e,t,r,i,o){if(!Ju(e)&&!(e instanceof Uint8Array))throw new TypeError(Ih(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(E8(n,r),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&ew(e,parseInt(n.slice(-3),10)),$Re(n,e,t,r,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&ew(e,parseInt(n.slice(1,4),10)),eDe(n,e,t,r,i,o);default:throw new Zt("Unsupported JWE Content Encryption Algorithm")}}function tw(...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 tDe=n=>typeof n=="object"&&n!==null;function Wo(n){if(!tDe(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 Ste(n,e){if(n.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function Cte(n,e,t){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"AES-KW",!0,[t]):(Cs(n,e,t),n)}async function pI(n,e,t){let r=await Cte(e,n,"wrapKey");Ste(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 mI(n,e,t){let r=await Cte(e,n,"unwrapKey");Ste(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 Lte(n,e){let t=`SHA-${n.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(t,e))}function xF(n){return Ss(b8(n.length),n)}async function nDe(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(b8(a),0),c.set(n,4),c.set(t,4+n.length);let u=await Lte("sha256",c);s.set(u,(a-1)*i)}return s.slice(0,r)}async function x8(n,e,t,r,i=new Uint8Array,o=new Uint8Array){Cs(n,"ECDH"),Cs(e,"ECDH","deriveBits");let s=xF(Ka(t)),a=xF(i),c=xF(o),u=b8(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,rDe(n)));return nDe(h,r,d)}function rDe(n){return n.algorithm.name==="X25519"?256:Math.ceil(parseInt(n.algorithm.namedCurve.slice(-3),10)/8)<<3}function v8(n){switch(n.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return n.algorithm.name==="X25519"}}function iDe(n,e){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits"]):(Cs(n,e,"deriveBits"),n)}var oDe=(n,e)=>Ss(Ka(n),Uint8Array.of(0),e);async function Dte(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=oDe(e,n),o=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:t,name:"PBKDF2",salt:i},a=await iDe(r,e);return new Uint8Array(await crypto.subtle.deriveBits(s,a,o))}async function Tte(n,e,t,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let o=await Dte(i,n,r,e);return{encryptedKey:await pI(n.slice(-6),o,t),p2c:r,p2s:Zr(i)}}async function Bte(n,e,t,r,i){let o=await Dte(i,n,r,e);return mI(n.slice(-6),o,t)}function vF(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 kte=n=>{switch(n){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Zt(`alg ${n} is not supported either by JOSE or your javascript runtime`)}};async function Mte(n,e,t){return Cs(e,n,"encrypt"),vF(n,e),new Uint8Array(await crypto.subtle.encrypt(kte(n),e,t))}async function Ote(n,e,t){return Cs(e,n,"decrypt"),vF(n,e),new Uint8Array(await crypto.subtle.decrypt(kte(n),e,t))}function gI(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 Zt(`Unsupported JWE Algorithm: ${n}`)}}var qu=n=>crypto.getRandomValues(new Uint8Array(gI(n)>>3));function sDe(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 Zt('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 Zt('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 Zt('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 Zt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new Zt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}async function nw(n){if(!n.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:t}=sDe(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 Nte(n,e,t){if(!Wo(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 Wr(n.k);case"RSA":if("oth"in n&&n.oth!==void 0)throw new Zt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return nw({...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 nw({...n,ext:r})}case"EC":case"OKP":return nw({...n,alg:e,ext:r});default:throw new Zt('Unsupported "kty" (Key Type) Parameter value')}}async function aDe(n,e,t,r,i){if(!(t instanceof Uint8Array))throw new TypeError(Ih(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,w8(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 cDe(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 S8(n,e,t,r,i){if(!Ju(t)&&!(t instanceof Uint8Array))throw new TypeError(Ih(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(r?E8(n,r):r=xte(n),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ew(t,parseInt(n.slice(-3),10)),aDe(n,e,t,r,i);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ew(t,parseInt(n.slice(1,4),10)),cDe(n,e,t,r,i);default:throw new Zt("Unsupported JWE Content Encryption Algorithm")}}async function Ute(n,e,t,r){let i=n.slice(0,7),o=await S8(i,t,e,r,new Uint8Array);return{encryptedKey:o.ciphertext,iv:Zr(o.iv),tag:Zr(o.tag)}}async function Gte(n,e,t,r,i){let o=n.slice(0,7);return A8(o,e,t,r,i,new Uint8Array)}async function Hte(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(!Wo(r.epk))throw new Ve('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if($0(e),!v8(e))throw new Zt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await Nte(r.epk,n);$0(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=Wr(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=Wr(r.apv)}catch{throw new Ve("Failed to base64url decode the apv")}}let c=await x8(o,e,n==="ECDH-ES"?r.enc:n,n==="ECDH-ES"?gI(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 mI(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 $0(e),Ote(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=Wr(r.p2s)}catch{throw new Ve("Failed to base64url decode the p2s")}return Bte(n,e,t,r.p2c,s)}case"A128KW":case"A192KW":case"A256KW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");return mI(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=Wr(r.iv)}catch{throw new Ve("Failed to base64url decode the iv")}let s;try{s=Wr(r.tag)}catch{throw new Ve("Failed to base64url decode the tag")}return Gte(n,e,t,o,s)}default:throw new Zt('Invalid or unsupported "alg" (JWE Algorithm) header value')}}function rw(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 Zt(`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 SF(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 yI=n=>Wo(n)&&typeof n.kty=="string",Kte=n=>n.kty!=="oct"&&(n.kty==="AKP"&&typeof n.priv=="string"||typeof n.d=="string"),Jte=n=>n.kty!=="oct"&&n.d===void 0&&n.priv===void 0,qte=n=>n.kty==="oct"&&typeof n.k=="string";var iw,Vte=async(n,e,t,r=!1)=>{iw||=new WeakMap;let i=iw.get(n);if(i?.[t])return i[t];let o=await nw({...e,alg:t});return r&&Object.freeze(n),i?i[t]=o:iw.set(n,{[t]:o}),o},lDe=(n,e)=>{iw||=new WeakMap;let t=iw.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:iw.set(n,{[e]:o}),o};async function Ah(n,e){if(n instanceof Uint8Array||Ju(n))return n;if(hI(n)){if(n.type==="secret")return n.export();if("toCryptoKey"in n&&typeof n.toCryptoKey=="function")try{return lDe(n,e)}catch(r){if(r instanceof TypeError)throw r}let t=n.export({format:"jwk"});return Vte(n,t,e)}if(yI(n))return n.k?Wr(n.k):Vte(n,n,e,!0);throw new Error("unreachable")}var ow=n=>n?.[Symbol.toStringTag],CF=(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},dDe=(n,e,t)=>{if(!(e instanceof Uint8Array)){if(yI(e)){if(qte(e)&&CF(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(!IF(e))throw new TypeError(EF(n,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${ow(e)} instances for symmetric algorithms must be of type "secret"`)}},fDe=(n,e,t)=>{if(yI(e))switch(t){case"decrypt":case"sign":if(Kte(e)&&CF(n,e,t))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Jte(e)&&CF(n,e,t))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!IF(e))throw new TypeError(EF(n,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${ow(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(t){case"sign":throw new TypeError(`${ow(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ow(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(t){case"verify":throw new TypeError(`${ow(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ow(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function sw(n,e,t){switch(n.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":dDe(n,e,t);break;default:fDe(n,e,t)}}async function wI(n,e,t){if(!Wo(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&&!Wo(n.header))throw new Ve("JWE Shared Unprotected Header incorrect type");if(n.unprotected!==void 0&&!Wo(n.unprotected))throw new Ve("JWE Per-Recipient Unprotected Header incorrect type");let r;if(n.protected)try{let U=Wr(n.protected);r=JSON.parse(_0.decode(U))}catch{throw new Ve("JWE Protected Header is invalid")}if(!tw(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(rw(Ve,new Map,t?.crit,r,i),i.zip!==void 0)throw new Zt('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&&SF("keyManagementAlgorithms",t.keyManagementAlgorithms),c=t&&SF("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms);if(a&&!a.has(o)||!a&&o.startsWith("PBES2"))throw new fI('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(s))throw new fI('"enc" (Encryption Algorithm) Header Parameter value not allowed');let u;if(n.encrypted_key!==void 0)try{u=Wr(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),sw(o==="dir"?s:o,e,"decrypt");let d=await Ah(e,o),h;try{h=await Hte(o,d,u,i,t)}catch(U){if(U instanceof TypeError||U instanceof Ve||U instanceof Zt)throw U;h=qu(s)}let f,m;if(n.iv!==void 0)try{f=Wr(n.iv)}catch{throw new Ve("Failed to base64url decode the iv")}if(n.tag!==void 0)try{m=Wr(n.tag)}catch{throw new Ve("Failed to base64url decode the tag")}let w=n.protected!==void 0?Ka(n.protected):new Uint8Array,b;n.aad!==void 0?b=Ss(w,Ka("."),Ka(n.aad)):b=w;let S;try{S=Wr(n.ciphertext)}catch{throw new Ve("Failed to base64url decode the ciphertext")}let G={plaintext:await A8(s,h,S,f,m,b)};if(n.protected!==void 0&&(G.protectedHeader=r),n.aad!==void 0)try{G.additionalAuthenticatedData=Wr(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 LF(n,e,t){if(!Wo(n))throw new Ve("General JWE must be an object");if(!Array.isArray(n.recipients)||!n.recipients.every(Wo))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 wI({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 bh}var C8=Symbol();async function Qte(n){if(hI(n))if(n.type==="secret")n=n.export();else return n.export({format:"jwk"});if(n instanceof Uint8Array)return{kty:"oct",k:Zr(n)};if(!Ju(n))throw new TypeError(Ih(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 zte(n){return Qte(n)}async function L8(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($0(t),!v8(t))throw new Zt("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 Ah(i.epk,n):l=(await crypto.subtle.generateKey(t.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:h,crv:f,kty:m}=await zte(l),w=await x8(t,l,n==="ECDH-ES"?e:n,n==="ECDH-ES"?gI(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=Zr(c)),u&&(s.apv=Zr(u)),n==="ECDH-ES"){a=w;break}a=r||qu(e);let b=n.slice(-6);o=await pI(b,w,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=r||qu(e),$0(t),o=await Mte(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 Tte(n,t,a,c,u));break}case"A128KW":case"A192KW":case"A256KW":{a=r||qu(e),o=await pI(n,t,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=r||qu(e);let{iv:c}=i;({encryptedKey:o,...s}=await Ute(n,t,a,c));break}default:throw new Zt('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:a,encryptedKey:o,parameters:s}}var bI=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(!tw(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(rw(Ve,new Map,t?.crit,this.#t,r),r.zip!==void 0)throw new Zt('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}`);sw(i==="dir"?o:i,e,"encrypt");let a;{let b,S=await Ah(e,i);({cek:a,encryptedKey:s,parameters:b}=await L8(i,o,S,this.#o,this.#a)),b&&(t&&C8 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=Zr(JSON.stringify(this.#t)),l=Ka(u)):(u="",l=new Uint8Array),this.#i){d=Zr(this.#i);let b=Ka(d);c=Ss(l,Ka("."),b)}else c=l;let{ciphertext:h,tag:f,iv:m}=await S8(o,this.#e,a,this.#s,c),w={ciphertext:Zr(h)};return m&&(w.iv=Zr(m)),f&&(w.tag=Zr(f)),s&&(w.encrypted_key=Zr(s)),d&&(w.aad=d),this.#t&&(w.protected=u),this.#n&&(w.unprotected=this.#n),this.#r&&(w.header=this.#r),w}};var RF=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}},EI=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let r=new RF(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 bI(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(!tw(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(rw(Ve,new Map,o.options.crit,this.#n,s),s.zip!==void 0)throw new Zt('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 bI(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(o.unprotectedHeader).setKeyManagementParameters(o.keyManagementParameters).encrypt(o.key,{...o.options,[C8]:!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;sw(a==="dir"?e:a,o.key,"encrypt");let c=await Ah(o.key,a),{encryptedKey:u,parameters:l}=await L8(a,e,c,t,o.keyManagementParameters);s.encrypted_key=Zr(u),(o.unprotectedHeader||l)&&(s.header={...o.unprotectedHeader,...l})}return r}};function DF(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(_0.decode(Wr(e)));if(!Wo(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var R8=class{constructor(e){this.resolvePrivateKeyByKid=e}async encrypt(e,t){let{enc:r,typ:i,recipients:o}=t,s=new EI(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(DF(r),r.header||{}),wI(e,t)}return LF(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 D8=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 BF={};Sr(BF,{DeviceNotificationStatus:()=>Wte,NotificationServiceType:()=>Yte,NotificationStatus:()=>jte,PushNotifier:()=>TF});var Yte=(e=>(e.Push="push-notification",e))(Yte||{}),jte=(t=>(t.Success="success",t.Failed="failed",t))(jte||{});var Wte=(r=>(r.Success="success",r.Rejected="rejected",r.Failed="failed",r))(Wte||{}),hDe={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()}}}},TF=class{constructor(e=hDe){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},Zte={state:0n,replacedByState:0n,createdAtTimestamp:0n,replacedAtTimestamp:0n,createdAtBlock:0n,replacedAtBlock:0n},cI=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,iM,this.provider),this._transactionService=new Xs(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??Yr.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??fg},this._stateCacheOptions={notReplacedTtl:t?.stateCacheOptions?.notReplacedTtl??Yr.DEFAULT_PROOF_VERIFY_DELAY/2,replacedTtl:t?.stateCacheOptions?.replacedTtl??Yr.DEFAULT_PROOF_VERIFY_DELAY,maxSize:t?.stateCacheOptions?.maxSize??fg},this._rootCacheOptions={replacedTtl:t?.rootCacheOptions?.replacedTtl??Yr.DEFAULT_AUTH_VERIFY_DELAY,notReplacedTtl:t?.rootCacheOptions?.notReplacedTtl??Yr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.rootCacheOptions?.maxSize??fg},this._gistProofCacheOptions={ttl:Yr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??fg},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??lh({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??lh({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??lh({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??lh({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(Ge.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 j0(s)&&!this._disableCache&&await this._latestStateResolveCache?.set(t,{id:e,...Zte},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(!rF(a))throw a;if(!Ax(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,...Zte,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 xE;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=F0(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),T={to:S.to,data:S.data,gasLimit:b,maxFeePerGas:m,maxPriorityFeePerGas:w},{txnHash:G}=await this._transactionService.sendTransactionRequest(t,T);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),T={to:S.to,data:S.data,gasLimit:b,maxFeePerGas:f,maxPriorityFeePerGas:m},{txnHash:G}=await this._transactionService.sendTransactionRequest(e,T);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=rm(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=rm(ve.blockchainFromId(t),ve.networkIdFromId(t)),i=this.networkByChainId(r),o=new jt(i.url);return{stateContract:new Ln(i.contractAddress,iM,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 PF=[{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 kF=[{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 MF=10000000n,Xte=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(Xte||{}),_te=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]},OF=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 _supportedCircuitsPubSignalsMap={credentialAtomicQueryMTPV2OnChain:{ctor:pE},credentialAtomicQuerySigV2OnChain:{ctor:IE},"credentialAtomicQueryV3OnChain-beta.1":{ctor:My},credentialAtomicQueryV3OnChain:{ctor:My},authV2:{ctor:Zs},authV3:{ctor:Uu},"authV3-8-32":{ctor:Uu,opts:{mtLevel:8,mtLevelClaim:32}}};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=F0(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,PF);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=MF}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,PF).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:c,maxPriorityFeePerGas:u},f;try{f=await e.estimateGas(h)}catch{f=MF}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,kF).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=MF}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":{let f=F0(i.zkp.proof);u=yC(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{u=$te(i.userDid);break}default:throw new Error("auth proof must use method AuthV2 or ethIdentity")}for(let f of r){this.checkSupportedCircuit(f.circuitId);let{requestId:m,zkProofEncoded:w,metadata:b}=sI(f);a.push({proof:f,requestId:m,encoded:w,metadata:b})}let l=r.map(f=>({circuitId:f.circuitId,pub_signals:f.pub_signals}));i.authMethod=="authV2"&&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:_te(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(!nM(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}=sI(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 xn.AbiCoder().encode(["tuple(string proofType,bytes proof)[]"],[r])}static packGlobalStateMsg(e){return new xn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,bytes2 idType,uint256 root,uint256 replacedAtTimestamp) globalStateMsg,bytes signature,)"],[e])}static packIdentityStateMsg(e){return new xn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,uint256 id,uint256 state,uint256 replacedAtTimestamp) idStateMsg,bytes signature,)"],[e])}static getOnChainGistRootStatePubSignals(e,t){let r=this._supportedCircuitsPubSignalsMap[e].ctor;if(!r)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=new r(this._supportedCircuitsPubSignalsMap[e].opts),o=ke.encode(JSON.stringify(t));return i.pubSignalsUnmarshal(o).getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await wp(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}}},$te=n=>`0x${Rr(Ct.intToBytes(ve.idFromDID(n).bigInt()))}`;var FF=[{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 NF=[{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"}],aw=class{static abi=NF;static createInterface(){return new dc(NF)}static connect(e,t){return new Ln(e,NF,t)}};var II=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=xn.getAddress(xn.hexlify(Xe.ethAddressFromId(ve.idFromDID(t)))),this._contract=aw.connect(this._contractAddress,new xn.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 Fr().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:ra(Number(e.issuanceDate)).getTime()},a=await this.existenceProof(i),c=Pr.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 Gr.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=ra(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 mc({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:c,coreClaim:e})}async validateSourceValue(e,t,r){if(await Tu.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 UF=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 II(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 II(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=xn.getAddress(xn.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,FF,new xn.JsonRpcProvider(o.url)),connection:o}}};var GF=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 wp(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 wp(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 wp(ve.parseFromId(Xe.fromBigInt(e)),this.resolverUrl,r),{info:o,published:s}=this.getIden3StateInfo2023(i);if(!o&&!s)throw new Error(Ge.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 ene=[{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 tne=[{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 ADe(n,e,t,r,i,o){let s=new Ln(e,ene,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 xDe(n,e){return new Ln(n,tne,e).decimals()}var ane=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(ane||{}),cne=(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))(cne||{}),HF=[!0,1,"true"],KF=[!1,0,"false"],nne=(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,HF.includes(n)&&HF.includes(e)||KF.includes(n)&&KF.includes(e)?!0:n===e),rne=(n,e)=>lne(n,e,(r,i)=>{switch(dne(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}}),ine=(n,e)=>lne(n,e,(r,i)=>{switch(dne(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}}),vDe=(n,e)=>!!(HF.includes(e)&&typeof n<"u"||KF.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),one=(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,sne=(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))},Vu={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>vDe(n,e),$eq:(n,e)=>nne(n,e),$in:(n,e)=>one(n,e),$nin:(n,e)=>!one(n,e),$gt:(n,e)=>rne(n,e),$lt:(n,e)=>!ine(n,e),$ne:(n,e)=>!nne(n,e),$gte:(n,e)=>ine(n,e),$lte:(n,e)=>!rne(n,e),$between:(n,e)=>sne(n,e),$nonbetween:(n,e)=>!sne(n,e)},une=(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},Kc=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=une(e,this.path);return t==null&&this.operatorFunc!==Vu.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},JF=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new Kc("id",Vu.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new Kc("issuer",Vu.$in,r));case"type":return e.concat(new Kc("type",Vu.$in,r,!0));case"context":return e.concat(new Kc("@context",Vu.$in,r,!0));case"credentialSubjectId":return e.concat(new Kc("credentialSubject.id",Vu.$eq,r));case"schema":return e.concat(new Kc("credentialSchema.id",Vu.$eq,r));case"credentialSubject":{let i=Object.keys(r).reduce((o,s)=>{let a=r[s];if(typeof a=="object"&&Object.keys(a).length===0)return o.concat([new Kc(`credentialSubject.${s}`,Vu.$noop,null)]);let c=Object.keys(a).map(u=>{let l=a[u],d=`credentialSubject.${s}`;return new Kc(d,Vu[u],l)});return o.concat(c)},[]);return e.concat(i)}case"proofType":case"groupId":case"skipClaimRevocationCheck":return e;default:throw new Error(`${t} : not defined query key`)}},[]),lne=(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),SDe=/^[+-]?\d+$/,CDe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,LDe=/^([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]))$/,RDe=/^(true)|(false)$/,DDe=/^\d{4}-\d{2}-\d{2}$/,dne=n=>SDe.test(n)?0:CDe.test(n)?2:LDe.test(n)||DDe.test(n)?3:RDe.test(n)?1:4;var qF=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 VF=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=Oy(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify([...i,...a])),[...i,...a]}let r=Oy(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 sa(new bw(Zc(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 sa(new bw(Zc(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 QF=class{constructor(e){this._storageKey=e;this._store=Od(`${e}-db`,e)}_store;async save(e,t,r="id"){return Fd(e,t,this._store)}async get(e,t="id"){return jc(e,this._store)}async load(){return zN(this._store)}async delete(e,t="id"){return VI(e,this._store)}};var zF=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=Od(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=Od(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Ut()}`),await jc(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=Oy(e);return await Fd(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await jc(e,this._merkleTreeMetaStore);if(t)return t;throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=await jc(e,this._merkleTreeMetaStore),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let o=r.find(s=>s.identifier===e&&s.type===t);if(!o)throw i;return new sa(new Ew(Zc(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await jc(e,this._merkleTreeMetaStore);if(!o)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=o.find(c=>c.identifier===e&&c.type===t);if(!s)throw new Error(`Merkle tree not found for identifier ${e} and type ${t}`);await new sa(new Ew(Zc(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await jc(e,this._merkleTreeMetaStore);if(!r||!r?.length)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=r.map(o=>({...o,identifier:t}));await VI(e,this._merkleTreeMetaStore),await Fd(t,i,this._merkleTreeMetaStore),await Fd(e,t,this._bindingStore)}};var YF=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 jF=class{constructor(e){this._dataSource=e}static storageKey="credentials";async listCredentials(){return(await this._dataSource.load()).filter(t=>t!==void 0).map(t=>t&&Pr.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&&Pr.fromJSON(t)}async findCredentialsByQuery(e){let t=JF(e);return(await this._dataSource.load()).filter(o=>t.every(s=>s.execute(o))).filter(o=>o!==void 0).map(o=>Pr.fromJSON(o))}};var WF=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 ZF=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 Qu=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:X5(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},xh=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}},T8=n=>{if(!n)return[{operator:dn.$noop,fieldName:""}];let e=[],t=Object.entries(n);if(!t.length)throw new Error("query must have at least 1 predicate");for(let[r,i]of t){let o=Object.entries(i);if(o.length===0){e.push({operator:dn.$sd,fieldName:r});continue}for(let[a,c]of o){if(!dn[a])throw new Error("operator is not supported by lib");let u=dn[a];e.push({operator:u,fieldName:r,operatorValue:c})}}return e},B8=async(n,e,t,r)=>{let i={...n,slotIndex:0,merklizedSchema:!1,datatype:"",claimPathKey:BigInt(0),values:[],path:new Gr};if(!n.fieldName&&n.operator!==0)throw new Error("query must have a field name if operator is not $noop");if(n.fieldName&&(i.datatype=await Gr.newTypeFromContext(e,`${t}.${n.fieldName}`,r)),await Q2(JSON.parse(e),r,t)||(i.merklizedSchema=!0),!i.merklizedSchema)i.slotIndex=await V2(n.fieldName,t,ke.encode(e));else try{let s=await b6(e,t,n.fieldName,r);i.claimPathKey=await s.mtEntry(),i.path=s}catch(s){throw new Error(`field does not exist in the schema ${s.message}`)}if(n.operatorValue!==void 0){if(!$5(i.datatype,n.operator))throw new Error(`operator ${n.operator} is not supported for datatype ${i.datatype}`);if((n.operator===0||n.operator===16)&&n.operatorValue)throw new Error(`operator value should be undefined for ${n.operator} operator`);let s;switch(n.operator){case 0:case 16:s=[];break;case 11:s=TDe(n.operatorValue);break;default:s=await P8(n.operatorValue,i.datatype)}i.values=s}return i},AI=async(n,e,t,r)=>{let i=T8(t);return Promise.all(i.map(o=>B8(o,e,n,r)))},P8=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await Tu.hashValue(e,n[r]);else t[0]=await Tu.hashValue(e,n);return t},TDe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")};async function $F(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.
|