@0xpolygonid/js-sdk 1.38.5 → 1.38.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/esm/index.js +1 -0
- package/dist/browser/esm/index.js.map +1 -1
- package/dist/browser/umd/index.global.js +1 -1
- package/dist/browser/umd/index.global.js.map +1 -1
- package/dist/node/cjs/index.cjs +1 -0
- package/dist/node/cjs/index.cjs.map +1 -1
- package/dist/node/esm/index.js +1 -0
- package/dist/node/esm/index.js.map +1 -1
- package/dist/types/iden3comm/handlers/fetch.d.ts +0 -3
- package/dist/types/iden3comm/handlers/fetch.d.ts.map +1 -1
- package/dist/types/iden3comm/handlers/message-handler.d.ts +3 -0
- package/dist/types/iden3comm/handlers/message-handler.d.ts.map +1 -1
- package/dist/types/iden3comm/handlers/payment.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/iden3comm/handlers/fetch.ts +0 -3
- package/src/iden3comm/handlers/message-handler.ts +3 -0
- package/src/iden3comm/handlers/payment.ts +1 -0
|
@@ -420,7 +420,7 @@ if (cid) {
|
|
|
420
420
|
`?i="":(i!==""&&(i+=" "),i+=l)},showSharedRWMemory:function(){u()}}}),s=e;return new hO(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+=pO(d).toString()}}var hO=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=pO(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=gLe(o),a=parseInt(s.slice(0,8),16),c=parseInt(s.slice(8,16),16),u=mLe(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=pLe(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(pO(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 pLe(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 pO(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 mLe(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 gLe(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 eI(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function mO(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Fc(n,...e){if(!eI(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 Iee(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mO(n.outputLen),mO(n.blockLen)}function jC(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 yLe(n,e){Fc(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function WC(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function rO(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Nu(n,e){return n<<32-e|n>>>e}var Aee=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wLe=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function jy(n){if(Fc(n),Aee)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=wLe[n[t]];return e}var md={_0:48,_9:57,A:65,F:70,a:97,f:102};function eee(n){if(n>=md._0&&n<=md._9)return n-md._0;if(n>=md.A&&n<=md.F)return n-(md.A-10);if(n>=md.a&&n<=md.f)return n-(md.a-10)}function ZC(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(Aee)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=eee(n.charCodeAt(o)),a=eee(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 tI(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function kO(n){return typeof n=="string"&&(n=tI(n)),Fc(n),n}function Mi(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];Fc(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 XC=class{};function bLe(n){let e=r=>n().update(kO(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function MO(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 ELe(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 ILe(n,e,t){return n&e^~n&t}function ALe(n,e,t){return n&e^n&t^e&t}var gO=class extends XC{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=rO(this.buffer)}update(e){jC(this),e=kO(e),Fc(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=rO(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){jC(this),yLe(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,WC(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;ELe(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=rO(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()}},hh=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xLe=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]),ph=new Uint32Array(64),yO=class extends gO{constructor(e=32){super(64,e,8,!1),this.A=hh[0]|0,this.B=hh[1]|0,this.C=hh[2]|0,this.D=hh[3]|0,this.E=hh[4]|0,this.F=hh[5]|0,this.G=hh[6]|0,this.H=hh[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)ph[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=ph[d-15],f=ph[d-2],m=Nu(h,7)^Nu(h,18)^h>>>3,b=Nu(f,17)^Nu(f,19)^f>>>10;ph[d]=b+ph[d-7]+m+ph[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=Nu(a,6)^Nu(a,11)^Nu(a,25),f=l+h+ILe(a,c,u)+xLe[d]+ph[d]|0,b=(Nu(r,2)^Nu(r,13)^Nu(r,22))+ALe(r,i,o)|0;l=u,u=c,c=a,a=s+f|0,s=o,o=i,i=r,r=f+b|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(){WC(ph)}destroy(){this.set(0,0,0,0,0,0,0,0),WC(this.buffer)}},xee=bLe(()=>new yO);var OO=BigInt(0),_C=BigInt(1);function $C(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function V0(n,e,t=""){let r=eI(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 qC(n){let e=n.toString(16);return e.length&1?"0"+e:e}function vee(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?OO:BigInt("0x"+n)}function nI(n){return vee(jy(n))}function See(n){return Fc(n),vee(jy(Uint8Array.from(n).reverse()))}function FO(n,e){return ZC(n.toString(16).padStart(e*2,"0"))}function Cee(n,e){return FO(n,e).reverse()}function so(n,e,t){let r;if(typeof e=="string")try{r=ZC(e)}catch(i){throw new Error(n+" must be hex string or Uint8Array, cause: "+i)}else if(eI(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");return r}var iO=n=>typeof n=="bigint"&&OO<=n;function Lee(n,e,t){return iO(n)&&iO(e)&&iO(t)&&e<=n&&n<t}function vLe(n,e,t,r){if(!Lee(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function ZE(n){let e;for(e=0;n>OO;n>>=_C,e+=1);return e}function SLe(n,e){return n>>BigInt(e)&_C}var rI=n=>(_C<<BigInt(n))-_C;function CLe(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 b=o.slice();m.push(b),f+=o.length}return Mi(...m)};return(f,m)=>{c(),l(f);let b;for(;!(b=m(d()));)l();return c(),b}}function LLe(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function i8(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 wO(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),Ree=BigInt(3),Dee=BigInt(4),Tee=BigInt(5),RLe=BigInt(7),Bee=BigInt(8),DLe=BigInt(9),Pee=BigInt(16);function Ga(n,e){let t=n%e;return t>=ea?t:e+t}function tee(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 NO(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)/Dee,r=n.pow(e,t);return NO(n,r,e),r}function TLe(n,e){let t=(n.ORDER-Tee)/Bee,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 NO(n,a,e),a}function BLe(n){let e=Zy(n),t=Mee(n),r=t(e,e.neg(e.ONE)),i=t(e,r),o=t(e,e.neg(r)),s=(n+RLe)/Pee;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 b=a.eql(a.sqr(l),c),w=a.cmov(u,l,b);return NO(a,w,c),w}}function Mee(n){if(n<Ree)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(;e8(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(e8(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,b=c.sqr(h);for(;!c.eql(b,c.ONE);)if(m++,b=c.sqr(b),m===l)throw new Error("Cannot find square root");let w=jo<<BigInt(l-m-1),S=c.pow(d,w);l=m,d=c.sqr(S),h=c.mul(h,d),f=c.mul(f,S)}return f}}function PLe(n){return n%Dee===Ree?kee:n%Bee===Tee?TLe:n%Pee===DLe?BLe(n):Mee(n)}var kLe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function MLe(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=kLe.reduce((r,i)=>(r[i]="function",r),e);return i8(n,t),n}function o8(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 iI(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 e8(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 Oee(n,e){e!==void 0&&mO(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}=Oee(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:rI(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)=>o8(d,h,f),div:(h,f)=>Ga(h*tee(f,n),n),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>tee(h,n),sqrt:o||(h=>(l||(l=PLe(n)),l(d,h))),toBytes:h=>t?Cee(h,u):FO(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 b=new Uint8Array(u);b.set(h,t?0:b.length-h.length),h=b}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let m=t?See(h):nI(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=>iI(d,h),cmov:(h,f,m)=>m?f:h});return Object.freeze(d)}function Fee(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 UO(n){let e=Fee(n);return e+Math.ceil(e/2)}function Nee(n,e,t=!1){let r=n.length,i=Fee(e),o=UO(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?See(n):nI(n),a=Ga(s,e-jo)+jo;return t?Cee(a,i):FO(a,i)}var Wy=BigInt(0),z0=BigInt(1);function t8(n,e){let t=e.negate();return n?t:e}function WE(n,e){let t=iI(n.Fp,e.map(r=>r.Z));return e.map((r,i)=>n.fromAffine(r.toAffine(t[i])))}function Uee(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function oO(n,e){Uee(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=rI(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function nee(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+=z0);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 OLe(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 FLe(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 sO=new WeakMap,Gee=new WeakMap;function aO(n){return Gee.get(n)||1}function ree(n){if(n!==Wy)throw new Error("invalid wNAF")}var bO=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&z0&&(r=r.add(i)),i=i.double(),t>>=z0;return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=oO(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=oO(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:h,offsetF:f}=nee(r,a,s);r=c,l?o=o.add(t8(h,t[f])):i=i.add(t8(d,t[u]))}return ree(r),{p:i,f:o}}wNAFUnsafe(e,t,r,i=this.ZERO){let o=oO(e,this.bits);for(let s=0;s<o.windows&&r!==Wy;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=nee(r,s,o);if(r=a,!u){let d=t[c];i=i.add(l?d.negate():d)}}return ree(r),i}getPrecomputes(e,t,r){let i=sO.get(t);return i||(i=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(i=r(i)),sO.set(t,i))),i}cached(e,t,r){let i=aO(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let o=aO(e);return o===1?this._unsafeLadder(e,t,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,i)}createCache(e,t){Uee(t,this.bits),Gee.set(e,t),sO.delete(e)}hasCache(e){return aO(e)!==1}};function NLe(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Wy||r>Wy;)t&z0&&(o=o.add(i)),r&z0&&(s=s.add(i)),i=i.double(),t>>=z0,r>>=z0;return{p1:o,p2:s}}function ULe(n,e,t,r){OLe(t,n),FLe(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=ZE(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=rI(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 b=0;b<o;b++){let w=r[b],S=Number(w>>BigInt(f)&u);l[S]=l[S].add(t[b])}let m=s;for(let b=l.length-1,w=s;b>0;b--)w=w.add(l[b]),m=m.add(w);if(h=h.add(m),f!==0)for(let b=0;b<c;b++)h=h.double()}return h}function iee(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return MLe(e),e}else return Zy(n,{isLE:t})}function GLe(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=iee(e.p,t.Fp,r),o=iee(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 HLe=nI;function mh(n,e){if(XE(n),XE(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 KLe(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 XE(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function Hee(n){if(!eI(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or string");return typeof n=="string"?tI(n):n}function JLe(n,e,t,r){Fc(n),XE(t),e=Hee(e),e.length>255&&(e=r(Mi(tI("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,mh(e.length,1)),c=mh(0,o),u=mh(t,2),l=new Array(s),d=r(Mi(c,n,u,mh(0,1),a));l[0]=r(Mi(d,mh(1,1),a));for(let f=1;f<=s;f++){let m=[KLe(d,l[f-1]),mh(f+1,1),a];l[f]=r(Mi(...m))}return Mi(...l).slice(0,t)}function qLe(n,e,t,r,i){if(Fc(n),XE(t),e=Hee(e),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update(tI("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(mh(t,2)).update(e).update(mh(e.length,1)).digest()}function cO(n,e,t){i8(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:c}=t;if(!LLe(t.hash))throw new Error("expected valid hash");Fc(n),XE(e);let u=r.toString(2).length,l=Math.ceil((u+i)/8),d=e*o*l,h;if(a==="xmd")h=JLe(n,c,d,s);else if(a==="xof")h=qLe(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 b=new Array(o);for(let w=0;w<o;w++){let S=l*(w+m*o),T=h.subarray(S,S+l);b[w]=Ga(HLe(T),r)}f[m]=b}return f}var VLe=tI("HashToScalar-");function oee(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=cO(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=cO(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:VLe},s);return cO(o,1,c)[0][0]}}}var n8=class extends XC{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Iee(e);let r=kO(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),WC(o)}update(e){return jC(this),this.iHash.update(e),this}digestInto(e){jC(this),Fc(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()}},Kee=(n,e,t)=>new n8(n,e).update(t).digest();Kee.create=(n,e)=>new n8(n,e);var see=(n,e)=>(n+(n>=0?e:-e)/Jee)/e;function QLe(n,e,t){let[[r,i],[o,s]]=e,a=see(s*n,t),c=see(-i*n,t),u=n-a*r-c*o,l=-a*i-c*s,d=u<yd,h=l<yd;d&&(u=-u),h&&(l=-l);let f=rI(Math.ceil(ZE(t)/2))+Y0;if(u<yd||u>=f||l<yd||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:d,k1:u,k2neg:h,k2:l}}function EO(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function uO(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return $C(t.lowS,"lowS"),$C(t.prehash,"prehash"),t.format!==void 0&&EO(t.format),t}var IO=class extends Error{constructor(e=""){super(e)}},gd={Err:IO,_tlv:{encode:(n,e)=>{let{Err:t}=gd;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=qC(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?qC(i.length/2|128):"";return qC(n)+o+i+e},decode(n,e){let{Err:t}=gd,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}=gd;if(n<yd)throw new e("integer: negative integers are not allowed");let t=qC(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}=gd;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 nI(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=gd,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}=gd,r=e.encode(2,t.encode(n.r)),i=e.encode(2,t.encode(n.s)),o=r+i;return e.encode(48,o)}},yd=BigInt(0),Y0=BigInt(1),Jee=BigInt(2),VC=BigInt(3),zLe=BigInt(4);function wd(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 qee(n,e={}){let t=GLe("weierstrass",n,e),{Fp:r,Fn:i}=t,o=t.CURVE,{h:s,n:a}=o;i8(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=Qee(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($C(p,"isCompressed"),p){l();let C=!r.isOdd(y);return Mi(Vee(C),I)}else return Mi(Uint8Array.of(4),I,r.toBytes(y))}function h(Q){V0(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=b(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(!w(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 b(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 w(Q,v){let p=r.sqr(v),x=b(Q);return r.eql(p,x)}if(!w(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=r.mul(r.pow(o.a,VC),zLe),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 QLe(Q,c.basises,i.ORDER)}let M=wO((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=wO(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(!w(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=t8(x,v),p=t8(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(V0(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(VC),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,VC),{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,VC),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=>WE(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 WE(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===yd||x.is0())return z.ZERO;if(v===Y0)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}=NLe(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===Y0?!0:v?v(z,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:v}=e;return s===Y0?this:v?v(z,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(v=!0){return $C(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 WE(z,v)}static msm(v,p){return ULe(z,i,v,p)}static fromPrivateKey(v){return z.BASE.multiply(wd(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 bO(z,e.endo?Math.ceil(j/2):j);return z.BASE.precompute(8),z}function Vee(n){return Uint8Array.of(n?2:3)}function Qee(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function YLe(n,e={}){let{Fn:t}=n,r=e.randomBytes||MO,i=Object.assign(Qee(n.Fp,t),{seed:UO(t.ORDER)});function o(f){try{return!!wd(t,f)}catch{return!1}}function s(f,m){let{publicKey:b,publicKeyUncompressed:w}=i;try{let S=f.length;return m===!0&&S!==b||m===!1&&S!==w?!1:!!n.fromBytes(f)}catch{return!1}}function a(f=r(i.seed)){return Nee(V0(f,i.seed,"seed"),t.ORDER)}function c(f,m=!0){return n.BASE.multiply(wd(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:b,publicKeyUncompressed:w}=i;if(t.allowedLengths||m===b)return;let S=so("key",f).length;return S===b||S===w}function d(f,m,b=!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 w=wd(t,f);return n.fromHex(m).multiply(w).toBytes(b)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:u,Point:n,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:f=>wd(t,f),precompute(f=8,m=n.BASE){return m.precompute(f,!1)}},lengths:i})}function jLe(n,e,t={}){Iee(e),i8(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=t.randomBytes||MO,i=t.hmac||((p,...x)=>Kee(e,p,Mi(...x))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f}=YLe(n,t),m={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},b="compact";function w(p){let x=a>>Y0;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){EO(x);let y=f.signature,I=x==="compact"?y:x==="recovered"?y+1:void 0;return V0(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=b){T(x,y);let I;if(y==="der"){let{r:O,s:R}=gd.toSig(V0(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(ZC(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*Jee<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(Vee((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 w(this.s)}toBytes(x=b){if(EO(x),x==="der")return ZC(gd.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=nI(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=rI(c);function A(p){return vLe("num < 2^"+c,p,yd,M),s.toBytes(p)}function D(p,x){return V0(p,void 0,"message"),x?V0(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}=uO(y,m);p=D(p,C);let N=H(p),O=wd(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===yd)return;let B=s.create(E*s.create(_+J*O));if(B===yd)return;let X=(V.x===J?0:2)|Number(V.y&Y0),ce=B;return I&&w(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 CLe(e.outputLen,s.BYTES,i)(I,C)}function Y(p){let x,y=typeof p=="string"||eI(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 gd.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}=uO(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}=uO(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 aee(n){let{CURVE:e,curveOpts:t}=zee(n),r=qee(e,t);return XLe(n,r)}function zee(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 WLe(n){let{CURVE:e,curveOpts:t}=zee(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 ZLe(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 XLe(n,e){let{Fp:t,Fn:r}=e;function i(s){return Lee(s,Y0,r.ORDER)}let o=ZLe(t,n.a,n.b);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s=>wd(r,s),weierstrassEquation:o,isWithinCurveOrder:i})}function _Le(n,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},n,Oee(t.Fn.ORDER,t.Fn.BITS))})}function $Le(n){let{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:i}=WLe(n),o=qee(e,t),s=jLe(o,r,i);return _Le(n,s)}var eRe=BigInt(0),QC=BigInt(1),cee=BigInt(2),Yy=BigInt(3);function tRe(n){let e=[];for(;n>QC;n>>=QC)(n&QC)===eRe?e.unshift(0):(n&Yy)===Yy?(e.unshift(-1),n+=QC):e.unshift(1);return e}function lO(n){if(!Array.isArray(n)||n.length===0)throw new Error("expected non-empty array")}function nRe(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,cee));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,cee)),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=tRe(a),b=wO(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 w(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=[];WE(e,G.map(({g1:M})=>M)),WE(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([b(A),D.x,D.y])}return w(H,U)}function T(G,U,H=!0){return S([{g1:G,g2:U}],H)}return{Fp12:o,millerLoopBatch:w,pairing:T,pairingBatch:S,calcPairingPrecomputes:b}}function uee(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=wd(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=wd(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 b=f.negate(),w=e.Point.BASE,S=u(h),T=d,G=s([l(b,S),l(w,T)]);return o.eql(G,o.ONE)},verifyBatch(d,h,f){if(lO(h),f.length!==h.length)throw new Error("amount of public keys and messages should be equal");let m=c(d),b=h,w=f.map(a),S=new Map;for(let U=0;U<w.length;U++){let H=w[U],M=b[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){lO(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){lO(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){Fc(d);let f=h?{DST:h}:void 0;return t.hashToCurve(d,f)},Signature:r}}function rRe(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=aee(n.G1),a=Object.assign(s,oee(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),c=aee(n.G2),u=Object.assign(c,oee(c.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),l=nRe(n.fields,a.Point,u.Point,{...n.params,postPrecompute:n.postPrecompute}),{millerLoopBatch:d,pairing:h,pairingBatch:f,calcPairingPrecomputes:m}=l,b=uee(l,a,u,n.G2.Signature,!1),w=uee(l,u,a,n.G1.ShortSignature,!0),S=n.randomBytes||MO,T=()=>{let C=UO(t.ORDER);return Nee(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:w.hash(so("point",C),F?.DST)}function A(C,F){return C instanceof u.Point?C:b.hash(so("point",C),F?.DST)}function D(C){return b.getPublicKey(C).toBytes(!0)}function z(C){return w.getPublicKey(C).toBytes(!0)}function j(C,F,N){let O=A(C,N),R=b.sign(O,F);return C instanceof u.Point?R:H.toBytes(R)}function Y(C,F,N){let O=M(C,N),R=w.sign(O,F);return C instanceof a.Point?R:U.toBytes(R)}function Q(C,F,N,O){let R=A(F,O);return b.verify(C,R,N)}function v(C,F,N,O){let R=M(F,O);return w.verify(C,R,N)}function p(C){let F=b.aggregatePublicKeys(C);return C[0]instanceof a.Point?F:F.toBytes(!0)}function x(C){let F=b.aggregateSignatures(C);return C[0]instanceof u.Point?F:H.toBytes(F)}function y(C){let F=w.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 b.verifyBatch(C,R,N)}return a.Point.BASE.precompute(4),{longSignatures:b,shortSignatures:w,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 lee=BigInt(0),bd=BigInt(1),Yo=BigInt(2),dee=BigInt(3);function GO(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=bd;h<r;h++){let m=(l*f-l)/s%a;d.push(n.pow(e,m)),f*=t}c.push(d)}return c}function iRe(n,e,t){let r=e.pow(t,(n.ORDER-bd)/dee),i=e.pow(t,(n.ORDER-bd)/Yo);function o(h,f){let m=e.mul(e.frobeniusMap(h,1),r),b=e.mul(e.frobeniusMap(f,1),i);return[m,b]}let s=e.pow(t,(n.ORDER**Yo-bd)/dee),a=e.pow(t,(n.ORDER**Yo-bd)/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 b=m.toAffine(),w=h(b.x,b.y);return f.fromAffine({x:w[0],y:w[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 fee=(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]}},AO=class{constructor(e,t={}){this.MASK=bd;let r=e.ORDER,i=r*r;this.Fp=e,this.ORDER=i,this.BITS=ZE(i),this.BYTES=Math.ceil(ZE(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=fee(e,t.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=GO(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=t.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return fee(this.Fp,e)}create(e){return e}isValid({c0:e,c1:t}){function r(i,o){return typeof i=="bigint"&&lee<=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 o8(this,e,t)}invertBatch(e){return iI(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 e8(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);e8(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:b,im:w}=r.reim(h);return m>w||m===w&&f>b?d:h}isOdd(e){let{re:t,im:r}=this.reim(e),i=t%Yo,o=t===lee,s=r%Yo;return BigInt(i||o&&s)==bd}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])}}},xO=class{constructor(e){this.MASK=bd,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=GO(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 o8(this,e,t)}invertBatch(e){return iI(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)}}},vO=class{constructor(e,t){this.MASK=bd;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=GO(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 o8(this,e,t)}invertBatch(e){return iI(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:b,second:w}=i.Fp4Square(s,l),S=i.mulByNonresidue(w);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(b,a),Yo),b)}),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),SLe(t,i)&&(r=this.mul(r,e));return r}};function oRe(n){let e=Zy(n.ORDER),t=new AO(e,n),r=new xO(t),i=new vO(r,n);return{Fp:e,Fp2:t,Fp6:r,Fp12:i}}var sRe=BigInt(0),SO=BigInt(1),Yee=BigInt(2),aRe=BigInt(3),jee=BigInt(6),s8=BigInt("4965661367192848881"),cRe=ZE(s8),uRe=jee*s8**Yee,a8={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:SO,a:sRe,b:aRe,Gx:SO,Gy:BigInt(2)},hee=Zy(a8.n),Wee={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:_E,Fp2:Uu,Fp6:lRe,Fp12:zn}=oRe({ORDER:a8.p,X_LEN:cRe,FP2_NONRESIDUE:[BigInt(9),SO],Fp2mulByB:n=>Uu.mul(n,Wee),Fp12finalExponentiate:n=>{let e=l=>zn.conjugate(zn._cyclotomicExp(l,s8)),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:dRe,psi:pee}=iRe(_E,Uu,Uu.NONRESIDUE),dO=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:_E.ORDER,m:2,k:128,expand:"xmd",hash:xee}),fRe=(n,e,t,r,i,o)=>{let s=pee(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=pee(s[0],s[1]);o(n,e,t,a[0],Uu.neg(a[1]))},hRe={p:Uu.ORDER,n:a8.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:Uu.ZERO,b:Wee,Gx:Uu.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:Uu.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},j0=rRe({fields:{Fp:_E,Fp2:Uu,Fp6:lRe,Fp12:zn,Fr:hee},G1:{...a8,Fp:_E,htfDefaults:{...dO,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:{...hRe,Fp:Uu,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...dO},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(uRe).equals(dRe(n,e)),mapToCurve:ci,fromBytes:ci,toBytes:ci,Signature:{fromBytes:ci,fromHex:ci,toBytes:ci,toRawBytes:ci,toHex:ci}},params:{ateLoopSize:s8*jee+Yee,r:hee.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:dO,postPrecompute:fRe});$Le({a:BigInt(0),b:BigInt(3),Fp:_E,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:xee});var c8="groth16",pRe="auth",mRe="authV2",gRe="authV3",yRe="authV3-8-32",wRe=new TextDecoder,mee=BigInt(0),gee=j0.fields.Fp2,yee=j0.fields.Fp12;async function HO(n,e,t){let r=await hLe(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:c}=await JC.prove(e,s);return{proof:a,pub_signals:c}}var[CO,bRe]=[j0.G1.ProjectivePoint,j0.G2.ProjectivePoint],zC=([n,e])=>CO.fromAffine({x:BigInt(n),y:BigInt(e)}),YC=([[n,e],[t,r]])=>bRe.fromAffine({x:gee.fromBigTuple([BigInt(n),BigInt(e)]),y:gee.fromBigTuple([BigInt(t),BigInt(r)])});async function KO(n,e,t,r){if(r(e.pub_signals).challenge!==KI(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(wRe.decode(t));return JO(e,o)}function JO(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=CO.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<mee||BigInt(r[s])>=j0.G1.CURVE.n)throw new Error(`Input value is not in the field ${j0.G1.CURVE.n}`);if(BigInt(r[s])!==mee){let[a,c]=e.IC[s+1].map(BigInt);i=i.add(CO.fromAffine({x:a,y:c}).multiply(BigInt(r[s])))}}i=i.add(zC(e.IC[0]));let o=j0.pairingBatch([{g1:zC(t.pi_a).negate(),g2:YC(t.pi_b)},{g1:i,g2:YC(e.vk_gamma_2)},{g1:zC(t.pi_c),g2:YC(e.vk_delta_2)},{g1:zC(e.vk_alpha_1),g2:YC(e.vk_beta_2)}]);return yee.eql(o,yee.ONE)}var LO=class{methodAlg;constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}unmarshall(e){let t={};if(e.length!=3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return t.challenge=BigInt(e[0]),t.userState=BigInt(e[1]),t.userId=$e.fromBigInt(BigInt(e[2])),t}async verify(e,t,r){return KO(e,t,r,this.unmarshall)}prove(e,t,r){return HO(e,t,r)}},RO=new LO(new Ed(c8,pRe)),DO=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 KO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await HO(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:$e.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},TO=new DO(new Ed(c8,mRe)),r8=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 KO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await HO(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:$e.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},BO=new r8(new Ed(c8,gRe)),PO=new r8(new Ed(c8,yRe));$E(RO.methodAlg,()=>RO);$E(TO.methodAlg,()=>TO);$E(BO.methodAlg,()=>BO);$E(PO.methodAlg,()=>PO);var W0={registerProvingMethod:$E,getProvingMethod:Eee,provingMethodGroth16AuthInstance:RO,provingMethodGroth16AuthV2Instance:TO,provingMethodGroth16AuthV3Instance:BO,provingMethodGroth16AuthV3_8_32Instance:PO};var Zee="unknown circuit ID. can't verify msg sender",u8="sender of message is not used for jwz token creation",Xee="message was packed with unsupported circuit",_ee="message proof is invalid",$ee="message state verification failed",ete="unknown proving method algorithm";var{getProvingMethod:ERe}=W0,qO=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},VO=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},QO=class{constructor(e,t,r={acceptedStateTransitionDelay:iM}){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 ERe(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(ete);let o=new gh(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 unpack(e){let t=await gh.parse(lt.decode(e)),r=new Ed(t.alg,t.circuitId),i=this.verificationParamsMap.get(r.toString());if(!i?.key)throw new Error(Xee);if(!await t.verify(i?.key))throw new Error(_ee);if(!await i?.verificationFn?.verify(t.circuitId,t.zkProof.pub_signals,this._opts))throw new Error($ee);let a=JSON.parse(t.getPayload());return IRe(t,a),a}mediaType(){return"application/iden3-zkp-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")};circuitIds=${this.supportedCircuitIds.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=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}},IRe=async(n,e)=>{switch(n.circuitId){case"authV2":case"authV3-8-32":case"authV3":{if(!e.from)throw new Error(u8);let t=(n.circuitId==="authV2"?new Zs:new N0).pubSignalsUnmarshal(ke.encode(JSON.stringify(n.zkProof.pub_signals))),r=xe.parseFromId(t.userID),i=await n.getMessageHash();if(Ct.bytesToInt(i.reverse())!==t.challenge)throw new Error(u8);if(e.from!==r.string())throw new Error(u8)}break;default:throw new Error(Zee)}};var tte=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(tte||{});var zO=(t=>(t.AUTHV2="authV2",t.ETH_IDENTITY="ethIdentity",t))(zO||{});var nte=(e=>(e.FeatureType="feature-type",e))(nte||{}),rte=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(rte||{});var Gu=W0.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")}},YO=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 Nc(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 Nc(e)},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};async function Nc(n){try{let e=lt.decode(n);return(await gh.parse(e)).method.methodAlg}catch{return Gu}}var ARe=n=>n.reduce((e,t)=>{let r=t.query.groupId;if(!r)return e;let i=e.get(r);if(!i){let s=Kc(12),c=new DataView(s.buffer).getUint32(0);return e.set(r,{query:t.query,linkNonce:c}),e}let o=E4(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=ARe(o),a=new Map,c=[];for(let u of o){let l;try{if(!i.supportedCircuits.includes(u.circuitId)){if(u.optional)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 w=m.query;if(!a.has(f)){let S=await r.findCredentialByProofQuery(n,m.query);if(!S.cred){if(u.optional)continue;throw new Error(Ke.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(w)}`)}a.set(f,S)}}let b=a.get(f);l=await r.generateProof(u,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h.skipClaimRevocationCheck,credential:b?.cred,credentialRevocationStatus:b?.revStatus,linkNonce:m?.linkNonce?BigInt(m.linkNonce):void 0,bypassCache:i.bypassProofsCache})}catch(d){let h=[Ke.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,Ke.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,Ke.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(Ke.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY))&&u.optional)continue;throw d}c.push(l)}return c},jO=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=ite(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")}},oI=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=U0(n.proof),o=hC(t,i.a,i.b,i.c);return{requestId:e,zkProofEncoded:o,metadata:r}},ite=(n,e)=>{let t=e.map(r=>{let i=oI(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")},xRe=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||Gu,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 vRe(n,e,t,r){return ote(n,"",e,t,r)}function ote(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 WO=class extends Oi{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=["credentialAtomicQueryV3-beta.1","credentialAtomicQuerySigV2","credentialAtomicQueryMTPV2","linkedMultiQuery10-beta.1"];handle(t,r){switch(t.type){case 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?xe.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=xe.parse(t.from),u=await Xy(i,t?.body.scope,c,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits,bypassProofsCache:r.bypassProofsCache});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}),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(b=>b.id.toString()===c.id.toString());if(!l){if(c.optional)continue;throw new Error(`proof is not given for requestId ${c.id}`)}let d=l.circuitId;if(d!==c.circuitId)throw new Error(`proof is not given for requested circuit expected: ${c.circuitId}, given ${d}`);let h=c.params??{};h.verifierDid=xe.parse(i.from);let f=[r.acceptedProofGenerationDelay,r.acceptedStateTransitionDelay].some(b=>b!==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(t&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",TE(t))&&(!r?.length||BE(r,t)))return t;if(r?.length){let i=W0.provingMethodGroth16AuthV3_8_32Instance.methodAlg;if(BE(r,i)&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",TE(i)))return i;let o=W0.provingMethodGroth16AuthV3Instance.methodAlg;if(BE(r,o)&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",TE(o)))return o}return Gu}};var ste=[{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 sI=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new jt(e.url);let i=new Ln(t,ste,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 CRe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function LRe(n){return(CRe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function _y(n,e){return LRe(n).includes(e)}function Z0(n){return _y(n,Ke.ERRORS.IDENTITY_DOES_NOT_EXIST)||_y(n,Ke.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function ZO(n){return _y(n,Ke.ERRORS.STATE_DOES_NOT_EXIST)||_y(n,Ke.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function XO(n){return _y(n,Ke.ERRORS.ROOT_DOES_NOT_EXIST)||_y(n,Ke.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var _O=class{constructor(e,t){this._configs=e;this._stateStorage=new aI(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=xe.idFromDID(t),c;try{let h=await this._stateStorage.getLatestStateById(a.bigInt());if(!h.state)throw new Error("state contract returned empty state");c=h.state}catch(h){if(!Z0(h))throw h;if(!s)throw new Error("latest state not found and state parameter is not present in credentialStatus.id");let f=be.fromHex(s).bigInt();if(!iu(t,f))throw new Error(`latest state not found and state parameter ${s} is not genesis state`);c=f}let u=xe.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 sI(r,t)}};var X0=class{async resolve(e){let r=await(await fetch(e.id)).json();return l8(r)}},l8=({issuer:n,mtp:e})=>({mtp:kt.fromJSON(e),issuer:n});var _0=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 $O=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 X0().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=xe.idFromDID(t),s;try{let l=await this._state.getLatestStateById(o.bigInt());if(!l.state)throw new Error("state contract returned empty state");s=l.state}catch(l){if(!Z0(l))throw l;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=be.fromHex(d).bigInt(),f=gp(t);if(!f&&!iu(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&&iu(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&&iu(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=_0.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 RRe(n,e){let t=xe.parse(n),r=xe.idFromDID(t),{method:i,blockchain:o,networkId:s}=xe.decodePartsFromId(r),a=Ct.hexToBytes(e),c=Ct.bytesToInt(a),u=Vc(i,o,s);return ate(xe.idFromDID(t).bigInt(),c,u)}function ate(n,e,t){let r=$e.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var cI=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var uI=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=DRe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return l8(a.body)}};function DRe(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 lI=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)}},eF=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(DR.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},$0=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 tF=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 nF=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new cI,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new X0),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new uI))}getCredentialStatusResolverRegistry(){return this._credentialStatusResolverRegistry}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:Ke.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ke.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(Ke.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:Ke.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ke.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=xe.parse(e.issuer),s=jl(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(Ke.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(Ke.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(Ke.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function d8(n,e,t,r){let i=await f8(r,e,n);await new $0().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function f8(n,e,t){let r=new rF;return n&&await BRe(r,e,n),await TRe(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new _0(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function TRe(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function BRe(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var rF=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 zc(o,s),c=await PRe(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 PRe(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 _0;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=Ch([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var iF=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=xe.parse(t.from),s=xe.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=xe.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":nM[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 Nc(t),senderDID:xe.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=xe.parse(t.to),i=xe.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(jl(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 oF=class extends Oi{constructor(t,r,i){super();this._packerMgr=t;this._proofService=r;this._zkpVerifier=i}_supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","authV2","credentialAtomicQueryV3-beta.1","linkedMultiQuery10-beta.1"];async handle(t,r){switch(t.type){case 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?xe.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[b,w]of f)m.set(b,{responses:w});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[b,w]of f)m.set(b,{responses:[w]});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=xe.parse(t.to),{authProof:b}=await jO(m,this._proofService,{supportedCircuits:this._supportedCircuits,acceptProfile:f,senderAddress:await o.getAddress(),zkpResponses:d}),w=await this._zkpVerifier.submitResponse(o,t.body.transaction_data,d,b);return t.body.transaction_data.txHash=w.keys().next().value,w}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?xe.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 sF=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=xe.parse(r),o=t?.mediaType||"application/iden3-zkp-json",s=t?.packerOptions??{senderDID:i,provingMethodAlg:Gu},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 aF=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=xe.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=xe.parse(o.to),c=ta(i.mediaType,i.packerOptions,{senderDID:a,provingMethodAlg:i.packerOptions?.provingMethodAlg||await Nc(r)});return this._packerMgr.pack(i.mediaType,ke.encode(JSON.stringify(s)),c)}};function kRe(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 MRe(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 cF=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=xe.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 Nc(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 cte(n,e,t,r,i){let o=Ut();return{id:o,thid:o,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PAYMENT_REQUEST_MESSAGE_TYPE,body:{agent:t,payments:r},created_time:Lt(new Date),expires_time:i?.expires_time?Lt(i.expires_time):void 0}}function ute(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 uF=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=xe.parse(t.to),o=xe.parse(t.from),s=[];for(let m=0;m<t.body.payments.length;m++){let{data:b}=t.body.payments[m],w=Array.isArray(b)?b.find(S=>S.type==="Iden3PaymentRequestCryptoV1"?S.id===r.nonce:S.nonce===r.nonce):b;if(!w)throw new Error(`failed request. no payment in request for nonce ${r.nonce}`);switch(w.type){case"Iden3PaymentRequestCryptoV1":s.push(await this.handleIden3PaymentRequestCryptoV1(w,r.paymentHandler));break;case"Iden3PaymentRailsRequestV1":s.push(await this.handleIden3PaymentRailsRequestV1(w,r.paymentHandler));break;case"Iden3PaymentRailsERC20RequestV1":s.push(await this.handleIden3PaymentRailsERC20RequestV1(w,r.paymentHandler,r.erc20TokenApproveHandler));break;case"Iden3PaymentRailsSolanaRequestV1":s.push(await this.handleIden3PaymentRailsSolanaRequestV1(w,r.paymentHandler));break;case"Iden3PaymentRailsSolanaSPLRequestV1":s.push(await this.handleIden3PaymentRailsSolanaSPLRequestV1({...w,type:"Iden3PaymentRailsSolanaSPLRequestV1"},r.paymentHandler));break}}let a=ute(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:{"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=xe.parse(i.to);r.packerOptions=ta(o,r.packerOptions,{provingMethodAlg:await Nc(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:b,chainId:w,optionId:S,expirationDate:T}=s[u].options[f],G=this._params.multiChainPaymentConfig?.find(z=>z.chainId===w);if(!G)throw new Error(`failed request. no config for chain ${w}`);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 bB(a.solSigner,A,w,H,U,BigInt(b),D,m);h.push(z)}else{let z=await EB(o,A,w,H,U,BigInt(b),D,m);h.push(z)}}c.push({data:h,credentials:l,description:d})}return cte(t,r,i,c)}async packMessage(t,r,i,o){let s=ke.encode(JSON.stringify(t)),a=i==="application/iden3comm-signed-json"?o:{provingMethodAlg:o?.provingMethodAlg||Gu};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 iS(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 rS(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 rS(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 iS(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 ORe(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 lte(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 lF=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(lte(i,{to:t.from,from:t.to,expires_time:r?.disclosureExpiresDate?Lt(r.disclosureExpiresDate):void 0}))}handleQuery(t){let r=[];switch(t["feature-type"]){case"accept":r=this.handleAcceptQuery();break;case"protocol":r=this.handleProtocolQuery();break;case"goal-code":r=this.handleGoalCodeQuery();break;case"header":r=this.handleHeaderQuery();break}return this.handleMatch(r,t.match)}handleAcceptQuery(){return this._options.packageManager.getSupportedProfiles().map(r=>({"feature-type":"accept",id:r}))}handleProtocolQuery(){return this._options.protocols?.map(t=>({"feature-type":"protocol",id:t}))??[]}handleGoalCodeQuery(){return this._options.goalCodes?.map(t=>({"feature-type":"goal-code",id:t}))??[]}handleHeaderQuery(){return this._options.headers?.map(t=>({"feature-type":"header",id:t}))??[]}handleMatch(t,r){if(!r||r==="*")return t;let i=this.wildcardToRegExp(r);return t.filter(o=>i.test(o.id))}wildcardToRegExp(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`)}};function dte(n,e){return{id:Ut(),pthid:e?.pthid,typ:"application/iden3comm-plain-json",type:at.PROBLEM_REPORT_MESSAGE_TYPE,ack:e?.ack,body:{code:n,comment:e?.comment,args:e?.args,escalate_to:e?.escalate_to},from:e?.from,to:e?.to}}function FRe(n,e,t){return dte(e,{pthid:n,...t})}var Wo=new TextEncoder,Id=new TextDecoder,h8=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 dF(n,e,t){if(e<0||e>=h8)throw new RangeError(`value must be >= 0 and <= ${h8-1}. Received ${e}`);n.set([e>>>24,e>>>16,e>>>8,e&255],t)}function p8(n){let e=Math.floor(n/h8),t=n%h8,r=new Uint8Array(8);return dF(r,e,0),dF(r,t,4),r}function m8(n){let e=new Uint8Array(4);return dF(e,n),e}function fte(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 hte(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:Id.decode(n),{alphabet:"base64url"});let e=n;e instanceof Uint8Array&&(e=Id.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return hte(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=Wo.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):fte(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 dI=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"},yh=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 fF(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 pte=n=>crypto.getRandomValues(new Uint8Array(fF(n)>>3));var g8=(n,e)=>{if(e.length<<3!==fF(n))throw new Ve("Invalid Initialization Vector length")};var 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`)};function wh(n,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${n}`)}function y8(n,e){return n.name===e}function GRe(n){return parseInt(n.name.slice(4),10)}function HRe(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(!y8(n.algorithm,"AES-GCM"))throw wh("AES-GCM");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw wh(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!y8(n.algorithm,"AES-KW"))throw wh("AES-KW");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw wh(r,"algorithm.length");break}case"ECDH":{switch(n.algorithm.name){case"ECDH":case"X25519":break;default:throw wh("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!y8(n.algorithm,"PBKDF2"))throw wh("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!y8(n.algorithm,"RSA-OAEP"))throw wh("RSA-OAEP");let r=parseInt(e.slice(9),10)||1;if(GRe(n.algorithm.hash)!==r)throw wh(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}HRe(n,t)}function mte(n,e,...t){if(t=t.filter(Boolean),t.length>2){let r=t.pop();n+=`one of type ${t.join(", ")}, or ${r}.`}else t.length===2?n+=`one of type ${t[0]} or ${t[1]}.`:n+=`of type ${t[0]}.`;return e==null?n+=` Received ${e}`:typeof e=="function"&&e.name?n+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(n+=` Received an instance of ${e.constructor.name}`),n}var bh=(n,...e)=>mte("Key must be ",n,...e);function hF(n,e,...t){return mte(`Key for the ${n} algorithm must be `,e,...t)}function em(n){if(!Hu(n))throw new Error("CryptoKey instance expected")}function Hu(n){return n?.[Symbol.toStringTag]==="CryptoKey"}function fI(n){return n?.[Symbol.toStringTag]==="KeyObject"}var pF=n=>Hu(n)||fI(n);async function KRe(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 JRe(n,e,t,r,i,o){if(!(e instanceof Uint8Array))throw new TypeError(bh(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,p8(o.length<<3)),l=new Uint8Array((await crypto.subtle.sign("HMAC",c,u)).slice(0,s>>3)),d;try{d=await KRe(i,l)}catch{}if(!d)throw new yh;let h;try{h=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:"AES-CBC"},a,t))}catch{}if(!h)throw new yh;return h}async function qRe(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 yh}}var w8=async(n,e,t,r,i,o)=>{if(!Hu(e)&&!(e instanceof Uint8Array))throw new TypeError(bh(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(g8(n,r),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&ew(e,parseInt(n.slice(-3),10)),JRe(n,e,t,r,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&ew(e,parseInt(n.slice(1,4),10)),qRe(n,e,t,r,i,o);default:throw new Zt("Unsupported JWE Content Encryption Algorithm")}};var 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};function VRe(n){return typeof n=="object"&&n!==null}var Zo=n=>{if(!VRe(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 gte(n,e){if(n.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function yte(n,e,t){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"AES-KW",!0,[t]):(Cs(n,e,t),n)}async function hI(n,e,t){let r=await yte(e,n,"wrapKey");gte(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 pI(n,e,t){let r=await yte(e,n,"unwrapKey");gte(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))}var wte=async(n,e)=>{let t=`SHA-${n.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(t,e))};function gF(n){return Ss(m8(n.length),n)}async function QRe(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(m8(a),0),c.set(n,4),c.set(t,4+n.length);let u=await wte("sha256",c);s.set(u,(a-1)*i)}return s.slice(0,r)}async function b8(n,e,t,r,i=new Uint8Array(0),o=new Uint8Array(0)){Cs(n,"ECDH"),Cs(e,"ECDH","deriveBits");let s=gF(Wo.encode(t)),a=gF(i),c=gF(o),u=m8(r),l=new Uint8Array(0),d=Ss(s,a,c,u,l),h=new Uint8Array(await crypto.subtle.deriveBits({name:n.algorithm.name,public:n},e,zRe(n)));return QRe(h,r,d)}function zRe(n){return n.algorithm.name==="X25519"?256:Math.ceil(parseInt(n.algorithm.namedCurve.slice(-3),10)/8)<<3}function E8(n){switch(n.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return n.algorithm.name==="X25519"}}function YRe(n,e){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits"]):(Cs(n,e,"deriveBits"),n)}var jRe=(n,e)=>Ss(Wo.encode(n),new Uint8Array([0]),e);async function Ete(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=jRe(e,n),o=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:t,name:"PBKDF2",salt:i},a=await YRe(r,e);return new Uint8Array(await crypto.subtle.deriveBits(s,a,o))}async function Ite(n,e,t,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let o=await Ete(i,n,r,e);return{encryptedKey:await hI(n.slice(-6),o,t),p2c:r,p2s:Zr(i)}}async function Ate(n,e,t,r,i){let o=await Ete(i,n,r,e);return pI(n.slice(-6),o,t)}var yF=(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 vte=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 Ste(n,e,t){return Cs(e,n,"encrypt"),yF(n,e),new Uint8Array(await crypto.subtle.encrypt(vte(n),e,t))}async function Cte(n,e,t){return Cs(e,n,"decrypt"),yF(n,e),new Uint8Array(await crypto.subtle.decrypt(vte(n),e,t))}function mI(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 Ku=n=>crypto.getRandomValues(new Uint8Array(mI(n)>>3));function WRe(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}}var nw=async n=>{if(!n.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:t}=WRe(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 Rte(n,e,t){if(!Zo(n))throw new TypeError("JWK must be an object");let r;switch(e??=n.alg,r??=t?.extractable??n.ext,n.kty){case"oct":if(typeof n.k!="string"||!n.k)throw new TypeError('missing "k" (Key Value) Parameter value');return 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 ZRe(n,e,t,r,i){if(!(t instanceof Uint8Array))throw new TypeError(bh(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,p8(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 XRe(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}}var I8=async(n,e,t,r,i)=>{if(!Hu(t)&&!(t instanceof Uint8Array))throw new TypeError(bh(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(r?g8(n,r):r=pte(n),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ew(t,parseInt(n.slice(-3),10)),ZRe(n,e,t,r,i);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ew(t,parseInt(n.slice(1,4),10)),XRe(n,e,t,r,i);default:throw new Zt("Unsupported JWE Content Encryption Algorithm")}};async function Dte(n,e,t,r){let i=n.slice(0,7),o=await I8(i,t,e,r,new Uint8Array(0));return{encryptedKey:o.ciphertext,iv:Zr(o.iv),tag:Zr(o.tag)}}async function Tte(n,e,t,r,i){let o=n.slice(0,7);return w8(o,e,t,r,i,new Uint8Array(0))}var Bte=async(n,e,t,r,i)=>{switch(n){case"dir":{if(t!==void 0)throw new Ve("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(t!==void 0)throw new Ve("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Zo(r.epk))throw new Ve('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(em(e),!E8(e))throw new Zt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await Rte(r.epk,n);em(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 b8(o,e,n==="ECDH-ES"?r.enc:n,n==="ECDH-ES"?mI(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 pI(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 em(e),Cte(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 Ate(n,e,t,r.p2c,s)}case"A128KW":case"A192KW":case"A256KW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");return pI(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 Tte(n,e,t,o,s)}default:throw new Zt('Invalid or unsupported "alg" (JWE Algorithm) header value')}};var 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)};var wF=(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)};function gI(n){return Zo(n)&&typeof n.kty=="string"}function Pte(n){return n.kty!=="oct"&&(n.kty==="AKP"&&typeof n.priv=="string"||typeof n.d=="string")}function kte(n){return n.kty!=="oct"&&typeof n.d>"u"&&typeof n.priv>"u"}function Mte(n){return n.kty==="oct"&&typeof n.k=="string"}var iw,Ote=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},$Re=(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},Eh=async(n,e)=>{if(n instanceof Uint8Array||Hu(n))return n;if(fI(n)){if(n.type==="secret")return n.export();if("toCryptoKey"in n&&typeof n.toCryptoKey=="function")try{return $Re(n,e)}catch(r){if(r instanceof TypeError)throw r}let t=n.export({format:"jwk"});return Ote(n,t,e)}if(gI(n))return n.k?Wr(n.k):Ote(n,n,e,!0);throw new Error("unreachable")};var ow=n=>n?.[Symbol.toStringTag],bF=(n,e,t)=>{if(e.use!==void 0){let r;switch(t){case"sign":case"verify":r="sig";break;case"encrypt":case"decrypt":r="enc";break}if(e.use!==r)throw new TypeError(`Invalid key for this operation, its "use" must be "${r}" when present`)}if(e.alg!==void 0&&e.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(e.key_ops)){let r;switch(!0){case(t==="sign"||t==="verify"):case n==="dir":case n.includes("CBC-HS"):r=t;break;case n.startsWith("PBES2"):r="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(n):!n.includes("GCM")&&n.endsWith("KW")?r=t==="encrypt"?"wrapKey":"unwrapKey":r=t;break;case(t==="encrypt"&&n.startsWith("RSA")):r="wrapKey";break;case t==="decrypt":r=n.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(r&&e.key_ops?.includes?.(r)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},eDe=(n,e,t)=>{if(!(e instanceof Uint8Array)){if(gI(e)){if(Mte(e)&&bF(n,e,t))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!pF(e))throw new TypeError(hF(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"`)}},tDe=(n,e,t)=>{if(gI(e))switch(t){case"decrypt":case"sign":if(Pte(e)&&bF(n,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"encrypt":case"verify":if(kte(e)&&bF(n,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!pF(e))throw new TypeError(hF(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"`);default:break}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"`);default:break}},sw=(n,e,t)=>{n.startsWith("HS")||n==="dir"||n.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(n)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(n)?eDe(n,e,t):tDe(n,e,t)};async function yI(n,e,t){if(!Zo(n))throw new Ve("Flattened JWE must be an object");if(n.protected===void 0&&n.header===void 0&&n.unprotected===void 0)throw new Ve("JOSE Header missing");if(n.iv!==void 0&&typeof n.iv!="string")throw new Ve("JWE Initialization Vector incorrect type");if(typeof n.ciphertext!="string")throw new Ve("JWE Ciphertext missing or incorrect type");if(n.tag!==void 0&&typeof n.tag!="string")throw new Ve("JWE Authentication Tag incorrect type");if(n.protected!==void 0&&typeof n.protected!="string")throw new Ve("JWE Protected Header incorrect type");if(n.encrypted_key!==void 0&&typeof n.encrypted_key!="string")throw new Ve("JWE Encrypted Key incorrect type");if(n.aad!==void 0&&typeof n.aad!="string")throw new Ve("JWE AAD incorrect type");if(n.header!==void 0&&!Zo(n.header))throw new Ve("JWE Shared Unprotected Header incorrect type");if(n.unprotected!==void 0&&!Zo(n.unprotected))throw new Ve("JWE Per-Recipient Unprotected Header incorrect type");let r;if(n.protected)try{let U=Wr(n.protected);r=JSON.parse(Id.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&&wF("keyManagementAlgorithms",t.keyManagementAlgorithms),c=t&&wF("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms);if(a&&!a.has(o)||!a&&o.startsWith("PBES2"))throw new dI('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(s))throw new dI('"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 Eh(e,o),h;try{h=await Bte(o,d,u,i,t)}catch(U){if(U instanceof TypeError||U instanceof Ve||U instanceof Zt)throw U;h=Ku(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 b=Wo.encode(n.protected??""),w;n.aad!==void 0?w=Ss(b,Wo.encode("."),Wo.encode(n.aad)):w=b;let S;try{S=Wr(n.ciphertext)}catch{throw new Ve("Failed to base64url decode the ciphertext")}let G={plaintext:await w8(s,h,S,f,m,w)};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 EF(n,e,t){if(!Zo(n))throw new Ve("General JWE must be an object");if(!Array.isArray(n.recipients)||!n.recipients.every(Zo))throw new Ve("JWE Recipients missing or incorrect type");if(!n.recipients.length)throw new Ve("JWE Recipients has no members");for(let r of n.recipients)try{return await yI({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 yh}var A8=Symbol();async function IF(n){if(fI(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(!Hu(n))throw new TypeError(bh(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 Fte(n){return IF(n)}var x8=async(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(em(t),!E8(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 Eh(i.epk,n):l=(await crypto.subtle.generateKey(t.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:h,crv:f,kty:m}=await Fte(l),b=await b8(t,l,n==="ECDH-ES"?e:n,n==="ECDH-ES"?mI(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=b;break}a=r||Ku(e);let w=n.slice(-6);o=await hI(w,b,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=r||Ku(e),em(t),o=await Ste(n,t,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=r||Ku(e);let{p2c:c,p2s:u}=i;({encryptedKey:o,...s}=await Ite(n,t,a,c,u));break}case"A128KW":case"A192KW":case"A256KW":{a=r||Ku(e),o=await hI(n,t,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=r||Ku(e);let{iv:c}=i;({encryptedKey:o,...s}=await Dte(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 wI=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,w=await Eh(e,i);({cek:a,encryptedKey:s,parameters:b}=await x8(i,o,w,this.#o,this.#a)),b&&(t&&A8 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;this.#t?u=Wo.encode(Zr(JSON.stringify(this.#t))):u=Wo.encode(""),this.#i?(l=Zr(this.#i),c=Ss(u,Wo.encode("."),Wo.encode(l))):c=u;let{ciphertext:d,tag:h,iv:f}=await I8(o,this.#e,a,this.#s,c),m={ciphertext:Zr(d)};return f&&(m.iv=Zr(f)),h&&(m.tag=Zr(h)),s&&(m.encrypted_key=Zr(s)),l&&(m.aad=l),this.#t&&(m.protected=Id.decode(u)),this.#n&&(m.unprotected=this.#n),this.#r&&(m.header=this.#r),m}};var AF=class{#e;unprotectedHeader;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}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},bI=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let r=new AF(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 wI(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=Ku(e),r={ciphertext:"",iv:"",recipients:[],tag:""};for(let i=0;i<this.#t.length;i++){let o=this.#t[i],s={};r.recipients.push(s);let c={...this.#n,...this.#r,...o.unprotectedHeader}.alg.startsWith("PBES2")?2048+i:void 0;if(i===0){let f=await new wI(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(o.unprotectedHeader).setKeyManagementParameters({p2c:c}).encrypt(o.key,{...o.options,[A8]:!0});r.ciphertext=f.ciphertext,r.iv=f.iv,r.tag=f.tag,f.aad&&(r.aad=f.aad),f.protected&&(r.protected=f.protected),f.unprotected&&(r.unprotected=f.unprotected),s.encrypted_key=f.encrypted_key,f.header&&(s.header=f.header);continue}let u=o.unprotectedHeader?.alg||this.#n?.alg||this.#r?.alg;sw(u==="dir"?e:u,o.key,"encrypt");let l=await Eh(o.key,u),{encryptedKey:d,parameters:h}=await x8(u,e,l,t,{p2c:c});s.encrypted_key=Zr(d),(o.unprotectedHeader||h)&&(s.header={...o.unprotectedHeader,...h})}return r}};function xF(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(Id.decode(Wr(e)));if(!Zo(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var v8=class{constructor(e){this.resolvePrivateKeyByKid=e}async encrypt(e,t){let{enc:r,typ:i,recipients:o}=t,s=new bI(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(xF(r),r.header||{}),yI(e,t)}return EF(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 S8=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 SF={};Sr(SF,{DeviceNotificationStatus:()=>Gte,NotificationServiceType:()=>Nte,NotificationStatus:()=>Ute,PushNotifier:()=>vF});var Nte=(e=>(e.Push="push-notification",e))(Nte||{}),Ute=(t=>(t.Success="success",t.Failed="failed",t))(Ute||{});var Gte=(r=>(r.Success="success",r.Rejected="rejected",r.Failed="failed",r))(Gte||{}),nDe={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()}}}},vF=class{constructor(e=nDe){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 Ad={url:"http://localhost:8545",defaultGasLimit:6e5,minGasPrice:"0",maxGasPrice:"100000000000",confirmationBlockCount:5,confirmationTimeout:6e5,contractAddress:"",receiptTimeout:6e5,rpcResponseTimeout:5e3,waitReceiptCycleTime:3e4,waitBlockCycleTime:3e3},aI=class{constructor(e,t){this.ethConfig=e;let r=Array.isArray(e)?e[0]:e;this.provider=new jt(r.url),this.stateContract=new Ln(r.contractAddress,X5,this.provider),this._transactionService=new Xs(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??Yr.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??hg},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??hg},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??hg},this._gistProofCacheOptions={ttl:Yr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??hg},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??ch({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??ch({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??ch({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??ch({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(Ke.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR);return s}}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=[];try{i=await r.getStateInfoById(e)}catch(s){throw Z0(s)&&!this._disableCache&&await this._latestStateResolveCache?.set(t,{id:e,state:0n,replacedByState:0n,createdAtTimestamp:0n,replacedAtTimestamp:0n,createdAtBlock:0n,replacedAtBlock:0n},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 c=await this._stateResolveCache?.get(r);if(c)return c}let{stateContract:i}=this.getStateContractAndProviderForId(e),o=await i.getStateInfoByIdAndState(e,t),s={id:BigInt(o[0]),state:BigInt(o[1]),replacedByState:BigInt(o[2]),createdAtTimestamp:BigInt(o[3]),replacedAtTimestamp:BigInt(o[4]),createdAtBlock:BigInt(o[5]),replacedAtBlock:BigInt(o[6])},a=s.replacedAtTimestamp===0n?this._stateCacheOptions.notReplacedTtl:this._stateCacheOptions.replacedTtl;return!this._disableCache&&await this._stateResolveCache?.set(r,s,a),s}async publishState(e,t){let r=new vE;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=U0(e.proof),h=[i.bigInt().toString(),o.bigInt().toString(),s.bigInt().toString(),a,d.a,d.b,d.c],f=await u.getFeeData(),m=Ad.maxFeePerGas?BigInt(Ad.maxFeePerGas):f.maxFeePerGas,b=Ad.maxPriorityFeePerGas?BigInt(Ad.maxPriorityFeePerGas):f.maxPriorityFeePerGas,w=await l.transitState.estimateGas(...h),S=await l.transitState.populateTransaction(...h),T={to:S.to,data:S.data,gasLimit:w,maxFeePerGas:m,maxPriorityFeePerGas:b},{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=Ad.maxFeePerGas?BigInt(Ad.maxFeePerGas):h.maxFeePerGas,m=Ad.maxPriorityFeePerGas?BigInt(Ad.maxPriorityFeePerGas):h.maxPriorityFeePerGas,b=[r.bigInt().toString(),i.bigInt().toString(),o.bigInt().toString(),s,a,c],w=await d.transitStateGeneric.estimateGas(...b),S=await d.transitStateGeneric.populateTransaction(...b),T={to:S.to,data:S.data,gasLimit:w,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=$e.fromBigInt(t),i=im(xe.blockchainFromId(r),xe.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=$e.fromBigInt(e),r=im(xe.blockchainFromId(t),xe.networkIdFromId(t)),i=this.networkByChainId(r),o=new jt(i.url);return{stateContract:new Ln(i.contractAddress,X5,o),provider:o}}networkByChainId(e){let r=(Array.isArray(this.ethConfig)?this.ethConfig:[this.ethConfig]).find(i=>i.chainId===e);if(!r)throw new Error(`chainId "${e}" not supported`);return r}getGistProofCacheKey(e){return`gist:${e.toString()}`}getLatestStateCacheKey(e){return`latest-state:${e.toString()}`}getStateCacheKey(e,t){return`state:${e.toString()}-${t.toString()}`}getRootCacheKey(e,t){return`root:${e.toString()}-${t.toString()}`}};var CF=[{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 LF=[{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 RF=10000000n,Hte=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(Hte||{}),Kte=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]},DF=class n{constructor(e,t){this._configs=e;this._opts=t}static _supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1"];static _supportedCircuitsPubSignalsMap={credentialAtomicQueryMTPV2OnChain:pE,credentialAtomicQuerySigV2OnChain:AE,"credentialAtomicQueryV3OnChain-beta.1":EE,authV2:Zs};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=U0(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,CF);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},b;try{b=await e.estimateGas(m)}catch{b=RF}m.gasLimit=b;let w=new Xs(o),{txnHash:S}=await w.sendTransactionRequest(e,m);s.set(S,d)}return s}async submitZKPResponseV2(e,t,r){let i=this._configs.find(w=>w.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,CF).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:c,maxPriorityFeePerGas:u},f;try{f=await e.estimateGas(h)}catch{f=RF}h.gasLimit=f;let m=new Xs(o),{txnHash:b}=await m.sendTransactionRequest(e,h);return new Map().set(b,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,LF).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=RF}f.gasLimit=m;let b=new Xs(s),{txnHash:w}=await b.sendTransactionRequest(e,f);return new Map().set(w,{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=U0(i.zkp.proof);u=hC(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{u=Jte(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:b,metadata:w}=oI(f);a.push({proof:f,requestId:m,encoded:b,metadata:w})}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:b}=this.getUpdateResolutions(e,t.chain_id,f.circuitId,f.pub_signals);m.length>0&&o.push(...await Promise.all(m)),b.length>0&&s.push(...await Promise.all(b))}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:Kte(h)}}async prepareTxArgsSubmit(e,t,r){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmit(this._opts.didResolverUrl,e,t,r)}static checkSupportedCircuit(e){if(!this._supportedCircuits.includes(e))throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`)}static getCrossChainResolvers(e,t,r,i){return[...new Set(e.map(o=>JSON.stringify({id:o.id.string(),[r]:r==="gist"?o.root?.string():o.state?.string()})))].reduce((o,s)=>{let a=JSON.parse(s),c=$e.fromString(a.id),u=dw(xe.parseFromId(c));if(t===u)return o;let l=this.resolveDidDocumentEip712MessageAndSignature(xe.parseFromId($e.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}=oI(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];if(!r)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=new r,o=ke.encode(JSON.stringify(t));return i.pubSignalsUnmarshal(o),i.getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await yp(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}}},Jte=n=>`0x${Rr(Ct.intToBytes(xe.idFromDID(n).bigInt()))}`;var TF=[{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 BF=[{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=BF;static createInterface(){return new lc(BF)}static connect(e,t){return new Ln(e,BF,t)}};var EI=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($e.ethAddressFromId(xe.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=xe.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 pc({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:c,coreClaim:e})}async validateSourceValue(e,t,r){if(await Ru.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 PF=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 EI(o,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});await a.isInterfaceSupported();let{credentialData:c,coreClaimBigInts:u,credentialSubjectFields:l}=await a.getCredential(xe.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 EI(i,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});return await s.isInterfaceSupported(),await s.getUserCredentialsIds(xe.idFromDID(t))}default:throw new Error(`Unsupported adapter version ${o}`)}}getContractConnection(e){let t=xe.idFromDID(e),r=dw(e),i=xn.getAddress(xn.hexlify($e.ethAddressFromId(t))),o=this._ethConnectionConfig.find(a=>a.chainId===r);if(!o)throw new Error(`No connection found for chain ID ${r}`);if(!o.url)throw new Error(`No URL found for chain ID ${r}`);return{contract:new Ln(i,TF,new xn.JsonRpcProvider(o.url)),connection:o}}};var kF=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 yp(xe.parseFromId($e.fromBigInt(e)),this.resolverUrl),{global:r}=this.getIden3StateInfo2023(t);if(!r)throw new Error("GIST root not found");let{proof:i}=r;if(!i)throw new Error("GIST proof not found");return{root:r.root,existence:i.existence,siblings:i.siblings?.map(o=>BigInt(o)),index:BigInt(0),value:BigInt(0),auxExistence:!!i.node_aux,auxIndex:i.node_aux?BigInt(i.node_aux.key):BigInt(0),auxValue:i.node_aux?BigInt(i.node_aux.value):BigInt(0)}}async getGISTRootInfo(e,t){let{didDocument:r}=await yp(xe.parseFromId($e.fromBigInt(t)),this.resolverUrl,{gist:be.fromBigInt(e)}),{global:i}=this.getIden3StateInfo2023(r);if(!i)throw new Error("GIST root not found");return i}getRpcProvider(){return new jt}publishState(){throw new Error("publishState method not implemented.")}publishStateGeneric(){throw new Error("publishStateGeneric method not implemented.")}async getStateInfo(e,t){let r=t?{state:be.fromBigInt(t)}:void 0,{didDocument:i}=await yp(xe.parseFromId($e.fromBigInt(e)),this.resolverUrl,r),{info:o,published:s}=this.getIden3StateInfo2023(i);if(!o&&!s)throw new Error(Ke.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 qte=[{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 Vte=[{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 dDe(n,e,t,r,i){let o=new Ln(e,qte,n),s=await o.nonces(await n.getAddress()),a=await o.eip712Domain(),c={name:a[1],version:a[2],chainId:a[3],verifyingContract:e},u={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},l={owner:await n.getAddress(),spender:t,value:r,nonce:s,deadline:i};return n.signTypedData(c,u,l)}async function fDe(n,e){return new Ln(n,Vte,e).decimals()}var Zte=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(Zte||{}),Xte=(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))(Xte||{}),MF=[!0,1,"true"],OF=[!1,0,"false"],Qte=(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,MF.includes(n)&&MF.includes(e)||OF.includes(n)&&OF.includes(e)?!0:n===e),zte=(n,e)=>$te(n,e,(r,i)=>{switch(ene(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}}),Yte=(n,e)=>$te(n,e,(r,i)=>{switch(ene(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}}),hDe=(n,e)=>!!(MF.includes(e)&&typeof n<"u"||OF.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),jte=(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,Wte=(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))},Ju={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>hDe(n,e),$eq:(n,e)=>Qte(n,e),$in:(n,e)=>jte(n,e),$nin:(n,e)=>!jte(n,e),$gt:(n,e)=>zte(n,e),$lt:(n,e)=>!Yte(n,e),$ne:(n,e)=>!Qte(n,e),$gte:(n,e)=>Yte(n,e),$lte:(n,e)=>!zte(n,e),$between:(n,e)=>Wte(n,e),$nonbetween:(n,e)=>!Wte(n,e)},_te=(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},Uc=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=_te(e,this.path);return t==null&&this.operatorFunc!==Ju.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},FF=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new Uc("id",Ju.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new Uc("issuer",Ju.$in,r));case"type":return e.concat(new Uc("type",Ju.$in,r,!0));case"context":return e.concat(new Uc("@context",Ju.$in,r,!0));case"credentialSubjectId":return e.concat(new Uc("credentialSubject.id",Ju.$eq,r));case"schema":return e.concat(new Uc("credentialSchema.id",Ju.$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 Uc(`credentialSubject.${s}`,Ju.$noop,null)]);let c=Object.keys(a).map(u=>{let l=a[u],d=`credentialSubject.${s}`;return new Uc(d,Ju[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`)}},[]),$te=(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),pDe=/^[+-]?\d+$/,mDe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,gDe=/^([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]))$/,yDe=/^(true)|(false)$/,wDe=/^\d{4}-\d{2}-\d{2}$/,ene=n=>pDe.test(n)?0:mDe.test(n)?2:gDe.test(n)||wDe.test(n)?3:yDe.test(n)?1:4;var NF=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 UF=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(Yc(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(Yc(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 GF=class{constructor(e){this._storageKey=e;this._store=Md(`${e}-db`,e)}_store;async save(e,t,r="id"){return Od(e,t,this._store)}async get(e,t="id"){return Qc(e,this._store)}async load(){return KN(this._store)}async delete(e,t="id"){return qI(e,this._store)}};var HF=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=Md(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=Md(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Ut()}`),await Qc(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=Oy(e);return await Od(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await Qc(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 Qc(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(Yc(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await Qc(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(Yc(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await Qc(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 qI(e,this._merkleTreeMetaStore),await Od(t,i,this._merkleTreeMetaStore),await Od(e,t,this._bindingStore)}};var KF=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=FF(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 qF=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 VF=class{constructor(e){this.opts=e;this._verificationKeyPath=this.opts.verificationFileName??this._verificationKeyPath,this._provingKeyPath=this.opts.provingFileName??this._provingKeyPath,this._wasmFilePath=this.opts.wasmFileName??this._wasmFilePath}_verificationKeyPath="verification_key.json";_provingKeyPath="circuit_final.zkey";_wasmFilePath="circuit.wasm";_fs=null;_browserNotSupportedError=new Error("File system operations are not supported in browser environment");async getFs(){return this._fs?this._fs:(this._fs={existsSync:()=>{throw this._browserNotSupportedError},readFileSync:()=>{throw this._browserNotSupportedError},writeFileSync:()=>{throw this._browserNotSupportedError},mkdirSync:()=>{throw this._browserNotSupportedError}},this._fs)}async loadCircuitData(e){let t=await this.loadCircuitFile(e,this._verificationKeyPath),r=await this.loadCircuitFile(e,this._provingKeyPath),i=await this.loadCircuitFile(e,this._wasmFilePath);return{circuitId:e,wasm:i,provingKey:r,verificationKey:t}}async loadCircuitFile(e,t){let r=`${this.opts.dirname}/${e}/${t}`,i=await this.getFs();if(i.existsSync(r)){let o=i.readFileSync(r);return new Uint8Array(o)}return null}async writeCircuitFile(e,t,r,i){let o=`${this.opts.dirname}/${e}`,s=`${o}/${t}`,a=await this.getFs();a.mkdirSync(o,{recursive:!0}),a.writeFileSync(s,r,i)}async saveCircuitData(e,t){t.verificationKey&&await this.writeCircuitFile(e,this._verificationKeyPath,t.verificationKey,"utf-8"),t.provingKey&&await this.writeCircuitFile(e,this._provingKeyPath,t.provingKey),t.wasm&&await this.writeCircuitFile(e,this._wasmFilePath,t.wasm)}};var 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:Y5(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},Ih=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}},C8=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},L8=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 m6(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(!W5(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=bDe(n.operatorValue);break;default:s=await R8(n.operatorValue,i.datatype)}i.values=s}return i},II=async(n,e,t,r)=>{let i=C8(t);return Promise.all(i.map(o=>L8(o,e,n,r)))},R8=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await Ru.hashValue(e,n[r]);else t[0]=await Ru.hashValue(e,n);return t},bDe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")};async function YF(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=pLe(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(pO(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 pLe(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 pO(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 mLe(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 gLe(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 eI(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function mO(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Fc(n,...e){if(!eI(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 Iee(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mO(n.outputLen),mO(n.blockLen)}function jC(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 yLe(n,e){Fc(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function WC(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function rO(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Nu(n,e){return n<<32-e|n>>>e}var Aee=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wLe=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function jy(n){if(Fc(n),Aee)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=wLe[n[t]];return e}var md={_0:48,_9:57,A:65,F:70,a:97,f:102};function eee(n){if(n>=md._0&&n<=md._9)return n-md._0;if(n>=md.A&&n<=md.F)return n-(md.A-10);if(n>=md.a&&n<=md.f)return n-(md.a-10)}function ZC(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(Aee)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=eee(n.charCodeAt(o)),a=eee(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 tI(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function kO(n){return typeof n=="string"&&(n=tI(n)),Fc(n),n}function Mi(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];Fc(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 XC=class{};function bLe(n){let e=r=>n().update(kO(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function MO(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 ELe(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 ILe(n,e,t){return n&e^~n&t}function ALe(n,e,t){return n&e^n&t^e&t}var gO=class extends XC{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=rO(this.buffer)}update(e){jC(this),e=kO(e),Fc(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=rO(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){jC(this),yLe(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,WC(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;ELe(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=rO(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()}},hh=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xLe=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]),ph=new Uint32Array(64),yO=class extends gO{constructor(e=32){super(64,e,8,!1),this.A=hh[0]|0,this.B=hh[1]|0,this.C=hh[2]|0,this.D=hh[3]|0,this.E=hh[4]|0,this.F=hh[5]|0,this.G=hh[6]|0,this.H=hh[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)ph[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=ph[d-15],f=ph[d-2],m=Nu(h,7)^Nu(h,18)^h>>>3,b=Nu(f,17)^Nu(f,19)^f>>>10;ph[d]=b+ph[d-7]+m+ph[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=Nu(a,6)^Nu(a,11)^Nu(a,25),f=l+h+ILe(a,c,u)+xLe[d]+ph[d]|0,b=(Nu(r,2)^Nu(r,13)^Nu(r,22))+ALe(r,i,o)|0;l=u,u=c,c=a,a=s+f|0,s=o,o=i,i=r,r=f+b|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(){WC(ph)}destroy(){this.set(0,0,0,0,0,0,0,0),WC(this.buffer)}},xee=bLe(()=>new yO);var OO=BigInt(0),_C=BigInt(1);function $C(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function V0(n,e,t=""){let r=eI(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 qC(n){let e=n.toString(16);return e.length&1?"0"+e:e}function vee(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?OO:BigInt("0x"+n)}function nI(n){return vee(jy(n))}function See(n){return Fc(n),vee(jy(Uint8Array.from(n).reverse()))}function FO(n,e){return ZC(n.toString(16).padStart(e*2,"0"))}function Cee(n,e){return FO(n,e).reverse()}function so(n,e,t){let r;if(typeof e=="string")try{r=ZC(e)}catch(i){throw new Error(n+" must be hex string or Uint8Array, cause: "+i)}else if(eI(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");return r}var iO=n=>typeof n=="bigint"&&OO<=n;function Lee(n,e,t){return iO(n)&&iO(e)&&iO(t)&&e<=n&&n<t}function vLe(n,e,t,r){if(!Lee(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function ZE(n){let e;for(e=0;n>OO;n>>=_C,e+=1);return e}function SLe(n,e){return n>>BigInt(e)&_C}var rI=n=>(_C<<BigInt(n))-_C;function CLe(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 b=o.slice();m.push(b),f+=o.length}return Mi(...m)};return(f,m)=>{c(),l(f);let b;for(;!(b=m(d()));)l();return c(),b}}function LLe(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function i8(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 wO(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),Ree=BigInt(3),Dee=BigInt(4),Tee=BigInt(5),RLe=BigInt(7),Bee=BigInt(8),DLe=BigInt(9),Pee=BigInt(16);function Ga(n,e){let t=n%e;return t>=ea?t:e+t}function tee(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 NO(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)/Dee,r=n.pow(e,t);return NO(n,r,e),r}function TLe(n,e){let t=(n.ORDER-Tee)/Bee,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 NO(n,a,e),a}function BLe(n){let e=Zy(n),t=Mee(n),r=t(e,e.neg(e.ONE)),i=t(e,r),o=t(e,e.neg(r)),s=(n+RLe)/Pee;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 b=a.eql(a.sqr(l),c),w=a.cmov(u,l,b);return NO(a,w,c),w}}function Mee(n){if(n<Ree)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(;e8(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(e8(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,b=c.sqr(h);for(;!c.eql(b,c.ONE);)if(m++,b=c.sqr(b),m===l)throw new Error("Cannot find square root");let w=jo<<BigInt(l-m-1),S=c.pow(d,w);l=m,d=c.sqr(S),h=c.mul(h,d),f=c.mul(f,S)}return f}}function PLe(n){return n%Dee===Ree?kee:n%Bee===Tee?TLe:n%Pee===DLe?BLe(n):Mee(n)}var kLe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function MLe(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=kLe.reduce((r,i)=>(r[i]="function",r),e);return i8(n,t),n}function o8(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 iI(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 e8(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 Oee(n,e){e!==void 0&&mO(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}=Oee(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:rI(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)=>o8(d,h,f),div:(h,f)=>Ga(h*tee(f,n),n),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>tee(h,n),sqrt:o||(h=>(l||(l=PLe(n)),l(d,h))),toBytes:h=>t?Cee(h,u):FO(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 b=new Uint8Array(u);b.set(h,t?0:b.length-h.length),h=b}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let m=t?See(h):nI(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=>iI(d,h),cmov:(h,f,m)=>m?f:h});return Object.freeze(d)}function Fee(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 UO(n){let e=Fee(n);return e+Math.ceil(e/2)}function Nee(n,e,t=!1){let r=n.length,i=Fee(e),o=UO(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?See(n):nI(n),a=Ga(s,e-jo)+jo;return t?Cee(a,i):FO(a,i)}var Wy=BigInt(0),z0=BigInt(1);function t8(n,e){let t=e.negate();return n?t:e}function WE(n,e){let t=iI(n.Fp,e.map(r=>r.Z));return e.map((r,i)=>n.fromAffine(r.toAffine(t[i])))}function Uee(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function oO(n,e){Uee(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=rI(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function nee(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+=z0);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 OLe(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 FLe(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 sO=new WeakMap,Gee=new WeakMap;function aO(n){return Gee.get(n)||1}function ree(n){if(n!==Wy)throw new Error("invalid wNAF")}var bO=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&z0&&(r=r.add(i)),i=i.double(),t>>=z0;return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=oO(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=oO(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:h,offsetF:f}=nee(r,a,s);r=c,l?o=o.add(t8(h,t[f])):i=i.add(t8(d,t[u]))}return ree(r),{p:i,f:o}}wNAFUnsafe(e,t,r,i=this.ZERO){let o=oO(e,this.bits);for(let s=0;s<o.windows&&r!==Wy;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=nee(r,s,o);if(r=a,!u){let d=t[c];i=i.add(l?d.negate():d)}}return ree(r),i}getPrecomputes(e,t,r){let i=sO.get(t);return i||(i=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(i=r(i)),sO.set(t,i))),i}cached(e,t,r){let i=aO(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let o=aO(e);return o===1?this._unsafeLadder(e,t,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,i)}createCache(e,t){Uee(t,this.bits),Gee.set(e,t),sO.delete(e)}hasCache(e){return aO(e)!==1}};function NLe(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Wy||r>Wy;)t&z0&&(o=o.add(i)),r&z0&&(s=s.add(i)),i=i.double(),t>>=z0,r>>=z0;return{p1:o,p2:s}}function ULe(n,e,t,r){OLe(t,n),FLe(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=ZE(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=rI(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 b=0;b<o;b++){let w=r[b],S=Number(w>>BigInt(f)&u);l[S]=l[S].add(t[b])}let m=s;for(let b=l.length-1,w=s;b>0;b--)w=w.add(l[b]),m=m.add(w);if(h=h.add(m),f!==0)for(let b=0;b<c;b++)h=h.double()}return h}function iee(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return MLe(e),e}else return Zy(n,{isLE:t})}function GLe(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=iee(e.p,t.Fp,r),o=iee(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 HLe=nI;function mh(n,e){if(XE(n),XE(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 KLe(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 XE(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function Hee(n){if(!eI(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or string");return typeof n=="string"?tI(n):n}function JLe(n,e,t,r){Fc(n),XE(t),e=Hee(e),e.length>255&&(e=r(Mi(tI("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,mh(e.length,1)),c=mh(0,o),u=mh(t,2),l=new Array(s),d=r(Mi(c,n,u,mh(0,1),a));l[0]=r(Mi(d,mh(1,1),a));for(let f=1;f<=s;f++){let m=[KLe(d,l[f-1]),mh(f+1,1),a];l[f]=r(Mi(...m))}return Mi(...l).slice(0,t)}function qLe(n,e,t,r,i){if(Fc(n),XE(t),e=Hee(e),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update(tI("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(mh(t,2)).update(e).update(mh(e.length,1)).digest()}function cO(n,e,t){i8(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:c}=t;if(!LLe(t.hash))throw new Error("expected valid hash");Fc(n),XE(e);let u=r.toString(2).length,l=Math.ceil((u+i)/8),d=e*o*l,h;if(a==="xmd")h=JLe(n,c,d,s);else if(a==="xof")h=qLe(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 b=new Array(o);for(let w=0;w<o;w++){let S=l*(w+m*o),T=h.subarray(S,S+l);b[w]=Ga(HLe(T),r)}f[m]=b}return f}var VLe=tI("HashToScalar-");function oee(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=cO(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=cO(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:VLe},s);return cO(o,1,c)[0][0]}}}var n8=class extends XC{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Iee(e);let r=kO(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),WC(o)}update(e){return jC(this),this.iHash.update(e),this}digestInto(e){jC(this),Fc(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()}},Kee=(n,e,t)=>new n8(n,e).update(t).digest();Kee.create=(n,e)=>new n8(n,e);var see=(n,e)=>(n+(n>=0?e:-e)/Jee)/e;function QLe(n,e,t){let[[r,i],[o,s]]=e,a=see(s*n,t),c=see(-i*n,t),u=n-a*r-c*o,l=-a*i-c*s,d=u<yd,h=l<yd;d&&(u=-u),h&&(l=-l);let f=rI(Math.ceil(ZE(t)/2))+Y0;if(u<yd||u>=f||l<yd||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:d,k1:u,k2neg:h,k2:l}}function EO(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function uO(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return $C(t.lowS,"lowS"),$C(t.prehash,"prehash"),t.format!==void 0&&EO(t.format),t}var IO=class extends Error{constructor(e=""){super(e)}},gd={Err:IO,_tlv:{encode:(n,e)=>{let{Err:t}=gd;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=qC(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?qC(i.length/2|128):"";return qC(n)+o+i+e},decode(n,e){let{Err:t}=gd,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}=gd;if(n<yd)throw new e("integer: negative integers are not allowed");let t=qC(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}=gd;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 nI(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=gd,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}=gd,r=e.encode(2,t.encode(n.r)),i=e.encode(2,t.encode(n.s)),o=r+i;return e.encode(48,o)}},yd=BigInt(0),Y0=BigInt(1),Jee=BigInt(2),VC=BigInt(3),zLe=BigInt(4);function wd(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 qee(n,e={}){let t=GLe("weierstrass",n,e),{Fp:r,Fn:i}=t,o=t.CURVE,{h:s,n:a}=o;i8(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=Qee(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($C(p,"isCompressed"),p){l();let C=!r.isOdd(y);return Mi(Vee(C),I)}else return Mi(Uint8Array.of(4),I,r.toBytes(y))}function h(Q){V0(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=b(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(!w(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 b(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 w(Q,v){let p=r.sqr(v),x=b(Q);return r.eql(p,x)}if(!w(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=r.mul(r.pow(o.a,VC),zLe),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 QLe(Q,c.basises,i.ORDER)}let M=wO((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=wO(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(!w(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=t8(x,v),p=t8(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(V0(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(VC),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,VC),{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,VC),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=>WE(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 WE(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===yd||x.is0())return z.ZERO;if(v===Y0)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}=NLe(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===Y0?!0:v?v(z,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:v}=e;return s===Y0?this:v?v(z,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(v=!0){return $C(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 WE(z,v)}static msm(v,p){return ULe(z,i,v,p)}static fromPrivateKey(v){return z.BASE.multiply(wd(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 bO(z,e.endo?Math.ceil(j/2):j);return z.BASE.precompute(8),z}function Vee(n){return Uint8Array.of(n?2:3)}function Qee(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function YLe(n,e={}){let{Fn:t}=n,r=e.randomBytes||MO,i=Object.assign(Qee(n.Fp,t),{seed:UO(t.ORDER)});function o(f){try{return!!wd(t,f)}catch{return!1}}function s(f,m){let{publicKey:b,publicKeyUncompressed:w}=i;try{let S=f.length;return m===!0&&S!==b||m===!1&&S!==w?!1:!!n.fromBytes(f)}catch{return!1}}function a(f=r(i.seed)){return Nee(V0(f,i.seed,"seed"),t.ORDER)}function c(f,m=!0){return n.BASE.multiply(wd(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:b,publicKeyUncompressed:w}=i;if(t.allowedLengths||m===b)return;let S=so("key",f).length;return S===b||S===w}function d(f,m,b=!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 w=wd(t,f);return n.fromHex(m).multiply(w).toBytes(b)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:u,Point:n,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:f=>wd(t,f),precompute(f=8,m=n.BASE){return m.precompute(f,!1)}},lengths:i})}function jLe(n,e,t={}){Iee(e),i8(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=t.randomBytes||MO,i=t.hmac||((p,...x)=>Kee(e,p,Mi(...x))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f}=YLe(n,t),m={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},b="compact";function w(p){let x=a>>Y0;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){EO(x);let y=f.signature,I=x==="compact"?y:x==="recovered"?y+1:void 0;return V0(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=b){T(x,y);let I;if(y==="der"){let{r:O,s:R}=gd.toSig(V0(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(ZC(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*Jee<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(Vee((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 w(this.s)}toBytes(x=b){if(EO(x),x==="der")return ZC(gd.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=nI(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=rI(c);function A(p){return vLe("num < 2^"+c,p,yd,M),s.toBytes(p)}function D(p,x){return V0(p,void 0,"message"),x?V0(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}=uO(y,m);p=D(p,C);let N=H(p),O=wd(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===yd)return;let B=s.create(E*s.create(_+J*O));if(B===yd)return;let X=(V.x===J?0:2)|Number(V.y&Y0),ce=B;return I&&w(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 CLe(e.outputLen,s.BYTES,i)(I,C)}function Y(p){let x,y=typeof p=="string"||eI(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 gd.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}=uO(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}=uO(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 aee(n){let{CURVE:e,curveOpts:t}=zee(n),r=qee(e,t);return XLe(n,r)}function zee(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 WLe(n){let{CURVE:e,curveOpts:t}=zee(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 ZLe(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 XLe(n,e){let{Fp:t,Fn:r}=e;function i(s){return Lee(s,Y0,r.ORDER)}let o=ZLe(t,n.a,n.b);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s=>wd(r,s),weierstrassEquation:o,isWithinCurveOrder:i})}function _Le(n,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},n,Oee(t.Fn.ORDER,t.Fn.BITS))})}function $Le(n){let{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:i}=WLe(n),o=qee(e,t),s=jLe(o,r,i);return _Le(n,s)}var eRe=BigInt(0),QC=BigInt(1),cee=BigInt(2),Yy=BigInt(3);function tRe(n){let e=[];for(;n>QC;n>>=QC)(n&QC)===eRe?e.unshift(0):(n&Yy)===Yy?(e.unshift(-1),n+=QC):e.unshift(1);return e}function lO(n){if(!Array.isArray(n)||n.length===0)throw new Error("expected non-empty array")}function nRe(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,cee));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,cee)),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=tRe(a),b=wO(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 w(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=[];WE(e,G.map(({g1:M})=>M)),WE(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([b(A),D.x,D.y])}return w(H,U)}function T(G,U,H=!0){return S([{g1:G,g2:U}],H)}return{Fp12:o,millerLoopBatch:w,pairing:T,pairingBatch:S,calcPairingPrecomputes:b}}function uee(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=wd(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=wd(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 b=f.negate(),w=e.Point.BASE,S=u(h),T=d,G=s([l(b,S),l(w,T)]);return o.eql(G,o.ONE)},verifyBatch(d,h,f){if(lO(h),f.length!==h.length)throw new Error("amount of public keys and messages should be equal");let m=c(d),b=h,w=f.map(a),S=new Map;for(let U=0;U<w.length;U++){let H=w[U],M=b[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){lO(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){lO(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){Fc(d);let f=h?{DST:h}:void 0;return t.hashToCurve(d,f)},Signature:r}}function rRe(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=aee(n.G1),a=Object.assign(s,oee(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),c=aee(n.G2),u=Object.assign(c,oee(c.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),l=nRe(n.fields,a.Point,u.Point,{...n.params,postPrecompute:n.postPrecompute}),{millerLoopBatch:d,pairing:h,pairingBatch:f,calcPairingPrecomputes:m}=l,b=uee(l,a,u,n.G2.Signature,!1),w=uee(l,u,a,n.G1.ShortSignature,!0),S=n.randomBytes||MO,T=()=>{let C=UO(t.ORDER);return Nee(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:w.hash(so("point",C),F?.DST)}function A(C,F){return C instanceof u.Point?C:b.hash(so("point",C),F?.DST)}function D(C){return b.getPublicKey(C).toBytes(!0)}function z(C){return w.getPublicKey(C).toBytes(!0)}function j(C,F,N){let O=A(C,N),R=b.sign(O,F);return C instanceof u.Point?R:H.toBytes(R)}function Y(C,F,N){let O=M(C,N),R=w.sign(O,F);return C instanceof a.Point?R:U.toBytes(R)}function Q(C,F,N,O){let R=A(F,O);return b.verify(C,R,N)}function v(C,F,N,O){let R=M(F,O);return w.verify(C,R,N)}function p(C){let F=b.aggregatePublicKeys(C);return C[0]instanceof a.Point?F:F.toBytes(!0)}function x(C){let F=b.aggregateSignatures(C);return C[0]instanceof u.Point?F:H.toBytes(F)}function y(C){let F=w.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 b.verifyBatch(C,R,N)}return a.Point.BASE.precompute(4),{longSignatures:b,shortSignatures:w,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 lee=BigInt(0),bd=BigInt(1),Yo=BigInt(2),dee=BigInt(3);function GO(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=bd;h<r;h++){let m=(l*f-l)/s%a;d.push(n.pow(e,m)),f*=t}c.push(d)}return c}function iRe(n,e,t){let r=e.pow(t,(n.ORDER-bd)/dee),i=e.pow(t,(n.ORDER-bd)/Yo);function o(h,f){let m=e.mul(e.frobeniusMap(h,1),r),b=e.mul(e.frobeniusMap(f,1),i);return[m,b]}let s=e.pow(t,(n.ORDER**Yo-bd)/dee),a=e.pow(t,(n.ORDER**Yo-bd)/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 b=m.toAffine(),w=h(b.x,b.y);return f.fromAffine({x:w[0],y:w[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 fee=(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]}},AO=class{constructor(e,t={}){this.MASK=bd;let r=e.ORDER,i=r*r;this.Fp=e,this.ORDER=i,this.BITS=ZE(i),this.BYTES=Math.ceil(ZE(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=fee(e,t.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=GO(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=t.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return fee(this.Fp,e)}create(e){return e}isValid({c0:e,c1:t}){function r(i,o){return typeof i=="bigint"&&lee<=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 o8(this,e,t)}invertBatch(e){return iI(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 e8(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);e8(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:b,im:w}=r.reim(h);return m>w||m===w&&f>b?d:h}isOdd(e){let{re:t,im:r}=this.reim(e),i=t%Yo,o=t===lee,s=r%Yo;return BigInt(i||o&&s)==bd}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])}}},xO=class{constructor(e){this.MASK=bd,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=GO(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 o8(this,e,t)}invertBatch(e){return iI(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)}}},vO=class{constructor(e,t){this.MASK=bd;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=GO(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 o8(this,e,t)}invertBatch(e){return iI(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:b,second:w}=i.Fp4Square(s,l),S=i.mulByNonresidue(w);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(b,a),Yo),b)}),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),SLe(t,i)&&(r=this.mul(r,e));return r}};function oRe(n){let e=Zy(n.ORDER),t=new AO(e,n),r=new xO(t),i=new vO(r,n);return{Fp:e,Fp2:t,Fp6:r,Fp12:i}}var sRe=BigInt(0),SO=BigInt(1),Yee=BigInt(2),aRe=BigInt(3),jee=BigInt(6),s8=BigInt("4965661367192848881"),cRe=ZE(s8),uRe=jee*s8**Yee,a8={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:SO,a:sRe,b:aRe,Gx:SO,Gy:BigInt(2)},hee=Zy(a8.n),Wee={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:_E,Fp2:Uu,Fp6:lRe,Fp12:zn}=oRe({ORDER:a8.p,X_LEN:cRe,FP2_NONRESIDUE:[BigInt(9),SO],Fp2mulByB:n=>Uu.mul(n,Wee),Fp12finalExponentiate:n=>{let e=l=>zn.conjugate(zn._cyclotomicExp(l,s8)),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:dRe,psi:pee}=iRe(_E,Uu,Uu.NONRESIDUE),dO=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:_E.ORDER,m:2,k:128,expand:"xmd",hash:xee}),fRe=(n,e,t,r,i,o)=>{let s=pee(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=pee(s[0],s[1]);o(n,e,t,a[0],Uu.neg(a[1]))},hRe={p:Uu.ORDER,n:a8.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:Uu.ZERO,b:Wee,Gx:Uu.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:Uu.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},j0=rRe({fields:{Fp:_E,Fp2:Uu,Fp6:lRe,Fp12:zn,Fr:hee},G1:{...a8,Fp:_E,htfDefaults:{...dO,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:{...hRe,Fp:Uu,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...dO},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(uRe).equals(dRe(n,e)),mapToCurve:ci,fromBytes:ci,toBytes:ci,Signature:{fromBytes:ci,fromHex:ci,toBytes:ci,toRawBytes:ci,toHex:ci}},params:{ateLoopSize:s8*jee+Yee,r:hee.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:dO,postPrecompute:fRe});$Le({a:BigInt(0),b:BigInt(3),Fp:_E,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:xee});var c8="groth16",pRe="auth",mRe="authV2",gRe="authV3",yRe="authV3-8-32",wRe=new TextDecoder,mee=BigInt(0),gee=j0.fields.Fp2,yee=j0.fields.Fp12;async function HO(n,e,t){let r=await hLe(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:c}=await JC.prove(e,s);return{proof:a,pub_signals:c}}var[CO,bRe]=[j0.G1.ProjectivePoint,j0.G2.ProjectivePoint],zC=([n,e])=>CO.fromAffine({x:BigInt(n),y:BigInt(e)}),YC=([[n,e],[t,r]])=>bRe.fromAffine({x:gee.fromBigTuple([BigInt(n),BigInt(e)]),y:gee.fromBigTuple([BigInt(t),BigInt(r)])});async function KO(n,e,t,r){if(r(e.pub_signals).challenge!==KI(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(wRe.decode(t));return JO(e,o)}function JO(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=CO.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<mee||BigInt(r[s])>=j0.G1.CURVE.n)throw new Error(`Input value is not in the field ${j0.G1.CURVE.n}`);if(BigInt(r[s])!==mee){let[a,c]=e.IC[s+1].map(BigInt);i=i.add(CO.fromAffine({x:a,y:c}).multiply(BigInt(r[s])))}}i=i.add(zC(e.IC[0]));let o=j0.pairingBatch([{g1:zC(t.pi_a).negate(),g2:YC(t.pi_b)},{g1:i,g2:YC(e.vk_gamma_2)},{g1:zC(t.pi_c),g2:YC(e.vk_delta_2)},{g1:zC(e.vk_alpha_1),g2:YC(e.vk_beta_2)}]);return yee.eql(o,yee.ONE)}var LO=class{methodAlg;constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}unmarshall(e){let t={};if(e.length!=3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return t.challenge=BigInt(e[0]),t.userState=BigInt(e[1]),t.userId=$e.fromBigInt(BigInt(e[2])),t}async verify(e,t,r){return KO(e,t,r,this.unmarshall)}prove(e,t,r){return HO(e,t,r)}},RO=new LO(new Ed(c8,pRe)),DO=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 KO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await HO(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:$e.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},TO=new DO(new Ed(c8,mRe)),r8=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 KO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await HO(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:$e.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},BO=new r8(new Ed(c8,gRe)),PO=new r8(new Ed(c8,yRe));$E(RO.methodAlg,()=>RO);$E(TO.methodAlg,()=>TO);$E(BO.methodAlg,()=>BO);$E(PO.methodAlg,()=>PO);var W0={registerProvingMethod:$E,getProvingMethod:Eee,provingMethodGroth16AuthInstance:RO,provingMethodGroth16AuthV2Instance:TO,provingMethodGroth16AuthV3Instance:BO,provingMethodGroth16AuthV3_8_32Instance:PO};var Zee="unknown circuit ID. can't verify msg sender",u8="sender of message is not used for jwz token creation",Xee="message was packed with unsupported circuit",_ee="message proof is invalid",$ee="message state verification failed",ete="unknown proving method algorithm";var{getProvingMethod:ERe}=W0,qO=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},VO=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},QO=class{constructor(e,t,r={acceptedStateTransitionDelay:iM}){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 ERe(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(ete);let o=new gh(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 unpack(e){let t=await gh.parse(lt.decode(e)),r=new Ed(t.alg,t.circuitId),i=this.verificationParamsMap.get(r.toString());if(!i?.key)throw new Error(Xee);if(!await t.verify(i?.key))throw new Error(_ee);if(!await i?.verificationFn?.verify(t.circuitId,t.zkProof.pub_signals,this._opts))throw new Error($ee);let a=JSON.parse(t.getPayload());return IRe(t,a),a}mediaType(){return"application/iden3-zkp-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")};circuitIds=${this.supportedCircuitIds.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=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}},IRe=async(n,e)=>{switch(n.circuitId){case"authV2":case"authV3-8-32":case"authV3":{if(!e.from)throw new Error(u8);let t=(n.circuitId==="authV2"?new Zs:new N0).pubSignalsUnmarshal(ke.encode(JSON.stringify(n.zkProof.pub_signals))),r=xe.parseFromId(t.userID),i=await n.getMessageHash();if(Ct.bytesToInt(i.reverse())!==t.challenge)throw new Error(u8);if(e.from!==r.string())throw new Error(u8)}break;default:throw new Error(Zee)}};var tte=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(tte||{});var zO=(t=>(t.AUTHV2="authV2",t.ETH_IDENTITY="ethIdentity",t))(zO||{});var nte=(e=>(e.FeatureType="feature-type",e))(nte||{}),rte=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(rte||{});var Gu=W0.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")}},YO=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 Nc(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 Nc(e)},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};async function Nc(n){try{let e=lt.decode(n);return(await gh.parse(e)).method.methodAlg}catch{return Gu}}var ARe=n=>n.reduce((e,t)=>{let r=t.query.groupId;if(!r)return e;let i=e.get(r);if(!i){let s=Kc(12),c=new DataView(s.buffer).getUint32(0);return e.set(r,{query:t.query,linkNonce:c}),e}let o=E4(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=ARe(o),a=new Map,c=[];for(let u of o){let l;try{if(!i.supportedCircuits.includes(u.circuitId)){if(u.optional)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 w=m.query;if(!a.has(f)){let S=await r.findCredentialByProofQuery(n,m.query);if(!S.cred){if(u.optional)continue;throw new Error(Ke.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(w)}`)}a.set(f,S)}}let b=a.get(f);l=await r.generateProof(u,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h.skipClaimRevocationCheck,credential:b?.cred,credentialRevocationStatus:b?.revStatus,linkNonce:m?.linkNonce?BigInt(m.linkNonce):void 0,bypassCache:i.bypassProofsCache})}catch(d){let h=[Ke.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,Ke.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,Ke.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(Ke.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY))&&u.optional)continue;throw d}c.push(l)}return c},jO=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=ite(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")}},oI=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=U0(n.proof),o=hC(t,i.a,i.b,i.c);return{requestId:e,zkProofEncoded:o,metadata:r}},ite=(n,e)=>{let t=e.map(r=>{let i=oI(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")},xRe=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||Gu,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 vRe(n,e,t,r){return ote(n,"",e,t,r)}function ote(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 WO=class extends Oi{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=["credentialAtomicQueryV3-beta.1","credentialAtomicQuerySigV2","credentialAtomicQueryMTPV2","linkedMultiQuery10-beta.1"];handle(t,r){switch(t.type){case 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?xe.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=xe.parse(t.from),u=await Xy(i,t?.body.scope,c,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits,bypassProofsCache:r.bypassProofsCache});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}),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(b=>b.id.toString()===c.id.toString());if(!l){if(c.optional)continue;throw new Error(`proof is not given for requestId ${c.id}`)}let d=l.circuitId;if(d!==c.circuitId)throw new Error(`proof is not given for requested circuit expected: ${c.circuitId}, given ${d}`);let h=c.params??{};h.verifierDid=xe.parse(i.from);let f=[r.acceptedProofGenerationDelay,r.acceptedStateTransitionDelay].some(b=>b!==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(t&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",TE(t))&&(!r?.length||BE(r,t)))return t;if(r?.length){let i=W0.provingMethodGroth16AuthV3_8_32Instance.methodAlg;if(BE(r,i)&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",TE(i)))return i;let o=W0.provingMethodGroth16AuthV3Instance.methodAlg;if(BE(r,o)&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",TE(o)))return o}return Gu}};var ste=[{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 sI=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new jt(e.url);let i=new Ln(t,ste,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 CRe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function LRe(n){return(CRe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function _y(n,e){return LRe(n).includes(e)}function Z0(n){return _y(n,Ke.ERRORS.IDENTITY_DOES_NOT_EXIST)||_y(n,Ke.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function ZO(n){return _y(n,Ke.ERRORS.STATE_DOES_NOT_EXIST)||_y(n,Ke.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function XO(n){return _y(n,Ke.ERRORS.ROOT_DOES_NOT_EXIST)||_y(n,Ke.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var _O=class{constructor(e,t){this._configs=e;this._stateStorage=new aI(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=xe.idFromDID(t),c;try{let h=await this._stateStorage.getLatestStateById(a.bigInt());if(!h.state)throw new Error("state contract returned empty state");c=h.state}catch(h){if(!Z0(h))throw h;if(!s)throw new Error("latest state not found and state parameter is not present in credentialStatus.id");let f=be.fromHex(s).bigInt();if(!iu(t,f))throw new Error(`latest state not found and state parameter ${s} is not genesis state`);c=f}let u=xe.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 sI(r,t)}};var X0=class{async resolve(e){let r=await(await fetch(e.id)).json();return l8(r)}},l8=({issuer:n,mtp:e})=>({mtp:kt.fromJSON(e),issuer:n});var _0=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 $O=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 X0().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=xe.idFromDID(t),s;try{let l=await this._state.getLatestStateById(o.bigInt());if(!l.state)throw new Error("state contract returned empty state");s=l.state}catch(l){if(!Z0(l))throw l;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=be.fromHex(d).bigInt(),f=gp(t);if(!f&&!iu(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&&iu(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&&iu(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=_0.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 RRe(n,e){let t=xe.parse(n),r=xe.idFromDID(t),{method:i,blockchain:o,networkId:s}=xe.decodePartsFromId(r),a=Ct.hexToBytes(e),c=Ct.bytesToInt(a),u=Vc(i,o,s);return ate(xe.idFromDID(t).bigInt(),c,u)}function ate(n,e,t){let r=$e.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var cI=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var uI=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=DRe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return l8(a.body)}};function DRe(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 lI=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)}},eF=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(DR.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},$0=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 tF=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 nF=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new cI,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new X0),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new uI))}getCredentialStatusResolverRegistry(){return this._credentialStatusResolverRegistry}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:Ke.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ke.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(Ke.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:Ke.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Ke.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=xe.parse(e.issuer),s=jl(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(Ke.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(Ke.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(Ke.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function d8(n,e,t,r){let i=await f8(r,e,n);await new $0().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function f8(n,e,t){let r=new rF;return n&&await BRe(r,e,n),await TRe(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new _0(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function TRe(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function BRe(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var rF=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 zc(o,s),c=await PRe(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 PRe(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 _0;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=Ch([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var iF=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=xe.parse(t.from),s=xe.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=xe.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":nM[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 Nc(t),senderDID:xe.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=xe.parse(t.to),i=xe.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(jl(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 oF=class extends Oi{constructor(t,r,i){super();this._packerMgr=t;this._proofService=r;this._zkpVerifier=i}_supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","authV2","credentialAtomicQueryV3-beta.1","linkedMultiQuery10-beta.1"];async handle(t,r){switch(t.type){case 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?xe.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[b,w]of f)m.set(b,{responses:w});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[b,w]of f)m.set(b,{responses:[w]});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=xe.parse(t.to),{authProof:b}=await jO(m,this._proofService,{supportedCircuits:this._supportedCircuits,acceptProfile:f,senderAddress:await o.getAddress(),zkpResponses:d}),w=await this._zkpVerifier.submitResponse(o,t.body.transaction_data,d,b);return t.body.transaction_data.txHash=w.keys().next().value,w}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?xe.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 sF=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=xe.parse(r),o=t?.mediaType||"application/iden3-zkp-json",s=t?.packerOptions??{senderDID:i,provingMethodAlg:Gu},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 aF=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=xe.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=xe.parse(o.to),c=ta(i.mediaType,i.packerOptions,{senderDID:a,provingMethodAlg:i.packerOptions?.provingMethodAlg||await Nc(r)});return this._packerMgr.pack(i.mediaType,ke.encode(JSON.stringify(s)),c)}};function kRe(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 MRe(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 cF=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=xe.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 Nc(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 cte(n,e,t,r,i){let o=Ut();return{id:o,thid:o,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:at.PAYMENT_REQUEST_MESSAGE_TYPE,body:{agent:t,payments:r},created_time:Lt(new Date),expires_time:i?.expires_time?Lt(i.expires_time):void 0}}function ute(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 uF=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=xe.parse(t.to),o=xe.parse(t.from),s=[];for(let m=0;m<t.body.payments.length;m++){let{data:b}=t.body.payments[m],w=Array.isArray(b)?b.find(S=>S.type==="Iden3PaymentRequestCryptoV1"?S.id===r.nonce:S.nonce===r.nonce):b;if(!w)throw new Error(`failed request. no payment in request for nonce ${r.nonce}`);switch(w.type){case"Iden3PaymentRequestCryptoV1":s.push(await this.handleIden3PaymentRequestCryptoV1(w,r.paymentHandler));break;case"Iden3PaymentRailsRequestV1":s.push(await this.handleIden3PaymentRailsRequestV1(w,r.paymentHandler));break;case"Iden3PaymentRailsERC20RequestV1":s.push(await this.handleIden3PaymentRailsERC20RequestV1(w,r.paymentHandler,r.erc20TokenApproveHandler));break;case"Iden3PaymentRailsSolanaRequestV1":s.push(await this.handleIden3PaymentRailsSolanaRequestV1(w,r.paymentHandler));break;case"Iden3PaymentRailsSolanaSPLRequestV1":s.push(await this.handleIden3PaymentRailsSolanaSPLRequestV1({...w,type:"Iden3PaymentRailsSolanaSPLRequestV1"},r.paymentHandler));break}}let a=ute(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=xe.parse(i.to);r.packerOptions=ta(o,r.packerOptions,{provingMethodAlg:await Nc(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:b,chainId:w,optionId:S,expirationDate:T}=s[u].options[f],G=this._params.multiChainPaymentConfig?.find(z=>z.chainId===w);if(!G)throw new Error(`failed request. no config for chain ${w}`);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 bB(a.solSigner,A,w,H,U,BigInt(b),D,m);h.push(z)}else{let z=await EB(o,A,w,H,U,BigInt(b),D,m);h.push(z)}}c.push({data:h,credentials:l,description:d})}return cte(t,r,i,c)}async packMessage(t,r,i,o){let s=ke.encode(JSON.stringify(t)),a=i==="application/iden3comm-signed-json"?o:{provingMethodAlg:o?.provingMethodAlg||Gu};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 iS(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 rS(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 rS(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 iS(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 ORe(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 lte(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 lF=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(lte(i,{to:t.from,from:t.to,expires_time:r?.disclosureExpiresDate?Lt(r.disclosureExpiresDate):void 0}))}handleQuery(t){let r=[];switch(t["feature-type"]){case"accept":r=this.handleAcceptQuery();break;case"protocol":r=this.handleProtocolQuery();break;case"goal-code":r=this.handleGoalCodeQuery();break;case"header":r=this.handleHeaderQuery();break}return this.handleMatch(r,t.match)}handleAcceptQuery(){return this._options.packageManager.getSupportedProfiles().map(r=>({"feature-type":"accept",id:r}))}handleProtocolQuery(){return this._options.protocols?.map(t=>({"feature-type":"protocol",id:t}))??[]}handleGoalCodeQuery(){return this._options.goalCodes?.map(t=>({"feature-type":"goal-code",id:t}))??[]}handleHeaderQuery(){return this._options.headers?.map(t=>({"feature-type":"header",id:t}))??[]}handleMatch(t,r){if(!r||r==="*")return t;let i=this.wildcardToRegExp(r);return t.filter(o=>i.test(o.id))}wildcardToRegExp(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`)}};function dte(n,e){return{id:Ut(),pthid:e?.pthid,typ:"application/iden3comm-plain-json",type:at.PROBLEM_REPORT_MESSAGE_TYPE,ack:e?.ack,body:{code:n,comment:e?.comment,args:e?.args,escalate_to:e?.escalate_to},from:e?.from,to:e?.to}}function FRe(n,e,t){return dte(e,{pthid:n,...t})}var Wo=new TextEncoder,Id=new TextDecoder,h8=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 dF(n,e,t){if(e<0||e>=h8)throw new RangeError(`value must be >= 0 and <= ${h8-1}. Received ${e}`);n.set([e>>>24,e>>>16,e>>>8,e&255],t)}function p8(n){let e=Math.floor(n/h8),t=n%h8,r=new Uint8Array(8);return dF(r,e,0),dF(r,t,4),r}function m8(n){let e=new Uint8Array(4);return dF(e,n),e}function fte(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 hte(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:Id.decode(n),{alphabet:"base64url"});let e=n;e instanceof Uint8Array&&(e=Id.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return hte(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=Wo.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):fte(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 dI=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"},yh=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 fF(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 pte=n=>crypto.getRandomValues(new Uint8Array(fF(n)>>3));var g8=(n,e)=>{if(e.length<<3!==fF(n))throw new Ve("Invalid Initialization Vector length")};var 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`)};function wh(n,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${n}`)}function y8(n,e){return n.name===e}function GRe(n){return parseInt(n.name.slice(4),10)}function HRe(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(!y8(n.algorithm,"AES-GCM"))throw wh("AES-GCM");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw wh(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!y8(n.algorithm,"AES-KW"))throw wh("AES-KW");let r=parseInt(e.slice(1,4),10);if(n.algorithm.length!==r)throw wh(r,"algorithm.length");break}case"ECDH":{switch(n.algorithm.name){case"ECDH":case"X25519":break;default:throw wh("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!y8(n.algorithm,"PBKDF2"))throw wh("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!y8(n.algorithm,"RSA-OAEP"))throw wh("RSA-OAEP");let r=parseInt(e.slice(9),10)||1;if(GRe(n.algorithm.hash)!==r)throw wh(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}HRe(n,t)}function mte(n,e,...t){if(t=t.filter(Boolean),t.length>2){let r=t.pop();n+=`one of type ${t.join(", ")}, or ${r}.`}else t.length===2?n+=`one of type ${t[0]} or ${t[1]}.`:n+=`of type ${t[0]}.`;return e==null?n+=` Received ${e}`:typeof e=="function"&&e.name?n+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(n+=` Received an instance of ${e.constructor.name}`),n}var bh=(n,...e)=>mte("Key must be ",n,...e);function hF(n,e,...t){return mte(`Key for the ${n} algorithm must be `,e,...t)}function em(n){if(!Hu(n))throw new Error("CryptoKey instance expected")}function Hu(n){return n?.[Symbol.toStringTag]==="CryptoKey"}function fI(n){return n?.[Symbol.toStringTag]==="KeyObject"}var pF=n=>Hu(n)||fI(n);async function KRe(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 JRe(n,e,t,r,i,o){if(!(e instanceof Uint8Array))throw new TypeError(bh(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,p8(o.length<<3)),l=new Uint8Array((await crypto.subtle.sign("HMAC",c,u)).slice(0,s>>3)),d;try{d=await KRe(i,l)}catch{}if(!d)throw new yh;let h;try{h=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:"AES-CBC"},a,t))}catch{}if(!h)throw new yh;return h}async function qRe(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 yh}}var w8=async(n,e,t,r,i,o)=>{if(!Hu(e)&&!(e instanceof Uint8Array))throw new TypeError(bh(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(g8(n,r),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&ew(e,parseInt(n.slice(-3),10)),JRe(n,e,t,r,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&ew(e,parseInt(n.slice(1,4),10)),qRe(n,e,t,r,i,o);default:throw new Zt("Unsupported JWE Content Encryption Algorithm")}};var 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};function VRe(n){return typeof n=="object"&&n!==null}var Zo=n=>{if(!VRe(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 gte(n,e){if(n.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function yte(n,e,t){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"AES-KW",!0,[t]):(Cs(n,e,t),n)}async function hI(n,e,t){let r=await yte(e,n,"wrapKey");gte(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 pI(n,e,t){let r=await yte(e,n,"unwrapKey");gte(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))}var wte=async(n,e)=>{let t=`SHA-${n.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(t,e))};function gF(n){return Ss(m8(n.length),n)}async function QRe(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(m8(a),0),c.set(n,4),c.set(t,4+n.length);let u=await wte("sha256",c);s.set(u,(a-1)*i)}return s.slice(0,r)}async function b8(n,e,t,r,i=new Uint8Array(0),o=new Uint8Array(0)){Cs(n,"ECDH"),Cs(e,"ECDH","deriveBits");let s=gF(Wo.encode(t)),a=gF(i),c=gF(o),u=m8(r),l=new Uint8Array(0),d=Ss(s,a,c,u,l),h=new Uint8Array(await crypto.subtle.deriveBits({name:n.algorithm.name,public:n},e,zRe(n)));return QRe(h,r,d)}function zRe(n){return n.algorithm.name==="X25519"?256:Math.ceil(parseInt(n.algorithm.namedCurve.slice(-3),10)/8)<<3}function E8(n){switch(n.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return n.algorithm.name==="X25519"}}function YRe(n,e){return n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits"]):(Cs(n,e,"deriveBits"),n)}var jRe=(n,e)=>Ss(Wo.encode(n),new Uint8Array([0]),e);async function Ete(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=jRe(e,n),o=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:t,name:"PBKDF2",salt:i},a=await YRe(r,e);return new Uint8Array(await crypto.subtle.deriveBits(s,a,o))}async function Ite(n,e,t,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let o=await Ete(i,n,r,e);return{encryptedKey:await hI(n.slice(-6),o,t),p2c:r,p2s:Zr(i)}}async function Ate(n,e,t,r,i){let o=await Ete(i,n,r,e);return pI(n.slice(-6),o,t)}var yF=(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 vte=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 Ste(n,e,t){return Cs(e,n,"encrypt"),yF(n,e),new Uint8Array(await crypto.subtle.encrypt(vte(n),e,t))}async function Cte(n,e,t){return Cs(e,n,"decrypt"),yF(n,e),new Uint8Array(await crypto.subtle.decrypt(vte(n),e,t))}function mI(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 Ku=n=>crypto.getRandomValues(new Uint8Array(mI(n)>>3));function WRe(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}}var nw=async n=>{if(!n.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:t}=WRe(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 Rte(n,e,t){if(!Zo(n))throw new TypeError("JWK must be an object");let r;switch(e??=n.alg,r??=t?.extractable??n.ext,n.kty){case"oct":if(typeof n.k!="string"||!n.k)throw new TypeError('missing "k" (Key Value) Parameter value');return 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 ZRe(n,e,t,r,i){if(!(t instanceof Uint8Array))throw new TypeError(bh(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,p8(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 XRe(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}}var I8=async(n,e,t,r,i)=>{if(!Hu(t)&&!(t instanceof Uint8Array))throw new TypeError(bh(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(r?g8(n,r):r=pte(n),n){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ew(t,parseInt(n.slice(-3),10)),ZRe(n,e,t,r,i);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ew(t,parseInt(n.slice(1,4),10)),XRe(n,e,t,r,i);default:throw new Zt("Unsupported JWE Content Encryption Algorithm")}};async function Dte(n,e,t,r){let i=n.slice(0,7),o=await I8(i,t,e,r,new Uint8Array(0));return{encryptedKey:o.ciphertext,iv:Zr(o.iv),tag:Zr(o.tag)}}async function Tte(n,e,t,r,i){let o=n.slice(0,7);return w8(o,e,t,r,i,new Uint8Array(0))}var Bte=async(n,e,t,r,i)=>{switch(n){case"dir":{if(t!==void 0)throw new Ve("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(t!==void 0)throw new Ve("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Zo(r.epk))throw new Ve('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(em(e),!E8(e))throw new Zt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await Rte(r.epk,n);em(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 b8(o,e,n==="ECDH-ES"?r.enc:n,n==="ECDH-ES"?mI(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 pI(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 em(e),Cte(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 Ate(n,e,t,r.p2c,s)}case"A128KW":case"A192KW":case"A256KW":{if(t===void 0)throw new Ve("JWE Encrypted Key missing");return pI(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 Tte(n,e,t,o,s)}default:throw new Zt('Invalid or unsupported "alg" (JWE Algorithm) header value')}};var 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)};var wF=(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)};function gI(n){return Zo(n)&&typeof n.kty=="string"}function Pte(n){return n.kty!=="oct"&&(n.kty==="AKP"&&typeof n.priv=="string"||typeof n.d=="string")}function kte(n){return n.kty!=="oct"&&typeof n.d>"u"&&typeof n.priv>"u"}function Mte(n){return n.kty==="oct"&&typeof n.k=="string"}var iw,Ote=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},$Re=(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},Eh=async(n,e)=>{if(n instanceof Uint8Array||Hu(n))return n;if(fI(n)){if(n.type==="secret")return n.export();if("toCryptoKey"in n&&typeof n.toCryptoKey=="function")try{return $Re(n,e)}catch(r){if(r instanceof TypeError)throw r}let t=n.export({format:"jwk"});return Ote(n,t,e)}if(gI(n))return n.k?Wr(n.k):Ote(n,n,e,!0);throw new Error("unreachable")};var ow=n=>n?.[Symbol.toStringTag],bF=(n,e,t)=>{if(e.use!==void 0){let r;switch(t){case"sign":case"verify":r="sig";break;case"encrypt":case"decrypt":r="enc";break}if(e.use!==r)throw new TypeError(`Invalid key for this operation, its "use" must be "${r}" when present`)}if(e.alg!==void 0&&e.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(e.key_ops)){let r;switch(!0){case(t==="sign"||t==="verify"):case n==="dir":case n.includes("CBC-HS"):r=t;break;case n.startsWith("PBES2"):r="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(n):!n.includes("GCM")&&n.endsWith("KW")?r=t==="encrypt"?"wrapKey":"unwrapKey":r=t;break;case(t==="encrypt"&&n.startsWith("RSA")):r="wrapKey";break;case t==="decrypt":r=n.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(r&&e.key_ops?.includes?.(r)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},eDe=(n,e,t)=>{if(!(e instanceof Uint8Array)){if(gI(e)){if(Mte(e)&&bF(n,e,t))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!pF(e))throw new TypeError(hF(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"`)}},tDe=(n,e,t)=>{if(gI(e))switch(t){case"decrypt":case"sign":if(Pte(e)&&bF(n,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"encrypt":case"verify":if(kte(e)&&bF(n,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!pF(e))throw new TypeError(hF(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"`);default:break}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"`);default:break}},sw=(n,e,t)=>{n.startsWith("HS")||n==="dir"||n.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(n)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(n)?eDe(n,e,t):tDe(n,e,t)};async function yI(n,e,t){if(!Zo(n))throw new Ve("Flattened JWE must be an object");if(n.protected===void 0&&n.header===void 0&&n.unprotected===void 0)throw new Ve("JOSE Header missing");if(n.iv!==void 0&&typeof n.iv!="string")throw new Ve("JWE Initialization Vector incorrect type");if(typeof n.ciphertext!="string")throw new Ve("JWE Ciphertext missing or incorrect type");if(n.tag!==void 0&&typeof n.tag!="string")throw new Ve("JWE Authentication Tag incorrect type");if(n.protected!==void 0&&typeof n.protected!="string")throw new Ve("JWE Protected Header incorrect type");if(n.encrypted_key!==void 0&&typeof n.encrypted_key!="string")throw new Ve("JWE Encrypted Key incorrect type");if(n.aad!==void 0&&typeof n.aad!="string")throw new Ve("JWE AAD incorrect type");if(n.header!==void 0&&!Zo(n.header))throw new Ve("JWE Shared Unprotected Header incorrect type");if(n.unprotected!==void 0&&!Zo(n.unprotected))throw new Ve("JWE Per-Recipient Unprotected Header incorrect type");let r;if(n.protected)try{let U=Wr(n.protected);r=JSON.parse(Id.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&&wF("keyManagementAlgorithms",t.keyManagementAlgorithms),c=t&&wF("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms);if(a&&!a.has(o)||!a&&o.startsWith("PBES2"))throw new dI('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(s))throw new dI('"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 Eh(e,o),h;try{h=await Bte(o,d,u,i,t)}catch(U){if(U instanceof TypeError||U instanceof Ve||U instanceof Zt)throw U;h=Ku(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 b=Wo.encode(n.protected??""),w;n.aad!==void 0?w=Ss(b,Wo.encode("."),Wo.encode(n.aad)):w=b;let S;try{S=Wr(n.ciphertext)}catch{throw new Ve("Failed to base64url decode the ciphertext")}let G={plaintext:await w8(s,h,S,f,m,w)};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 EF(n,e,t){if(!Zo(n))throw new Ve("General JWE must be an object");if(!Array.isArray(n.recipients)||!n.recipients.every(Zo))throw new Ve("JWE Recipients missing or incorrect type");if(!n.recipients.length)throw new Ve("JWE Recipients has no members");for(let r of n.recipients)try{return await yI({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 yh}var A8=Symbol();async function IF(n){if(fI(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(!Hu(n))throw new TypeError(bh(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 Fte(n){return IF(n)}var x8=async(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(em(t),!E8(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 Eh(i.epk,n):l=(await crypto.subtle.generateKey(t.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:h,crv:f,kty:m}=await Fte(l),b=await b8(t,l,n==="ECDH-ES"?e:n,n==="ECDH-ES"?mI(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=b;break}a=r||Ku(e);let w=n.slice(-6);o=await hI(w,b,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=r||Ku(e),em(t),o=await Ste(n,t,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=r||Ku(e);let{p2c:c,p2s:u}=i;({encryptedKey:o,...s}=await Ite(n,t,a,c,u));break}case"A128KW":case"A192KW":case"A256KW":{a=r||Ku(e),o=await hI(n,t,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=r||Ku(e);let{iv:c}=i;({encryptedKey:o,...s}=await Dte(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 wI=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,w=await Eh(e,i);({cek:a,encryptedKey:s,parameters:b}=await x8(i,o,w,this.#o,this.#a)),b&&(t&&A8 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;this.#t?u=Wo.encode(Zr(JSON.stringify(this.#t))):u=Wo.encode(""),this.#i?(l=Zr(this.#i),c=Ss(u,Wo.encode("."),Wo.encode(l))):c=u;let{ciphertext:d,tag:h,iv:f}=await I8(o,this.#e,a,this.#s,c),m={ciphertext:Zr(d)};return f&&(m.iv=Zr(f)),h&&(m.tag=Zr(h)),s&&(m.encrypted_key=Zr(s)),l&&(m.aad=l),this.#t&&(m.protected=Id.decode(u)),this.#n&&(m.unprotected=this.#n),this.#r&&(m.header=this.#r),m}};var AF=class{#e;unprotectedHeader;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}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},bI=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let r=new AF(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 wI(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=Ku(e),r={ciphertext:"",iv:"",recipients:[],tag:""};for(let i=0;i<this.#t.length;i++){let o=this.#t[i],s={};r.recipients.push(s);let c={...this.#n,...this.#r,...o.unprotectedHeader}.alg.startsWith("PBES2")?2048+i:void 0;if(i===0){let f=await new wI(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(o.unprotectedHeader).setKeyManagementParameters({p2c:c}).encrypt(o.key,{...o.options,[A8]:!0});r.ciphertext=f.ciphertext,r.iv=f.iv,r.tag=f.tag,f.aad&&(r.aad=f.aad),f.protected&&(r.protected=f.protected),f.unprotected&&(r.unprotected=f.unprotected),s.encrypted_key=f.encrypted_key,f.header&&(s.header=f.header);continue}let u=o.unprotectedHeader?.alg||this.#n?.alg||this.#r?.alg;sw(u==="dir"?e:u,o.key,"encrypt");let l=await Eh(o.key,u),{encryptedKey:d,parameters:h}=await x8(u,e,l,t,{p2c:c});s.encrypted_key=Zr(d),(o.unprotectedHeader||h)&&(s.header={...o.unprotectedHeader,...h})}return r}};function xF(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(Id.decode(Wr(e)));if(!Zo(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var v8=class{constructor(e){this.resolvePrivateKeyByKid=e}async encrypt(e,t){let{enc:r,typ:i,recipients:o}=t,s=new bI(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(xF(r),r.header||{}),yI(e,t)}return EF(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 S8=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 SF={};Sr(SF,{DeviceNotificationStatus:()=>Gte,NotificationServiceType:()=>Nte,NotificationStatus:()=>Ute,PushNotifier:()=>vF});var Nte=(e=>(e.Push="push-notification",e))(Nte||{}),Ute=(t=>(t.Success="success",t.Failed="failed",t))(Ute||{});var Gte=(r=>(r.Success="success",r.Rejected="rejected",r.Failed="failed",r))(Gte||{}),nDe={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()}}}},vF=class{constructor(e=nDe){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 Ad={url:"http://localhost:8545",defaultGasLimit:6e5,minGasPrice:"0",maxGasPrice:"100000000000",confirmationBlockCount:5,confirmationTimeout:6e5,contractAddress:"",receiptTimeout:6e5,rpcResponseTimeout:5e3,waitReceiptCycleTime:3e4,waitBlockCycleTime:3e3},aI=class{constructor(e,t){this.ethConfig=e;let r=Array.isArray(e)?e[0]:e;this.provider=new jt(r.url),this.stateContract=new Ln(r.contractAddress,X5,this.provider),this._transactionService=new Xs(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??Yr.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??hg},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??hg},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??hg},this._gistProofCacheOptions={ttl:Yr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??hg},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??ch({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??ch({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??ch({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??ch({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(Ke.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR);return s}}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=[];try{i=await r.getStateInfoById(e)}catch(s){throw Z0(s)&&!this._disableCache&&await this._latestStateResolveCache?.set(t,{id:e,state:0n,replacedByState:0n,createdAtTimestamp:0n,replacedAtTimestamp:0n,createdAtBlock:0n,replacedAtBlock:0n},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 c=await this._stateResolveCache?.get(r);if(c)return c}let{stateContract:i}=this.getStateContractAndProviderForId(e),o=await i.getStateInfoByIdAndState(e,t),s={id:BigInt(o[0]),state:BigInt(o[1]),replacedByState:BigInt(o[2]),createdAtTimestamp:BigInt(o[3]),replacedAtTimestamp:BigInt(o[4]),createdAtBlock:BigInt(o[5]),replacedAtBlock:BigInt(o[6])},a=s.replacedAtTimestamp===0n?this._stateCacheOptions.notReplacedTtl:this._stateCacheOptions.replacedTtl;return!this._disableCache&&await this._stateResolveCache?.set(r,s,a),s}async publishState(e,t){let r=new vE;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=U0(e.proof),h=[i.bigInt().toString(),o.bigInt().toString(),s.bigInt().toString(),a,d.a,d.b,d.c],f=await u.getFeeData(),m=Ad.maxFeePerGas?BigInt(Ad.maxFeePerGas):f.maxFeePerGas,b=Ad.maxPriorityFeePerGas?BigInt(Ad.maxPriorityFeePerGas):f.maxPriorityFeePerGas,w=await l.transitState.estimateGas(...h),S=await l.transitState.populateTransaction(...h),T={to:S.to,data:S.data,gasLimit:w,maxFeePerGas:m,maxPriorityFeePerGas:b},{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=Ad.maxFeePerGas?BigInt(Ad.maxFeePerGas):h.maxFeePerGas,m=Ad.maxPriorityFeePerGas?BigInt(Ad.maxPriorityFeePerGas):h.maxPriorityFeePerGas,b=[r.bigInt().toString(),i.bigInt().toString(),o.bigInt().toString(),s,a,c],w=await d.transitStateGeneric.estimateGas(...b),S=await d.transitStateGeneric.populateTransaction(...b),T={to:S.to,data:S.data,gasLimit:w,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=$e.fromBigInt(t),i=im(xe.blockchainFromId(r),xe.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=$e.fromBigInt(e),r=im(xe.blockchainFromId(t),xe.networkIdFromId(t)),i=this.networkByChainId(r),o=new jt(i.url);return{stateContract:new Ln(i.contractAddress,X5,o),provider:o}}networkByChainId(e){let r=(Array.isArray(this.ethConfig)?this.ethConfig:[this.ethConfig]).find(i=>i.chainId===e);if(!r)throw new Error(`chainId "${e}" not supported`);return r}getGistProofCacheKey(e){return`gist:${e.toString()}`}getLatestStateCacheKey(e){return`latest-state:${e.toString()}`}getStateCacheKey(e,t){return`state:${e.toString()}-${t.toString()}`}getRootCacheKey(e,t){return`root:${e.toString()}-${t.toString()}`}};var CF=[{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 LF=[{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 RF=10000000n,Hte=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(Hte||{}),Kte=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]},DF=class n{constructor(e,t){this._configs=e;this._opts=t}static _supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1"];static _supportedCircuitsPubSignalsMap={credentialAtomicQueryMTPV2OnChain:pE,credentialAtomicQuerySigV2OnChain:AE,"credentialAtomicQueryV3OnChain-beta.1":EE,authV2:Zs};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=U0(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,CF);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},b;try{b=await e.estimateGas(m)}catch{b=RF}m.gasLimit=b;let w=new Xs(o),{txnHash:S}=await w.sendTransactionRequest(e,m);s.set(S,d)}return s}async submitZKPResponseV2(e,t,r){let i=this._configs.find(w=>w.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,CF).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:c,maxPriorityFeePerGas:u},f;try{f=await e.estimateGas(h)}catch{f=RF}h.gasLimit=f;let m=new Xs(o),{txnHash:b}=await m.sendTransactionRequest(e,h);return new Map().set(b,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,LF).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=RF}f.gasLimit=m;let b=new Xs(s),{txnHash:w}=await b.sendTransactionRequest(e,f);return new Map().set(w,{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=U0(i.zkp.proof);u=hC(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{u=Jte(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:b,metadata:w}=oI(f);a.push({proof:f,requestId:m,encoded:b,metadata:w})}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:b}=this.getUpdateResolutions(e,t.chain_id,f.circuitId,f.pub_signals);m.length>0&&o.push(...await Promise.all(m)),b.length>0&&s.push(...await Promise.all(b))}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:Kte(h)}}async prepareTxArgsSubmit(e,t,r){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmit(this._opts.didResolverUrl,e,t,r)}static checkSupportedCircuit(e){if(!this._supportedCircuits.includes(e))throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`)}static getCrossChainResolvers(e,t,r,i){return[...new Set(e.map(o=>JSON.stringify({id:o.id.string(),[r]:r==="gist"?o.root?.string():o.state?.string()})))].reduce((o,s)=>{let a=JSON.parse(s),c=$e.fromString(a.id),u=dw(xe.parseFromId(c));if(t===u)return o;let l=this.resolveDidDocumentEip712MessageAndSignature(xe.parseFromId($e.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}=oI(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];if(!r)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=new r,o=ke.encode(JSON.stringify(t));return i.pubSignalsUnmarshal(o),i.getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await yp(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}}},Jte=n=>`0x${Rr(Ct.intToBytes(xe.idFromDID(n).bigInt()))}`;var TF=[{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 BF=[{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=BF;static createInterface(){return new lc(BF)}static connect(e,t){return new Ln(e,BF,t)}};var EI=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($e.ethAddressFromId(xe.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=xe.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 pc({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:c,coreClaim:e})}async validateSourceValue(e,t,r){if(await Ru.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 PF=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 EI(o,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});await a.isInterfaceSupported();let{credentialData:c,coreClaimBigInts:u,credentialSubjectFields:l}=await a.getCredential(xe.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 EI(i,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});return await s.isInterfaceSupported(),await s.getUserCredentialsIds(xe.idFromDID(t))}default:throw new Error(`Unsupported adapter version ${o}`)}}getContractConnection(e){let t=xe.idFromDID(e),r=dw(e),i=xn.getAddress(xn.hexlify($e.ethAddressFromId(t))),o=this._ethConnectionConfig.find(a=>a.chainId===r);if(!o)throw new Error(`No connection found for chain ID ${r}`);if(!o.url)throw new Error(`No URL found for chain ID ${r}`);return{contract:new Ln(i,TF,new xn.JsonRpcProvider(o.url)),connection:o}}};var kF=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 yp(xe.parseFromId($e.fromBigInt(e)),this.resolverUrl),{global:r}=this.getIden3StateInfo2023(t);if(!r)throw new Error("GIST root not found");let{proof:i}=r;if(!i)throw new Error("GIST proof not found");return{root:r.root,existence:i.existence,siblings:i.siblings?.map(o=>BigInt(o)),index:BigInt(0),value:BigInt(0),auxExistence:!!i.node_aux,auxIndex:i.node_aux?BigInt(i.node_aux.key):BigInt(0),auxValue:i.node_aux?BigInt(i.node_aux.value):BigInt(0)}}async getGISTRootInfo(e,t){let{didDocument:r}=await yp(xe.parseFromId($e.fromBigInt(t)),this.resolverUrl,{gist:be.fromBigInt(e)}),{global:i}=this.getIden3StateInfo2023(r);if(!i)throw new Error("GIST root not found");return i}getRpcProvider(){return new jt}publishState(){throw new Error("publishState method not implemented.")}publishStateGeneric(){throw new Error("publishStateGeneric method not implemented.")}async getStateInfo(e,t){let r=t?{state:be.fromBigInt(t)}:void 0,{didDocument:i}=await yp(xe.parseFromId($e.fromBigInt(e)),this.resolverUrl,r),{info:o,published:s}=this.getIden3StateInfo2023(i);if(!o&&!s)throw new Error(Ke.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 qte=[{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 Vte=[{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 dDe(n,e,t,r,i){let o=new Ln(e,qte,n),s=await o.nonces(await n.getAddress()),a=await o.eip712Domain(),c={name:a[1],version:a[2],chainId:a[3],verifyingContract:e},u={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},l={owner:await n.getAddress(),spender:t,value:r,nonce:s,deadline:i};return n.signTypedData(c,u,l)}async function fDe(n,e){return new Ln(n,Vte,e).decimals()}var Zte=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(Zte||{}),Xte=(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))(Xte||{}),MF=[!0,1,"true"],OF=[!1,0,"false"],Qte=(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,MF.includes(n)&&MF.includes(e)||OF.includes(n)&&OF.includes(e)?!0:n===e),zte=(n,e)=>$te(n,e,(r,i)=>{switch(ene(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}}),Yte=(n,e)=>$te(n,e,(r,i)=>{switch(ene(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}}),hDe=(n,e)=>!!(MF.includes(e)&&typeof n<"u"||OF.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),jte=(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,Wte=(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))},Ju={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>hDe(n,e),$eq:(n,e)=>Qte(n,e),$in:(n,e)=>jte(n,e),$nin:(n,e)=>!jte(n,e),$gt:(n,e)=>zte(n,e),$lt:(n,e)=>!Yte(n,e),$ne:(n,e)=>!Qte(n,e),$gte:(n,e)=>Yte(n,e),$lte:(n,e)=>!zte(n,e),$between:(n,e)=>Wte(n,e),$nonbetween:(n,e)=>!Wte(n,e)},_te=(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},Uc=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=_te(e,this.path);return t==null&&this.operatorFunc!==Ju.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},FF=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new Uc("id",Ju.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new Uc("issuer",Ju.$in,r));case"type":return e.concat(new Uc("type",Ju.$in,r,!0));case"context":return e.concat(new Uc("@context",Ju.$in,r,!0));case"credentialSubjectId":return e.concat(new Uc("credentialSubject.id",Ju.$eq,r));case"schema":return e.concat(new Uc("credentialSchema.id",Ju.$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 Uc(`credentialSubject.${s}`,Ju.$noop,null)]);let c=Object.keys(a).map(u=>{let l=a[u],d=`credentialSubject.${s}`;return new Uc(d,Ju[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`)}},[]),$te=(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),pDe=/^[+-]?\d+$/,mDe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,gDe=/^([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]))$/,yDe=/^(true)|(false)$/,wDe=/^\d{4}-\d{2}-\d{2}$/,ene=n=>pDe.test(n)?0:mDe.test(n)?2:gDe.test(n)||wDe.test(n)?3:yDe.test(n)?1:4;var NF=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 UF=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(Yc(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(Yc(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 GF=class{constructor(e){this._storageKey=e;this._store=Md(`${e}-db`,e)}_store;async save(e,t,r="id"){return Od(e,t,this._store)}async get(e,t="id"){return Qc(e,this._store)}async load(){return KN(this._store)}async delete(e,t="id"){return qI(e,this._store)}};var HF=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=Md(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=Md(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Ut()}`),await Qc(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=Oy(e);return await Od(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await Qc(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 Qc(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(Yc(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await Qc(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(Yc(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await Qc(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 qI(e,this._merkleTreeMetaStore),await Od(t,i,this._merkleTreeMetaStore),await Od(e,t,this._bindingStore)}};var KF=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=FF(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 qF=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 VF=class{constructor(e){this.opts=e;this._verificationKeyPath=this.opts.verificationFileName??this._verificationKeyPath,this._provingKeyPath=this.opts.provingFileName??this._provingKeyPath,this._wasmFilePath=this.opts.wasmFileName??this._wasmFilePath}_verificationKeyPath="verification_key.json";_provingKeyPath="circuit_final.zkey";_wasmFilePath="circuit.wasm";_fs=null;_browserNotSupportedError=new Error("File system operations are not supported in browser environment");async getFs(){return this._fs?this._fs:(this._fs={existsSync:()=>{throw this._browserNotSupportedError},readFileSync:()=>{throw this._browserNotSupportedError},writeFileSync:()=>{throw this._browserNotSupportedError},mkdirSync:()=>{throw this._browserNotSupportedError}},this._fs)}async loadCircuitData(e){let t=await this.loadCircuitFile(e,this._verificationKeyPath),r=await this.loadCircuitFile(e,this._provingKeyPath),i=await this.loadCircuitFile(e,this._wasmFilePath);return{circuitId:e,wasm:i,provingKey:r,verificationKey:t}}async loadCircuitFile(e,t){let r=`${this.opts.dirname}/${e}/${t}`,i=await this.getFs();if(i.existsSync(r)){let o=i.readFileSync(r);return new Uint8Array(o)}return null}async writeCircuitFile(e,t,r,i){let o=`${this.opts.dirname}/${e}`,s=`${o}/${t}`,a=await this.getFs();a.mkdirSync(o,{recursive:!0}),a.writeFileSync(s,r,i)}async saveCircuitData(e,t){t.verificationKey&&await this.writeCircuitFile(e,this._verificationKeyPath,t.verificationKey,"utf-8"),t.provingKey&&await this.writeCircuitFile(e,this._provingKeyPath,t.provingKey),t.wasm&&await this.writeCircuitFile(e,this._wasmFilePath,t.wasm)}};var 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:Y5(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},Ih=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}},C8=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},L8=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 m6(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(!W5(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=bDe(n.operatorValue);break;default:s=await R8(n.operatorValue,i.datatype)}i.values=s}return i},II=async(n,e,t,r)=>{let i=C8(t);return Promise.all(i.map(o=>L8(o,e,n,r)))},R8=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await Ru.hashValue(e,n[r]);else t[0]=await Ru.hashValue(e,n);return t},bDe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")};async function YF(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.
|