@pybara/pybara-js 0.2.0 → 0.3.0
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/README.md +19 -11
- package/checkout.schema.json +17 -9
- package/dist/admin/core/PybaraAdminClient.d.ts +5 -0
- package/dist/admin/core/PybaraAdminClient.d.ts.map +1 -1
- package/dist/admin/index.d.ts +7 -2
- package/dist/admin/index.d.ts.map +1 -1
- package/dist/admin/index.js +1 -1
- package/dist/{admin-D2vUTEg1.js → admin-B1pVP25-.js} +29 -7
- package/dist/checkout.d.ts +16 -10
- package/dist/checkout.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/modal/config.d.ts +19 -0
- package/dist/modal/config.d.ts.map +1 -0
- package/dist/modal/index.d.ts +16 -0
- package/dist/modal/index.d.ts.map +1 -0
- package/dist/modal/index.js +1 -0
- package/dist/modal/lock-page-scroll.d.ts +9 -0
- package/dist/modal/lock-page-scroll.d.ts.map +1 -0
- package/dist/modal/modal.d.ts +160 -0
- package/dist/modal/modal.d.ts.map +1 -0
- package/dist/modal-BCDMoDW9.js +192 -0
- package/dist/pybara-js.iife.js +5 -5
- package/dist/pybara-js.js +144 -307
- package/dist/types.d.ts +16 -7
- package/dist/types.d.ts.map +1 -1
- package/package.json +5 -3
- package/dist/constants.d.ts +0 -13
- package/dist/constants.d.ts.map +0 -1
package/dist/pybara-js.iife.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var Pybara=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.defineProperty,n=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},r={prod:`https://pybara.io`,staging:`https://staging.pybara.io`},i={prod:{admin_core:`mbonm-rqaaa-aaaas-amwoa-cai`,admin_regs:`kng5p-gyaaa-aaaas-amwzq-cai`},staging:{admin_core:`efc3v-fyaaa-aaaak-qy7yq-cai`,admin_regs:`labft-vaaaa-aaaak-qzdda-cai`}},a;(function(e){e[e.SysFatal=1]=`SysFatal`,e[e.SysTransient=2]=`SysTransient`,e[e.DestinationInvalid=3]=`DestinationInvalid`,e[e.CanisterReject=4]=`CanisterReject`,e[e.CanisterError=5]=`CanisterError`})(a||={});var o;(function(e){e.Replied=`replied`,e.Rejected=`rejected`})(o||={});function s(e){return e!=null&&`reject_code`in e}function c(e){return e!=null&&`certificate`in e}var l=`abcdefghijklmnopqrstuvwxyz234567`,u=Object.create(null);for(let e=0;e<32;e++)u[l[e]]=e;u[0]=u.o,u[1]=u.i;function d(e){let t=0,n=0,r=``;function i(e){return t<0?n|=e>>-t:n=e<<t&248,t>3?(t-=8,1):(t<4&&(r+=l[n>>3],t+=5),0)}for(let t=0;t<e.length;)t+=i(e[t]);return r+(t<0?l[n>>3]:``)}function f(e){let t=0,n=0,r=new Uint8Array(e.length*4/3|0),i=0;function a(e){let a=u[e.toLowerCase()];if(a===void 0)throw Error(`Invalid character: ${JSON.stringify(e)}`);a<<=3,n|=a>>>t,t+=5,t>=8&&(r[i++]=n,t-=8,n=t>0?a<<5-t&255:0)}for(let t of e)a(t);return r.slice(0,i)}var p=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function m(e){let t=-1;for(let n=0;n<e.length;n++)t=p[(e[n]^t)&255]^t>>>8;return(t^-1)>>>0}var h=typeof globalThis==`object`&&`crypto`in globalThis?globalThis.crypto:void 0;function g(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function _(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function v(e,...t){if(!g(e))throw Error(`Uint8Array expected`);if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length `+t+`, got length=`+e.length)}function y(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function b(e,t){v(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function x(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ee(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function S(e,t){return e<<32-t|e>>>t}var te=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,C=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function w(e){if(v(e),te)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=C[e[n]];return t}var ne={_0:48,_9:57,A:65,F:70,a:97,f:102};function re(e){if(e>=ne._0&&e<=ne._9)return e-ne._0;if(e>=ne.A&&e<=ne.F)return e-(ne.A-10);if(e>=ne.a&&e<=ne.f)return e-(ne.a-10)}function ie(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(te)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw Error(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=re(e.charCodeAt(i)),a=re(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw Error(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function T(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function ae(e){return typeof e==`string`&&(e=T(e)),v(e),e}function E(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];v(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}var oe=class{};function se(e){let t=t=>e().update(ae(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function ce(e=32){if(h&&typeof h.getRandomValues==`function`)return h.getRandomValues(new Uint8Array(e));if(h&&typeof h.randomBytes==`function`)return Uint8Array.from(h.randomBytes(e));throw Error(`crypto.getRandomValues must be defined`)}function le(e,t,n,r){if(typeof e.setBigUint64==`function`)return e.setBigUint64(t,n,r);let i=BigInt(32),a=BigInt(4294967295),o=Number(n>>i&a),s=Number(n&a),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,s,r)}function ue(e,t,n){return e&t^~e&n}function de(e,t,n){return e&t^e&n^t&n}var fe=class extends oe{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=ee(this.buffer)}update(e){y(this),e=ae(e),v(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=ee(e);for(;r<=i-a;a+=r)this.process(t,a)}else n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){y(this),b(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,x(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;le(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=ee(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen should be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},pe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),me=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),D=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),he=BigInt(2**32-1),ge=BigInt(32);function _e(e,t=!1){return t?{h:Number(e&he),l:Number(e>>ge&he)}:{h:Number(e>>ge&he)|0,l:Number(e&he)|0}}function ve(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=_e(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}var ye=(e,t,n)=>e>>>n,be=(e,t,n)=>e<<32-n|t>>>n,xe=(e,t,n)=>e>>>n|t<<32-n,Se=(e,t,n)=>e<<32-n|t>>>n,Ce=(e,t,n)=>e<<64-n|t>>>n-32,we=(e,t,n)=>e>>>n-32|t<<64-n;function Te(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var Ee=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),De=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Oe=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ke=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Ae=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),je=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,Me=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]),Ne=new Uint32Array(64),Pe=class extends fe{constructor(e=32){super(64,e,8,!1),this.A=pe[0]|0,this.B=pe[1]|0,this.C=pe[2]|0,this.D=pe[3]|0,this.E=pe[4]|0,this.F=pe[5]|0,this.G=pe[6]|0,this.H=pe[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)Ne[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Ne[e-15],n=Ne[e-2],r=S(t,7)^S(t,18)^t>>>3,i=S(n,17)^S(n,19)^n>>>10;Ne[e]=i+Ne[e-7]+r+Ne[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=S(o,6)^S(o,11)^S(o,25),u=l+t+ue(o,s,c)+Me[e]+Ne[e]|0,d=(S(n,2)^S(n,13)^S(n,22))+de(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){x(Ne)}destroy(){this.set(0,0,0,0,0,0,0,0),x(this.buffer)}},Fe=class extends Pe{constructor(){super(28),this.A=me[0]|0,this.B=me[1]|0,this.C=me[2]|0,this.D=me[3]|0,this.E=me[4]|0,this.F=me[5]|0,this.G=me[6]|0,this.H=me[7]|0}},Ie=ve(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(e=>BigInt(e))),Le=Ie[0],Re=Ie[1],ze=new Uint32Array(80),Be=new Uint32Array(80),Ve=class extends fe{constructor(e=64){super(128,e,16,!1),this.Ah=D[0]|0,this.Al=D[1]|0,this.Bh=D[2]|0,this.Bl=D[3]|0,this.Ch=D[4]|0,this.Cl=D[5]|0,this.Dh=D[6]|0,this.Dl=D[7]|0,this.Eh=D[8]|0,this.El=D[9]|0,this.Fh=D[10]|0,this.Fl=D[11]|0,this.Gh=D[12]|0,this.Gl=D[13]|0,this.Hh=D[14]|0,this.Hl=D[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:h}=this;return[e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h]}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let n=0;n<16;n++,t+=4)ze[n]=e.getUint32(t),Be[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=ze[e-15]|0,n=Be[e-15]|0,r=xe(t,n,1)^xe(t,n,8)^ye(t,n,7),i=Se(t,n,1)^Se(t,n,8)^be(t,n,7),a=ze[e-2]|0,o=Be[e-2]|0,s=xe(a,o,19)^Ce(a,o,61)^ye(a,o,6),c=Oe(i,Se(a,o,19)^we(a,o,61)^be(a,o,6),Be[e-7],Be[e-16]),l=ke(c,r,s,ze[e-7],ze[e-16]);ze[e]=l|0,Be[e]=c|0}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:h,Hh:g,Hl:_}=this;for(let e=0;e<80;e++){let t=xe(u,d,14)^xe(u,d,18)^Ce(u,d,41),v=Se(u,d,14)^Se(u,d,18)^we(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=Ae(_,v,b,Re[e],Be[e]),ee=je(x,g,t,y,Le[e],ze[e]),S=x|0,te=xe(n,r,28)^Ce(n,r,34)^Ce(n,r,39),C=Se(n,r,28)^we(n,r,34)^we(n,r,39),w=n&i^n&o^i&o,ne=r&a^r&s^a&s;g=m|0,_=h|0,m=f|0,h=p|0,f=u|0,p=d|0,{h:u,l:d}=Te(c|0,l|0,ee|0,S|0),c=o|0,l=s|0,o=i|0,s=a|0,i=n|0,a=r|0;let re=Ee(S,C,ne);n=De(re,ee,te,w),r=re|0}({h:n,l:r}=Te(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=Te(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=Te(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=Te(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Te(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=Te(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=Te(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=Te(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}roundClean(){x(ze,Be)}destroy(){x(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},He=se(()=>new Pe),Ue=se(()=>new Fe),We=se(()=>new Ve),Ge=`__principal__`,Ke=2,qe=4,Je=`aaaaa-aa`,O=class e{static anonymous(){return new this(new Uint8Array([qe]))}static managementCanister(){return this.fromText(Je)}static selfAuthenticating(e){let t=Ue(e);return new this(new Uint8Array([...t,Ke]))}static from(t){if(typeof t==`string`)return e.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new e(t);if(e.isPrincipal(t))return new e(t._arr);throw Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(e){return new this(ie(e))}static fromText(e){let t=e;if(e.includes(`__principal__`)){let n=JSON.parse(e);`__principal__`in n&&(t=n[Ge])}let n=f(t.toLowerCase().replace(/-/g,``));n=n.slice(4,n.length);let r=new this(n);if(r.toText()!==t)throw Error(`Principal "${r.toText()}" does not have a valid checksum (original value "${t}" may not be a valid Principal ID).`);return r}static fromUint8Array(e){return new this(e)}static isPrincipal(t){return t instanceof e||typeof t==`object`&&!!t&&`_isPrincipal`in t&&t._isPrincipal===!0&&`_arr`in t&&t._arr instanceof Uint8Array}constructor(e){this._arr=e,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===qe}toUint8Array(){return this._arr}toHex(){return w(this._arr).toUpperCase()}toText(){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,m(this._arr));let t=new Uint8Array(e),n=d(new Uint8Array([...t,...this._arr])).match(/.{1,5}/g);if(!n)throw Error();return n.join(`-`)}toString(){return this.toText()}toJSON(){return{[Ge]:this.toText()}}compareTo(e){for(let t=0;t<Math.min(this._arr.length,e._arr.length);t++){if(this._arr[t]<e._arr[t])return`lt`;if(this._arr[t]>e._arr[t])return`gt`}return this._arr.length<e._arr.length?`lt`:this._arr.length>e._arr.length?`gt`:`eq`}ltEq(e){let t=this.compareTo(e);return t==`lt`||t==`eq`}gtEq(e){let t=this.compareTo(e);return t==`gt`||t==`eq`}},Ye;(function(e){e.Trust=`Trust`,e.Protocol=`Protocol`,e.Reject=`Reject`,e.Transport=`Transport`,e.External=`External`,e.Limit=`Limit`,e.Input=`Input`,e.Unknown=`Unknown`})(Ye||={});var Xe;(function(e){e.Normal=`normal`,e.Verbose=`verbose`})(Xe||={});var Ze=new Set([`arg`,`certificate`,`nonce`]);function Qe(e){return(t,n)=>n instanceof Uint8Array?e===Xe.Normal&&Ze.has(t)?`<${n.length} bytes, set ErrorCode.verbosity = ErrorVerbosity.Verbose to display>`:`hex(${n.length}):${w(n)}`:n}var k=class e{static{this.verbosity=Xe.Normal}constructor(e=!1){this.isCertified=e}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`\nRequest context:\n Request ID (hex): ${this.requestContext.requestId?w(this.requestContext.requestId):`undefined`}\n Sender pubkey (hex): ${w(this.requestContext.senderPubKey)}\n Sender signature (hex): ${w(this.requestContext.senderSignature)}\n Ingress expiry: ${this.requestContext.ingressExpiry.toString()}`),this.callContext&&(t+=`\nCall context:\n Canister ID: ${this.callContext.canisterId.toText()}\n Method name: ${this.callContext.methodName}`,`httpDetails`in this.callContext&&(t+=`\n HTTP details: ${JSON.stringify(this.callContext.httpDetails,Qe(e.verbosity),2)}`)),t}},$e=class e extends Error{get code(){return this.cause.code}set code(e){this.cause.code=e}get kind(){return this.cause.kind}set kind(e){this.cause.kind=e}get isCertified(){return this.code.isCertified}constructor(t,n){super(t.toString()),this.name=`AgentError`,this.cause={code:t,kind:n},Object.setPrototypeOf(this,e.prototype)}hasCode(e){return this.code instanceof e}toString(){return`${this.name} (${this.kind}): ${this.message}`}},et=class extends $e{static fromCode(e){return new this(e)}},tt=class e extends et{constructor(t){super(t,Ye.Trust),this.name=`TrustError`,Object.setPrototypeOf(this,e.prototype)}},A=class e extends et{constructor(t){super(t,Ye.Protocol),this.name=`ProtocolError`,Object.setPrototypeOf(this,e.prototype)}},nt=class e extends et{constructor(t){super(t,Ye.Reject),this.name=`RejectError`,Object.setPrototypeOf(this,e.prototype)}},rt=class e extends et{constructor(t){super(t,Ye.Transport),this.name=`TransportError`,Object.setPrototypeOf(this,e.prototype)}},it=class e extends et{constructor(t){super(t,Ye.External),this.name=`ExternalError`,Object.setPrototypeOf(this,e.prototype)}},j=class e extends et{constructor(t){super(t,Ye.Input),this.name=`InputError`,Object.setPrototypeOf(this,e.prototype)}},at=class e extends et{constructor(t){super(t,Ye.Unknown),this.name=`UnknownError`,Object.setPrototypeOf(this,e.prototype)}},ot=class e extends k{constructor(t,n){super(),this.reason=t,this.error=n,this.name=`CertificateVerificationErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let e=this.reason;return this.error&&(e+=`: ${Kt(this.error)}`),`Certificate verification error: "${e}"`}},st=class e extends k{constructor(t,n,r,i,a){super(),this.maxAgeInMinutes=t,this.certificateTime=n,this.currentTime=r,this.timeDiffMsecs=i,this.ageType=a,this.name=`CertificateTimeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`}},ct=class e extends k{constructor(){super(),this.name=`CertificateHasTooManyDelegationsErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Certificate has too many delegations`}},lt=class e extends k{constructor(t,n){super(),this.canisterId=t,this.subnetId=n,this.name=`CertificateNotAuthorizedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`}},ut=class e extends k{constructor(t){super(),this.subnetId=t,this.name=`CertificateNotAuthorizedForSubnetErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate is not authorized for subnet ${this.subnetId.toText()}`}},dt=class e extends k{constructor(t,n){super(),this.message=t,this.lookupStatus=n,this.name=`LookupErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}},ft=class e extends k{constructor(t){super(),this.message=t,this.name=`MalformedLookupFoundValueErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},pt=class e extends k{constructor(t){super(),this.message=t,this.name=`MissingLookupValueErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},mt=class e extends k{constructor(t,n){super(),this.expectedLength=t,this.actualLength=n,this.name=`DerKeyLengthMismatchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}},ht=class e extends k{constructor(t,n){super(),this.expectedPrefix=t,this.actualPrefix=n,this.name=`DerPrefixMismatchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${w(this.expectedPrefix)}, but got ${w(this.actualPrefix)}`}},gt=class e extends k{constructor(t,n){super(),this.expectedLength=t,this.actualLength=n,this.name=`DerDecodeLengthMismatchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}},_t=class e extends k{constructor(t){super(),this.error=t,this.name=`DerDecodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},vt=class e extends k{constructor(t){super(),this.error=t,this.name=`DerEncodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},yt=class e extends k{constructor(t,n){super(),this.error=t,this.input=n,this.name=`CborDecodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${Kt(this.error)}, input: ${w(this.input)}`}},bt=class e extends k{constructor(t,n){super(),this.error=t,this.value=n,this.name=`CborEncodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${Kt(this.error)}, input: ${this.value}`}},xt=class e extends k{constructor(t,n,r){super(),this.message=t,this.requestId=n,this.status=r,this.name=`TimeoutWaitingForResponseErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let e=`${this.message}\n`;return this.requestId&&(e+=` Request ID: ${w(this.requestId)}\n`),this.status&&(e+=` Request status: ${this.status}\n`),e}},St=class e extends k{constructor(t,n,r){super(),this.maxIngressExpiryInMinutes=t,this.requestId=n,this.retryTimes=r,this.name=`CertificateOutdatedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let e=`Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?\n Request ID: ${w(this.requestId)}\n`;return this.retryTimes!==void 0&&(e+=` Retried ${this.retryTimes} times.`),e}},Ct=class e extends k{constructor(t,n,r,i){super(!0),this.requestId=t,this.rejectCode=n,this.rejectMessage=r,this.rejectErrorCode=i,this.name=`CertifiedRejectErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:\n Request ID: ${w(this.requestId)}\n Reject code: ${this.rejectCode}\n Reject text: ${this.rejectMessage}\n Error code: ${this.rejectErrorCode}\n`}},wt=class e extends k{constructor(t,n,r,i,a){super(),this.requestId=t,this.rejectCode=n,this.rejectMessage=r,this.rejectErrorCode=i,this.signatures=a,this.name=`UncertifiedRejectErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:\n Request ID: ${w(this.requestId)}\n Reject code: ${this.rejectCode}\n Reject text: ${this.rejectMessage}\n Error code: ${this.rejectErrorCode}\n`}},Tt=class e extends k{constructor(t,n,r,i){super(),this.requestId=t,this.rejectCode=n,this.rejectMessage=r,this.rejectErrorCode=i,this.name=`UncertifiedRejectUpdateErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:\n Request ID: ${w(this.requestId)}\n Reject code: ${this.rejectCode}\n Reject text: ${this.rejectMessage}\n Error code: ${this.rejectErrorCode}\n`}},Et=class e extends k{constructor(t){super(),this.requestId=t,this.name=`RequestStatusDoneNoReplyErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Call was marked as done but we never saw the reply:\n Request ID: ${w(this.requestId)}\n`}},Dt=class e extends k{constructor(t){super(),this.shouldFetchRootKey=t,this.name=`MissingRootKeyErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.shouldFetchRootKey===void 0?`Agent is missing root key`:`Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`}},Ot=class e extends k{constructor(t){super(),this.value=t,this.name=`HashValueErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}},kt=class e extends k{constructor(){super(),this.name=`IdentityInvalidErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`This identity has expired due this application's security policy. Please refresh your authentication.`}},At=class e extends k{constructor(t,n){super(),this.message=t,this.providedIngressExpiryInMinutes=n,this.name=`IngressExpiryInvalidErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}},jt=class e extends k{constructor(){super(),this.name=`MissingFetchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"No fetch implementation available. Provide a `fetch` function in HttpAgentOptions or ensure `globalThis.fetch` is defined."}},Mt=class e extends k{constructor(){super(),this.name=`CreateHttpAgentErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to create agent from provided agent`}},Nt=class e extends k{constructor(t,n){super(),this.signatureCount=t,this.maxExpected=n,this.name=`ExcessiveSignaturesErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contains ${this.signatureCount} signatures, which exceeds the subnet size of ${this.maxExpected}. This suggests a malformed or malicious response.`}},Pt=class e extends k{constructor(t){super(),this.error=t,this.name=`MalformedSignatureErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},Ft=class e extends k{constructor(){super(),this.name=`MalformedPublicKeyErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Read state response contained a malformed public key`}},It=class e extends k{constructor(t){super(),this.nodeId=t,this.name=`QuerySignatureVerificationFailedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},Lt=class e extends k{constructor(t){super(),this.error=t,this.name=`UnexpectedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${Kt(this.error)}`}},Rt=class e extends k{constructor(t,n,r,i){super(),this.status=t,this.requestId=n,this.response=r,this.rawCertificate=i,this.name=`UnexpectedV4StatusErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected request status in v4 sync response: "${this.status}"\n Request ID (hex): ${w(this.requestId)}\n Response: ${JSON.stringify(this.response,(e,t)=>t instanceof Uint8Array?`hex(${t.length}):${w(t)}`:t,2)}`}},zt=class e extends k{constructor(t){super(),this.error=t,this.name=`HashTreeDecodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},Bt=class e extends k{constructor(t,n,r,i){super(),this.status=t,this.statusText=n,this.headers=r,this.bodyText=i,this.name=`HttpErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let e=`HTTP request failed:
|
|
2
|
-
Status: ${this.status} (${this.statusText})\n Headers: ${JSON.stringify(this.headers,Qe(k.verbosity))}\n`;return this.bodyText&&(e+=` Body: ${this.bodyText}\n`),e}},Vt=class e extends k{constructor(){super(),this.name=`HttpV4ApiNotSupportedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`HTTP request failed: v4 API is not supported`}},Ht=class e extends k{constructor(t){super(),this.error=t,this.name=`HttpFetchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${Kt(this.error)}`}},Ut=class e extends k{constructor(t){super(),this.receivedCanisterId=t,this.name=`MissingCanisterIdErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Canister ID is required, but received ${typeof this.receivedCanisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`}},Wt=class e extends k{constructor(t){super(),this.request=t,this.name=`InvalidReadStateRequestErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},Gt=class e extends k{constructor(t){super(),this.error=t,this.name=`ExpiryJsonDeserializeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function Kt(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e,Qe(k.verbosity))}catch{return String(e)}}var qt=Error(`unreachable`);function M(...e){let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}var Jt=class{save(){return this._view}restore(e){if(!(e instanceof Uint8Array))throw Error(`Checkpoint must be a Uint8Array`);this._view=e}constructor(e,t=e?.byteLength||0){if(e&&!(e instanceof Uint8Array))try{e=Yt(e)}catch{throw Error(`Buffer must be a Uint8Array`)}if(t<0||!Number.isInteger(t))throw Error(`Length must be a non-negative integer`);if(e&&t>e.byteLength)throw Error(`Length cannot exceed buffer length`);this._buffer=e||new Uint8Array,this._view=new Uint8Array(this._buffer.buffer,0,t)}get buffer(){return this._view.slice()}get byteLength(){return this._view.byteLength}read(e){let t=this._view.subarray(0,e);return this._view=this._view.subarray(e),t.slice()}readUint8(){if(this._view.byteLength===0)return;let e=this._view[0];return this._view=this._view.subarray(1),e}write(e){if(!(e instanceof Uint8Array))throw Error(`Buffer must be a Uint8Array`);let t=this._view.byteLength;this._view.byteOffset+this._view.byteLength+e.byteLength>=this._buffer.byteLength?this.alloc(e.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+e.byteLength),this._view.set(e,t)}get end(){return this._view.byteLength===0}alloc(e){if(e<=0||!Number.isInteger(e))throw Error(`Amount must be a positive integer`);let t=new Uint8Array((this._buffer.byteLength+e)*1.2|0),n=new Uint8Array(t.buffer,0,this._view.byteLength+e);n.set(this._view),this._buffer=t,this._view=n}};function Yt(e){if(!e)throw Error(`Input cannot be null or undefined`);return e instanceof Uint8Array?e:e instanceof ArrayBuffer||Array.isArray(e)?new Uint8Array(e):`buffer`in e?Yt(e.buffer):new Uint8Array(e)}function Xt(e,t){if(e.byteLength!==t.byteLength)return e.byteLength-t.byteLength;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]-t[n];return 0}function Zt(e){if(!(e instanceof Uint8Array))throw Error(`Input must be a Uint8Array`);return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Qt(e){let t=new TextEncoder().encode(e),n=0;for(let e of t)n=(n*223+e)%2**32;return n}function $t(e){if(/^_\d+_$/.test(e)||/^_0x[0-9a-fA-F]+_$/.test(e)){let t=+e.slice(1,-1);if(Number.isSafeInteger(t)&&t>=0&&t<2**32)return t}return Qt(e)}function en(e){let t=BigInt(e);if(e<=0)throw RangeError(`Input must be positive`);return t.toString(2).length-1}function tn(e){let t=BigInt(e);if(e<0)throw RangeError(`Input must be non-negative`);return BigInt(1)<<t}function nn(){throw Error(`unexpected end of buffer`)}function rn(e,t){return e.byteLength<t&&nn(),e.read(t)}function an(e){let t=e.readUint8();return t===void 0&&nn(),t}function N(e){if(typeof e==`number`&&(e=BigInt(e)),e<BigInt(0))throw Error(`Cannot leb encode negative values.`);let t=(e===BigInt(0)?0:en(e))+1,n=new Jt(new Uint8Array(t),0);for(;;){let t=Number(e&BigInt(127));if(e/=BigInt(128),e===BigInt(0)){n.write(new Uint8Array([t]));break}n.write(new Uint8Array([t|128]))}return n.buffer}function P(e){let t=BigInt(1),n=BigInt(0),r;do r=an(e),n+=BigInt(r&127).valueOf()*t,t*=BigInt(128);while(r>=128);return n}function F(e){typeof e==`number`&&(e=BigInt(e));let t=e<BigInt(0);t&&(e=-e-BigInt(1));let n=(e===BigInt(0)?0:en(e))+1,r=new Jt(new Uint8Array(n),0);for(;;){let n=i(e);if(e/=BigInt(128),t&&e===BigInt(0)&&n&64||!t&&e===BigInt(0)&&!(n&64)){r.write(new Uint8Array([n]));break}r.write(new Uint8Array([n|128]))}function i(e){let n=e%BigInt(128);return Number(t?BigInt(128)-n-BigInt(1):n)}return r.buffer}function on(e){let t=new Uint8Array(e.buffer),n=0;for(;n<t.byteLength;n++)if(t[n]<128){if(!(t[n]&64))return P(e);break}let r=new Uint8Array(rn(e,n+1)),i=BigInt(0);for(let e=r.byteLength-1;e>=0;e--)i=i*BigInt(128)+BigInt(128-(r[e]&127)-1);return-i-BigInt(1)}function sn(e,t){if(BigInt(e)<BigInt(0))throw Error(`Cannot write negative values.`);return cn(e,t)}function cn(e,t){e=BigInt(e);let n=new Jt(new Uint8Array(Math.min(1,t)),0),r=0,i=BigInt(256),a=BigInt(0),o=Number(e%i);for(n.write(new Uint8Array([o]));++r<t;)e<0&&a===BigInt(0)&&o!==0&&(a=BigInt(1)),o=Number((e/i-a)%BigInt(256)),n.write(new Uint8Array([o])),i*=BigInt(256);return n.buffer}function ln(e,t){if(t<=0||!Number.isInteger(t))throw Error(`Byte length must be a positive integer`);let n=BigInt(an(e)),r=BigInt(1),i=0;for(;++i<t;){r*=BigInt(256);let t=BigInt(an(e));n+=r*t}return n}function un(e,t){if(t<=0||!Number.isInteger(t))throw Error(`Byte length must be a positive integer`);let n=ln(e,t),r=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return n>=r&&(n-=r*BigInt(2)),n}var dn=n({Bool:()=>Jn,BoolClass:()=>wn,CandidDecodeError:()=>fn,ConstructType:()=>xn,Empty:()=>Gn,EmptyClass:()=>Sn,FixedIntClass:()=>jn,FixedNatClass:()=>Mn,Float32:()=>$n,Float64:()=>er,FloatClass:()=>An,Func:()=>gr,FuncClass:()=>Vn,Int:()=>Zn,Int16:()=>nr,Int32:()=>rr,Int64:()=>ir,Int8:()=>tr,IntClass:()=>On,Nat:()=>Qn,Nat16:()=>or,Nat32:()=>sr,Nat64:()=>cr,Nat8:()=>ar,NatClass:()=>kn,Null:()=>Yn,NullClass:()=>Tn,Opt:()=>fr,OptClass:()=>Pn,PrimitiveType:()=>bn,Principal:()=>lr,PrincipalClass:()=>Bn,Rec:()=>hr,RecClass:()=>Rn,Record:()=>pr,RecordClass:()=>Fn,Reserved:()=>Kn,ReservedClass:()=>En,Service:()=>_r,ServiceClass:()=>Hn,Text:()=>Xn,TextClass:()=>Dn,Tuple:()=>ur,TupleClass:()=>In,Type:()=>yn,Unknown:()=>qn,UnknownClass:()=>Cn,Variant:()=>mr,VariantClass:()=>Ln,Vec:()=>dr,VecClass:()=>Nn,Visitor:()=>vn,decode:()=>Wn,encode:()=>Un,resetSubtypeCache:()=>br,subtype:()=>Cr}),fn=class e extends Error{constructor(t){super(t),this.name=`CandidDecodeError`,Object.setPrototypeOf(this,e.prototype)}},I;(function(e){e[e.Null=-1]=`Null`,e[e.Bool=-2]=`Bool`,e[e.Nat=-3]=`Nat`,e[e.Int=-4]=`Int`,e[e.Float32=-13]=`Float32`,e[e.Float64=-14]=`Float64`,e[e.Text=-15]=`Text`,e[e.Reserved=-16]=`Reserved`,e[e.Empty=-17]=`Empty`,e[e.Opt=-18]=`Opt`,e[e.Vector=-19]=`Vector`,e[e.Record=-20]=`Record`,e[e.Variant=-21]=`Variant`,e[e.Func=-22]=`Func`,e[e.Service=-23]=`Service`,e[e.Principal=-24]=`Principal`})(I||={});var pn=`DIDL`,mn=new TextEncoder().encode(pn),hn=400;function gn(e,t,n){return e.map((e,r)=>n(e,t[r]))}var _n=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(e){return this._idx.has(e.name)}add(e,t){let n=this._typs.length;this._idx.set(e.name,n),this._idxRefCount.set(n,1),this._typs.push(t)}merge(e,t){let n=this._idx.get(e.name),r=this._idx.get(t);if(n===void 0)throw Error(`Missing type index for ${e}`);if(r===void 0)throw Error(`Missing type index for ${t}`);this._typs[n]=this._typs[r];let i=this._getIdxRefCount(n),a=this._getIdxRefCount(r);this._idxRefCount.set(n,i+a),this._idx.set(t,n),this._idxRefCount.set(r,0),this._compactFromEnd()}_getIdxRefCount(e){return this._idxRefCount.get(e)||0}_compactFromEnd(){for(;this._typs.length>0;){let e=this._typs.length-1;if(this._getIdxRefCount(e)>0)break;this._typs.pop(),this._idxRefCount.delete(e)}}encode(){return M(N(this._typs.length),M(...this._typs))}indexOf(e){if(!this._idx.has(e))throw Error(`Missing type index for ${e}`);return F(this._idx.get(e)||0)}},vn=class{visitType(e,t){throw Error(`Not implemented`)}visitPrimitive(e,t){return this.visitType(e,t)}visitEmpty(e,t){return this.visitPrimitive(e,t)}visitBool(e,t){return this.visitPrimitive(e,t)}visitNull(e,t){return this.visitPrimitive(e,t)}visitReserved(e,t){return this.visitPrimitive(e,t)}visitText(e,t){return this.visitPrimitive(e,t)}visitNumber(e,t){return this.visitPrimitive(e,t)}visitInt(e,t){return this.visitNumber(e,t)}visitNat(e,t){return this.visitNumber(e,t)}visitFloat(e,t){return this.visitPrimitive(e,t)}visitFixedInt(e,t){return this.visitNumber(e,t)}visitFixedNat(e,t){return this.visitNumber(e,t)}visitPrincipal(e,t){return this.visitPrimitive(e,t)}visitConstruct(e,t){return this.visitType(e,t)}visitVec(e,t,n){return this.visitConstruct(e,n)}visitOpt(e,t,n){return this.visitConstruct(e,n)}visitRecord(e,t,n){return this.visitConstruct(e,n)}visitTuple(e,t,n){let r=t.map((e,t)=>[`_${t}_`,e]);return this.visitRecord(e,r,n)}visitVariant(e,t,n){return this.visitConstruct(e,n)}visitRec(e,t,n){return this.visitConstruct(t,n)}visitFunc(e,t){return this.visitConstruct(e,t)}visitService(e,t){return this.visitConstruct(e,t)}},L;(function(e){e.EmptyClass=`__IDL_EmptyClass__`,e.UnknownClass=`__IDL_UnknownClass__`,e.BoolClass=`__IDL_BoolClass__`,e.NullClass=`__IDL_NullClass__`,e.ReservedClass=`__IDL_ReservedClass__`,e.TextClass=`__IDL_TextClass__`,e.IntClass=`__IDL_IntClass__`,e.NatClass=`__IDL_NatClass__`,e.FloatClass=`__IDL_FloatClass__`,e.FixedIntClass=`__IDL_FixedIntClass__`,e.FixedNatClass=`__IDL_FixedNatClass__`,e.VecClass=`__IDL_VecClass__`,e.OptClass=`__IDL_OptClass__`,e.RecordClass=`__IDL_RecordClass__`,e.TupleClass=`__IDL_TupleClass__`,e.VariantClass=`__IDL_VariantClass__`,e.RecClass=`__IDL_RecClass__`,e.PrincipalClass=`__IDL_PrincipalClass__`,e.FuncClass=`__IDL_FuncClass__`,e.ServiceClass=`__IDL_ServiceClass__`})(L||={});var yn=class{display(){return this.name}valueToString(e){return R(e)}buildTypeTable(e){e.has(this)||this._buildTypeTableImpl(e)}},bn=class extends yn{checkType(e){if(this.name!==e.name)throw Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`);return e}_buildTypeTableImpl(e){}},xn=class extends yn{checkType(e){if(e instanceof Rn){let t=e.getType();if(t===void 0)throw new fn(`Type mismatch: cannot decode from uninitialized recursive type`);return t}throw Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`)}encodeType(e){return e.indexOf(this.name)}},Sn=class extends bn{get typeName(){return L.EmptyClass}static[Symbol.hasInstance](e){return e.typeName===L.EmptyClass}accept(e,t){return e.visitEmpty(this,t)}covariant(e){throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(){throw Error(`Empty cannot appear as a function argument`)}valueToString(){throw Error(`Empty cannot appear as a value`)}encodeType(){return F(I.Empty)}decodeValue(){throw Error(`Empty cannot appear as an output`)}get name(){return`empty`}},Cn=class extends yn{get typeName(){return L.UnknownClass}static[Symbol.hasInstance](e){return e.typeName===L.UnknownClass}checkType(e){throw Error(`Method not implemented for unknown.`)}accept(e,t){throw e.visitType(this,t)}covariant(e){throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(){throw Error(`Unknown cannot appear as a function argument`)}valueToString(){throw Error(`Unknown cannot appear as a value`)}encodeType(){throw Error(`Unknown cannot be serialized`)}decodeValue(e,t){let n=t.decodeValue(e,t);Object(n)!==n&&(n=Object(n));let r;return r=t instanceof Rn?()=>t.getType():()=>t,Object.defineProperty(n,"type",{value:r,writable:!0,enumerable:!1,configurable:!0}),n}_buildTypeTableImpl(){throw Error(`Unknown cannot be serialized`)}get name(){return`Unknown`}},wn=class extends bn{get typeName(){return L.BoolClass}static[Symbol.hasInstance](e){return e.typeName===L.BoolClass}accept(e,t){return e.visitBool(this,t)}covariant(e){if(typeof e==`boolean`)return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){return new Uint8Array([+!!e])}encodeType(){return F(I.Bool)}decodeValue(e,t){switch(this.checkType(t),an(e)){case 0:return!1;case 1:return!0;default:throw Error(`Boolean value out of range`)}}get name(){return`bool`}},Tn=class extends bn{get typeName(){return L.NullClass}static[Symbol.hasInstance](e){return e.typeName===L.NullClass}accept(e,t){return e.visitNull(this,t)}covariant(e){if(e===null)return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(){return new Uint8Array}encodeType(){return F(I.Null)}decodeValue(e,t){return this.checkType(t),null}get name(){return`null`}},En=class extends bn{get typeName(){return L.ReservedClass}static[Symbol.hasInstance](e){return e.typeName===L.ReservedClass}accept(e,t){return e.visitReserved(this,t)}covariant(e){return!0}encodeValue(){return new Uint8Array}encodeType(){return F(I.Reserved)}decodeValue(e,t){return t.name!==this.name&&t.decodeValue(e,t),null}get name(){return`reserved`}},Dn=class extends bn{get typeName(){return L.TextClass}static[Symbol.hasInstance](e){return e.typeName===L.TextClass}accept(e,t){return e.visitText(this,t)}covariant(e){if(typeof e==`string`)return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){let t=new TextEncoder().encode(e);return M(N(t.byteLength),t)}encodeType(){return F(I.Text)}decodeValue(e,t){this.checkType(t);let n=P(e),r=rn(e,Number(n));return new TextDecoder(`utf8`,{fatal:!0}).decode(r)}get name(){return`text`}valueToString(e){return`"${e}"`}},On=class extends bn{get typeName(){return L.IntClass}static[Symbol.hasInstance](e){return e.typeName===L.IntClass}accept(e,t){return e.visitInt(this,t)}covariant(e){if(typeof e==`bigint`||Number.isInteger(e))return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){return F(e)}encodeType(){return F(I.Int)}decodeValue(e,t){return this.checkType(t),on(e)}get name(){return`int`}valueToString(e){return e.toString()}},kn=class extends bn{get typeName(){return L.NatClass}static[Symbol.hasInstance](e){return e.typeName===L.NatClass}accept(e,t){return e.visitNat(this,t)}covariant(e){if(typeof e==`bigint`&&e>=BigInt(0)||Number.isInteger(e)&&e>=0)return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){return N(e)}encodeType(){return F(I.Nat)}decodeValue(e,t){return this.checkType(t),P(e)}get name(){return`nat`}valueToString(e){return e.toString()}},An=class extends bn{get typeName(){return L.FloatClass}static[Symbol.hasInstance](e){return e.typeName===L.FloatClass}constructor(e){if(super(),this._bits=e,e!==32&&e!==64)throw Error(`not a valid float type`)}accept(e,t){return e.visitFloat(this,t)}covariant(e){if(typeof e==`number`||e instanceof Number)return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){let t=new ArrayBuffer(this._bits/8),n=new DataView(t);return this._bits===32?n.setFloat32(0,e,!0):n.setFloat64(0,e,!0),new Uint8Array(t)}encodeType(){return F(this._bits===32?I.Float32:I.Float64)}decodeValue(e,t){this.checkType(t);let n=Zt(rn(e,this._bits/8));return this._bits===32?n.getFloat32(0,!0):n.getFloat64(0,!0)}get name(){return`float${this._bits}`}valueToString(e){return e.toString()}},jn=class extends bn{get typeName(){return L.FixedIntClass}static[Symbol.hasInstance](e){return e.typeName===L.FixedIntClass}constructor(e){super(),this._bits=e}accept(e,t){return e.visitFixedInt(this,t)}covariant(e){let t=tn(this._bits-1)*BigInt(-1),n=tn(this._bits-1)-BigInt(1);if(typeof e==`bigint`){if(e>=t&&e<=n)return!0}else if(Number.isInteger(e)){let r=BigInt(e);if(r>=t&&r<=n)return!0}throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){return cn(e,this._bits/8)}encodeType(){return F(-9-(Math.log2(this._bits)-3))}decodeValue(e,t){this.checkType(t);let n=un(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(e){return e.toString()}},Mn=class extends bn{get typeName(){return L.FixedNatClass}static[Symbol.hasInstance](e){return e.typeName===L.FixedNatClass}constructor(e){super(),this._bits=e}accept(e,t){return e.visitFixedNat(this,t)}covariant(e){let t=tn(this._bits);if(typeof e==`bigint`&&e>=BigInt(0)){if(e<t)return!0}else if(Number.isInteger(e)&&e>=0&&BigInt(e)<t)return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){return sn(e,this._bits/8)}encodeType(){return F(-5-(Math.log2(this._bits)-3))}decodeValue(e,t){this.checkType(t);let n=ln(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(e){return e.toString()}},Nn=class e extends xn{get typeName(){return L.VecClass}static[Symbol.hasInstance](e){return e.typeName===L.VecClass}constructor(e){super(),this._type=e,this._blobOptimization=!1,e instanceof Mn&&e._bits===8&&(this._blobOptimization=!0)}accept(e,t){return e.visitVec(this,this._type,t)}covariant(e){let t=this._type instanceof Mn||this._type instanceof jn?this._type._bits:0;if(ArrayBuffer.isView(e)&&t==e.BYTES_PER_ELEMENT*8||Array.isArray(e)&&e.every((e,t)=>{try{return this._type.covariant(e)}catch(e){throw Error(`Invalid ${this.display()} argument: \n\nindex ${t} -> ${e.message}`,{cause:e})}}))return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){let t=N(e.length);if(this._blobOptimization)return M(t,new Uint8Array(e));if(ArrayBuffer.isView(e)){if(e instanceof Int16Array||e instanceof Uint16Array){let n=new DataView(new ArrayBuffer(e.length*2));for(let t=0;t<e.length;t++)e instanceof Int16Array?n.setInt16(t*2,e[t],!0):n.setUint16(t*2,e[t],!0);return M(t,new Uint8Array(n.buffer))}if(e instanceof Int32Array||e instanceof Uint32Array){let n=new DataView(new ArrayBuffer(e.length*4));for(let t=0;t<e.length;t++)e instanceof Int32Array?n.setInt32(t*4,e[t],!0):n.setUint32(t*4,e[t],!0);return M(t,new Uint8Array(n.buffer))}if(e instanceof BigInt64Array||e instanceof BigUint64Array){let n=new DataView(new ArrayBuffer(e.length*8));for(let t=0;t<e.length;t++)e instanceof BigInt64Array?n.setBigInt64(t*8,e[t],!0):n.setBigUint64(t*8,e[t],!0);return M(t,new Uint8Array(n.buffer))}return M(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}let n=new Jt(new Uint8Array(t.byteLength+e.length),0);n.write(t);for(let t of e){let e=this._type.encodeValue(t);n.write(new Uint8Array(e))}return n.buffer}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let t=F(I.Vector),n=this._type.encodeType(e);e.add(this,M(t,n))}decodeValue(t,n){let r=this.checkType(n);if(!(r instanceof e))throw new fn(`Expected type '${this.display()}', but received non-vector type '${r.display()}'`);let i=Number(P(t));if(this._type instanceof Mn){if(this._type._bits==8)return new Uint8Array(t.read(i));if(this._type._bits==16){let e=t.read(i*2);return new Uint16Array(e.buffer,e.byteOffset,i)}if(this._type._bits==32){let e=t.read(i*4);return new Uint32Array(e.buffer,e.byteOffset,i)}if(this._type._bits==64)return new BigUint64Array(t.read(i*8).buffer)}if(this._type instanceof jn){if(this._type._bits==8)return new Int8Array(t.read(i));if(this._type._bits==16){let e=t.read(i*2),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Int16Array(i);for(let e=0;e<i;e++)r[e]=n.getInt16(e*2,!0);return r}if(this._type._bits==32){let e=t.read(i*4),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Int32Array(i);for(let e=0;e<i;e++)r[e]=n.getInt32(e*4,!0);return r}if(this._type._bits==64){let e=t.read(i*8),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new BigInt64Array(i);for(let e=0;e<i;e++)r[e]=n.getBigInt64(e*8,!0);return r}}let a=[];for(let e=0;e<i;e++)a.push(this._type.decodeValue(t,r._type));return a}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(e){return`vec {${e.map(e=>this._type.valueToString(e)).join(`; `)}}`}},Pn=class e extends xn{get typeName(){return L.OptClass}static[Symbol.hasInstance](e){return e.typeName===L.OptClass}constructor(e){super(),this._type=e}accept(e,t){return e.visitOpt(this,this._type,t)}covariant(e){try{if(Array.isArray(e)&&(e.length===0||e.length===1&&this._type.covariant(e[0])))return!0}catch(t){throw Error(`Invalid ${this.display()} argument: ${R(e)} \n\n-> ${t.message}`,{cause:t})}throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){return e.length===0?new Uint8Array([0]):M(new Uint8Array([1]),this._type.encodeValue(e[0]))}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let t=F(I.Opt),n=this._type.encodeType(e);e.add(this,M(t,n))}decodeValue(t,n){if(n instanceof Tn||n instanceof En)return[];let r=n;if(n instanceof Rn){let e=n.getType();if(e===void 0)throw new fn(`Type mismatch: cannot decode from uninitialized recursive type`);r=e}if(r instanceof e)switch(an(t)){case 0:return[];case 1:{let e=t.save();try{return[this._type.decodeValue(t,r._type)]}catch{return t.restore(e),r._type.decodeValue(t,r._type),[]}}default:throw new fn(`Invalid option value: expected 0 (None) or 1 (Some) for type '${this.display()}'`)}else if(this._type instanceof Tn||this._type instanceof e||this._type instanceof En)return r.decodeValue(t,r),[];else{let e=t.save();try{return[this._type.decodeValue(t,n)]}catch{return t.restore(e),r.decodeValue(t,n),[]}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(e){return e.length===0?`null`:`opt ${this._type.valueToString(e[0])}`}},Fn=class e extends xn{get typeName(){return L.RecordClass}static[Symbol.hasInstance](e){return e.typeName===L.RecordClass||e.typeName===L.TupleClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((e,t)=>$t(e[0])-$t(t[0]))}accept(e,t){return e.visitRecord(this,this._fields,t)}tryAsTuple(){let e=[];for(let t=0;t<this._fields.length;t++){let[n,r]=this._fields[t];if(n!==`_${t}_`)return null;e.push(r)}return e}covariant(e){if(typeof e==`object`&&this._fields.every(([t,n])=>{if(!e.hasOwnProperty(t))throw Error(`Record is missing key "${t}".`);try{return n.covariant(e[t])}catch(e){throw Error(`Invalid ${this.display()} argument: \n\nfield ${t} -> ${e.message}`,{cause:e})}}))return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){let t=this._fields.map(([t])=>e[t]);return M(...gn(this._fields,t,([,e],t)=>e.encodeValue(t)))}_buildTypeTableImpl(e){this._fields.forEach(([t,n])=>n.buildTypeTable(e));let t=F(I.Record),n=N(this._fields.length),r=this._fields.map(([t,n])=>M(N($t(t)),n.encodeType(e)));e.add(this,M(t,n,M(...r)))}decodeValue(t,n){let r=this.checkType(n);if(!(r instanceof e))throw new fn(`Expected type '${this.display()}', but received non-record type '${r.display()}'`);let i={},a=0,o=0;for(;o<r._fields.length;){let[e,n]=r._fields[o];if(a>=this._fields.length){n.decodeValue(t,n),o++;continue}let[s,c]=this._fields[a],l=$t(this._fields[a][0]),u=$t(e);if(l===u)i[s]=c.decodeValue(t,n),a++,o++;else if(u>l){if(c instanceof Pn||c instanceof En)i[s]=[],a++;else throw new fn(`Cannot find required field '${s}' in record, expected fields: [${this._fields.map(([e])=>e).join(`, `)}], received fields: [${r._fields.map(([e])=>e).join(`, `)}]`)}else n.decodeValue(t,n),o++}for(let[e,t]of this._fields.slice(a))if(t instanceof Pn||t instanceof En)i[e]=[];else throw new fn(`Cannot find required field '${e}' in record, expected fields: [${this._fields.map(([e])=>e).join(`, `)}], received fields: [${r._fields.map(([e])=>e).join(`, `)}]`);return i}get fieldsAsObject(){let e={};for(let[t,n]of this._fields)e[$t(t)]=n;return e}get name(){return`record {${this._fields.map(([e,t])=>`${e}:${t.name}`).join(`; `)}}`}display(){return`record {${this._fields.map(([e,t])=>`${e}:${t.display()}`).join(`; `)}}`}valueToString(e){let t=this._fields.map(([t])=>e[t]);return`record {${gn(this._fields,t,([e,t],n)=>`${e}=${t.valueToString(n)}`).join(`; `)}}`}},In=class e extends Fn{get typeName(){return L.TupleClass}static[Symbol.hasInstance](e){return e.typeName===L.TupleClass}constructor(e){let t={};e.forEach((e,n)=>t[`_${n}_`]=e),super(t),this._components=e}accept(e,t){return e.visitTuple(this,this._components,t)}covariant(e){if(Array.isArray(e)&&e.length>=this._fields.length&&this._components.every((t,n)=>{try{return t.covariant(e[n])}catch(e){throw Error(`Invalid ${this.display()} argument: \n\nindex ${n} -> ${e.message}`,{cause:e})}}))return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){return M(...gn(this._components,e,(e,t)=>e.encodeValue(t)))}decodeValue(t,n){let r=this.checkType(n);if(!(r instanceof e))throw new fn(`Expected type '${this.display()}', but received non-tuple type '${r.display()}'`);if(r._components.length<this._components.length)throw new fn(`Tuple mismatch: expected ${this._components.length} components, but received ${r._components.length}`);let i=[];for(let[e,n]of r._components.entries())e>=this._components.length?n.decodeValue(t,n):i.push(this._components[e].decodeValue(t,n));return i}display(){return`record {${this._components.map(e=>e.display()).join(`; `)}}`}valueToString(e){return`record {${gn(this._components,e,(e,t)=>e.valueToString(t)).join(`; `)}}`}},Ln=class e extends xn{get typeName(){return L.VariantClass}static[Symbol.hasInstance](e){return e.typeName===L.VariantClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((e,t)=>$t(e[0])-$t(t[0]))}accept(e,t){return e.visitVariant(this,this._fields,t)}covariant(e){if(typeof e==`object`&&Object.entries(e).length===1&&this._fields.every(([t,n])=>{try{return!e.hasOwnProperty(t)||n.covariant(e[t])}catch(e){throw Error(`Invalid ${this.display()} argument: \n\nvariant ${t} -> ${e.message}`,{cause:e})}}))return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){for(let t=0;t<this._fields.length;t++){let[n,r]=this._fields[t];if(e.hasOwnProperty(n))return M(N(t),r.encodeValue(e[n]))}throw Error(`Variant has no data: ${e}`)}_buildTypeTableImpl(e){this._fields.forEach(([,t])=>{t.buildTypeTable(e)});let t=F(I.Variant),n=N(this._fields.length),r=this._fields.map(([t,n])=>M(N($t(t)),n.encodeType(e)));e.add(this,M(t,n,...r))}decodeValue(t,n){let r=this.checkType(n);if(!(r instanceof e))throw new fn(`Expected type '${this.display()}', but received non-variant type '${r.display()}'`);let i=Number(P(t));if(i>=r._fields.length)throw Error(`Invalid variant index: ${i}`);let[a,o]=r._fields[i];for(let[e,n]of this._fields)if($t(a)===$t(e)){let r=n.decodeValue(t,o);return{[e]:r}}throw new fn(`Cannot find field hash ${a} in variant, expected fields: [${this._fields.map(([e])=>e).join(`, `)}]`)}get name(){return`variant {${this._fields.map(([e,t])=>`${e}:${t.name}`).join(`; `)}}`}display(){return`variant {${this._fields.map(([e,t])=>e+(t.name===`null`?``:`:${t.display()}`)).join(`; `)}}`}valueToString(e){for(let[t,n]of this._fields)if(e.hasOwnProperty(t)){let r=n.valueToString(e[t]);return r===`null`?`variant {${t}}`:`variant {${t}=${r}}`}throw Error(`Variant has no data: ${e}`)}get alternativesAsObject(){let e={};for(let[t,n]of this._fields)e[$t(t)]=n;return e}},Rn=class e extends xn{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return L.RecClass}static{this._counter=0}static[Symbol.hasInstance](e){return e.typeName===L.RecClass}accept(e,t){if(!this._type)throw Error(`Recursive type uninitialized.`);return e.visitRec(this,this._type,t)}fill(e){this._type=e}getType(){return this._type}covariant(e){if(this._type&&this._type.covariant(e))return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){if(!this._type)throw Error(`Recursive type uninitialized.`);return this._type.encodeValue(e)}_buildTypeTableImpl(e){if(!this._type)throw Error(`Recursive type uninitialized.`);e.add(this,new Uint8Array([])),this._type.buildTypeTable(e),e.merge(this,this._type.name)}decodeValue(e,t){if(!this._type)throw Error(`Recursive type uninitialized.`);return this._type.decodeValue(e,t)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error(`Recursive type uninitialized.`);return`μ${this.name}.${this._type.name}`}valueToString(e){if(!this._type)throw Error(`Recursive type uninitialized.`);return this._type.valueToString(e)}};function zn(e){if(an(e)!==1)throw Error(`Cannot decode principal`);let t=Number(P(e));return O.fromUint8Array(new Uint8Array(rn(e,t)))}var Bn=class extends bn{get typeName(){return L.PrincipalClass}static[Symbol.hasInstance](e){return e.typeName===L.PrincipalClass}accept(e,t){return e.visitPrincipal(this,t)}covariant(e){if(e&&e._isPrincipal)return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){let t=e.toUint8Array(),n=N(t.byteLength);return M(new Uint8Array([1]),n,t)}encodeType(){return F(I.Principal)}decodeValue(e,t){return this.checkType(t),zn(e)}get name(){return`principal`}valueToString(e){return`${this.name} "${e.toText()}"`}},Vn=class extends xn{get typeName(){return L.FuncClass}static[Symbol.hasInstance](e){return e.typeName===L.FuncClass}static argsToString(e,t){if(e.length!==t.length)throw Error(`arity mismatch`);return`(${e.map((e,n)=>e.valueToString(t[n])).join(`, `)})`}constructor(e,t,n=[]){super(),this.argTypes=e,this.retTypes=t,this.annotations=n}accept(e,t){return e.visitFunc(this,t)}covariant(e){if(Array.isArray(e)&&e.length===2&&e[0]&&e[0]._isPrincipal&&typeof e[1]==`string`)return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue([e,t]){let n=e.toUint8Array(),r=N(n.byteLength),i=M(new Uint8Array([1]),r,n),a=new TextEncoder().encode(t),o=N(a.byteLength);return M(new Uint8Array([1]),i,o,a)}_buildTypeTableImpl(e){this.argTypes.forEach(t=>t.buildTypeTable(e)),this.retTypes.forEach(t=>t.buildTypeTable(e));let t=F(I.Func),n=N(this.argTypes.length),r=M(...this.argTypes.map(t=>t.encodeType(e))),i=N(this.retTypes.length),a=M(...this.retTypes.map(t=>t.encodeType(e))),o=N(this.annotations.length),s=M(...this.annotations.map(e=>this.encodeAnnotation(e)));e.add(this,M(t,n,r,i,a,o,s))}decodeValue(e,t){let n=t instanceof Rn?t.getType()??t:t;if(!Cr(n,this))throw Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(an(e)!==1)throw Error(`Cannot decode function reference`);let r=zn(e),i=rn(e,Number(P(e)));return[r,new TextDecoder(`utf8`,{fatal:!0}).decode(i)]}get name(){return`(${this.argTypes.map(e=>e.name).join(`, `)}) -> (${this.retTypes.map(e=>e.name).join(`, `)})${` ${this.annotations.join(` `)}`}`}valueToString([e,t]){return`func "${e.toText()}".${t}`}display(){return`(${this.argTypes.map(e=>e.display()).join(`, `)}) → (${this.retTypes.map(e=>e.display()).join(`, `)})${` ${this.annotations.join(` `)}`}`}encodeAnnotation(e){if(e===`query`)return new Uint8Array([1]);if(e===`oneway`)return new Uint8Array([2]);if(e===`composite_query`)return new Uint8Array([3]);throw Error(`Illegal function annotation`)}},Hn=class extends xn{get typeName(){return L.ServiceClass}static[Symbol.hasInstance](e){return e.typeName===L.ServiceClass}constructor(e){super(),this._fields=Object.entries(e).sort((e,t)=>e[0]<t[0]?-1:+(e[0]>t[0]))}accept(e,t){return e.visitService(this,t)}covariant(e){if(e&&e._isPrincipal)return!0;throw Error(`Invalid ${this.display()} argument: ${R(e)}`)}encodeValue(e){let t=e.toUint8Array(),n=N(t.length);return M(new Uint8Array([1]),n,t)}_buildTypeTableImpl(e){this._fields.forEach(([t,n])=>n.buildTypeTable(e));let t=F(I.Service),n=N(this._fields.length),r=this._fields.map(([t,n])=>{let r=new TextEncoder().encode(t);return M(N(r.length),r,n.encodeType(e))});e.add(this,M(t,n,...r))}decodeValue(e,t){let n=t instanceof Rn?t.getType()??t:t;if(!Cr(n,this))throw Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return zn(e)}get name(){return`service {${this._fields.map(([e,t])=>`${e}:${t.name}`).join(`; `)}}`}valueToString(e){return`service "${e.toText()}"`}fieldsAsObject(){let e={};for(let[t,n]of this._fields)e[t]=n;return e}};function R(e){let t=JSON.stringify(e,(e,t)=>typeof t==`bigint`?`BigInt(${t})`:t);return t&&t.length>hn?`${t.substring(0,397)}...`:t}function Un(e,t){if(t.length<e.length)throw Error(`Wrong number of message arguments`);let n=new _n;return e.forEach(e=>e.buildTypeTable(n)),M(mn,n.encode(),N(t.length),M(...e.map(e=>e.encodeType(n))),M(...gn(e,t,(e,t)=>{try{e.covariant(t)}catch(e){throw Error(`${e.message}\n\n`)}return e.encodeValue(t)})))}function Wn(e,t){let n=new Jt(t);if(t.byteLength<4)throw Error(`Message length smaller than magic number`);let r=rn(n,4),i=new TextDecoder().decode(r);if(i!==pn)throw Error(`Wrong magic number: ${JSON.stringify(i)}`);function a(e){let t=[],n=Number(P(e));for(let r=0;r<n;r++){let n=Number(on(e));switch(n){case I.Opt:case I.Vector:{let r=Number(on(e));t.push([n,r]);break}case I.Record:case I.Variant:{let r=[],i=Number(P(e)),a;for(;i--;){let t=Number(P(e));if(t>=2**32)throw Error(`field id out of 32-bit range`);if(typeof a==`number`&&a>=t)throw Error(`field id collision or not sorted`);a=t;let n=Number(on(e));r.push([t,n])}t.push([n,r]);break}case I.Func:{let r=[],i=Number(P(e));for(;i--;)r.push(Number(on(e)));let a=[],o=Number(P(e));for(;o--;)a.push(Number(on(e)));let s=[],c=Number(P(e));for(;c--;)switch(Number(P(e))){case 1:s.push(`query`);break;case 2:s.push(`oneway`);break;case 3:s.push(`composite_query`);break;default:throw Error(`unknown annotation`)}t.push([n,[r,a,s]]);break}case I.Service:{let r=Number(P(e)),i=[];for(;r--;){let t=Number(P(e)),n=new TextDecoder().decode(rn(e,t)),r=on(e);i.push([n,r])}t.push([n,i]);break}default:throw Error(`Illegal op_code: ${n}`)}}let r=[],i=Number(P(e));for(let t=0;t<i;t++)r.push(Number(on(e)));return[t,r]}let[o,s]=a(n);if(s.length<e.length)throw Error(`Wrong number of return values`);let c=o.map(e=>hr());function l(e){if(e<-24)throw Error(`future value not supported`);if(e<0)switch(e){case-1:return Yn;case-2:return Jn;case-3:return Qn;case-4:return Zn;case-5:return ar;case-6:return or;case-7:return sr;case-8:return cr;case-9:return tr;case-10:return nr;case-11:return rr;case-12:return ir;case-13:return $n;case-14:return er;case-15:return Xn;case-16:return Kn;case-17:return Gn;case-24:return lr;default:throw Error(`Illegal op_code: ${e}`)}if(e>=o.length)throw Error(`type index out of range`);return c[e]}function u(e){switch(e[0]){case I.Vector:return dr(l(e[1]));case I.Opt:return fr(l(e[1]));case I.Record:{let t={};for(let[n,r]of e[1]){let e=`_${n}_`;t[e]=l(r)}let n=pr(t),r=n.tryAsTuple();return Array.isArray(r)?ur(...r):n}case I.Variant:{let t={};for(let[n,r]of e[1]){let e=`_${n}_`;t[e]=l(r)}return mr(t)}case I.Func:{let[t,n,r]=e[1];return gr(t.map(e=>l(e)),n.map(e=>l(e)),r)}case I.Service:{let t={},n=e[1];for(let[e,r]of n){let n=l(r);if(n instanceof Rn&&(n=n.getType()),!(n instanceof Vn))throw Error(`Illegal service definition: services can only contain functions`);t[e]=n}return _r(t)}default:throw Error(`Illegal op_code: ${e[0]}`)}}o.forEach((e,t)=>{if(e[0]===I.Func){let n=u(e);c[t].fill(n)}}),o.forEach((e,t)=>{if(e[0]!==I.Func){let n=u(e);c[t].fill(n)}}),br();let d=s.map(e=>l(e));try{let t=e.map((e,t)=>e.decodeValue(n,d[t]));for(let t=e.length;t<d.length;t++)d[t].decodeValue(n,d[t]);if(n.byteLength>0)throw Error(`decode: Left-over bytes`);return t}finally{br()}}var Gn=new Sn,Kn=new En,qn=new Cn,Jn=new wn,Yn=new Tn,Xn=new Dn,Zn=new On,Qn=new kn,$n=new An(32),er=new An(64),tr=new jn(8),nr=new jn(16),rr=new jn(32),ir=new jn(64),ar=new Mn(8),or=new Mn(16),sr=new Mn(32),cr=new Mn(64),lr=new Bn;function ur(...e){return new In(e)}function dr(e){return new Nn(e)}function fr(e){return new Pn(e)}function pr(e){return new Fn(e)}function mr(e){return new Ln(e)}function hr(){return new Rn}function gr(e,t,n=[]){return new Vn(e,t,n)}function _r(e){return new Hn(e)}var vr=class e{constructor(e=new Map){this.rels=e}copy(){let t=new Map;for(let[e,n]of this.rels.entries()){let r=new Map(n);t.set(e,r)}return new e(t)}known(e,t){return this.rels.get(e.name)?.get(t.name)}addNegative(e,t){this.addNames(e.name,t.name,!1)}add(e,t){this.addNames(e.name,t.name,!0)}display(){let e=``;for(let[t,n]of this.rels)for(let[r,i]of n)e+=`${t} ${i?`:<`:`!<:`} ${r}\n`;return e}addNames(e,t,n){let r=this.rels.get(e);if(r==null){let r=new Map;r.set(t,n),this.rels.set(e,r)}else r.set(t,n)}},yr=new vr;function br(){yr=new vr}function xr(e,t){let n=new Set(e.annotations),r=new Set(t.annotations);if(n.size!==r.size)return!1;for(let e of n)if(!r.has(e))return!1;return!0}function Sr(e){return e instanceof Pn||e instanceof Tn||e instanceof En}function Cr(e,t){let n=wr(yr.copy(),e,t);return n?yr.add(e,t):yr.addNegative(e,t),n}function wr(e,t,n){if(t.name===n.name)return!0;let r=e.known(t,n);if(r!==void 0)return r;if(e.add(t,n),n instanceof En||t instanceof Sn||t instanceof kn&&n instanceof On)return!0;if(t instanceof Nn&&n instanceof Nn)return wr(e,t._type,n._type);if(n instanceof Pn)return!0;if(t instanceof Fn&&n instanceof Fn){let r=t.fieldsAsObject;for(let[t,i]of n._fields){let n=r[$t(t)];if(!n){if(!Sr(i))return!1}else if(!wr(e,n,i))return!1}return!0}if(t instanceof Vn&&n instanceof Vn){if(!xr(t,n))return!1;for(let r=0;r<t.argTypes.length;r++){let i=t.argTypes[r];if(r<n.argTypes.length){if(!wr(e,n.argTypes[r],i))return!1}else if(!Sr(i))return!1}for(let r=0;r<n.retTypes.length;r++){let i=n.retTypes[r];if(r<t.retTypes.length){if(!wr(e,t.retTypes[r],i))return!1}else if(!Sr(i))return!1}return!0}if(t instanceof Ln&&n instanceof Ln){let r=n.alternativesAsObject;for(let[n,i]of t._fields){let t=r[$t(n)];if(!t||!wr(e,i,t))return!1}return!0}if(t instanceof Hn&&n instanceof Hn){let r=t.fieldsAsObject();for(let[t,i]of n._fields){let n=r[t];if(!n||!wr(e,n,i))return!1}return!0}return t instanceof Rn?wr(e,t.getType(),n):n instanceof Rn&&wr(e,t,n.getType())}var Tr=class{constructor(e,t){this.idl=e,this.ui=t,this.label=null,this.value=void 0;let n=document.createElement(`span`);n.className=`status`,this.status=n,t.input&&(t.input.addEventListener(`blur`,()=>{t.input.value!==``&&this.parse()}),t.input.addEventListener(`input`,()=>{n.style.display=`none`,t.input.classList.remove(`reject`)}))}isRejected(){return this.value===void 0}parse(e={}){if(this.ui.form){let t=this.ui.form.parse(e);return this.value=t,t}if(this.ui.input){let t=this.ui.input;try{let n=this.ui.parse(this.idl,e,t.value);if(!this.idl.covariant(n))throw Error(`${t.value} is not of type ${this.idl.display()}`);return this.status.style.display=`none`,this.value=n,n}catch(e){t.classList.add(`reject`),this.status.style.display=`block`,this.status.innerHTML=`InputError: ${e.message}`,this.value=void 0;return}}return null}render(e){let t=document.createElement(`span`);if(this.label){let e=document.createElement(`label`);e.innerText=this.label,t.appendChild(e)}this.ui.input&&(t.appendChild(this.ui.input),t.appendChild(this.status)),this.ui.form&&this.ui.form.render(t),e.appendChild(t)}},Er=class{constructor(e){this.ui=e,this.form=[]}renderForm(e){this.ui.container?(this.form.forEach(e=>e.render(this.ui.container)),e.appendChild(this.ui.container)):this.form.forEach(t=>t.render(e))}render(e){if(this.ui.open&&this.ui.event){e.appendChild(this.ui.open);let t=this;t.ui.open.addEventListener(t.ui.event,()=>{if(t.ui.container)t.ui.container.innerHTML=``;else{let e=t.ui.open.nextElementSibling;e&&e.parentNode.removeChild(e)}t.generateForm(),t.renderForm(e)})}else this.generateForm(),this.renderForm(e)}},Dr=class extends Er{constructor(e,t){super(t),this.fields=e,this.ui=t}generateForm(){this.form=this.fields.map(([e,t])=>{let n=this.ui.render(t);return n.label=this.ui.labelMap&&this.ui.labelMap.hasOwnProperty(e)?`${this.ui.labelMap[e]} `:`${e} `,n})}parse(e){let t={};if(this.fields.forEach(([n,r],i)=>{let a=this.form[i].parse(e);t[n]=a}),!this.form.some(e=>e.isRejected()))return t}},Or=class extends Er{constructor(e,t){super(t),this.components=e,this.ui=t}generateForm(){this.form=this.components.map(e=>this.ui.render(e))}parse(e){let t=[];if(this.components.forEach((n,r)=>{let i=this.form[r].parse(e);t.push(i)}),!this.form.some(e=>e.isRejected()))return t}},kr=class extends Er{constructor(e,t){super(t),this.fields=e,this.ui=t}generateForm(){let e=this.ui.open.selectedIndex,[t,n]=this.fields[e],r=this.ui.render(n);this.form=[r]}parse(e){let t=this.ui.open,n=t.options[t.selectedIndex].value,r=this.form[0].parse(e);if(r===void 0)return;let i={};return i[n]=r,i}},Ar=class extends Er{constructor(e,t){super(t),this.ty=e,this.ui=t}generateForm(){if(this.ui.open.checked){let e=this.ui.render(this.ty);this.form=[e]}else this.form=[]}parse(e){if(this.form.length===0)return[];let t=this.form[0].parse(e);if(t!==void 0)return[t]}},jr=class extends Er{constructor(e,t){super(t),this.ty=e,this.ui=t}generateForm(){let e=+this.ui.open.value;this.form=[];for(let t=0;t<e;t++){let e=this.ui.render(this.ty);this.form.push(e)}}parse(e){let t=this.form.map(t=>t.parse(e));if(!this.form.some(e=>e.isRejected()))return t}},Mr={parse:Ur},Nr={render:Wr},Pr=(e,t)=>new Tr(e,{...Mr,...t}),Fr=(e,t)=>new Dr(e,{...Nr,...t}),Ir=(e,t)=>new Or(e,{...Nr,...t}),Lr=(e,t)=>new kr(e,{...Nr,...t}),Rr=(e,t)=>new Ar(e,{...Nr,...t}),zr=(e,t)=>new jr(e,{...Nr,...t}),Br=class extends vn{visitType(e,t){let n=document.createElement(`input`);return n.classList.add(`argument`),n.placeholder=e.display(),Pr(e,{input:n})}visitNull(e,t){return Pr(e,{})}visitRecord(e,t,n){let r={};if(t.length>1){let e=document.createElement(`div`);e.classList.add(`popup-form`),r={container:e}}return Pr(e,{form:Fr(t,r)})}visitTuple(e,t,n){let r={};if(t.length>1){let e=document.createElement(`div`);e.classList.add(`popup-form`),r={container:e}}return Pr(e,{form:Ir(t,r)})}visitVariant(e,t,n){let r=document.createElement(`select`);for(let[e,n]of t){let t=new Option(e);r.add(t)}return r.selectedIndex=-1,r.classList.add(`open`),Pr(e,{form:Lr(t,{open:r,event:`change`})})}visitOpt(e,t,n){let r=document.createElement(`input`);return r.type=`checkbox`,r.classList.add(`open`),Pr(e,{form:Rr(t,{open:r,event:`change`})})}visitVec(e,t,n){let r=document.createElement(`input`);r.type=`number`,r.min=`0`,r.max=`100`,r.style.width=`8rem`,r.placeholder=`len`,r.classList.add(`open`);let i=document.createElement(`div`);return i.classList.add(`popup-form`),Pr(e,{form:zr(t,{open:r,event:`change`,container:i})})}visitRec(e,t,n){return Wr(t)}},Vr=class extends vn{visitNull(e,t){return null}visitBool(e,t){if(t===`true`)return!0;if(t===`false`)return!1;throw Error(`Cannot parse ${t} as boolean`)}visitText(e,t){return t}visitFloat(e,t){return parseFloat(t)}visitFixedInt(e,t){return e._bits<=32?parseInt(t,10):BigInt(t)}visitFixedNat(e,t){return e._bits<=32?parseInt(t,10):BigInt(t)}visitNumber(e,t){return BigInt(t)}visitPrincipal(e,t){return O.fromText(t)}visitService(e,t){return O.fromText(t)}visitFunc(e,t){let n=t.split(`.`,2);return[O.fromText(n[0]),n[1]]}},Hr=class extends vn{visitNull(e,t){return null}visitBool(e,t){return Math.random()<.5}visitText(e,t){return Math.random().toString(36).substring(6)}visitFloat(e,t){return Math.random()}visitInt(e,t){return BigInt(this.generateNumber(!0))}visitNat(e,t){return BigInt(this.generateNumber(!1))}visitFixedInt(e,t){let n=this.generateNumber(!0);return e._bits<=32?n:BigInt(t)}visitFixedNat(e,t){let n=this.generateNumber(!1);return e._bits<=32?n:BigInt(t)}generateNumber(e){let t=Math.floor(Math.random()*100);return e&&Math.random()<.5?-t:t}};function Ur(e,t,n){return t.random&&n===``?e.accept(new Hr,n):e.accept(new Vr,n)}function Wr(e){return e.accept(new Br,null)}function Gr(e,t,n){return e.accept(new Kr,{input:t,value:n})}var Kr=class extends vn{visitType(e,t){t.input.ui.input.value=e.valueToString(t.value)}visitNull(e,t){}visitText(e,t){t.input.ui.input.value=t.value}visitRec(e,t,n){Gr(t,n.input,n.value)}visitOpt(e,t,n){if(n.value.length!==0){let e=n.input.ui.form,r=e.ui.open;r.checked=!0,r.dispatchEvent(new Event(e.ui.event)),Gr(t,e.form[0],n.value[0])}}visitRecord(e,t,n){let r=n.input.ui.form;t.forEach(([e,t],i)=>{Gr(t,r.form[i],n.value[e])})}visitTuple(e,t,n){let r=n.input.ui.form;t.forEach((e,t)=>{Gr(e,r.form[t],n.value[t])})}visitVariant(e,t,n){let r=n.input.ui.form,i=Object.entries(n.value)[0];t.forEach(([e,t],n)=>{if(e===i[0]){let e=r.ui.open;e.selectedIndex=n,e.dispatchEvent(new Event(r.ui.event)),Gr(t,r.form[0],i[1])}})}visitVec(e,t,n){let r=n.input.ui.form,i=n.value.length,a=r.ui.open;a.value=i,a.dispatchEvent(new Event(r.ui.event)),n.value.forEach((e,n)=>{Gr(t,r.form[n],e)})}};function qr(e){if(!e)throw Error(`Input cannot be null or undefined`);return e instanceof Uint8Array?e:e instanceof ArrayBuffer||Array.isArray(e)?new Uint8Array(e):`buffer`in e?qr(e.buffer):new Uint8Array(e)}function Jr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Yr(e){if(typeof e==`string`)return Xr(e);if(typeof e==`number`)return He(N(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return He(qr(e));if(Array.isArray(e))return He(E(...e.map(Yr)));if(e&&typeof e==`object`&&e._isPrincipal)return He(e.toUint8Array());if(typeof e==`object`&&e&&typeof e.toHash==`function`)return Yr(e.toHash());if(typeof e==`object`)return Qr(e);if(typeof e==`bigint`)return He(N(e));throw j.fromCode(new Ot(e))}var Xr=e=>He(new TextEncoder().encode(e));function Zr(e){return Qr(e)}function Qr(e){return He(E(...Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>[Xr(e),Yr(t)]).sort(([e],[t])=>Xt(e,t)).map(e=>E(...e))))}var $r=new TextEncoder().encode(`\ric-state-root`);new TextEncoder().encode(`
|
|
3
|
-
ic-request`);var ei=new TextEncoder().encode(`\vic-response`);new TextEncoder().encode(`ic-request-auth-delegation`);var ti=class{getPrincipal(){return O.anonymous()}async transformRequest(e){return{...e,body:{content:e.body}}}},ni=class extends Error{constructor(e){super(e),this.name=`DecodingError`}},ri=55799,ii=Symbol(`CBOR_STOP_CODE`),ai=(e=>(e[e.False=20]=`False`,e[e.True=21]=`True`,e[e.Null=22]=`Null`,e[e.Undefined=23]=`Undefined`,e[e.Break=31]=`Break`,e))(ai||{}),z=(e=>(e[e.UnsignedInteger=0]=`UnsignedInteger`,e[e.NegativeInteger=1]=`NegativeInteger`,e[e.ByteString=2]=`ByteString`,e[e.TextString=3]=`TextString`,e[e.Array=4]=`Array`,e[e.Map=5]=`Map`,e[e.Tag=6]=`Tag`,e[e.Simple=7]=`Simple`,e))(z||{}),oi=23,si=255,ci=65535,li=4294967295,ui=BigInt(`0xffffffffffffffff`),di=(e=>(e[e.Value=23]=`Value`,e[e.OneByte=24]=`OneByte`,e[e.TwoBytes=25]=`TwoBytes`,e[e.FourBytes=26]=`FourBytes`,e[e.EightBytes=27]=`EightBytes`,e[e.Indefinite=31]=`Indefinite`,e))(di||{}),fi=!1;function pi(e){return e==null}function mi(e,t){let n=new Uint8Array(t);return n.set(e),n}var hi=new TextDecoder;function gi(e){return(e&224)>>5}function _i(e){return e&31}var vi=new Uint8Array,yi,bi=0;function xi(e,t){vi=e,bi=0;let n=Si(t);return t?.(n)??n}function Si(e){let[t,n]=Ci();switch(t){case z.UnsignedInteger:return Di(n);case z.NegativeInteger:return Oi(n);case z.ByteString:return ki(n);case z.TextString:return Ai(n);case z.Array:return wi(n,e);case z.Map:return Ei(n,e);case z.Tag:return ji(n,e);case z.Simple:return Ti(n)}throw new ni(`Unsupported major type: ${t}`)}function Ci(){let e=vi.at(bi);if(pi(e))throw new ni(`Provided CBOR data is empty`);let t=gi(e),n=_i(e);return bi++,[t,n]}function wi(e,t){let n=Di(e);if(n===1/0){let e=[],n=Si(t);for(;n!==ii;)e.push(t?.(n)??n),n=Si(t);return e}let r=Array(n);for(let e=0;e<n;e++){let n=Si(t);r[e]=t?.(n)??n}return r}function Ti(e){switch(e){case ai.False:return!1;case ai.True:return!0;case ai.Null:return null;case ai.Undefined:return;case ai.Break:return ii}throw new ni(`Unrecognized simple type: ${e.toString(2)}`)}function Ei(e,t){let n=Di(e),r={};if(n===1/0){let[e,n]=Ci();for(;e!==z.Simple&&n!==ai.Break;){let i=Ai(n),a=Si(t);r[i]=t?.(a,i)??a,[e,n]=Ci()}return r}for(let e=0;e<n;e++){let[e,n]=Ci();if(e!==z.TextString)throw new ni(`Map keys must be text strings`);let i=Ai(n),a=Si(t);r[i]=t?.(a,i)??a}return r}function Di(e){if(e<=di.Value)return e;switch(yi=new DataView(vi.buffer,vi.byteOffset+bi),e){case di.OneByte:return bi++,yi.getUint8(0);case di.TwoBytes:return bi+=2,yi.getUint16(0,fi);case di.FourBytes:return bi+=4,yi.getUint32(0,fi);case di.EightBytes:return bi+=8,yi.getBigUint64(0,fi);case di.Indefinite:return 1/0;default:throw new ni(`Unsupported integer info: ${e.toString(2)}`)}}function Oi(e){let t=Di(e);return typeof t==`number`?-1-t:-1n-t}function ki(e){let t=Di(e);if(t>2**53-1)throw new ni(`Byte length is too large`);let n=Number(t);return bi+=n,vi.slice(bi-n,bi)}function Ai(e){let t=ki(e);return hi.decode(t)}function ji(e,t){let n=Di(e);if(n===ri)return Si(t);throw new ni(`Unsupported tag: ${n}.`)}var Mi=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},Ni=2048,Pi=100,Fi=new TextEncoder;function Ii(e){return e<<5}var Li=new Uint8Array(Ni),Ri=new DataView(Li.buffer),B=0,zi=[];function Bi(e,t){return B=0,ta(ri,t?.(e)??e,t),Li.slice(0,B)}function Vi(e){let t=Li.length*2;for(;t<e;)t*=2;Li=mi(Li,t),Ri=new DataView(Li.buffer)}function Hi(e,t){if(e===!1||e===!0||e==null)Ki(e);else if(typeof e==`number`||typeof e==`bigint`)Qi(e);else if(typeof e==`string`)$i(e);else if(e instanceof Uint8Array)ea(e);else if(e instanceof ArrayBuffer)ea(new Uint8Array(e));else if(Array.isArray(e))Ui(e,t);else if(typeof e==`object`)Wi(e,t);else throw new Mi(`Unsupported type: ${typeof e}`)}function Ui(e,t){Gi(z.Array,e.length),e.forEach((e,n)=>{Hi(t?.(e,n.toString())??e,t)})}function Wi(e,t){zi=Object.entries(e),Gi(z.Map,zi.length),zi.forEach(([e,n])=>{$i(e),Hi(t?.(n,e)??n,t)})}function Gi(e,t){if(B>Li.length-Pi&&Vi(B+Pi),t<=oi)Ri.setUint8(B++,Ii(e)|Number(t));else if(t<=si)Ri.setUint8(B++,Ii(e)|di.OneByte),Ri.setUint8(B,Number(t)),B+=1;else if(t<=ci)Ri.setUint8(B++,Ii(e)|di.TwoBytes),Ri.setUint16(B,Number(t),fi),B+=2;else if(t<=li)Ri.setUint8(B++,Ii(e)|di.FourBytes),Ri.setUint32(B,Number(t),fi),B+=4;else if(t<=ui)Ri.setUint8(B++,Ii(e)|di.EightBytes),Ri.setBigUint64(B,BigInt(t),fi),B+=8;else throw new Mi(`Value too large to encode: ${t}`)}function Ki(e){Gi(z.Simple,qi(e))}function qi(e){if(e===!1)return ai.False;if(e===!0)return ai.True;if(e===null)return ai.Null;if(e===void 0)return ai.Undefined;throw new Mi(`Unrecognized simple value: ${e.toString()}`)}function Ji(e,t){Gi(e,t.length),B>Li.length-t.length&&Vi(B+t.length),Li.set(t,B),B+=t.length}function Yi(e,t){Gi(e,t)}function Xi(e){Yi(z.UnsignedInteger,e)}function Zi(e){Yi(z.NegativeInteger,typeof e==`bigint`?-1n-e:-1-e)}function Qi(e){e>=0?Xi(e):Zi(e)}function $i(e){Ji(z.TextString,Fi.encode(e))}function ea(e){Ji(z.ByteString,e)}function ta(e,t,n){Gi(z.Tag,e),Hi(t,n)}var na=`__expiry__`,ra=BigInt(1e3),ia=BigInt(1e6),aa=BigInt(60)*ra,oa=BigInt(1)*aa;function sa(e){return e/ra*ra}function ca(e){return e/aa*aa}var la=class e{constructor(e){this.__expiry__=e,this._isExpiry=!0}static fromDeltaInMilliseconds(t,n=0){let r=BigInt(Date.now())+BigInt(n),i=r+BigInt(t),a=ca(i),o;return o=a>=r+oa?a:sa(i),new e(o*ia)}toBigInt(){return this.__expiry__}toHash(){return N(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[na]:this.toString()}}static fromJSON(t){let n=JSON.parse(t);if(n.__expiry__)try{let t=BigInt(n[na]);return new e(t)}catch(e){throw new j(new Gt(`Not a valid BigInt: ${e}`))}throw new j(new Gt(`The input does not contain the key ${na}`))}static isExpiry(t){return t instanceof e||typeof t==`object`&&!!t&&`_isExpiry`in t&&t._isExpiry===!0&&`__expiry__`in t&&typeof t.__expiry__==`bigint`}};function ua(e){return typeof e==`object`&&!!e&&`toCborValue`in e}function da(e){try{return Bi(e,e=>O.isPrincipal(e)?e.toUint8Array():la.isExpiry(e)?e.toBigInt():ua(e)?e.toCborValue():e)}catch(t){throw j.fromCode(new bt(t,e))}}function fa(e){try{return xi(e)}catch(t){throw j.fromCode(new yt(t,e))}}var pa=()=>{if(typeof window<`u`&&window.crypto&&window.crypto.getRandomValues){let e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if(typeof crypto<`u`&&crypto.getRandomValues){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return typeof crypto<`u`&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)},ma;(function(e){e.Query=`read`,e.ReadState=`read_state`,e.Call=`call`})(ma||={});var ha;(function(e){e.Call=`call`})(ha||={});var ga;(function(e){e.Query=`query`,e.ReadState=`read_state`})(ga||={});var _a;(function(e){e.Received=`received`,e.Processing=`processing`,e.Replied=`replied`,e.Rejected=`rejected`,e.Unknown=`unknown`,e.Done=`done`})(_a||={});function va(){let e=new ArrayBuffer(16),t=new DataView(e),n=pa(),r=pa(),i=pa(),a=pa();return t.setUint32(0,n),t.setUint32(4,r),t.setUint32(8,i),t.setUint32(12,a),Object.assign(new Uint8Array(e),{__nonce__:void 0})}function ya(e=va){return async t=>{let n=t.request.headers;t.request.headers=n,t.endpoint===ma.Call&&(t.body.nonce=e())}}function ba(e){let t=[];return e.forEach((e,n)=>{t.push([n,e])}),t}var xa=BigInt(0),Sa=BigInt(1);function Ca(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}"`;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function wa(e,t,n=``){let r=g(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function Ta(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?xa:BigInt(`0x`+e)}function Ea(e){return Ta(w(e))}function Da(e){return v(e),Ta(w(Uint8Array.from(e).reverse()))}function V(e,t){return ie(e.toString(16).padStart(t*2,`0`))}function Oa(e,t){return V(e,t).reverse()}function H(e,t,n){let r;if(typeof t==`string`)try{r=ie(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(g(t))r=Uint8Array.from(t);else throw Error(e+` must be hex string or Uint8Array`);let i=r.length;if(typeof n==`number`&&i!==n)throw Error(e+` of length `+n+` expected, got `+i);return r}function ka(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function Aa(e){return Uint8Array.from(e)}var ja=e=>typeof e==`bigint`&&xa<=e;function Ma(e,t,n){return ja(e)&&ja(t)&&ja(n)&&t<=e&&e<n}function Na(e,t,n,r){if(!Ma(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function Pa(e){let t=0;for(;e>xa;e>>=Sa,t+=1);return t}function Fa(e,t){return e>>BigInt(t)&Sa}var Ia=e=>(Sa<<BigInt(e))-Sa;function La(e){return typeof e==`function`&&Number.isSafeInteger(e.outputLen)}function Ra(e,t,n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}var za=()=>{throw Error(`not implemented`)};function Ba(e){let t=new WeakMap;return(n,...r)=>{let i=t.get(n);if(i!==void 0)return i;let a=e(n,...r);return t.set(n,a),a}}var U=BigInt(0),W=BigInt(1),Va=BigInt(2),Ha=BigInt(3),Ua=BigInt(4),Wa=BigInt(5),Ga=BigInt(7),Ka=BigInt(8),qa=BigInt(9),Ja=BigInt(16);function G(e,t){let n=e%t;return n>=U?n:t+n}function Ya(e,t,n){let r=e;for(;t-->U;)r*=r,r%=n;return r}function Xa(e,t){if(e===U)throw Error(`invert: expected non-zero number`);if(t<=U)throw Error(`invert: expected positive modulus, got `+t);let n=G(e,t),r=t,i=U,a=W,o=W,s=U;for(;n!==U;){let e=r/n,t=r%n,c=i-o*e,l=a-s*e;r=n,n=t,i=o,a=s,o=c,s=l}if(r!==W)throw Error(`invert: does not exist`);return G(i,t)}function Za(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function Qa(e,t){let n=(e.ORDER+W)/Ua,r=e.pow(t,n);return Za(e,r,t),r}function $a(e,t){let n=(e.ORDER-Wa)/Ka,r=e.mul(t,Va),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,Va),i),s=e.mul(a,e.sub(o,e.ONE));return Za(e,s,t),s}function eo(e){let t=uo(e),n=to(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+Ga)/Ja;return(e,t)=>{let n=e.pow(t,o),s=e.mul(n,r),c=e.mul(n,i),l=e.mul(n,a),u=e.eql(e.sqr(s),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,s,u),s=e.cmov(l,c,d);let f=e.eql(e.sqr(s),t),p=e.cmov(n,s,f);return Za(e,p,t),p}}function to(e){if(e<Ha)throw Error(`sqrt is not defined for small field`);let t=e-W,n=0;for(;t%Va===U;)t/=Va,n++;let r=Va,i=uo(e);for(;co(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return Qa;let a=i.pow(r,t),o=(t+W)/Va;return function(e,r){if(e.is0(r))return r;if(co(e,r)!==1)throw Error(`Cannot find square root`);let i=n,s=e.mul(e.ONE,a),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw Error(`Cannot find square root`);let r=W<<BigInt(i-t-1),a=e.pow(s,r);i=t,s=e.sqr(a),c=e.mul(c,s),l=e.mul(l,a)}return l}}function no(e){return e%Ua===Ha?Qa:e%Ka===Wa?$a:e%Ja===qa?eo(e):to(e)}var ro=(e,t)=>(G(e,t)&W)===W,io=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function ao(e){return Ra(e,io.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function oo(e,t,n){if(n<U)throw Error(`invalid exponent, negatives unsupported`);if(n===U)return e.ONE;if(n===W)return t;let r=e.ONE,i=t;for(;n>U;)n&W&&(r=e.mul(r,i)),i=e.sqr(i),n>>=W;return r}function so(e,t,n=!1){let r=Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),a=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),a),r}function co(e,t){let n=(e.ORDER-W)/Va,r=e.pow(t,n),i=e.eql(r,e.ONE),a=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!a&&!o)throw Error(`invalid Legendre symbol result`);return i?1:a?0:-1}function lo(e,t){t!==void 0&&_(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function uo(e,t,n=!1,r={}){if(e<=U)throw Error(`invalid field: expected ORDER > 0, got `+e);let i,a,o=!1,s;if(typeof t==`object`&&t){if(r.sqrt||n)throw Error(`cannot specify opts in two arguments`);let e=t;e.BITS&&(i=e.BITS),e.sqrt&&(a=e.sqrt),typeof e.isLE==`boolean`&&(n=e.isLE),typeof e.modFromBytes==`boolean`&&(o=e.modFromBytes),s=e.allowedLengths}else typeof t==`number`&&(i=t),r.sqrt&&(a=r.sqrt);let{nBitLength:c,nByteLength:l}=lo(e,i);if(l>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);let u,d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:Ia(c),ZERO:U,ONE:W,allowedLengths:s,create:t=>G(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof t);return U<=t&&t<e},is0:e=>e===U,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&W)===W,neg:t=>G(-t,e),eql:(e,t)=>e===t,sqr:t=>G(t*t,e),add:(t,n)=>G(t+n,e),sub:(t,n)=>G(t-n,e),mul:(t,n)=>G(t*n,e),pow:(e,t)=>oo(d,e,t),div:(t,n)=>G(t*Xa(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Xa(t,e),sqrt:a||(t=>(u||=no(e),u(d,t))),toBytes:e=>n?Oa(e,l):V(e,l),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw Error(`Field.fromBytes: expected `+s+` bytes, got `+t.length);let e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw Error(`Field.fromBytes: expected `+l+` bytes, got `+t.length);let i=n?Da(t):Ea(t);if(o&&(i=G(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>so(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function fo(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function po(e){let t=fo(e);return t+Math.ceil(t/2)}function mo(e,t,n=!1){let r=e.length,i=fo(t),a=po(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=G(n?Da(e):Ea(e),t-W)+W;return n?Oa(o,i):V(o,i)}var ho=BigInt(0),go=BigInt(1);function _o(e,t){let n=t.negate();return e?n:t}function vo(e,t){let n=so(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function yo(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function bo(e,t){yo(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:Ia(e),maxNumber:i,shiftBy:BigInt(e)}}function xo(e,t,n){let{windowSize:r,mask:i,maxNumber:a,shiftBy:o}=n,s=Number(e&i),c=e>>o;s>r&&(s-=a,c+=go);let l=t*r,u=l+Math.abs(s)-1,d=s===0,f=s<0,p=t%2!=0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function So(e,t){if(!Array.isArray(e))throw Error(`array expected`);e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function Co(e,t){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,n)=>{if(!t.isValid(e))throw Error(`invalid scalar at index `+n)})}var wo=new WeakMap,To=new WeakMap;function Eo(e){return To.get(e)||1}function Do(e){if(e!==ho)throw Error(`invalid wNAF`)}var Oo=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>ho;)t&go&&(n=n.add(r)),r=r.double(),t>>=go;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=bo(t,this.bits),i=[],a=e,o=a;for(let e=0;e<n;e++){o=a,i.push(o);for(let e=1;e<r;e++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw Error(`invalid scalar`);let r=this.ZERO,i=this.BASE,a=bo(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=xo(n,e,a);n=o,c?i=i.add(_o(u,t[d])):r=r.add(_o(l,t[s]))}return Do(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=bo(e,this.bits);for(let e=0;e<i.windows&&n!==ho;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=xo(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return Do(n),r}getPrecomputes(e,t,n){let r=wo.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),wo.set(t,r))),r}cached(e,t,n){let r=Eo(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=Eo(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){yo(t,this.bits),To.set(e,t),wo.delete(e)}hasCache(e){return Eo(e)!==1}};function ko(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>ho||r>ho;)n&go&&(a=a.add(i)),r&go&&(o=o.add(i)),i=i.double(),n>>=go,r>>=go;return{p1:a,p2:o}}function Ao(e,t,n,r){So(n,e),Co(r,t);let i=n.length,a=r.length;if(i!==a)throw Error(`arrays of points and scalars must have equal length`);let o=e.ZERO,s=Pa(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=Ia(c),u=Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c,f=o;for(let e=d;e>=0;e-=c){u.fill(o);for(let t=0;t<a;t++){let i=r[t],a=Number(i>>BigInt(e)&l);u[a]=u[a].add(n[t])}let t=o;for(let e=u.length-1,n=o;e>0;e--)n=n.add(u[e]),t=t.add(n);if(f=f.add(t),e!==0)for(let e=0;e<c;e++)f=f.double()}return f}function jo(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return ao(t),t}return uo(e,{isLE:n})}function Mo(e,t,n={},r){if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(typeof n==`bigint`&&n>ho))throw Error(`CURVE.${e} must be positive bigint`)}let i=jo(t.p,n.Fp,r),a=jo(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}var No=Ea;function Po(e,t){if(Io(e),Io(t),e<0||e>=1<<8*t)throw Error(`invalid I2OSP input: `+e);let n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function Fo(e,t){let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function Io(e){if(!Number.isSafeInteger(e))throw Error(`number expected`)}function Lo(e){if(!g(e)&&typeof e!=`string`)throw Error(`DST must be Uint8Array or string`);return typeof e==`string`?T(e):e}function Ro(e,t,n,r){v(e),Io(n),t=Lo(t),t.length>255&&(t=r(E(T(`H2C-OVERSIZE-DST-`),t)));let{outputLen:i,blockLen:a}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw Error(`expand_message_xmd: invalid lenInBytes`);let s=E(t,Po(t.length,1)),c=Po(0,a),l=Po(n,2),u=Array(o),d=r(E(c,e,l,Po(0,1),s));u[0]=r(E(d,Po(1,1),s));for(let e=1;e<=o;e++){let t=[Fo(d,u[e-1]),Po(e+1,1),s];u[e]=r(E(...t))}return E(...u).slice(0,n)}function zo(e,t,n,r,i){if(v(e),Io(n),t=Lo(t),t.length>255){let e=Math.ceil(2*r/8);t=i.create({dkLen:e}).update(T(`H2C-OVERSIZE-DST-`)).update(t).digest()}if(n>65535||t.length>255)throw Error(`expand_message_xof: invalid lenInBytes`);return i.create({dkLen:n}).update(e).update(Po(n,2)).update(t).update(Po(t.length,1)).digest()}function Bo(e,t,n){Ra(n,{p:`bigint`,m:`number`,k:`number`,hash:`function`});let{p:r,k:i,m:a,hash:o,expand:s,DST:c}=n;if(!La(n.hash))throw Error(`expected valid hash`);v(e),Io(t);let l=r.toString(2).length,u=Math.ceil((l+i)/8),d=t*a*u,f;if(s===`xmd`)f=Ro(e,c,d,o);else if(s===`xof`)f=zo(e,c,d,i,o);else if(s===`_internal_pass`)f=e;else throw Error(`expand must be "xmd" or "xof"`);let p=Array(t);for(let e=0;e<t;e++){let t=Array(a);for(let n=0;n<a;n++){let i=u*(n+e*a),o=f.subarray(i,i+u);t[n]=G(No(o),r)}p[e]=t}return p}function Vo(e,t){let n=t.map(e=>Array.from(e).reverse());return(t,r)=>{let[i,a,o,s]=n.map(n=>n.reduce((n,r)=>e.add(e.mul(n,t),r))),[c,l]=so(e,[a,s],!0);return t=e.mul(i,c),r=e.mul(r,e.mul(o,l)),{x:t,y:r}}}var Ho=T(`HashToScalar-`);function Uo(e,t,n){if(typeof t!=`function`)throw Error(`mapToCurve() must be defined`);function r(n){return e.fromAffine(t(n))}function i(t){let n=t.clearCofactor();return n.equals(e.ZERO)?e.ZERO:(n.assertValidity(),n)}return{defaults:n,hashToCurve(e,t){let a=Bo(e,2,Object.assign({},n,t)),o=r(a[0]),s=r(a[1]);return i(o.add(s))},encodeToCurve(e,t){let a=n.encodeDST?{DST:n.encodeDST}:{};return i(r(Bo(e,1,Object.assign({},n,a,t))[0]))},mapToCurve(e){if(!Array.isArray(e))throw Error(`expected array of bigints`);for(let t of e)if(typeof t!=`bigint`)throw Error(`expected array of bigints`);return i(r(e))},hashToScalar(t,r){let i=e.Fn.ORDER;return Bo(t,1,Object.assign({},n,{p:i,m:1,DST:Ho},r))[0][0]}}}var Wo=(e,t)=>(e+(e>=0?t:-t)/qo)/t;function Go(e,t,n){let[[r,i],[a,o]]=t,s=Wo(o*e,n),c=Wo(-i*e,n),l=e-s*r-c*a,u=-s*i-c*o,d=l<Ko,f=u<Ko;d&&(l=-l),f&&(u=-u);let p=Ia(Math.ceil(Pa(n)/2))+K;if(l<Ko||l>=p||u<Ko||u>=p)throw Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}var Ko=BigInt(0),K=BigInt(1),qo=BigInt(2),Jo=BigInt(3),Yo=BigInt(4);function Xo(e,t){let{BYTES:n}=e,r;if(typeof t==`bigint`)r=t;else{let i=H(`private key`,t);try{r=e.fromBytes(i)}catch{throw Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw Error(`invalid private key: out of range [1..N-1]`);return r}function Zo(e,t={}){let n=Mo(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;Ra(t,{},{allowInfinityPoint:`boolean`,clearCofactor:`function`,isTorsionFree:`function`,fromBytes:`function`,toBytes:`function`,endo:`object`,wrapPrivateKey:`boolean`});let{endo:c}=t;if(c&&(!r.is0(a.a)||typeof c.beta!=`bigint`||!Array.isArray(c.basises)))throw Error(`invalid endo: expected "beta": bigint and "basises": array`);let l=ts(r,i);function u(){if(!r.isOdd)throw Error(`compression is not supported: Field does not have .isOdd()`)}function d(e,t,n){let{x:i,y:a}=t.toAffine(),o=r.toBytes(i);return Ca(n,`isCompressed`),n?(u(),E(Qo(!r.isOdd(a)),o)):E(Uint8Array.of(4),o,r.toBytes(a))}function f(e){wa(e,void 0,`Point`);let{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,a=e[0],o=e.subarray(1);if(i===t&&(a===2||a===3)){let e=r.fromBytes(o);if(!r.isValid(e))throw Error(`bad point: is not on curve, wrong x`);let t=h(e),n;try{n=r.sqrt(t)}catch(e){let t=e instanceof Error?`: `+e.message:``;throw Error(`bad point: is not on curve, sqrt error`+t)}u();let i=r.isOdd(n);return(a&1)==1!==i&&(n=r.neg(n)),{x:e,y:n}}if(i===n&&a===4){let e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.subarray(e,e*2));if(!g(t,n))throw Error(`bad point: is not on curve`);return{x:t,y:n}}throw Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}let p=t.toBytes||d,m=t.fromBytes||f;function h(e){let t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,a.a)),a.b)}function g(e,t){let n=r.sqr(t),i=h(e);return r.eql(n,i)}if(!g(a.Gx,a.Gy))throw Error(`bad curve params: generator point`);let _=r.mul(r.pow(a.a,Jo),Yo),v=r.mul(r.sqr(a.b),BigInt(27));if(r.is0(r.add(_,v)))throw Error(`bad curve params: a or b`);function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw Error(`bad point coordinate ${e}`);return t}function b(e){if(!(e instanceof C))throw Error(`ProjectivePoint expected`)}function x(e){if(!c||!c.basises)throw Error(`no endo`);return Go(e,c.basises,i.ORDER)}let ee=Ba((e,t)=>{let{X:n,Y:i,Z:a}=e;if(r.eql(a,r.ONE))return{x:n,y:i};let o=e.is0();t??=o?r.ONE:r.inv(a);let s=r.mul(n,t),c=r.mul(i,t),l=r.mul(a,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw Error(`invZ was invalid`);return{x:s,y:c}}),S=Ba(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw Error(`bad point: ZERO`)}let{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error(`bad point: x or y not field elements`);if(!g(n,i))throw Error(`bad point: equation left != right`);if(!e.isTorsionFree())throw Error(`bad point: not in prime-order subgroup`);return!0});function te(e,t,n,i,a){return n=new C(r.mul(n.X,e),n.Y,n.Z),t=_o(i,t),n=_o(a,n),t.add(n)}class C{constructor(e,t,n){this.X=y(`x`,e),this.Y=y(`y`,t,!0),this.Z=y(`z`,n),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){let{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error(`invalid affine point`);if(e instanceof C)throw Error(`projective point not allowed`);return r.is0(t)&&r.is0(n)?C.ZERO:new C(t,n,r.ONE)}static fromBytes(e){let t=C.fromAffine(m(wa(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return C.fromBytes(H(`pointHex`,e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return re.createCache(this,e),t||this.multiply(Jo),this}assertValidity(){S(this)}hasEvenY(){let{y:e}=this.toAffine();if(!r.isOdd)throw Error(`Field doesn't support isOdd`);return!r.isOdd(e)}equals(e){b(e);let{X:t,Y:n,Z:i}=this,{X:a,Y:o,Z:s}=e,c=r.eql(r.mul(t,s),r.mul(a,i)),l=r.eql(r.mul(n,s),r.mul(o,i));return c&&l}negate(){return new C(this.X,r.neg(this.Y),this.Z)}double(){let{a:e,b:t}=a,n=r.mul(t,Jo),{X:i,Y:o,Z:s}=this,c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),f=r.mul(o,o),p=r.mul(s,s),m=r.mul(i,o);return m=r.add(m,m),u=r.mul(i,s),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,p),l=r.add(c,l),c=r.sub(f,l),l=r.add(f,l),l=r.mul(c,l),c=r.mul(m,c),u=r.mul(n,u),p=r.mul(e,p),m=r.sub(d,p),m=r.mul(e,m),m=r.add(m,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,p),d=r.mul(d,m),l=r.add(l,d),p=r.mul(o,s),p=r.add(p,p),d=r.mul(p,m),c=r.sub(c,d),u=r.mul(p,f),u=r.add(u,u),u=r.add(u,u),new C(c,l,u)}add(e){b(e);let{X:t,Y:n,Z:i}=this,{X:o,Y:s,Z:c}=e,l=r.ZERO,u=r.ZERO,d=r.ZERO,f=a.a,p=r.mul(a.b,Jo),m=r.mul(t,o),h=r.mul(n,s),g=r.mul(i,c),_=r.add(t,n),v=r.add(o,s);_=r.mul(_,v),v=r.add(m,h),_=r.sub(_,v),v=r.add(t,i);let y=r.add(o,c);return v=r.mul(v,y),y=r.add(m,g),v=r.sub(v,y),y=r.add(n,i),l=r.add(s,c),y=r.mul(y,l),l=r.add(h,g),y=r.sub(y,l),d=r.mul(f,v),l=r.mul(p,g),d=r.add(l,d),l=r.sub(h,d),d=r.add(h,d),u=r.mul(l,d),h=r.add(m,m),h=r.add(h,m),g=r.mul(f,g),v=r.mul(p,v),h=r.add(h,g),g=r.sub(m,g),g=r.mul(f,g),v=r.add(v,g),m=r.mul(h,v),u=r.add(u,m),m=r.mul(y,v),l=r.mul(_,l),l=r.sub(l,m),m=r.mul(_,h),d=r.mul(y,d),d=r.add(d,m),new C(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(C.ZERO)}multiply(e){let{endo:n}=t;if(!i.isValidNot0(e))throw Error(`invalid scalar: out of range`);let r,a,o=e=>re.cached(this,e,e=>vo(C,e));if(n){let{k1neg:t,k1:i,k2neg:s,k2:c}=x(e),{p:l,f:u}=o(i),{p:d,f}=o(c);a=u.add(f),r=te(n.beta,l,d,t,s)}else{let{p:t,f:n}=o(e);r=t,a=n}return vo(C,[r,a])[0]}multiplyUnsafe(e){let{endo:n}=t,r=this;if(!i.isValid(e))throw Error(`invalid scalar: out of range`);if(e===Ko||r.is0())return C.ZERO;if(e===K)return r;if(re.hasCache(this))return this.multiply(e);if(n){let{k1neg:t,k1:i,k2neg:a,k2:o}=x(e),{p1:s,p2:c}=ko(C,r,i,o);return te(n.beta,s,c,t,a)}return re.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){let r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return ee(this,e)}isTorsionFree(){let{isTorsionFree:e}=t;return o===K?!0:e?e(C,this):re.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:e}=t;return o===K?this:e?e(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Ca(e,`isCompressed`),this.assertValidity(),p(C,this,e)}toHex(e=!0){return w(this.toBytes(e))}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return vo(C,e)}static msm(e,t){return Ao(C,i,e,t)}static fromPrivateKey(e){return C.BASE.multiply(Xo(i,e))}}C.BASE=new C(a.Gx,a.Gy,r.ONE),C.ZERO=new C(r.ZERO,r.ONE,r.ZERO),C.Fp=r,C.Fn=i;let ne=i.BITS,re=new Oo(C,t.endo?Math.ceil(ne/2):ne);return C.BASE.precompute(8),C}function Qo(e){return Uint8Array.of(e?2:3)}function $o(e,t){let n=e.ORDER,r=Ko;for(let e=n-K;e%qo===Ko;e/=qo)r+=K;let i=r,a=qo<<i-K-K,o=a*qo,s=(n-K)/o,c=(s-K)/qo,l=o-K,u=a,d=e.pow(t,s),f=e.pow(t,(s+K)/qo),p=(t,n)=>{let r=d,a=e.pow(n,l),o=e.sqr(a);o=e.mul(o,n);let s=e.mul(t,o);s=e.pow(s,c),s=e.mul(s,a),a=e.mul(s,n),o=e.mul(s,t);let p=e.mul(o,a);s=e.pow(p,u);let m=e.eql(s,e.ONE);a=e.mul(o,f),s=e.mul(p,r),o=e.cmov(a,o,m),p=e.cmov(s,p,m);for(let t=i;t>K;t--){let n=t-qo;n=qo<<n-K;let i=e.pow(p,n),s=e.eql(i,e.ONE);a=e.mul(o,r),r=e.mul(r,r),i=e.mul(p,r),o=e.cmov(a,o,s),p=e.cmov(i,p,s)}return{isValid:m,value:o}};if(e.ORDER%Yo===Jo){let n=(e.ORDER-Jo)/Yo,r=e.sqrt(e.neg(t));p=(t,i)=>{let a=e.sqr(i),o=e.mul(t,i);a=e.mul(a,o);let s=e.pow(a,n);s=e.mul(s,o);let c=e.mul(s,r),l=e.mul(e.sqr(s),i),u=e.eql(l,t);return{isValid:u,value:e.cmov(c,s,u)}}}return p}function es(e,t){ao(e);let{A:n,B:r,Z:i}=t;if(!e.isValid(n)||!e.isValid(r)||!e.isValid(i))throw Error(`mapToCurveSimpleSWU: invalid opts`);let a=$o(e,i);if(!e.isOdd)throw Error(`Field does not have .isOdd()`);return t=>{let o,s,c,l,u,d,f,p;o=e.sqr(t),o=e.mul(o,i),s=e.sqr(o),s=e.add(s,o),c=e.add(s,e.ONE),c=e.mul(c,r),l=e.cmov(i,e.neg(s),!e.eql(s,e.ZERO)),l=e.mul(l,n),s=e.sqr(c),d=e.sqr(l),u=e.mul(d,n),s=e.add(s,u),s=e.mul(s,c),d=e.mul(d,l),u=e.mul(d,r),s=e.add(s,u),f=e.mul(o,c);let{isValid:m,value:h}=a(s,d);p=e.mul(o,t),p=e.mul(p,h),f=e.cmov(f,c,m),p=e.cmov(p,h,m);let g=e.isOdd(t)===e.isOdd(p);p=e.cmov(e.neg(p),p,g);let _=so(e,[l],!0)[0];return f=e.mul(f,_),{x:f,y:p}}}function ts(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function ns(e){let{CURVE:t,curveOpts:n}=rs(e);return as(e,Zo(t,n))}function rs(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:uo(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}function is(e,t,n){function r(r){let i=e.sqr(r),a=e.mul(i,r);return e.add(e.add(a,e.mul(r,t)),n)}return r}function as(e,t){let{Fp:n,Fn:r}=t;function i(e){return Ma(e,K,r.ORDER)}let a=is(n,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:e=>Xo(r,e),weierstrassEquation:a,isWithinCurveOrder:i})}var os=BigInt(0),ss=BigInt(1),cs=BigInt(2),ls=BigInt(3);function us(e){let t=[];for(;e>ss;e>>=ss)(e&ss)===os?t.unshift(0):(e&ls)===ls?(t.unshift(-1),e+=ss):t.unshift(1);return t}function ds(e){if(!Array.isArray(e)||e.length===0)throw Error(`expected non-empty array`)}function fs(e,t,n,r){let{Fp2:i,Fp12:a}=e,{twistType:o,ateLoopSize:s,xNegative:c,postPrecompute:l}=r,u;if(o===`multiplicative`)u=(e,t,n,r,o,s)=>a.mul014(r,e,i.mul(t,o),i.mul(n,s));else if(o===`divisive`)u=(e,t,n,r,o,s)=>a.mul034(r,i.mul(n,s),i.mul(t,o),e);else throw Error(`bls: unknown twist type`);let d=i.div(i.ONE,i.mul(i.ONE,cs));function f(e,t,n,r){let a=i.sqr(n),o=i.sqr(r),s=i.mulByB(i.mul(o,ls)),c=i.mul(s,ls),l=i.sub(i.sub(i.sqr(i.add(n,r)),o),a),u=i.sub(s,a),f=i.mul(i.sqr(t),ls),p=i.neg(l);return e.push([u,f,p]),t=i.mul(i.mul(i.mul(i.sub(a,c),t),n),d),n=i.sub(i.sqr(i.mul(i.add(a,c),d)),i.mul(i.sqr(s),ls)),r=i.mul(a,l),{Rx:t,Ry:n,Rz:r}}function p(e,t,n,r,a,o){let s=i.sub(n,i.mul(o,r)),c=i.sub(t,i.mul(a,r)),l=i.sub(i.mul(s,a),i.mul(c,o)),u=i.neg(s),d=c;e.push([l,u,d]);let f=i.sqr(c),p=i.mul(f,c),m=i.mul(f,t),h=i.add(i.sub(p,i.mul(m,cs)),i.mul(i.sqr(s),r));return t=i.mul(c,h),n=i.sub(i.mul(i.sub(m,h),s),i.mul(p,n)),r=i.mul(r,p),{Rx:t,Ry:n,Rz:r}}let m=us(s),h=Ba(e=>{let{x:t,y:n}=e.toAffine(),r=t,a=n,o=i.neg(n),s=r,c=a,u=i.ONE,d=[];for(let e of m){let t=[];({Rx:s,Ry:c,Rz:u}=f(t,s,c,u)),e&&({Rx:s,Ry:c,Rz:u}=p(t,s,c,u,r,e===-1?o:a)),d.push(t)}if(l){let e=d[d.length-1];l(s,c,u,r,a,p.bind(null,e))}return d});function g(e,t=!1){let n=a.ONE;if(e.length){let t=e[0][0].length;for(let r=0;r<t;r++){n=a.sqr(n);for(let[t,i,a]of e)for(let[e,o,s]of t[r])n=u(e,o,s,n,i,a)}}return c&&(n=a.conjugate(n)),t?a.finalExponentiate(n):n}function _(e,r=!0){let i=[];vo(t,e.map(({g1:e})=>e)),vo(n,e.map(({g2:e})=>e));for(let{g1:t,g2:n}of e){if(t.is0()||n.is0())throw Error(`pairing is not available for ZERO point`);t.assertValidity(),n.assertValidity();let e=t.toAffine();i.push([h(n),e.x,e.y])}return g(i,r)}function v(e,t,n=!0){return _([{g1:e,g2:t}],n)}return{Fp12:a,millerLoopBatch:g,pairing:v,pairingBatch:_,calcPairingPrecomputes:h}}function ps(e,t,n,r,i){let{Fp12:a,pairingBatch:o}=e;function s(e){return e instanceof t.Point?e:t.Point.fromHex(e)}function c(e){return e instanceof n.Point?e:n.Point.fromHex(e)}function l(e){if(!(e instanceof n.Point))throw Error(`expected valid message hashed to ${i?`G1`:`G2`} curve`);return e}let u=i?(e,t)=>({g1:t,g2:e}):(e,t)=>({g1:e,g2:t});return{getPublicKey(e){let n=Xo(t.Point.Fn,e);return t.Point.BASE.multiply(n)},sign(e,n,r){if(r!=null)throw Error(`sign() expects 2 arguments`);let i=Xo(t.Point.Fn,n);return l(e).assertValidity(),e.multiply(i)},verify(e,n,r,i){if(i!=null)throw Error(`verify() expects 3 arguments`);e=c(e),r=s(r);let d=r.negate(),f=t.Point.BASE,p=l(n),m=e,h=o([u(d,p),u(f,m)]);return a.eql(h,a.ONE)},verifyBatch(e,n,r){if(ds(n),r.length!==n.length)throw Error(`amount of public keys and messages should be equal`);let i=c(e),l=n,d=r.map(s),f=new Map;for(let e=0;e<d.length;e++){let t=d[e],n=l[e],r=f.get(n);r===void 0&&(r=[],f.set(n,r)),r.push(t)}let p=[],m=t.Point.BASE;try{for(let[e,t]of f){let n=t.reduce((e,t)=>e.add(t));p.push(u(n,e))}return p.push(u(m.negate(),i)),a.eql(o(p),a.ONE)}catch{return!1}},aggregatePublicKeys(e){ds(e),e=e.map(e=>s(e));let n=e.reduce((e,t)=>e.add(t),t.Point.ZERO);return n.assertValidity(),n},aggregateSignatures(e){ds(e),e=e.map(e=>c(e));let t=e.reduce((e,t)=>e.add(t),n.Point.ZERO);return t.assertValidity(),t},hash(e,t){v(e);let r=t?{DST:t}:void 0;return n.hashToCurve(e,r)},Signature:r}}function ms(e){let{Fp:t,Fr:n,Fp2:r,Fp6:i,Fp12:a}=e.fields,o=ns(e.G1),s=Object.assign(o,Uo(o.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=ns(e.G2),l=Object.assign(c,Uo(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),u=fs(e.fields,s.Point,l.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:d,pairing:f,pairingBatch:p,calcPairingPrecomputes:m}=u,h=ps(u,s,l,e.G2.Signature,!1),g=ps(u,l,s,e.G1.ShortSignature,!0),_=e.randomBytes||ce,v=()=>{let e=po(n.ORDER);return mo(_(e),n.ORDER)},y={randomSecretKey:v,randomPrivateKey:v,calcPairingPrecomputes:m},{ShortSignature:b}=e.G1,{Signature:x}=e.G2;function ee(e,t){return e instanceof s.Point?e:g.hash(H(`point`,e),t?.DST)}function S(e,t){return e instanceof l.Point?e:h.hash(H(`point`,e),t?.DST)}function te(e){return h.getPublicKey(e).toBytes(!0)}function C(e){return g.getPublicKey(e).toBytes(!0)}function w(e,t,n){let r=S(e,n),i=h.sign(r,t);return e instanceof l.Point?i:x.toBytes(i)}function ne(e,t,n){let r=ee(e,n),i=g.sign(r,t);return e instanceof s.Point?i:b.toBytes(i)}function re(e,t,n,r){let i=S(t,r);return h.verify(e,i,n)}function ie(e,t,n,r){let i=ee(t,r);return g.verify(e,i,n)}function T(e){let t=h.aggregatePublicKeys(e);return e[0]instanceof s.Point?t:t.toBytes(!0)}function ae(e){let t=h.aggregateSignatures(e);return e[0]instanceof l.Point?t:x.toBytes(t)}function E(e){let t=g.aggregateSignatures(e);return e[0]instanceof s.Point?t:b.toBytes(t)}function oe(e,t,n,r){let i=t.map(e=>S(e,r));return h.verifyBatch(e,i,n)}return s.Point.BASE.precompute(4),{longSignatures:h,shortSignatures:g,millerLoopBatch:d,pairing:f,pairingBatch:p,verifyBatch:oe,fields:{Fr:n,Fp:t,Fp2:r,Fp6:i,Fp12:a},params:{ateLoopSize:e.params.ateLoopSize,twistType:e.params.twistType,r:e.params.r,G1b:e.G1.b,G2b:e.G2.b},utils:y,getPublicKey:te,getPublicKeyForShortSignatures:C,sign:w,signShortSignature:ne,verify:re,verifyShortSignature:ie,aggregatePublicKeys:T,aggregateSignatures:ae,aggregateShortSignatures:E,G1:s,G2:l,Signature:x,ShortSignature:b}}var hs=BigInt(0),gs=BigInt(1),_s=BigInt(2),vs=BigInt(3);function ys(e,t,n,r,i=1,a){let o=BigInt(a===void 0?r:a),s=n**BigInt(r),c=[];for(let a=0;a<i;a++){let i=BigInt(a+1),l=[];for(let a=0,c=gs;a<r;a++){let r=(i*c-i)/o%s;l.push(e.pow(t,r)),c*=n}c.push(l)}return c}function bs(e,t,n){let r=t.pow(n,(e.ORDER-gs)/vs),i=t.pow(n,(e.ORDER-gs)/_s);function a(e,n){return[t.mul(t.frobeniusMap(e,1),r),t.mul(t.frobeniusMap(n,1),i)]}let o=t.pow(n,(e.ORDER**_s-gs)/vs),s=t.pow(n,(e.ORDER**_s-gs)/_s);if(!t.eql(s,t.neg(t.ONE)))throw Error(`psiFrobenius: PSI2_Y!==-1`);function c(e,n){return[t.mul(e,o),t.neg(n)]}let l=e=>(t,n)=>{let r=n.toAffine(),i=e(r.x,r.y);return t.fromAffine({x:i[0],y:i[1]})};return{psi:a,psi2:c,G2psi:l(a),G2psi2:l(c),PSI_X:r,PSI_Y:i,PSI2_X:o,PSI2_Y:s}}var xs=(e,t)=>{if(t.length!==2)throw Error(`invalid tuple`);let n=t.map(t=>e.create(t));return{c0:n[0],c1:n[1]}},Ss=class{constructor(e,t={}){this.MASK=gs;let n=e.ORDER,r=n*n;this.Fp=e,this.ORDER=r,this.BITS=Pa(r),this.BYTES=Math.ceil(Pa(r)/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,_s),this.NONRESIDUE=xs(e,t.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=ys(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=t.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return xs(this.Fp,e)}create(e){return e}isValid({c0:e,c1:t}){function n(e,t){return typeof e==`bigint`&&hs<=e&&e<t}return n(e,this.ORDER)&&n(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:n,c1:r}){return this.Fp.eql(e,n)&&this.Fp.eql(t,r)}neg({c0:e,c1:t}){return{c0:this.Fp.neg(e),c1:this.Fp.neg(t)}}pow(e,t){return oo(this,e,t)}invertBatch(e){return so(this,e)}add(e,t){let{c0:n,c1:r}=e,{c0:i,c1:a}=t;return{c0:this.Fp.add(n,i),c1:this.Fp.add(r,a)}}sub({c0:e,c1:t},{c0:n,c1:r}){return{c0:this.Fp.sub(e,n),c1:this.Fp.sub(t,r)}}mul({c0:e,c1:t},n){let{Fp:r}=this;if(typeof n==`bigint`)return{c0:r.mul(e,n),c1:r.mul(t,n)};let{c0:i,c1:a}=n,o=r.mul(e,i),s=r.mul(t,a);return{c0:r.sub(o,s),c1:r.sub(r.mul(r.add(e,t),r.add(i,a)),r.add(o,s))}}sqr({c0:e,c1:t}){let{Fp:n}=this,r=n.add(e,t),i=n.sub(e,t),a=n.add(e,e);return{c0:n.mul(r,i),c1:n.mul(a,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:n}=this;return this.mul(e,typeof t==`bigint`?n.inv(n.create(t)):this.inv(t))}inv({c0:e,c1:t}){let{Fp:n}=this,r=n.inv(n.create(e*e+t*t));return{c0:n.mul(r,n.create(e)),c1:n.mul(r,n.create(-t))}}sqrt(e){let{Fp:t}=this,n=this,{c0:r,c1:i}=e;if(t.is0(i))return co(t,r)===1?n.create({c0:t.sqrt(r),c1:t.ZERO}):n.create({c0:t.ZERO,c1:t.sqrt(t.div(r,this.Fp_NONRESIDUE))});let a=t.sqrt(t.sub(t.sqr(r),t.mul(t.sqr(i),this.Fp_NONRESIDUE))),o=t.mul(t.add(a,r),this.Fp_div2);co(t,o)===-1&&(o=t.sub(o,a));let s=t.sqrt(o),c=n.create({c0:s,c1:t.div(t.mul(i,this.Fp_div2),s)});if(!n.eql(n.sqr(c),e))throw Error(`Cannot find square root`);let l=c,u=n.neg(l),{re:d,im:f}=n.reim(l),{re:p,im:m}=n.reim(u);return f>m||f===m&&d>p?l:u}isOdd(e){let{re:t,im:n}=this.reim(e),r=t%_s,i=t===hs,a=n%_s;return BigInt(r||i&&a)==gs}fromBytes(e){let{Fp:t}=this;if(e.length!==this.BYTES)throw 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 E(this.Fp.toBytes(e),this.Fp.toBytes(t))}cmov({c0:e,c1:t},{c0:n,c1:r},i){return{c0:this.Fp.cmov(e,n,i),c1:this.Fp.cmov(t,r,i)}}reim({c0:e,c1:t}){return{re:e,im:t}}Fp4Square(e,t){let n=this,r=n.sqr(e),i=n.sqr(t);return{first:n.add(n.mulByNonresidue(i),r),second:n.sub(n.sub(n.sqr(n.add(e,t)),r),i)}}mulByNonresidue({c0:e,c1:t}){return this.mul({c0:e,c1:t},this.NONRESIDUE)}frobeniusMap({c0:e,c1:t},n){return{c0:e,c1:this.Fp.mul(t,this.FROBENIUS_COEFFICIENTS[n%2])}}},Cs=class{constructor(e){this.MASK=gs,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,n=ys(e,e.NONRESIDUE,t.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=n[0],this.FROBENIUS_COEFFICIENTS_2=n[1],Object.seal(this)}add({c0:e,c1:t,c2:n},{c0:r,c1:i,c2:a}){let{Fp2:o}=this;return{c0:o.add(e,r),c1:o.add(t,i),c2:o.add(n,a)}}sub({c0:e,c1:t,c2:n},{c0:r,c1:i,c2:a}){let{Fp2:o}=this;return{c0:o.sub(e,r),c1:o.sub(t,i),c2:o.sub(n,a)}}mul({c0:e,c1:t,c2:n},r){let{Fp2:i}=this;if(typeof r==`bigint`)return{c0:i.mul(e,r),c1:i.mul(t,r),c2:i.mul(n,r)};let{c0:a,c1:o,c2:s}=r,c=i.mul(e,a),l=i.mul(t,o),u=i.mul(n,s);return{c0:i.add(c,i.mulByNonresidue(i.sub(i.mul(i.add(t,n),i.add(o,s)),i.add(l,u)))),c1:i.add(i.sub(i.mul(i.add(e,t),i.add(a,o)),i.add(c,l)),i.mulByNonresidue(u)),c2:i.sub(i.add(l,i.mul(i.add(e,n),i.add(a,s))),i.add(c,u))}}sqr({c0:e,c1:t,c2:n}){let{Fp2:r}=this,i=r.sqr(e),a=r.mul(r.mul(e,t),_s),o=r.mul(r.mul(t,n),_s),s=r.sqr(n);return{c0:r.add(r.mulByNonresidue(o),i),c1:r.add(r.mulByNonresidue(s),a),c2:r.sub(r.sub(r.add(r.add(a,r.sqr(r.add(r.sub(e,t),n))),o),i),s)}}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:n}){let{Fp2:r}=this;return r.isValid(e)&&r.isValid(t)&&r.isValid(n)}is0({c0:e,c1:t,c2:n}){let{Fp2:r}=this;return r.is0(e)&&r.is0(t)&&r.is0(n)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:t,c2:n}){let{Fp2:r}=this;return{c0:r.neg(e),c1:r.neg(t),c2:r.neg(n)}}eql({c0:e,c1:t,c2:n},{c0:r,c1:i,c2:a}){let{Fp2:o}=this;return o.eql(e,r)&&o.eql(t,i)&&o.eql(n,a)}sqrt(e){return za()}div(e,t){let{Fp2:n}=this,{Fp:r}=n;return this.mul(e,typeof t==`bigint`?r.inv(r.create(t)):this.inv(t))}pow(e,t){return oo(this,e,t)}invertBatch(e){return so(this,e)}inv({c0:e,c1:t,c2:n}){let{Fp2:r}=this,i=r.sub(r.sqr(e),r.mulByNonresidue(r.mul(n,t))),a=r.sub(r.mulByNonresidue(r.sqr(n)),r.mul(e,t)),o=r.sub(r.sqr(t),r.mul(e,n)),s=r.inv(r.add(r.mulByNonresidue(r.add(r.mul(n,a),r.mul(t,o))),r.mul(e,i)));return{c0:r.mul(s,i),c1:r.mul(s,a),c2:r.mul(s,o)}}fromBytes(e){let{Fp2:t}=this;if(e.length!==this.BYTES)throw Error(`fromBytes invalid length=`+e.length);let n=t.BYTES;return{c0:t.fromBytes(e.subarray(0,n)),c1:t.fromBytes(e.subarray(n,n*2)),c2:t.fromBytes(e.subarray(2*n))}}toBytes({c0:e,c1:t,c2:n}){let{Fp2:r}=this;return E(r.toBytes(e),r.toBytes(t),r.toBytes(n))}cmov({c0:e,c1:t,c2:n},{c0:r,c1:i,c2:a},o){let{Fp2:s}=this;return{c0:s.cmov(e,r,o),c1:s.cmov(t,i,o),c2:s.cmov(n,a,o)}}fromBigSix(e){let{Fp2:t}=this;if(!Array.isArray(e)||e.length!==6)throw 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:n},r){let{Fp2:i}=this;return{c0:i.frobeniusMap(e,r),c1:i.mul(i.frobeniusMap(t,r),this.FROBENIUS_COEFFICIENTS_1[r%6]),c2:i.mul(i.frobeniusMap(n,r),this.FROBENIUS_COEFFICIENTS_2[r%6])}}mulByFp2({c0:e,c1:t,c2:n},r){let{Fp2:i}=this;return{c0:i.mul(e,r),c1:i.mul(t,r),c2:i.mul(n,r)}}mulByNonresidue({c0:e,c1:t,c2:n}){let{Fp2:r}=this;return{c0:r.mulByNonresidue(n),c1:e,c2:t}}mul1({c0:e,c1:t,c2:n},r){let{Fp2:i}=this;return{c0:i.mulByNonresidue(i.mul(n,r)),c1:i.mul(e,r),c2:i.mul(t,r)}}mul01({c0:e,c1:t,c2:n},r,i){let{Fp2:a}=this,o=a.mul(e,r),s=a.mul(t,i);return{c0:a.add(a.mulByNonresidue(a.sub(a.mul(a.add(t,n),i),s)),o),c1:a.sub(a.sub(a.mul(a.add(r,i),a.add(e,t)),o),s),c2:a.add(a.sub(a.mul(a.add(e,n),r),o),s)}}},ws=class{constructor(e,t){this.MASK=gs;let{Fp2:n}=e,{Fp:r}=n;this.Fp6=e,this.ORDER=n.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=ys(n,n.NONRESIDUE,r.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:n}=this;return n.isValid(e)&&n.isValid(t)}is0({c0:e,c1:t}){let{Fp6:n}=this;return n.is0(e)&&n.is0(t)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:t}){let{Fp6:n}=this;return{c0:n.neg(e),c1:n.neg(t)}}eql({c0:e,c1:t},{c0:n,c1:r}){let{Fp6:i}=this;return i.eql(e,n)&&i.eql(t,r)}sqrt(e){za()}inv({c0:e,c1:t}){let{Fp6:n}=this,r=n.inv(n.sub(n.sqr(e),n.mulByNonresidue(n.sqr(t))));return{c0:n.mul(e,r),c1:n.neg(n.mul(t,r))}}div(e,t){let{Fp6:n}=this,{Fp2:r}=n,{Fp:i}=r;return this.mul(e,typeof t==`bigint`?i.inv(i.create(t)):this.inv(t))}pow(e,t){return oo(this,e,t)}invertBatch(e){return so(this,e)}add({c0:e,c1:t},{c0:n,c1:r}){let{Fp6:i}=this;return{c0:i.add(e,n),c1:i.add(t,r)}}sub({c0:e,c1:t},{c0:n,c1:r}){let{Fp6:i}=this;return{c0:i.sub(e,n),c1:i.sub(t,r)}}mul({c0:e,c1:t},n){let{Fp6:r}=this;if(typeof n==`bigint`)return{c0:r.mul(e,n),c1:r.mul(t,n)};let{c0:i,c1:a}=n,o=r.mul(e,i),s=r.mul(t,a);return{c0:r.add(o,r.mulByNonresidue(s)),c1:r.sub(r.mul(r.add(e,t),r.add(i,a)),r.add(o,s))}}sqr({c0:e,c1:t}){let{Fp6:n}=this,r=n.mul(e,t);return{c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(t),e),n.add(e,t)),r),n.mulByNonresidue(r)),c1:n.add(r,r)}}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 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:n}=this;return E(n.toBytes(e),n.toBytes(t))}cmov({c0:e,c1:t},{c0:n,c1:r},i){let{Fp6:a}=this;return{c0:a.cmov(e,n,i),c1:a.cmov(t,r,i)}}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:n}=this,{Fp2:r}=n,{c0:i,c1:a,c2:o}=n.frobeniusMap(e.c1,t),s=this.FROBENIUS_COEFFICIENTS[t%12];return{c0:n.frobeniusMap(e.c0,t),c1:n.create({c0:r.mul(i,s),c1:r.mul(a,s),c2:r.mul(o,s)})}}mulByFp2({c0:e,c1:t},n){let{Fp6:r}=this;return{c0:r.mulByFp2(e,n),c1:r.mulByFp2(t,n)}}conjugate({c0:e,c1:t}){return{c0:e,c1:this.Fp6.neg(t)}}mul014({c0:e,c1:t},n,r,i){let{Fp6:a}=this,{Fp2:o}=a,s=a.mul01(e,n,r),c=a.mul1(t,i);return{c0:a.add(a.mulByNonresidue(c),s),c1:a.sub(a.sub(a.mul01(a.add(t,e),n,o.add(r,i)),s),c)}}mul034({c0:e,c1:t},n,r,i){let{Fp6:a}=this,{Fp2:o}=a,s=a.create({c0:o.mul(e.c0,n),c1:o.mul(e.c1,n),c2:o.mul(e.c2,n)}),c=a.mul01(t,r,i),l=a.mul01(a.add(e,t),o.add(n,r),i);return{c0:a.add(a.mulByNonresidue(c),s),c1:a.sub(l,a.add(s,c))}}_cyclotomicSquare({c0:e,c1:t}){let{Fp6:n}=this,{Fp2:r}=n,{c0:i,c1:a,c2:o}=e,{c0:s,c1:c,c2:l}=t,{first:u,second:d}=r.Fp4Square(i,c),{first:f,second:p}=r.Fp4Square(s,o),{first:m,second:h}=r.Fp4Square(a,l),g=r.mulByNonresidue(h);return{c0:n.create({c0:r.add(r.mul(r.sub(u,i),_s),u),c1:r.add(r.mul(r.sub(f,a),_s),f),c2:r.add(r.mul(r.sub(m,o),_s),m)}),c1:n.create({c0:r.add(r.mul(r.add(g,s),_s),g),c1:r.add(r.mul(r.add(d,c),_s),d),c2:r.add(r.mul(r.add(p,l),_s),p)})}}_cyclotomicExp(e,t){let n=this.ONE;for(let r=this.X_LEN-1;r>=0;r--)n=this._cyclotomicSquare(n),Fa(t,r)&&(n=this.mul(n,e));return n}};function Ts(e){let t=uo(e.ORDER),n=new Ss(t,e),r=new Cs(n);return{Fp:t,Fp2:n,Fp6:r,Fp12:new ws(r,e)}}var q=BigInt(0),Es=BigInt(1),Ds=BigInt(2),Os=BigInt(3),ks=BigInt(4),As=BigInt(`0xd201000000010000`),js=Pa(As),Ms={p:BigInt(`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab`),n:BigInt(`0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001`),h:BigInt(`0x396c8c005555e1568c00aaab0000aaab`),a:q,b:ks,Gx:BigInt(`0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb`),Gy:BigInt(`0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1`)},Ns=uo(Ms.n,{modFromBytes:!0,isLE:!0}),{Fp:J,Fp2:Y,Fp6:Ps,Fp12:X}=Ts({ORDER:Ms.p,X_LEN:js,FP2_NONRESIDUE:[Es,Es],Fp2mulByB:({c0:e,c1:t})=>{let n=J.mul(e,ks),r=J.mul(t,ks);return{c0:J.sub(n,r),c1:J.add(n,r)}},Fp12finalExponentiate:e=>{let t=As,n=X.div(X.frobeniusMap(e,6),e),r=X.mul(X.frobeniusMap(n,2),n),i=X.conjugate(X._cyclotomicExp(r,t)),a=X.mul(X.conjugate(X._cyclotomicSquare(r)),i),o=X.conjugate(X._cyclotomicExp(a,t)),s=X.conjugate(X._cyclotomicExp(o,t)),c=X.mul(X.conjugate(X._cyclotomicExp(s,t)),X._cyclotomicSquare(i)),l=X.conjugate(X._cyclotomicExp(c,t)),u=X.frobeniusMap(X.mul(i,s),2),d=X.frobeniusMap(X.mul(o,r),3),f=X.frobeniusMap(X.mul(c,X.conjugate(r)),1),p=X.mul(X.mul(l,X.conjugate(a)),r);return X.mul(X.mul(X.mul(u,d),f),p)}}),{G2psi:Fs,G2psi2:Is}=bs(J,Y,Y.div(Y.ONE,Y.NONRESIDUE)),Ls=Object.freeze({DST:`BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_`,encodeDST:`BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_`,p:J.ORDER,m:2,k:128,expand:`xmd`,hash:He}),Rs={p:Y.ORDER,n:Ms.n,h:BigInt(`0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5`),a:Y.ZERO,b:Y.fromBigTuple([ks,ks]),Gx:Y.fromBigTuple([BigInt(`0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8`),BigInt(`0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e`)]),Gy:Y.fromBigTuple([BigInt(`0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801`),BigInt(`0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be`)])},zs=Vs(J.toBytes(q),{infinity:!0,compressed:!0});function Bs(e){e=e.slice();let t=e[0]&224,n=!!(t>>7&1),r=!!(t>>6&1),i=!!(t>>5&1);return e[0]&=31,{compressed:n,infinity:r,sort:i,value:e}}function Vs(e,t){if(e[0]&224)throw Error(`setMask: non-empty mask`);return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function Hs(e,t,n){let{BYTES:r,ORDER:i}=J,a=t.is0(),{x:o,y:s}=t.toAffine();if(n){if(a)return zs.slice();let e=!!(s*Ds/i);return Vs(V(o,r),{compressed:!0,sort:e})}return a?E(Uint8Array.of(64),new Uint8Array(2*r-1)):E(V(o,r),V(s,r))}function Us(e){e.assertValidity();let{BYTES:t,ORDER:n}=J,{x:r,y:i}=e.toAffine();if(e.is0())return zs.slice();let a=!!(i*Ds/n);return Vs(V(r,t),{compressed:!0,sort:a})}function Ws(e){let{compressed:t,infinity:n,sort:r,value:i}=Bs(e),{BYTES:a,ORDER:o}=J;if(i.length===48&&t){let e=Ea(i),t=J.create(e&Ia(J.BITS));if(n){if(t!==q)throw Error(`invalid G1 point: non-empty, at infinity, with compression`);return{x:q,y:q}}let a=J.add(J.pow(t,Os),J.create(Ms.b)),s=J.sqrt(a);if(!s)throw Error(`invalid G1 point: compressed point`);return s*Ds/o!==BigInt(r)&&(s=J.neg(s)),{x:J.create(t),y:J.create(s)}}if(i.length===96&&!t){let e=Ea(i.subarray(0,a)),t=Ea(i.subarray(a));if(n){if(e!==q||t!==q)throw Error(`G1: non-empty point at infinity`);return Xs.G1.Point.ZERO.toAffine()}return{x:J.create(e),y:J.create(t)}}throw Error(`invalid G1 point: expected 48/96 bytes`)}function Gs(e){let{infinity:t,sort:n,value:r}=Bs(H(`signatureHex`,e,48)),i=J.ORDER,a=Xs.G1.Point,o=Ea(r);if(t)return a.ZERO;let s=J.create(o&Ia(J.BITS)),c=J.add(J.pow(s,Os),J.create(Ms.b)),l=J.sqrt(c);if(!l)throw Error(`invalid G1 point: compressed`);let u=BigInt(n);l*Ds/i!==u&&(l=J.neg(l));let d=a.fromAffine({x:s,y:l});return d.assertValidity(),d}function Ks(e,t,n){let{BYTES:r,ORDER:i}=J,a=t.is0(),{x:o,y:s}=t.toAffine();if(n){if(a)return E(zs,V(q,r));let e=!!(s.c1===q?s.c0*Ds/i:s.c1*Ds/i);return E(Vs(V(o.c1,r),{compressed:!0,sort:e}),V(o.c0,r))}{if(a)return E(Uint8Array.of(64),new Uint8Array(4*r-1));let{re:e,im:t}=Y.reim(o),{re:n,im:i}=Y.reim(s);return E(V(t,r),V(e,r),V(i,r),V(n,r))}}function qs(e){e.assertValidity();let{BYTES:t}=J;if(e.is0())return E(zs,V(q,t));let{x:n,y:r}=e.toAffine(),{re:i,im:a}=Y.reim(n),{re:o,im:s}=Y.reim(r),c=!!((s>q?s*Ds:o*Ds)/J.ORDER&Es),l=i;return E(Vs(V(a,t),{sort:c,compressed:!0}),V(l,t))}function Js(e){let{BYTES:t,ORDER:n}=J,{compressed:r,infinity:i,sort:a,value:o}=Bs(e);if(!r&&!i&&a||!r&&i&&a||a&&i&&r)throw Error(`invalid encoding flag: `+(e[0]&224));let s=(e,t,n)=>Ea(e.slice(t,n));if(o.length===96&&r){if(i){if(o.reduce((e,t)=>e===0?t:t+1,0)>0)throw Error(`invalid G2 point: compressed`);return{x:Y.ZERO,y:Y.ZERO}}let e=s(o,0,t),r=s(o,t,2*t),c=Y.create({c0:J.create(r),c1:J.create(e)}),l=Y.add(Y.pow(c,Os),Rs.b),u=Y.sqrt(l),d=u.c1===q?u.c0*Ds/n:u.c1*Ds/n?Es:q;return u=a&&d>0?u:Y.neg(u),{x:c,y:u}}if(o.length===192&&!r){if(i){if(o.reduce((e,t)=>e===0?t:t+1,0)>0)throw Error(`invalid G2 point: uncompressed`);return{x:Y.ZERO,y:Y.ZERO}}let e=s(o,0*t,1*t),n=s(o,1*t,2*t),r=s(o,2*t,3*t),a=s(o,3*t,4*t);return{x:Y.fromBigTuple([n,e]),y:Y.fromBigTuple([a,r])}}throw Error(`invalid G2 point: expected 96/192 bytes`)}function Ys(e){let{ORDER:t}=J,{infinity:n,sort:r,value:i}=Bs(H(`signatureHex`,e)),a=Xs.G2.Point,o=i.length/2;if(o!==48&&o!==96)throw Error(`invalid compressed signature length, expected 96/192 bytes`);let s=Ea(i.slice(0,o)),c=Ea(i.slice(o));if(n)return a.ZERO;let l=J.create(s&Ia(J.BITS)),u=J.create(c),d=Y.create({c0:u,c1:l}),f=Y.add(Y.pow(d,Os),Rs.b),p=Y.sqrt(f);if(!p)throw Error(`Failed to find a square root`);let{re:m,im:h}=Y.reim(p),g=BigInt(r),_=h>q&&h*Ds/t!==g,v=h===q&&m*Ds/t!==g;(_||v)&&(p=Y.neg(p));let y=a.fromAffine({x:d,y:p});return y.assertValidity(),y}var Xs=ms({fields:{Fp:J,Fp2:Y,Fp6:Ps,Fp12:X,Fr:Ns},G1:{...Ms,Fp:J,htfDefaults:{...Ls,m:1,DST:`BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_`},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(e,t)=>{let n=BigInt(`0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe`),r=new e(J.mul(t.X,n),t.Y,t.Z);return t.multiplyUnsafe(As).negate().multiplyUnsafe(As).equals(r)},clearCofactor:(e,t)=>t.multiplyUnsafe(As).add(t),mapToCurve:tc,fromBytes:Ws,toBytes:Hs,ShortSignature:{fromBytes(e){return v(e),Gs(e)},fromHex(e){return Gs(e)},toBytes(e){return Us(e)},toRawBytes(e){return Us(e)},toHex(e){return w(Us(e))}}},G2:{...Rs,Fp:Y,hEff:BigInt(`0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551`),htfDefaults:{...Ls},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:nc,isTorsionFree:(e,t)=>t.multiplyUnsafe(As).negate().equals(Fs(e,t)),clearCofactor:(e,t)=>{let n=As,r=t.multiplyUnsafe(n).negate(),i=Fs(e,t),a=t.double();return a=Is(e,a),a=a.subtract(i),i=r.add(i),i=i.multiplyUnsafe(n).negate(),a=a.add(i),a=a.subtract(r),a.subtract(t)},fromBytes:Js,toBytes:Ks,Signature:{fromBytes(e){return v(e),Ys(e)},fromHex(e){return Ys(e)},toBytes(e){return qs(e)},toRawBytes(e){return qs(e)},toHex(e){return w(qs(e))}}},params:{ateLoopSize:As,r:Ms.n,xNegative:!0,twistType:`multiplicative`},htfDefaults:Ls,hash:He}),Zs=Vo(Y,[[[`0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6`,`0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6`],[`0x0`,`0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a`],[`0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e`,`0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d`],[`0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1`,`0x0`]],[[`0x0`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63`],[`0xc`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f`],[`0x1`,`0x0`]],[[`0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706`,`0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706`],[`0x0`,`0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be`],[`0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c`,`0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f`],[`0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10`,`0x0`]],[[`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb`],[`0x0`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3`],[`0x12`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99`],[`0x1`,`0x0`]]].map(e=>e.map(e=>Y.fromBigTuple(e.map(BigInt))))),Qs=Vo(J,[[`0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7`,`0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb`,`0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0`,`0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861`,`0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9`,`0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983`,`0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84`,`0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e`,`0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317`,`0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e`,`0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b`,`0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229`],[`0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c`,`0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff`,`0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19`,`0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8`,`0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e`,`0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5`,`0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a`,`0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e`,`0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641`,`0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a`,`0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001`],[`0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33`,`0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696`,`0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6`,`0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb`,`0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb`,`0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0`,`0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2`,`0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29`,`0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587`,`0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30`,`0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132`,`0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e`,`0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8`,`0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133`,`0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b`,`0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604`],[`0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1`,`0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d`,`0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2`,`0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416`,`0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d`,`0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac`,`0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c`,`0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9`,`0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a`,`0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55`,`0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8`,`0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092`,`0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc`,`0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7`,`0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f`,`0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001`]].map(e=>e.map(e=>BigInt(e)))),$s=es(J,{A:J.create(BigInt(`0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d`)),B:J.create(BigInt(`0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0`)),Z:J.create(BigInt(11))}),ec=es(Y,{A:Y.create({c0:J.create(q),c1:J.create(BigInt(240))}),B:Y.create({c0:J.create(BigInt(1012)),c1:J.create(BigInt(1012))}),Z:Y.create({c0:J.create(BigInt(-2)),c1:J.create(BigInt(-1))})});function tc(e){let{x:t,y:n}=$s(J.create(e[0]));return Qs(t,n)}function nc(e){let{x:t,y:n}=ec(Y.fromBigTuple(e));return Zs(t,n)}function rc(e,t,n){let r=typeof e==`string`?e:w(e),i=typeof t==`string`?t:w(t),a=typeof n==`string`?n:w(n);return Xs.verifyShortSignature(i,a,r)}var ic=BigInt(1e6),ac=e=>P(new Jt(e)),oc=e=>{let t=ac(e)/ic;return new Date(Number(t))},sc=6e4,cc=1440,lc=5,uc=5,dc=30*cc,Z;(function(e){e[e.Empty=0]=`Empty`,e[e.Fork=1]=`Fork`,e[e.Labeled=2]=`Labeled`,e[e.Leaf=3]=`Leaf`,e[e.Pruned=4]=`Pruned`})(Z||={});function fc(e,t){for(let n=0;n<e.length;n++)if(e[n]>t[n])return!0;return!1}var pc=class e{#e=!1;#t=void 0;static async create(t){let n=e.createUnverified(t);return await n.verify(),n}static createUnverified(t){return new e(t.certificate,t.rootKey,t.principal,t.blsVerify??rc,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(e,t,n,r,i=lc,a=!1,o){this._rootKey=t,this._principal=n,this._blsVerify=r,this._maxAgeInMinutes=i,this.#e=a,this.cert=fa(e),o&&`getTimeDiffMsecs`in o&&`hasSyncedTime`in o&&`syncTime`in o&&`syncTimeWithSubnet`in o&&(this.#t=o)}lookup_path(e){return Tc(e,this.cert.tree)}lookup_subtree(e){return Ec(e,this.cert.tree)}async verify(){let e=await bc(this.cert.tree),t=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,r=vc(t),i=E($r,e),a=yc(this.lookup_path([`time`]));if(!a)throw A.fromCode(new ot(`Certificate does not contain a time`));if(!this.#e){let e=this.#t?.getTimeDiffMsecs()??0,t=this._maxAgeInMinutes*sc,n=new Date,r=n.getTime()+e,i=r-t,o=r+uc*sc,s=oc(a),c=s.getTime()<i,l=s.getTime()>o;if((c||l)&&this.#t&&!this.#t.hasSyncedTime())return await this._syncTime(),await this.verify();if(c)throw tt.fromCode(new st(this._maxAgeInMinutes,s,n,e,`past`));if(l)throw this.#t?.hasSyncedTime()?at.fromCode(new Lt(`System time has been synced with the IC network, but certificate is still too far in the future.`)):tt.fromCode(new st(5,s,n,e,`future`))}try{if(!await this._blsVerify(r,n,i))throw tt.fromCode(new ot(`Invalid signature`))}catch(e){throw tt.fromCode(new ot(`Signature verification failed`,e))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let n=e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,principal:this._principal,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:dc,agent:this.#t});if(n.cert.delegation)throw A.fromCode(new ct);await n.verify();let r;if(hc(this._principal)){let e=this._principal.canisterId;if(r=O.fromUint8Array(t.subnet_id),!Ac({canisterId:e,subnetId:r,tree:n.cert.tree}))throw tt.fromCode(new lt(e,r))}else if(mc(this._principal))r=this._principal.subnetId;else throw qt;let i=yc(n.lookup_path([`subnet`,r.toUint8Array(),`public_key`]));if(!i)throw mc(this._principal)?tt.fromCode(new ut(r)):tt.fromCode(new pt(`Could not find subnet key for subnet ID ${r.toText()}`));return i}async _syncTime(){this.#t&&(hc(this._principal)?await this.#t.syncTime(this._principal.canisterId):await this.#t.syncTimeWithSubnet(this._principal.subnetId))}};function mc(e){return`subnetId`in e}function hc(e){return`canisterId`in e}var gc=ie(`308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100`),_c=96;function vc(e){let t=gc.byteLength+_c;if(e.byteLength!==t)throw A.fromCode(new mt(t,e.byteLength));let n=e.slice(0,gc.byteLength);if(!Jr(n,gc))throw A.fromCode(new ht(gc,n));return e.slice(gc.byteLength)}function yc(e){if(e.status===Cc.Found&&e.value instanceof Uint8Array)return e.value}async function bc(e){switch(e[0]){case Z.Empty:return He(xc(`ic-hashtree-empty`));case Z.Pruned:return e[1];case Z.Leaf:return He(E(xc(`ic-hashtree-leaf`),e[1]));case Z.Labeled:return He(E(xc(`ic-hashtree-labeled`),e[1],await bc(e[2])));case Z.Fork:return He(E(xc(`ic-hashtree-fork`),await bc(e[1]),await bc(e[2])));default:throw qt}}function xc(e){return E(new Uint8Array([e.length]),new TextEncoder().encode(e))}function Sc(e){return typeof e[0]==`string`?T(e[0]):e[0]}var Cc;(function(e){e.Unknown=`Unknown`,e.Absent=`Absent`,e.Found=`Found`,e.Error=`Error`})(Cc||={});var wc;(function(e){e.Absent=`Absent`,e.Unknown=`Unknown`,e.Found=`Found`})(wc||={});var Q;(function(e){e.Absent=`Absent`,e.Unknown=`Unknown`,e.Found=`Found`,e.Less=`Less`,e.Greater=`Greater`})(Q||={});function Tc(e,t){if(e.length===0)switch(t[0]){case Z.Empty:return{status:Cc.Absent};case Z.Leaf:if(!t[1])throw at.fromCode(new zt(`Invalid tree structure for leaf`));if(t[1]instanceof Uint8Array)return{status:Cc.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw qt;case Z.Pruned:return{status:Cc.Unknown};case Z.Labeled:case Z.Fork:return{status:Cc.Error};default:throw qt}let n=Oc(Sc(e),t);switch(n.status){case Q.Found:return Tc(e.slice(1),n.value);case Q.Absent:case Q.Greater:case Q.Less:return{status:Cc.Absent};case Q.Unknown:return{status:Cc.Unknown};default:throw qt}}function Ec(e,t){if(e.length===0)return{status:wc.Found,value:t};let n=Oc(Sc(e),t);switch(n.status){case Q.Found:return Ec(e.slice(1),n.value);case Q.Unknown:return{status:wc.Unknown};case Q.Absent:case Q.Greater:case Q.Less:return{status:wc.Absent};default:throw qt}}function Dc(e){switch(e[0]){case Z.Empty:return[];case Z.Fork:return Dc(e[1]).concat(Dc(e[2]));default:return[e]}}function Oc(e,t){switch(t[0]){case Z.Labeled:return fc(e,t[1])?{status:Q.Greater}:Jr(e,t[1])?{status:Q.Found,value:t[2]}:{status:Q.Less};case Z.Fork:{let n=Oc(e,t[1]);switch(n.status){case Q.Greater:{let n=Oc(e,t[2]);return n.status===Q.Less?{status:Q.Absent}:n}case Q.Unknown:{let n=Oc(e,t[2]);return n.status===Q.Less?{status:Q.Unknown}:n}default:return n}}case Z.Pruned:return{status:Q.Unknown};default:return{status:Q.Absent}}}function kc(e,t){switch(t[0]){case Z.Empty|Z.Pruned:return[];case Z.Leaf:return[e];case Z.Fork:return kc(e,t[1]).concat(kc(e,t[2]));case Z.Labeled:{let n=t[1],r=t[2];return kc([...e,n],r)}default:throw qt}}function Ac(e){let t=Nc(jc(e)),{canisterId:n}=e;return t.some(e=>e[0].ltEq(n)&&e[1].gtEq(n))}function jc(e){let{subnetId:t,tree:n,canisterId:r}=e,i=Ec([`canister_ranges`,t.toUint8Array()],n);if(i.status!==wc.Found)return Mc(t,n);let a=i.value,o=Pc(a);if(o.length===0)throw A.fromCode(new lt(r,t));o.sort(Xt);let s=o[Fc(o,r)];return Ic(s,a)}function Mc(e,t){let n=Tc([`subnet`,e.toUint8Array(),`canister_ranges`],t);if(n.status!==Cc.Found)throw A.fromCode(new dt(`Could not find canister ranges for subnet ${e.toText()}`,n.status));return n.value}function Nc(e){return fa(e).map(e=>[O.fromUint8Array(e[0]),O.fromUint8Array(e[1])])}function Pc(e){let t=[];for(let n of kc([],e)){let e=n[0];if(!e)throw A.fromCode(new ot(`Path is invalid`));t.push(e)}return t}function Fc(e,t){let n=t.toUint8Array(),r=0,i=e.length-1;for(;r<i;){let t=Math.floor((r+i)/2);Xt(e[t],n)<=0?i=t:r=t+1}return r}function Ic(e,t){let n=Tc([e],t);if(n.status!==Cc.Found)throw A.fromCode(new dt(`Could not find canister range for shard ${e.toString()}`,n.status));return n.value}function Lc(e,t){return e.delegation?O.fromUint8Array(e.delegation.subnet_id):O.selfAuthenticating(t)}var Rc=O.fromText(`tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe`);function zc(e,t){switch(t){case`raw`:return e;case`leb128`:return ac(e);case`cbor`:return fa(e);case`hex`:return w(e);case`utf-8`:return new TextDecoder().decode(e)}}function Bc(e){return fa(e).map(e=>O.fromUint8Array(e))}function Vc(e,t){let n=typeof e==`string`?T(e):e;return[T(`canister`),t,T(`metadata`),n]}function Hc(e){return typeof e==`object`&&!!e&&`key`in e&&`path`in e}function Uc(e,t){let n=Ec([`subnet`,t.toUint8Array(),`node`],e.tree);if(n.status!==wc.Found)throw A.fromCode(new dt(`Node not found`,n.status));if(n.value instanceof Uint8Array)throw at.fromCode(new zt(`Invalid node tree`));let r=Dc(n.value),i=new Map;return r.forEach(e=>{let t=O.from(e[1]).toText(),n=Tc([`public_key`],e[2]);if(n.status!==Cc.Found)throw A.fromCode(new dt(`Public key not found`,n.status));let r=n.value;if(r.byteLength!==44)throw A.fromCode(new mt(44,r.byteLength));i.set(t,r)}),i}var Wc=async e=>{let{agent:t,paths:n,disableCertificateTimeVerification:r=!1}=e,i=O.from(e.canisterId),a=[...new Set(n)],o=new Map,s=a.map((e,n)=>{let s=Kc(e,i);return(async()=>{try{if(t.rootKey===null)throw it.fromCode(new Dt);let e=t.rootKey,c=await t.readState(i,{paths:[s]}),{path:l,data:u}=((t,n)=>n===`subnet`?{path:n,data:Gc(c.certificate,i,e)}:{path:n,data:yc(t.lookup_path(s))})(await pc.create({certificate:c.certificate,rootKey:e,principal:{canisterId:i},disableTimeVerification:r,agent:t}),a[n]);if(!u)typeof l==`string`?o.set(l,null):o.set(l.key,null);else switch(l){case`time`:o.set(l,oc(u));break;case`controllers`:o.set(l,Bc(u));break;case`module_hash`:o.set(l,w(u));break;case`subnet`:o.set(l,u);break;case`candid`:o.set(l,new TextDecoder().decode(u));break;default:Hc(l)&&o.set(l.key,zc(u,l.decodeStrategy))}}catch(t){if(t instanceof $e&&(t.hasCode(ot)||t.hasCode(st)))throw t;Hc(e)?o.set(e.key,null):o.set(e,null)}})()});return await Promise.all(s),o},Gc=(e,t,n)=>{if(!t._isPrincipal)throw j.fromCode(new Lt(`Invalid canisterId`));let r=fa(e),{delegation:i}=r,a;a=i&&i.subnet_id?O.fromUint8Array(new Uint8Array(i.subnet_id)):!i&&n!==void 0?O.selfAuthenticating(new Uint8Array(n)):Rc;let o=Uc(r,a);return{subnetId:a.toText(),nodeKeys:o}},Kc=(e,t)=>{let n=t.toUint8Array();switch(e){case`time`:return[T(`time`)];case`controllers`:return[T(`canister`),n,T(`controllers`)];case`module_hash`:return[T(`canister`),n,T(`module_hash`)];case`subnet`:return[T(`subnet`)];case`candid`:return[T(`canister`),n,T(`metadata`),T(`candid:service`)];default:if(Hc(e))return typeof e.path==`string`||e.path instanceof Uint8Array?Vc(e.path,n):e.path}throw at.fromCode(new Lt(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))};async function qc(e){let{agent:t,paths:n,disableCertificateTimeVerification:r=!1}=e,i=O.from(e.subnetId),a=[...new Set(n)],o=new Map,s=a.map((e,n)=>{let s=Jc(e,i);return(async()=>{try{if(t.rootKey===null)throw it.fromCode(new Dt);let e=t.rootKey,c=await t.readSubnetState(i,{paths:[s]}),{path:l,data:u}=((e,t)=>t===`nodeKeys`?{path:t,data:Uc(e.cert,i)}:{path:t,data:yc(e.lookup_path(s))})(await pc.create({certificate:c.certificate,rootKey:e,principal:{subnetId:i},disableTimeVerification:r,agent:t}),a[n]);if(!u)typeof l==`string`?o.set(l,null):o.set(l.key,null);else switch(l){case`time`:o.set(l,oc(u));break;case`canisterRanges`:o.set(l,Nc(u));break;case`publicKey`:o.set(l,u);break;case`nodeKeys`:o.set(l,u);break;default:Hc(l)&&o.set(l.key,zc(u,l.decodeStrategy))}}catch(t){if(t instanceof $e&&(t.hasCode(ot)||t.hasCode(st)))throw t;Hc(e)?o.set(e.key,null):o.set(e,null)}})()});return await Promise.all(s),o}function Jc(e,t){let n=t.toUint8Array();switch(e){case`time`:return[T(`time`)];case`canisterRanges`:return[T(`canister_ranges`),n];case`publicKey`:return[T(`subnet`),n,T(`public_key`)];case`nodeKeys`:return[T(`subnet`),n,T(`node`)];default:if(Hc(e)){if(typeof e.path==`string`||e.path instanceof Uint8Array){let t=typeof e.path==`string`?T(e.path):e.path;return[T(`subnet`),n,t]}return e.path}}throw at.fromCode(new Lt(`Error while encoding your path for subnet status. Please ensure that your path ${e} was formatted correctly.`))}function Yc(e,t,n){let r=new Uint8Array(yc(e.lookup_path([...t,`reject_code`])))[0],i=new TextDecoder().decode(yc(e.lookup_path([...t,`reject_message`]))),a=yc(e.lookup_path([...t,`error_code`]));return new Ct(n,r,i,a?new TextDecoder().decode(a):void 0)}var Xc=BigInt(0),$=BigInt(1),Zc=BigInt(2),Qc=BigInt(8);function $c(e,t,n,r){let i=e.sqr(n),a=e.sqr(r),o=e.add(e.mul(t.a,i),a),s=e.add(e.ONE,e.mul(t.d,e.mul(i,a)));return e.eql(o,s)}function el(e,t={}){let n=Mo(`edwards`,e,t,t.FpFnLE),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o}=a;Ra(t,{},{uvRatio:`function`});let s=Zc<<BigInt(i.BYTES*8)-$,c=e=>r.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch{return{isValid:!1,value:Xc}}});if(!$c(r,a,a.Gx,a.Gy))throw Error(`bad curve params: generator point`);function u(e,t,n=!1){let r=n?$:Xc;return Na(`coordinate `+e,t,r,s),t}function d(e){if(!(e instanceof m))throw Error(`ExtendedPoint expected`)}let f=Ba((e,t)=>{let{X:n,Y:i,Z:a}=e,o=e.is0();t??=o?Qc:r.inv(a);let s=c(n*t),l=c(i*t),u=r.mul(a,t);if(o)return{x:Xc,y:$};if(u!==$)throw Error(`invZ was invalid`);return{x:s,y:l}}),p=Ba(e=>{let{a:t,d:n}=a;if(e.is0())throw Error(`bad point: ZERO`);let{X:r,Y:i,Z:o,T:s}=e,l=c(r*r),u=c(i*i),d=c(o*o),f=c(d*d),p=c(l*t);if(c(d*c(p+u))!==c(f+c(n*c(l*u))))throw Error(`bad point: equation left != right (1)`);if(c(r*i)!==c(o*s))throw Error(`bad point: equation left != right (2)`);return!0});class m{constructor(e,t,n,r){this.X=u(`x`,e),this.Y=u(`y`,t),this.Z=u(`z`,n,!0),this.T=u(`t`,r),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){if(e instanceof m)throw Error(`extended point not allowed`);let{x:t,y:n}=e||{};return u(`x`,t),u(`y`,n),new m(t,n,$,c(t*n))}static fromBytes(e,t=!1){let n=r.BYTES,{a:i,d:o}=a;e=Aa(wa(e,n,`point`)),Ca(t,`zip215`);let u=Aa(e),d=e[n-1];u[n-1]=d&-129;let f=Da(u);Na(`point.y`,f,Xc,t?s:r.ORDER);let p=c(f*f),h=c(p-$),g=c(o*p-i),{isValid:_,value:v}=l(h,g);if(!_)throw Error(`bad point: invalid y coordinate`);let y=(v&$)===$,b=!!(d&128);if(!t&&v===Xc&&b)throw Error(`bad point: x=0 and x_0=1`);return b!==y&&(v=c(-v)),m.fromAffine({x:v,y:f})}static fromHex(e,t=!1){return m.fromBytes(H(`point`,e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return h.createCache(this,e),t||this.multiply(Zc),this}assertValidity(){p(this)}equals(e){d(e);let{X:t,Y:n,Z:r}=this,{X:i,Y:a,Z:o}=e,s=c(t*o),l=c(i*r),u=c(n*o),f=c(a*r);return s===l&&u===f}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:e}=a,{X:t,Y:n,Z:r}=this,i=c(t*t),o=c(n*n),s=c(Zc*c(r*r)),l=c(e*i),u=t+n,d=c(c(u*u)-i-o),f=l+o,p=f-s,h=l-o,g=c(d*p),_=c(f*h),v=c(d*h),y=c(p*f);return new m(g,_,y,v)}add(e){d(e);let{a:t,d:n}=a,{X:r,Y:i,Z:o,T:s}=this,{X:l,Y:u,Z:f,T:p}=e,h=c(r*l),g=c(i*u),_=c(s*n*p),v=c(o*f),y=c((r+i)*(l+u)-h-g),b=v-_,x=v+_,ee=c(g-t*h),S=c(y*b),te=c(x*ee),C=c(y*ee),w=c(b*x);return new m(S,te,w,C)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw Error(`invalid scalar: expected 1 <= sc < curve.n`);let{p:t,f:n}=h.cached(this,e,e=>vo(m,e));return vo(m,[t,n])[0]}multiplyUnsafe(e,t=m.ZERO){if(!i.isValid(e))throw Error(`invalid scalar: expected 0 <= sc < curve.n`);return e===Xc?m.ZERO:this.is0()||e===$?this:h.unsafe(this,e,e=>vo(m,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return h.unsafe(this,a.n).is0()}toAffine(e){return f(this,e)}clearCofactor(){return o===$?this:this.multiplyUnsafe(o)}toBytes(){let{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&$?128:0,n}toHex(){return w(this.toBytes())}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return vo(m,e)}static msm(e,t){return Ao(m,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}m.BASE=new m(a.Gx,a.Gy,$,c(a.Gx*a.Gy)),m.ZERO=new m(Xc,$,$,Xc),m.Fp=r,m.Fn=i;let h=new Oo(m,i.BITS);return m.BASE.precompute(8),m}var tl=class{constructor(e){this.ep=e}static fromBytes(e){za()}static fromHex(e){za()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return w(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function nl(e,t,n={}){if(typeof t!=`function`)throw Error(`"hash" function param is required`);Ra(n,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,mapToCurve:`function`});let{prehash:r}=n,{BASE:i,Fp:a,Fn:o}=e,s=n.randomBytes||ce,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(Ca(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e});function u(e){return o.create(Da(e))}function d(e){let n=b.secretKey;e=H(`private key`,e,n);let r=H(`hashed private key`,t(e),2*n),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}function f(e){let{head:t,prefix:n,scalar:r}=d(e),a=i.multiply(r);return{head:t,prefix:n,scalar:r,point:a,pointBytes:a.toBytes()}}function p(e){return f(e).pointBytes}function m(e=Uint8Array.of(),...n){let i=E(...n);return u(t(l(i,H(`context`,e),!!r)))}function h(e,t,n={}){e=H(`message`,e),r&&(e=r(e));let{prefix:a,scalar:s,pointBytes:c}=f(t),l=m(n.context,a,e),u=i.multiply(l).toBytes(),d=m(n.context,u,c,e),p=o.create(l+d*s);if(!o.isValid(p))throw Error(`sign failed: invalid s`);return wa(E(u,o.toBytes(p)),b.signature,`result`)}let _={zip215:!0};function v(t,n,a,o=_){let{context:s,zip215:c}=o,l=b.signature;t=H(`signature`,t,l),n=H(`message`,n),a=H(`publicKey`,a,b.publicKey),c!==void 0&&Ca(c,`zip215`),r&&(n=r(n));let u=l/2,d=t.subarray(0,u),f=Da(t.subarray(u,l)),p,h,g;try{p=e.fromBytes(a,c),h=e.fromBytes(d,c),g=i.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let v=m(s,h.toBytes(),p.toBytes(),n);return h.add(p.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()}let y=a.BYTES,b={secretKey:y,publicKey:y,signature:2*y,seed:y};function x(e=s(b.seed)){return wa(e,b.seed,`seed`)}function ee(e){let t=C.randomSecretKey(e);return{secretKey:t,publicKey:p(t)}}function S(e){return g(e)&&e.length===o.BYTES}function te(t,n){try{return!!e.fromBytes(t,n)}catch{return!1}}let C={getExtendedPublicKey:f,randomSecretKey:x,isValidSecretKey:S,isValidPublicKey:te,toMontgomery(t){let{y:n}=e.fromBytes(t),r=b.publicKey,i=r===32;if(!i&&r!==57)throw Error(`only defined for 25519 and 448`);let o=i?a.div($+n,$-n):a.div(n-$,n+$);return a.toBytes(o)},toMontgomerySecret(e){let n=b.secretKey;wa(e,n);let r=t(e.subarray(0,n));return c(r).subarray(0,n)},randomPrivateKey:x,precompute(t=8,n=e.BASE){return n.precompute(t,!1)}};return Object.freeze({keygen:ee,getPublicKey:p,sign:h,verify:v,utils:C,Point:e,lengths:b})}function rl(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n={Fp:e.Fp,Fn:uo(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}function il(e,t){let n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function al(e){let{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=rl(e);return il(e,nl(el(t,n),r,i))}var ol=BigInt(0),sl=BigInt(1),cl=BigInt(2),ll=BigInt(5),ul=BigInt(8),dl=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),fl={p:dl,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:ul,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function pl(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=dl,o=e*e%a*e%a,s=Ya(Ya(o,cl,a)*o%a,sl,a)*e%a,c=Ya(s,ll,a)*s%a,l=Ya(c,t,a)*c%a,u=Ya(l,n,a)*l%a,d=Ya(u,r,a)*u%a;return{pow_p_5_8:Ya(Ya(Ya(Ya(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,cl,a)*e%a,b2:o}}function ml(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var hl=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function gl(e,t){let n=dl,r=G(t*t*t,n),i=pl(e*G(r*r*t,n)).pow_p_5_8,a=G(e*r*i,n),o=G(t*a*a,n),s=a,c=G(a*hl,n),l=o===e,u=o===G(-e,n),d=o===G(-e*hl,n);return l&&(a=s),(u||d)&&(a=c),ro(a,n)&&(a=G(-a,n)),{isValid:l||u,value:a}}var _l=uo(fl.p,{isLE:!0}),vl=uo(fl.n,{isLE:!0}),yl=al({...fl,Fp:_l,hash:We,adjustScalarBytes:ml,uvRatio:gl}),bl=hl,xl=BigInt(`25063068953384623474111414158702152701244531502492656460079210482610430750235`),Sl=BigInt(`54469307008909316920995813868745141605393597292927456921205312896311721017578`),Cl=BigInt(`1159843021668779879193775521855586647937357759715417654439879720876111806838`),wl=BigInt(`40440834346308536858101042469323190826248399146238708352240133220865137265952`),Tl=e=>gl(sl,e),El=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),Dl=e=>yl.Point.Fp.create(Da(e)&El);function Ol(e){let{d:t}=fl,n=dl,r=e=>_l.create(e),i=r(bl*e*e),a=r((i+sl)*Cl),o=BigInt(-1),s=r((o-t*i)*r(i+t)),{isValid:c,value:l}=gl(a,s),u=r(l*e);ro(u,n)||(u=r(-u)),c||(l=u),c||(o=i);let d=r(o*(i-sl)*wl-s),f=l*l,p=r((l+l)*s),m=r(d*xl),h=r(sl-f),g=r(sl+f);return new yl.Point(r(p*g),r(h*m),r(m*g),r(p*h))}function kl(e){v(e,64);let t=Ol(Dl(e.subarray(0,32))),n=Ol(Dl(e.subarray(32,64)));return new Al(t.add(n))}var Al=class e extends tl{constructor(e){super(e)}static fromAffine(t){return new e(yl.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw Error(`RistrettoPoint expected`)}init(t){return new e(t)}static hashToCurve(e){return kl(H(`ristrettoHash`,e,64))}static fromBytes(t){v(t,32);let{a:n,d:r}=fl,i=dl,a=e=>_l.create(e),o=Dl(t);if(!ka(_l.toBytes(o),t)||ro(o,i))throw Error(`invalid ristretto255 encoding 1`);let s=a(o*o),c=a(sl+n*s),l=a(sl-n*s),u=a(c*c),d=a(l*l),f=a(n*r*u-d),{isValid:p,value:m}=Tl(a(f*d)),h=a(m*l),g=a(m*h*f),_=a((o+o)*h);ro(_,i)&&(_=a(-_));let y=a(c*g),b=a(_*y);if(!p||ro(b,i)||y===ol)throw Error(`invalid ristretto255 encoding 2`);return new e(new yl.Point(_,y,sl,b))}static fromHex(t){return e.fromBytes(H(`ristrettoHex`,t,32))}static msm(t,n){return Ao(e,yl.Point.Fn,t,n)}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep,i=dl,a=e=>_l.create(e),o=a(a(n+t)*a(n-t)),s=a(e*t),{value:c}=Tl(a(o*a(s*s))),l=a(c*o),u=a(c*s),d=a(l*u*r),f;if(ro(r*d,i)){let n=a(t*bl),r=a(e*bl);e=n,t=r,f=a(l*Sl)}else f=u;ro(e*d,i)&&(t=a(-t));let p=a((n-t)*f);return ro(p,i)&&(p=a(-p)),_l.toBytes(p)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:r,Y:i}=e.ep,a=e=>_l.create(e),o=a(t*i)===a(n*r),s=a(n*i)===a(t*r);return o||s}is0(){return this.equals(e.ZERO)}};Al.BASE=new Al(yl.Point.BASE),Al.ZERO=new Al(yl.Point.ZERO),Al.Fp=_l,Al.Fn=vl;function jl(e){if(!Number.isFinite(e)||e<=0)throw Error(`expirationTime must be a positive finite number, got ${e}`)}var Ml=class{#e;#t;#n=null;constructor(e){if(globalThis.indexedDB===void 0)throw Error(`IndexedDBExpirableStore requires IndexedDB, which is not available in this environment`);jl(e.expirationTime),this.#e=e.dbName,this.#t=e.storeName,this.expirationTime=e.expirationTime}#r(){return this.#n||=this.#i().catch(e=>{throw this.#n=null,e}),this.#n}async#i(){let e=await this.#a();if(e.objectStoreNames.contains(this.#t))return e;let t=e.version+1;return e.close(),this.#a(t)}#a(e){let t=this.#t;return new Promise((n,r)=>{let i=globalThis.indexedDB.open(this.#e,e);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(t)||e.createObjectStore(t,{keyPath:`key`})},i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>{e.close(),this.#n=null},n(e)},i.onerror=()=>r(i.error)})}async get(e){let t=await this.#r();return new Promise((n,r)=>{let i=t.transaction(this.#t,`readonly`).objectStore(this.#t).get(e);i.onsuccess=()=>{let t=i.result;t?Date.now()-t.timestamp>this.expirationTime?this.delete(e).then(()=>n(void 0),()=>n(void 0)):n(t.value):n(void 0)},i.onerror=()=>r(i.error)})}async set(e,t){await this.#o();let n=await this.#r();return new Promise((r,i)=>{let a=n.transaction(this.#t,`readwrite`),o=a.objectStore(this.#t),s={key:e,value:t,timestamp:Date.now()};o.put(s),a.oncomplete=()=>r(),a.onerror=()=>i(a.error)})}async delete(e){let t=await this.#r();return new Promise((n,r)=>{let i=t.transaction(this.#t,`readwrite`);i.objectStore(this.#t).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async#o(){let e=await this.#r(),t=Date.now();return new Promise((n,r)=>{let i=e.transaction(this.#t,`readwrite`),a=i.objectStore(this.#t).openCursor();a.onsuccess=()=>{let e=a.result;if(!e)return;let n=e.value;t-n.timestamp>this.expirationTime&&e.delete(),e.continue()},i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}},Nl=class{#e;constructor(e){jl(e.expirationTime),this.expirationTime=e.expirationTime,this.#e=new Map}get(e){let t=this.#e.get(e);return t?Date.now()-t.timestamp>this.expirationTime?(this.#e.delete(e),Promise.resolve(void 0)):Promise.resolve(t.value):Promise.resolve(void 0)}set(e,t){return this.#t(),this.#e.set(e,{value:t,timestamp:Date.now()}),Promise.resolve()}delete(e){return this.#e.delete(e),Promise.resolve()}#t(){let e=Date.now();for(let[t,n]of this.#e)e-n.timestamp>this.expirationTime&&this.#e.delete(t)}};function Pl(e){return globalThis.indexedDB===void 0?new Nl({expirationTime:e.expirationTime}):new Ml(e)}var Fl=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw j.fromCode(new vt(`Length too long (> 4 bytes)`))},Il=(e,t,n)=>{if(n<=127)return e[t]=n,1;if(n<=255)return e[t]=129,e[t+1]=n,2;if(n<=65535)return e[t]=130,e[t+1]=n>>8,e[t+2]=n,3;if(n<=16777215)return e[t]=131,e[t+1]=n>>16,e[t+2]=n>>8,e[t+3]=n,4;throw j.fromCode(new vt(`Length too long (> 4 bytes)`))},Ll=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw j.fromCode(new _t(`Invalid length 0`));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw j.fromCode(new _t(`Length too long (> 4 bytes)`))},Rl=(e,t)=>{let n=Ll(e,t);if(n===1)return e[t];if(n===2)return e[t+1];if(n===3)return(e[t+1]<<8)+e[t+2];if(n===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw j.fromCode(new _t(`Length too long (> 4 bytes)`))};Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]);var zl=Uint8Array.from([48,5,6,3,43,101,112]);Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),Uint8Array.from([48,29,6,13,43,6,1,4,1,130,220,124,5,3,1,2,1,6,12,43,6,1,4,1,130,220,124,5,3,2,1]);function Bl(e,t){let n=2+Fl(e.byteLength+1),r=t.byteLength+n+e.byteLength,i=0,a=new Uint8Array(1+Fl(r)+r);return a[i++]=48,i+=Il(a,i,r),a.set(t,i),i+=t.byteLength,a[i++]=3,i+=Il(a,i,e.byteLength+1),a[i++]=0,a.set(new Uint8Array(e),i),a}var Vl=(e,t)=>{let n=0,r=(e,t)=>{if(i[n++]!==e)throw j.fromCode(new _t(`Expected ${t} at offset ${n}`))},i=new Uint8Array(e);if(r(48,`sequence`),n+=Ll(i,n),!Jr(i.slice(n,n+t.byteLength),t))throw j.fromCode(new _t(`Not the expected OID.`));n+=t.byteLength,r(3,`bit string`);let a=Rl(i,n)-1;n+=Ll(i,n),r(0,`0 padding`);let o=i.slice(n);if(a!==o.length)throw j.fromCode(new gt(a,o.length));return o},Hl=class e{static from(e){return this.fromDer(e.toDer())}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(e){return Bl(e,zl)}static derDecode(e){let t=Vl(e,zl);if(t.length!==this.RAW_KEY_LENGTH)throw j.fromCode(new _t(`An Ed25519 public key must be exactly 32 bytes long`));return t}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw j.fromCode(new _t(`An Ed25519 public key must be exactly 32 bytes long`));this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}},Ul=class{constructor(){this.observers=[]}subscribe(e){this.observers.push(e)}unsubscribe(e){this.observers=this.observers.filter(t=>t!==e)}notify(e,...t){this.observers.forEach(n=>n(e,...t))}},Wl=class extends Ul{constructor(){super()}print(e,...t){this.notify({message:e,level:`info`},...t)}warn(e,...t){this.notify({message:e,level:`warn`},...t)}error(e,t,...n){this.notify({message:e,level:`error`,error:t},...n)}},Gl=.5,Kl=1.5,ql=500,Jl=6e4,Yl=9e5,Xl=10,Zl=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c=0;static{this.default={initialInterval:ql,randomizationFactor:Gl,multiplier:Kl,maxInterval:Jl,maxElapsedTime:Yl,maxIterations:Xl,date:Date}}constructor(t=e.default){let{initialInterval:n=ql,randomizationFactor:r=Gl,multiplier:i=Kl,maxInterval:a=Jl,maxElapsedTime:o=Yl,maxIterations:s=Xl,date:c=Date}=t;this.#e=n,this.#t=r,this.#n=i,this.#r=a,this.#s=c,this.#i=c.now(),this.#a=o,this.#o=s}get ellapsedTimeInMsec(){return this.#s.now()-this.#i}get currentInterval(){return this.#e}get count(){return this.#c}get randomValueFromInterval(){let e=this.#t*this.#e,t=this.#e-e,n=this.#e+e;return Math.random()*(n-t)+t}incrementCurrentInterval(){return this.#e=Math.min(this.#e*this.#n,this.#r),this.#c++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#a||this.#c>=this.#o?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}},Ql=3e5;function $l(){return iu(tu(eu(),1e3),ru(1e3,1.2),nu(Ql))}function eu(){let e=!0;return async()=>e?(e=!1,!0):!1}function tu(e,t){return async(n,r,i)=>{if(await e(n,r,i))return new Promise(e=>setTimeout(e,t))}}function nu(e){let t=Date.now()+e;return async(n,r,i)=>{if(Date.now()>t)throw A.fromCode(new xt(`Request timed out after ${e} msec`,r,i))}}function ru(e,t){let n=e;return()=>new Promise(e=>setTimeout(()=>{n*=t,e()},n))}function iu(...e){return async(t,n,r)=>{for(let i of e)await i(t,n,r)}}var au={preSignReadStateRequest:!1};function ou(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function su(e,t){return typeof e==`object`&&!!e&&ou(e,t)}function cu(e,t){return ou(e,t)&&typeof e[t]==`function`}function lu(e){return su(e,`body`)&&su(e.body,`content`)&&e.body.content.request_type===ga.ReadState&&su(e.body.content,`ingress_expiry`)&&typeof e.body.content.ingress_expiry==`object`&&e.body.content.ingress_expiry!==null&&cu(e.body.content.ingress_expiry,`toHash`)}async function uu(e,t,n,r={}){let i=[T(`request_status`),n],a,o;if(r.preSignReadStateRequest??!1?(o=await du({paths:[i],agent:e,pollingOptions:r}),a=await e.readState(t,{paths:[i]},void 0,o)):a=await e.readState(t,{paths:[i]}),e.rootKey==null)throw it.fromCode(new Dt);let s=await pc.create({certificate:a.certificate,rootKey:e.rootKey,principal:{canisterId:t},blsVerify:r.blsVerify,agent:e}),c=yc(s.lookup_path([...i,T(`status`)])),l;switch(l=c===void 0?_a.Unknown:new TextDecoder().decode(c),l){case _a.Replied:return{reply:yc(s.lookup_path([...i,`reply`])),certificate:s,rawCertificate:a.certificate};case _a.Received:case _a.Unknown:case _a.Processing:{let i=r.strategy??$l();return await i(t,n,l),uu(e,t,n,{...r,strategy:i,request:o})}case _a.Rejected:throw nt.fromCode(Yc(s,i,n));case _a.Done:throw at.fromCode(new Et(n))}throw qt}async function du(e){let{paths:t,agent:n,pollingOptions:r}=e;if(r.request&&lu(r.request))return r.request;let i=await n.createReadStateRequest?.({paths:t},void 0);if(!lu(i))throw j.fromCode(new Wt(i));return i}var fu=6e4,pu=1e6,mu=0,hu=`308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae`,gu=`ic0.app`,_u=`.ic0.app`,vu=`icp0.io`,yu=`.icp0.io`,bu=`icp-api.io`,xu=`.icp-api.io`,Su=200,Cu=202,wu=404;function Tu(e){let t;if(e!==void 0)t=!e.match(/^[a-z]+:/)&&typeof window<`u`?new URL(`${window.location.protocol}//${e}`):new URL(e);else{let e=[`ic0.app`,`icp0.io`,`127.0.0.1`,`localhost`],n=[`.github.dev`,`.gitpod.io`],r=typeof window<`u`?window.location:void 0,i=r?.hostname,a;i&&typeof i==`string`&&(a=n.some(e=>i.endsWith(e))?i:e.find(e=>i.endsWith(e))),t=r&&a?new URL(`${r.protocol}//${a}${r.port?`:${r.port}`:``}`):new URL(`https://icp-api.io`)}return t.toString()}var Eu=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;get#h(){return this.#p*fu}#g;#_;#v;#y;constructor(e={}){if(this.#e=null,this.#t=!1,this.#n=mu,this.#r=!1,this.#i=null,this.#a=!1,this._isAgent=!0,this.config={},this.log=new Wl,this.#g=[],this.#_=[],this.#v=new Map,this.#y=!0,this.#w=(e,t)=>{if(this.#y===!1)return e;let{status:n,signatures:r=[],requestId:i}=e,a=t.size;if(r.length>a)throw A.fromCode(new Nt(r.length,a));for(let a of r){let{timestamp:r,identity:s}=a,c=O.fromUint8Array(s).toText(),l;if(n===o.Replied){let{reply:t}=e;l=Qr({status:n,reply:t,timestamp:BigInt(r),request_id:i})}else if(n===o.Rejected){let{reject_code:t,reject_message:a,error_code:o}=e;l=Qr({status:n,reject_code:t,reject_message:a,error_code:o,timestamp:BigInt(r),request_id:i})}else throw at.fromCode(new Lt(`Unknown status: ${n}`));let u=E(ei,l),d=t.get(c);if(!d)throw A.fromCode(new Ft);let f=Hl.fromDer(d).rawKey;if(!yl.verify(a.signature,u,f))throw tt.fromCode(new It(c))}return e},this.config=e,e.fetch)this.#s=e.fetch;else{let e=globalThis.fetch;if(typeof e!=`function`)throw j.fromCode(new jt);this.#s=e.bind(globalThis)}this.#c=e.fetchOptions,this.#l=e.callOptions,this.#t=e.shouldFetchRootKey??!1,this.#a=e.shouldSyncTime??!1,this.rootKey=e.rootKey?e.rootKey:this.#t?null:ie(hu);let t=Tu(e.host);this.host=new URL(t),this.host.hostname.endsWith(_u)?this.host.hostname=gu:this.host.hostname.endsWith(yu)?this.host.hostname=vu:this.host.hostname.endsWith(xu)&&(this.host.hostname=bu),e.verifyQuerySignatures!==void 0&&(this.#y=e.verifyQuerySignatures),this.#m=e.subnetNodeKeyExpirableStore??Pl({dbName:`icp-sdk-${this.host.host}`,storeName:`subnetNodeKeys`,expirationTime:5*fu}),this.#d=e.retryTimes??3;let n=()=>new Zl({maxIterations:this.#d});if(this.#f=e.backoffStrategy||n,e.credentials){let{name:t,password:n}=e.credentials;this.#u=`${t}${n?`:${n}`:``}`}if(this.#o=Promise.resolve(e.identity||new ti),e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes>5)throw j.fromCode(new At(`The maximum ingress expiry time is 5 minutes.`,e.ingressExpiryInMinutes));if(e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes<=0)throw j.fromCode(new At(`Ingress expiry time must be greater than 0.`,e.ingressExpiryInMinutes));this.#p=e.ingressExpiryInMinutes||5,this.addTransform(`update`,ya(va)),e.useQueryNonces&&this.addTransform(`query`,ya(va)),e.logToConsole&&this.log.subscribe(e=>{e.level===`error`?console.error(e.message):e.level===`warn`?console.warn(e.message):console.log(e.message)})}static createSync(e={}){return new this({...e})}static async create(t={}){let n=e.createSync(t);return await n.#D(),n}static async from(t){try{return`config`in t?await e.create(t.config):await e.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw j.fromCode(new Mt)}}isLocal(){let e=this.host.hostname;return e===`127.0.0.1`||e.endsWith(`127.0.0.1`)}addTransform(e,t,n=t.priority||0){if(e===`update`){let e=this.#_.findIndex(e=>(e.priority||0)<n);this.#_.splice(e>=0?e:this.#_.length,0,Object.assign(t,{priority:n}))}else if(e===`query`){let e=this.#g.findIndex(e=>(e.priority||0)<n);this.#g.splice(e>=0?e:this.#g.length,0,Object.assign(t,{priority:n}))}}async getPrincipal(){if(!this.#o)throw it.fromCode(new kt);return(await this.#o).getPrincipal()}async call(e,t,n){let r=t.callSync??!0,i=await(n??this.#o);if(!i)throw it.fromCode(new kt);let a=O.from(e),o=t.effectiveCanisterId?O.from(t.effectiveCanisterId):a;await this.#D(o);let s=i.getPrincipal(),c=Du(this.#p,this.#n),l={request_type:ha.Call,canister_id:a,method_name:t.methodName,arg:t.arg,sender:s,ingress_expiry:c},u=await this._transform({request:{body:null,method:`POST`,headers:{"Content-Type":`application/cbor`,...this.#u?{Authorization:`Basic ${btoa(this.#u)}`}:{}}},endpoint:ma.Call,body:l}),d;d=t?.nonce?f(t.nonce):u.body.nonce?f(u.body.nonce):void 0,l.nonce=d;function f(e){return Object.assign(e,{__nonce__:void 0})}u=await i.transformRequest(u);let p=Zr(u.body.content??l),m=da(u.body),h=this.#f();try{let e=r?()=>{let e=new URL(`/api/v4/canister/${o.toText()}/call`,this.host);return this.log.print(`fetching "${e.pathname}" with request:`,u),this.#s(e,{...this.#l,...u.request,body:m})}:()=>{let e=new URL(`/api/v2/canister/${o.toText()}/call`,this.host);return this.log.print(`fetching "${e.pathname}" with request:`,u),this.#s(e,{...this.#l,...u.request,body:m})},{responseBodyBytes:t,...n}=await this.#C({requestFn:e,backoff:h,tries:0}),i=t.byteLength>0?fa(t):null;return{requestId:p,response:{...n,body:i},requestDetails:l}}catch(r){let i;if(r instanceof $e){if(r.hasCode(Vt))return this.log.warn(`v4 api not supported. Fall back to v2`),this.call(e,{...t,callSync:!1},n);if(r.hasCode(At)&&!this.#r)return await this.syncTime(a),this.call(a,t,n);r.code.requestContext={requestId:p,senderPubKey:u.body.sender_pubkey,senderSignature:u.body.sender_sig,ingressExpiry:u.body.content.ingress_expiry},i=r}else i=at.fromCode(new Lt(r));throw this.log.error(`Error while making call: ${i.message}`,i),i}}async update(e,t,n={}){let r=O.from(t.effectiveCanisterId),{requestId:i,response:a,requestDetails:o}=await this.call(e,t),{body:l,...u}=a;if(c(l))return this.#b(l,a,i,r,t.methodName,u,o,n,t.onPollingStarted);if(s(l)&&this.#x(l,i,r,t.methodName,u),a.status===Cu)return t.onPollingStarted?.(),{...await uu(this,r,i,n),requestDetails:o,callResponse:a};let d=new Lt(`Unexpected response from call: status ${a.status} with unrecognized body`);throw d.callContext={canisterId:r,methodName:t.methodName,httpDetails:u},at.fromCode(d)}async#b(e,t,n,r,i,a,o,s,c){if(this.rootKey==null)throw it.fromCode(new Dt);let l=e.certificate,u=await pc.create({certificate:l,rootKey:this.rootKey,principal:{canisterId:r},blsVerify:s.blsVerify,agent:this}),d=[T(`request_status`),n],f=yc(u.lookup_path([...d,T(`status`)])),p=f?new TextDecoder().decode(f):void 0;switch(p){case _a.Replied:return{reply:yc(u.lookup_path([...d,`reply`])),certificate:u,rawCertificate:l,requestDetails:o,callResponse:t};case _a.Rejected:{let e=Yc(u,d,n);throw e.callContext={canisterId:r,methodName:i,httpDetails:a},nt.fromCode(e)}case void 0:return this.log.warn(`v4 sync response certificate does not contain request ID ${w(n)} status. Falling back to polling.`),c?.(),{...await uu(this,r,n,s),requestDetails:o,callResponse:t};default:{let e=new Rt(p,n,t,l);throw e.callContext={canisterId:r,methodName:i,httpDetails:a},at.fromCode(e)}}}#x(e,t,n,r,i){let{reject_code:a,reject_message:o,error_code:s}=e,c=new Tt(t,a,o,s);throw c.callContext={canisterId:n,methodName:r,httpDetails:i},nt.fromCode(c)}async#S(e){let{ecid:t,transformedRequest:n,body:r,requestId:i,backoff:a,tries:o}=e,s=o===0?0:a.next(),c=new URL(`/api/v3/canister/${t.toString()}/query`,this.host);if(this.log.print(`fetching "${c.pathname}" with tries:`,{tries:o,backoff:a,delay:s}),s===null)throw at.fromCode(new xt(`Backoff strategy exhausted after ${o} attempts.`,i));s>0&&await new Promise(e=>setTimeout(e,s));let l;try{this.log.print(`fetching "${c.pathname}" with request:`,n),l=await this.#s(c,{...this.#c,...n.request,body:r})}catch(t){if(o<this.#d)return this.log.warn(`Caught exception while attempting to make query:\n ${t}\n Retrying query.`),await this.#S({...e,tries:o+1});throw rt.fromCode(new Ht(t))}let u=ba(l.headers);if(l.status!==Su){let t=await l.text();if(Ou(t))throw j.fromCode(new At(t,this.#p));if(o<this.#d)return await this.#S({...e,tries:o+1});throw A.fromCode(new Bt(l.status,l.statusText,u,t))}let d={...fa(qr(await l.arrayBuffer())),httpDetails:{ok:l.ok,status:l.status,statusText:l.statusText,headers:u},requestId:i};if(!this.#y)return d;let f=d.signatures?.[0]?.timestamp;if(!f)throw A.fromCode(new Pt(`Timestamp not found in query response. This suggests a malformed or malicious response.`));let p=Number(BigInt(f)/BigInt(pu));if(Date.now()+this.#n-p>this.#h){if(o<this.#d)return this.log.warn(`Timestamp is older than the max ingress expiry. Retrying query.`,{requestId:i,signatureTimestampMs:p}),await this.syncTime(t),await this.#S({...e,tries:o+1});throw tt.fromCode(new St(this.#p,i,o))}return d}async#C(e){let{requestFn:t,backoff:n,tries:r}=e,i=r===0?0:n.next();if(i===null)throw A.fromCode(new xt(`Retry strategy exhausted after ${r} attempts.`));i>0&&await new Promise(e=>setTimeout(e,i));let a,o=new Uint8Array;try{a=await t(),a.status===Su&&(o=qr(await a.clone().arrayBuffer()))}catch(e){if(r<this.#d)return this.log.warn(`Caught exception while attempting to make request:\n ${e}\n Retrying request.`),await this.#C({requestFn:t,backoff:n,tries:r+1});throw rt.fromCode(new Ht(e))}let s=ba(a.headers);if(a.status===Su||a.status===Cu)return{ok:a.ok,status:a.status,statusText:a.statusText,responseBodyBytes:o,headers:s};let c=await a.text();if(a.status===wu&&a.url.includes(`api/v4`))throw A.fromCode(new Vt);if(Ou(c))throw j.fromCode(new At(c,this.#p));if(r<this.#d)return await this.#C({requestFn:t,backoff:n,tries:r+1});throw A.fromCode(new Bt(a.status,a.statusText,s,c))}async query(e,t,n){let r=this.#f(),i=t.effectiveCanisterId?O.from(t.effectiveCanisterId):O.from(e);await this.#D(i),this.log.print(`ecid ${i.toString()}`),this.log.print(`canisterId ${e.toString()}`);let a,o=await(n??this.#o);if(!o)throw it.fromCode(new kt);let s=O.from(e),c=o.getPrincipal(),l=Du(this.#p,this.#n),u={request_type:ga.Query,canister_id:s,method_name:t.methodName,arg:t.arg,sender:c,ingress_expiry:l};a=await this._transform({request:{method:`POST`,headers:{"Content-Type":`application/cbor`,...this.#u?{Authorization:`Basic ${btoa(this.#u)}`}:{}}},endpoint:ma.Query,body:u}),a=await o.transformRequest(a);let d=Zr(a.body.content??u),f=da(a.body),p={canister:s.toText(),ecid:i,transformedRequest:a,body:f,requestId:d,backoff:r,tries:0},m=async()=>{let e=await this.#S(p);return{requestDetails:u,...e}};try{if(!this.#y)return await m();let[e,t]=await Promise.all([m(),this.fetchSubnetKeys(i)]);try{return this.#w(e,t)}catch{this.log.warn(`Query response verification failed. Retrying with fresh subnet keys.`),await this.#m.delete(i.toString());let t=await this.fetchSubnetKeys(i);return this.#w(e,t)}}catch(r){let o;if(r instanceof $e){if(r.hasCode(At)&&!this.#r)return await this.syncTime(i),this.query(e,t,n);r.code.requestContext={requestId:d,senderPubKey:a.body.sender_pubkey,senderSignature:a.body.sender_sig,ingressExpiry:a.body.content.ingress_expiry},o=r}else o=at.fromCode(new Lt(r));throw this.log.error(`Error while making query: ${o.message}`,o),o}}#w;async createReadStateRequest(e,t){await this.#D();let n=await(t??this.#o);if(!n)throw it.fromCode(new kt);let r=n.getPrincipal(),i=await this._transform({request:{method:`POST`,headers:{"Content-Type":`application/cbor`,...this.#u?{Authorization:`Basic ${btoa(this.#u)}`}:{}}},endpoint:ma.ReadState,body:{request_type:ga.ReadState,paths:e.paths,sender:r,ingress_expiry:Du(this.#p,this.#n)}});return n.transformRequest(i)}async readState(e,t,n,r){await this.#O();let i=O.from(e);function a(e){for(let t of e.paths){let[e,n]=t;if(Jr(e,new TextEncoder().encode(`request_status`)))return n}}let o,s;if(r)o=r;else{s=a(t);let e=await this.#o;if(!e)throw it.fromCode(new kt);o=await this.createReadStateRequest(t,e)}let c=new URL(`/api/v3/canister/${i.toString()}/read_state`,this.host);return await this.#T(c,{canisterId:i},o,s)}async readSubnetState(e,t){await this.#O();let n=O.from(e),r=new URL(`/api/v3/subnet/${n.toString()}/read_state`,this.host),i=await this.createReadStateRequest(t,this.#o??void 0);return await this.#T(r,{subnetId:n},i)}async#T(e,t,n,r){let i=this.#f();try{let{responseBodyBytes:t}=await this.#C({requestFn:()=>this.#s(e,{...this.#c,...n.request,body:da(n.body)}),backoff:i,tries:0});return fa(t)}catch(i){let a;if(i instanceof $e){if(i.hasCode(At)&&!this.#r){if(`canisterId`in t)await this.syncTime(t.canisterId);else if(`subnetId`in t)await this.syncTimeWithSubnet(t.subnetId);else throw qt;return await this.#T(e,t,n,r)}i.code.requestContext={requestId:r??Zr(n),senderPubKey:n.body.sender_pubkey,senderSignature:n.body.sender_sig,ingressExpiry:n.body.content.ingress_expiry},a=i}else a=at.fromCode(new Lt(i));throw this.log.error(`Error while making read state: ${a.message}`,a),a}}parseTimeFromResponse(e){let t;if(e.certificate){let n=fa(e.certificate);if(n&&`tree`in n)t=n.tree;else throw A.fromCode(new zt(`Could not decode time from response`));let r=Tc([`time`],t);if(r.status!==Cc.Found)throw A.fromCode(new dt(`Time was not found in the response or was not in its expected format.`,r.status));if(!(r.value instanceof Uint8Array)&&!ArrayBuffer.isView(r))throw A.fromCode(new ft(`Time was not in its expected format.`));let i=oc(r.value);return this.log.print(`Time from response:`,i),this.log.print(`Time from response in milliseconds:`,i.getTime()),i.getTime()}return this.log.warn(`No certificate found in response`),0}async syncTime(t){this.#i=this.#i??(async()=>{await this.#O();let n=Date.now();try{t||this.log.print(`Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai`);let r=t??O.from(`ryjl3-tyaaa-aaaaa-aaaba-cai`),i=e.createSync({identity:new ti,host:this.host.toString(),fetch:this.#s,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),a=await Promise.all([,,,].fill(null).map(async()=>{let e=(await Wc({canisterId:r,agent:i,paths:[`time`],disableCertificateTimeVerification:!0})).get(`time`);if(e instanceof Date)return e.getTime()},[]));this.#E(n,a)}catch(e){let t=e instanceof $e?e:at.fromCode(new Lt(e));throw this.log.error(`Caught exception while attempting to sync time`,t),t}})(),await this.#i.finally(()=>{this.#i=null})}async syncTimeWithSubnet(t){await this.#O();let n=Date.now();try{let r=e.createSync({identity:new ti,host:this.host.toString(),fetch:this.#s,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),i=await Promise.all([,,,].fill(null).map(async()=>{let e=(await qc({subnetId:t,agent:r,paths:[`time`],disableCertificateTimeVerification:!0})).get(`time`);if(e instanceof Date)return e.getTime()},[]));this.#E(n,i)}catch(e){let t=e instanceof $e?e:at.fromCode(new Lt(e));throw this.log.error(`Caught exception while attempting to sync time with subnet`,t),t}}#E(e,t){let n=t.reduce((e,t)=>typeof t==`number`&&t>e?t:e,0);n>0&&(this.#n=n-e,this.#r=!0,this.log.notify({message:`Syncing time: offset of ${this.#n}`,level:`info`}))}async status(){let e=this.#u?{Authorization:`Basic ${btoa(this.#u)}`}:{},t=new URL(`/api/v2/status`,this.host);this.log.print(`fetching "${t.pathname}"`);let n=this.#f(),{responseBodyBytes:r}=await this.#C({backoff:n,requestFn:()=>this.#s(t,{headers:e,...this.#c}),tries:0});return fa(r)}async fetchRootKey(){return this.#e=this.#e??(async()=>{let e=await this.status();return this.rootKey=e.root_key,this.rootKey})(),await this.#e.finally(()=>{this.#e=null})}async#D(e){await Promise.all([this.#O(),this.#k(e)])}async#O(){if(!this.rootKey){if(this.rootKey===null&&this.host.toString()!==`https://icp-api.io`&&this.#t)await this.fetchRootKey();else throw it.fromCode(new Dt(this.#t))}}async#k(e){this.#a&&!this.hasSyncedTime()&&await this.syncTime(e)}invalidateIdentity(){this.#o=null}replaceIdentity(e){this.#o=Promise.resolve(e)}async fetchSubnetKeys(e){let t=O.from(e),n=await this.#m.get(t.toText());if(n)return n;let r=this.#v.get(t.toText());if(r)return r;let i=this.#A(t).finally(()=>{this.#v.delete(t.toText())});return this.#v.set(t.toText(),i),i}async#A(e){await this.#D(e);let t=this.rootKey,n=await this.readState(e,{paths:[[T(`subnet`)]]}),r=await pc.create({certificate:n.certificate,rootKey:t,principal:{canisterId:e},agent:this});if(!r.cert.delegation){let n=O.selfAuthenticating(t);if(!Ac({canisterId:e,subnetId:n,tree:r.cert.tree}))throw tt.fromCode(new lt(e,n))}let i=Lc(r.cert,t),a=Uc(r.cert,i);return await this.#m.set(e.toText(),a),a}async getSubnetIdFromCanister(e){let t=O.from(e);await this.#D(t);let n=await this.readState(t,{paths:[[T(`time`)]]});return Lc((await pc.create({certificate:n.certificate,rootKey:this.rootKey,principal:{canisterId:t},agent:this})).cert,this.rootKey)}_transform(e){let t=Promise.resolve(e);if(e.endpoint===ma.Call)for(let e of this.#_)t=t.then(t=>e(t).then(e=>e||t));else for(let e of this.#g)t=t.then(t=>e(t).then(e=>e||t));return t}getTimeDiffMsecs(){return this.#n}hasSyncedTime(){return this.#r}};function Du(e,t){let n=e*fu;return la.fromDeltaInMilliseconds(n,t)}function Ou(e){return e.includes(`Invalid request expiry: `)}var ku=Symbol.for(`ic-agent-metadata`),Au=class{static agentOf(e){return e[ku].config.agent}static interfaceOf(e){return e[ku].service}static canisterIdOf(e){return O.from(e[ku].config.canisterId)}static createActorClass(e,t){let n=e({IDL:dn});class r extends Au{constructor(e){if(!e.canisterId)throw j.fromCode(new Ut(e.canisterId));let r=typeof e.canisterId==`string`?O.fromText(e.canisterId):e.canisterId;super({config:{...Mu,...e,canisterId:r},service:n});for(let[r,i]of n._fields)t?.httpDetails&&i.annotations.push(Nu),t?.certificate&&i.annotations.push(Pu),this[r]=Fu(this,r,i,e.blsVerify)}}return r}static createActor(e,t){if(!t.canisterId)throw j.fromCode(new Ut(t.canisterId));return new(this.createActorClass(e))(t)}static createActorWithHttpDetails(e,t){return new(this.createActorClass(e,{httpDetails:!0}))(t)}static createActorWithExtendedDetails(e,t,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(e,n))(t)}constructor(e){this[ku]=Object.freeze(e)}};function ju(e,t){let n=Wn(e,t);switch(n.length){case 0:return;case 1:return n[0];default:return n}}var Mu={pollingOptions:au,queryStrategy:`query`},Nu=`http-details`,Pu=`certificate`;function Fu(e,t,n,r){let i,a=n.annotations.includes(`query`)||n.annotations.includes(`composite_query`),s=e[ku].config.queryStrategy;i=a&&s===`query`?async(r,...i)=>{r={...r,...e[ku].config.queryTransform?.(t,i,{...e[ku].config,...r})};let a=r.agent||e[ku].config.agent||new Eu,s=O.from(r.canisterId||e[ku].config.canisterId),c=Un(n.argTypes,i),l=await a.query(s,{methodName:t,arg:c,effectiveCanisterId:r.effectiveCanisterId}),u={...l.httpDetails,requestDetails:l.requestDetails};switch(l.status){case o.Rejected:{let e=new wt(l.requestId,l.reject_code,l.reject_message,l.error_code,l.signatures);throw e.callContext={canisterId:s,methodName:t,httpDetails:u},nt.fromCode(e)}case o.Replied:return n.annotations.includes(`http-details`)?{httpDetails:u,result:ju(n.retTypes,l.reply.arg)}:ju(n.retTypes,l.reply.arg)}}:async(i,...a)=>{i={...i,...e[ku].config.callTransform?.(t,a,{...e[ku].config,...i})};let o=i.agent||e[ku].config.agent||Eu.createSync(),{canisterId:s,effectiveCanisterId:c,pollingOptions:l}={...Mu,...e[ku].config,...i},u=O.from(s),d=c===void 0?u:O.from(c),f=Un(n.argTypes,a),p,m,h,g;try{({reply:p,certificate:m,callResponse:h,requestDetails:g}=await o.update(u,{methodName:t,arg:f,effectiveCanisterId:d,nonce:i.nonce},{...l,blsVerify:r}))}catch(e){if(e instanceof nt){let n=Object.create(Object.getPrototypeOf(e.code),Object.getOwnPropertyDescriptors(e.code));throw n.callContext={...e.code.callContext,canisterId:u,methodName:t},nt.fromCode(n)}throw e}let _=n.annotations.includes(Nu),v=n.annotations.includes(Pu),y={...h,requestDetails:g};return _&&v?{httpDetails:y,certificate:m,result:ju(n.retTypes,p)}:v?{certificate:m,result:ju(n.retTypes,p)}:_?{httpDetails:y,result:ju(n.retTypes,p)}:ju(n.retTypes,p)};let c=(...e)=>i({},...e);return c.withOptions=e=>(...t)=>i(e,...t),c}var Iu=({IDL:e})=>e.Service({get_fiat_rates:e.Func([],[e.Opt(e.Record({rates:e.Vec(e.Tuple(e.Text,e.Float64)),lastUpdated:e.Int}))],[`query`]),get_fiat_rate:e.Func([e.Text],[e.Opt(e.Float64)],[`query`]),get_pybara_admin_config:e.Func([],[e.Record({supported_tokens:e.Vec(e.Text),supported_wallets:e.Vec(e.Text),supported_plugins:e.Vec(e.Text),decimals:e.Vec(e.Tuple(e.Text,e.Nat8)),transfer_fees:e.Vec(e.Tuple(e.Text,e.Nat)),minimums:e.Vec(e.Tuple(e.Text,e.Nat))})],[`query`])}),Lu=({IDL:e})=>{let t=e.Record({id:e.Nat,site_url:e.Text,nanoid:e.Text,registered_at:e.Int,is_founder_rate:e.Bool,commission_bps:e.Nat}),n=e.Record({identity:t,is_allowed:e.Bool,issues_tax_receipts:e.Bool});return e.Service({get_merchant:e.Func([e.Text],[e.Opt(n)],[`query`]),get_recipient:e.Func([e.Text],[e.Opt(n)],[`query`])})},Ru=`https://icp-api.io`,zu=class{constructor(e){this.agent=null,this.adminCoreActor=null,this.adminRegsActor=null,this.adminConfig=null,this.merchantDataCache=new Map,this.recipientDataCache=new Map,this.adminCoreCanisterId=e.adminCoreCanisterId,this.adminRegsCanisterId=e.adminCoreCanisterId===i.staging.admin_core?i.staging.admin_regs:i.prod.admin_regs,this.debug=e.debug??!1}async init(){this.agent=await Eu.create({host:Ru}),this.adminCoreActor=Au.createActor(Iu,{agent:this.agent,canisterId:this.adminCoreCanisterId})}async getFiatRates(){let e=await this.getAdminActor();try{let t=(await e.get_fiat_rates())[0];if(t){let e={};return t.rates.forEach(([t,n])=>{e[t]=n}),e}return await this.fetchFiatRatesFallback()}catch(e){return this.debug&&console.warn(`🧩 ⚠️ Canister fiat rates failed, using fallback:`,e),await this.fetchFiatRatesFallback()}}async getFiatRate(e){if(e===`USD`)return 1;let t=await this.getAdminActor();try{let n=await t.get_fiat_rate(e);return n.length>0?n[0]??null:(await this.getFiatRates())[e]??null}catch(t){return this.debug&&console.warn(`🧩 ⚠️ Failed to get ${e}/USD rate:`,t),(await this.fetchFiatRatesFallback())[e]??null}}async getPybaraAdminConfig(){if(this.adminConfig)return this.adminConfig;let e=await this.getAdminActor();try{let t=await e.get_pybara_admin_config(),n={},r={},i={};t.decimals.forEach(([e,t])=>{n[e]=Number(t)}),t.minimums.forEach(([e,t])=>{r[e]=Number(t)}),t.transfer_fees&&Array.isArray(t.transfer_fees)&&t.transfer_fees.forEach(([e,t])=>{i[e]=t.toString()});let a={supported_tokens:t.supported_tokens||[],supported_wallets:t.supported_wallets||[],supported_plugins:t.supported_plugins||[],decimals:n,minimums:r,transfer_fees:i};return this.adminConfig=a,a}catch(e){throw this.debug&&console.error(`🧩 ❌ Get Pybara admin config failed:`,e),e}}async getMerchantDataWithCache(e){let t=Date.now(),n=this.merchantDataCache.get(e);if(n&&t-n.timestamp<3e5)return this.validateMerchantAccess(n.data),n.data;let r=(await(await this.getRegsActor()).get_merchant(e))?.[0]??null;return this.merchantDataCache.set(e,{data:r,timestamp:t}),this.validateMerchantAccess(r),r}async getRecipientDataWithCache(e){let t=Date.now(),n=this.recipientDataCache.get(e);if(n&&t-n.timestamp<3e5)return this.validateRecipientAccess(n.data),n.data;let r=(await(await this.getRegsActor()).get_recipient(e))?.[0]??null;return this.recipientDataCache.set(e,{data:r,timestamp:t}),this.validateRecipientAccess(r),r}async validatePlugin(e,t){this.adminConfig||await this.getPybaraAdminConfig();let n=this.adminConfig?.supported_plugins||[],r=t?`${e.toLowerCase()}-${t}`:e.toLowerCase();if(!n.includes(r))throw Error(`Plugin disabled by Pybara Administration: ${r}. Please contact Pybara support.`)}async getAgent(){if(this.agent||await this.init(),!this.agent)throw Error(`Agent initialization failed`);return this.agent}async getAdminActor(){return this.adminCoreActor||=Au.createActor(Iu,{agent:await this.getAgent(),canisterId:this.adminCoreCanisterId}),this.adminCoreActor}async getRegsActor(){return this.adminRegsActor||=Au.createActor(Lu,{agent:await this.getAgent(),canisterId:this.adminRegsCanisterId}),this.adminRegsActor}async fetchFiatRatesFallback(){try{let e=await fetch(`https://api.frankfurter.app/latest?from=USD`);if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json(),n={USD:1};for(let[e,r]of Object.entries(t.rates))n[e]=1/r;return n}catch(e){throw this.debug&&console.error(`🧩 ❌ Fiat rates fallback also failed:`,e),Error(`Unable to fetch fiat exchange rates from any source`)}}validateMerchantAccess(e){if(e&&!e.is_allowed)throw Error(`Merchant suspended by Pybara Administration`)}validateRecipientAccess(e){if(e&&!e.is_allowed)throw Error(`Donation recipient suspended by Pybara Administration`)}},Bu={Z_INDEX:999999,BACKGROUND:`rgba(0, 0, 0, 0.7)`},Vu={OVERLAY_FADE_IN_MS:200,PANEL_OPEN_MS:300,PANEL_CLOSE_MS:200,OVERLAY_FADE_OUT_DELAY_MS:50,OVERLAY_FADE_OUT_MS:150},Hu=0,Uu=0,Wu=0;function Gu(e){e.preventDefault()}function Ku(e){e.preventDefault()}function qu(e){e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||[`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&e.preventDefault()}function Ju(){window.scrollTo(Uu,Wu)}function Yu(){Hu===0&&(Uu=window.scrollX,Wu=window.scrollY,window.addEventListener(`wheel`,Gu,{passive:!1}),window.addEventListener(`touchmove`,Ku,{passive:!1}),window.addEventListener(`keydown`,qu),window.addEventListener(`scroll`,Ju)),Hu+=1}function Xu(){Hu!==0&&(--Hu,Hu===0&&(window.removeEventListener(`wheel`,Gu),window.removeEventListener(`touchmove`,Ku),window.removeEventListener(`keydown`,qu),window.removeEventListener(`scroll`,Ju)))}function Zu(){return window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}var Qu=[`DESTINATION_REFUSED`,`INVALID_BENEFICIARY`,`NO_WALLET_AVAILABLE`,`SITE_MISMATCH`];function $u(e){return Qu.includes(e)?e:`UNKNOWN`}var ed=class extends Error{constructor(e,t){super(t),this.name=`EmbeddedError`,this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};function td(e){return typeof e==`object`&&!!e&&typeof e.type==`string`&&e.type.startsWith(`pybara_embedded_`)}var nd=class{constructor(e){this.overlay=null,this.iframe=null,this.spinner=null,this.handleMessage=null,this.handleEscapeKey=null,this.closable=!0,this.iframeLoaded=!1,this.pendingPaymentData=null,this.config=e,this.walletOrigin=new URL(e.walletUrl).origin,this.createIframe()}createIframe(){let e=document.createElement(`div`);e.className=`pybara-checkout-overlay`,e.style.cssText=`
|
|
1
|
+
var Pybara=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.defineProperty,n=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},r={prod:`https://pybara.io`,staging:`https://staging.pybara.io`},i={prod:{admin_core:`mbonm-rqaaa-aaaas-amwoa-cai`,admin_regs:`kng5p-gyaaa-aaaas-amwzq-cai`},staging:{admin_core:`efc3v-fyaaa-aaaak-qy7yq-cai`,admin_regs:`labft-vaaaa-aaaak-qzdda-cai`}},a;(function(e){e[e.SysFatal=1]=`SysFatal`,e[e.SysTransient=2]=`SysTransient`,e[e.DestinationInvalid=3]=`DestinationInvalid`,e[e.CanisterReject=4]=`CanisterReject`,e[e.CanisterError=5]=`CanisterError`})(a||={});var o;(function(e){e.Replied=`replied`,e.Rejected=`rejected`})(o||={});function s(e){return e!=null&&`reject_code`in e}function c(e){return e!=null&&`certificate`in e}var l=`abcdefghijklmnopqrstuvwxyz234567`,u=Object.create(null);for(let e=0;e<32;e++)u[l[e]]=e;u[0]=u.o,u[1]=u.i;function d(e){let t=0,n=0,r=``;function i(e){return t<0?n|=e>>-t:n=e<<t&248,t>3?(t-=8,1):(t<4&&(r+=l[n>>3],t+=5),0)}for(let t=0;t<e.length;)t+=i(e[t]);return r+(t<0?l[n>>3]:``)}function f(e){let t=0,n=0,r=new Uint8Array(e.length*4/3|0),i=0;function a(e){let a=u[e.toLowerCase()];if(a===void 0)throw Error(`Invalid character: ${JSON.stringify(e)}`);a<<=3,n|=a>>>t,t+=5,t>=8&&(r[i++]=n,t-=8,n=t>0?a<<5-t&255:0)}for(let t of e)a(t);return r.slice(0,i)}var p=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function m(e){let t=-1;for(let n=0;n<e.length;n++)t=p[(e[n]^t)&255]^t>>>8;return(t^-1)>>>0}var h=typeof globalThis==`object`&&`crypto`in globalThis?globalThis.crypto:void 0;function g(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function _(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function v(e,...t){if(!g(e))throw Error(`Uint8Array expected`);if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length `+t+`, got length=`+e.length)}function y(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function b(e,t){v(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function x(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ee(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function S(e,t){return e<<32-t|e>>>t}var te=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,C=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function w(e){if(v(e),te)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=C[e[n]];return t}var ne={_0:48,_9:57,A:65,F:70,a:97,f:102};function re(e){if(e>=ne._0&&e<=ne._9)return e-ne._0;if(e>=ne.A&&e<=ne.F)return e-(ne.A-10);if(e>=ne.a&&e<=ne.f)return e-(ne.a-10)}function ie(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(te)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw Error(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=re(e.charCodeAt(i)),a=re(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw Error(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function T(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function ae(e){return typeof e==`string`&&(e=T(e)),v(e),e}function E(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];v(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}var oe=class{};function se(e){let t=t=>e().update(ae(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function ce(e=32){if(h&&typeof h.getRandomValues==`function`)return h.getRandomValues(new Uint8Array(e));if(h&&typeof h.randomBytes==`function`)return Uint8Array.from(h.randomBytes(e));throw Error(`crypto.getRandomValues must be defined`)}function le(e,t,n,r){if(typeof e.setBigUint64==`function`)return e.setBigUint64(t,n,r);let i=BigInt(32),a=BigInt(4294967295),o=Number(n>>i&a),s=Number(n&a),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,s,r)}function ue(e,t,n){return e&t^~e&n}function de(e,t,n){return e&t^e&n^t&n}var fe=class extends oe{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=ee(this.buffer)}update(e){y(this),e=ae(e),v(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=ee(e);for(;r<=i-a;a+=r)this.process(t,a)}else n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){y(this),b(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,x(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;le(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=ee(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen should be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},pe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),me=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),D=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),he=BigInt(2**32-1),ge=BigInt(32);function _e(e,t=!1){return t?{h:Number(e&he),l:Number(e>>ge&he)}:{h:Number(e>>ge&he)|0,l:Number(e&he)|0}}function ve(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=_e(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}var ye=(e,t,n)=>e>>>n,be=(e,t,n)=>e<<32-n|t>>>n,xe=(e,t,n)=>e>>>n|t<<32-n,Se=(e,t,n)=>e<<32-n|t>>>n,Ce=(e,t,n)=>e<<64-n|t>>>n-32,we=(e,t,n)=>e>>>n-32|t<<64-n;function Te(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var Ee=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),De=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Oe=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ke=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Ae=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),je=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,Me=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]),Ne=new Uint32Array(64),Pe=class extends fe{constructor(e=32){super(64,e,8,!1),this.A=pe[0]|0,this.B=pe[1]|0,this.C=pe[2]|0,this.D=pe[3]|0,this.E=pe[4]|0,this.F=pe[5]|0,this.G=pe[6]|0,this.H=pe[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)Ne[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Ne[e-15],n=Ne[e-2],r=S(t,7)^S(t,18)^t>>>3,i=S(n,17)^S(n,19)^n>>>10;Ne[e]=i+Ne[e-7]+r+Ne[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=S(o,6)^S(o,11)^S(o,25),u=l+t+ue(o,s,c)+Me[e]+Ne[e]|0,d=(S(n,2)^S(n,13)^S(n,22))+de(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){x(Ne)}destroy(){this.set(0,0,0,0,0,0,0,0),x(this.buffer)}},Fe=class extends Pe{constructor(){super(28),this.A=me[0]|0,this.B=me[1]|0,this.C=me[2]|0,this.D=me[3]|0,this.E=me[4]|0,this.F=me[5]|0,this.G=me[6]|0,this.H=me[7]|0}},Ie=ve(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(e=>BigInt(e))),Le=Ie[0],Re=Ie[1],ze=new Uint32Array(80),Be=new Uint32Array(80),Ve=class extends fe{constructor(e=64){super(128,e,16,!1),this.Ah=D[0]|0,this.Al=D[1]|0,this.Bh=D[2]|0,this.Bl=D[3]|0,this.Ch=D[4]|0,this.Cl=D[5]|0,this.Dh=D[6]|0,this.Dl=D[7]|0,this.Eh=D[8]|0,this.El=D[9]|0,this.Fh=D[10]|0,this.Fl=D[11]|0,this.Gh=D[12]|0,this.Gl=D[13]|0,this.Hh=D[14]|0,this.Hl=D[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:h}=this;return[e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h]}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let n=0;n<16;n++,t+=4)ze[n]=e.getUint32(t),Be[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=ze[e-15]|0,n=Be[e-15]|0,r=xe(t,n,1)^xe(t,n,8)^ye(t,n,7),i=Se(t,n,1)^Se(t,n,8)^be(t,n,7),a=ze[e-2]|0,o=Be[e-2]|0,s=xe(a,o,19)^Ce(a,o,61)^ye(a,o,6),c=Oe(i,Se(a,o,19)^we(a,o,61)^be(a,o,6),Be[e-7],Be[e-16]),l=ke(c,r,s,ze[e-7],ze[e-16]);ze[e]=l|0,Be[e]=c|0}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:h,Hh:g,Hl:_}=this;for(let e=0;e<80;e++){let t=xe(u,d,14)^xe(u,d,18)^Ce(u,d,41),v=Se(u,d,14)^Se(u,d,18)^we(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=Ae(_,v,b,Re[e],Be[e]),ee=je(x,g,t,y,Le[e],ze[e]),S=x|0,te=xe(n,r,28)^Ce(n,r,34)^Ce(n,r,39),C=Se(n,r,28)^we(n,r,34)^we(n,r,39),w=n&i^n&o^i&o,ne=r&a^r&s^a&s;g=m|0,_=h|0,m=f|0,h=p|0,f=u|0,p=d|0,{h:u,l:d}=Te(c|0,l|0,ee|0,S|0),c=o|0,l=s|0,o=i|0,s=a|0,i=n|0,a=r|0;let re=Ee(S,C,ne);n=De(re,ee,te,w),r=re|0}({h:n,l:r}=Te(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=Te(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=Te(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=Te(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Te(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=Te(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=Te(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=Te(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}roundClean(){x(ze,Be)}destroy(){x(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},He=se(()=>new Pe),Ue=se(()=>new Fe),We=se(()=>new Ve),Ge=`__principal__`,Ke=2,qe=4,Je=`aaaaa-aa`,O=class e{static anonymous(){return new this(new Uint8Array([qe]))}static managementCanister(){return this.fromText(Je)}static selfAuthenticating(e){let t=Ue(e);return new this(new Uint8Array([...t,Ke]))}static from(t){if(typeof t==`string`)return e.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new e(t);if(e.isPrincipal(t))return new e(t._arr);throw Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(e){return new this(ie(e))}static fromText(e){let t=e;if(e.includes(`__principal__`)){let n=JSON.parse(e);`__principal__`in n&&(t=n[Ge])}let n=f(t.toLowerCase().replace(/-/g,``));n=n.slice(4,n.length);let r=new this(n);if(r.toText()!==t)throw Error(`Principal "${r.toText()}" does not have a valid checksum (original value "${t}" may not be a valid Principal ID).`);return r}static fromUint8Array(e){return new this(e)}static isPrincipal(t){return t instanceof e||typeof t==`object`&&!!t&&`_isPrincipal`in t&&t._isPrincipal===!0&&`_arr`in t&&t._arr instanceof Uint8Array}constructor(e){this._arr=e,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===qe}toUint8Array(){return this._arr}toHex(){return w(this._arr).toUpperCase()}toText(){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,m(this._arr));let t=new Uint8Array(e),n=d(new Uint8Array([...t,...this._arr])).match(/.{1,5}/g);if(!n)throw Error();return n.join(`-`)}toString(){return this.toText()}toJSON(){return{[Ge]:this.toText()}}compareTo(e){for(let t=0;t<Math.min(this._arr.length,e._arr.length);t++){if(this._arr[t]<e._arr[t])return`lt`;if(this._arr[t]>e._arr[t])return`gt`}return this._arr.length<e._arr.length?`lt`:this._arr.length>e._arr.length?`gt`:`eq`}ltEq(e){let t=this.compareTo(e);return t==`lt`||t==`eq`}gtEq(e){let t=this.compareTo(e);return t==`gt`||t==`eq`}},Ye;(function(e){e.Trust=`Trust`,e.Protocol=`Protocol`,e.Reject=`Reject`,e.Transport=`Transport`,e.External=`External`,e.Limit=`Limit`,e.Input=`Input`,e.Unknown=`Unknown`})(Ye||={});var Xe;(function(e){e.Normal=`normal`,e.Verbose=`verbose`})(Xe||={});var Ze=new Set([`arg`,`certificate`,`nonce`]);function Qe(e){return(t,n)=>n instanceof Uint8Array?e===Xe.Normal&&Ze.has(t)?`<${n.length} bytes, set ErrorCode.verbosity = ErrorVerbosity.Verbose to display>`:`hex(${n.length}):${w(n)}`:n}var k=class e{static{this.verbosity=Xe.Normal}constructor(e=!1){this.isCertified=e}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`\nRequest context:\n Request ID (hex): ${this.requestContext.requestId?w(this.requestContext.requestId):`undefined`}\n Sender pubkey (hex): ${w(this.requestContext.senderPubKey)}\n Sender signature (hex): ${w(this.requestContext.senderSignature)}\n Ingress expiry: ${this.requestContext.ingressExpiry.toString()}`),this.callContext&&(t+=`\nCall context:\n Canister ID: ${this.callContext.canisterId.toText()}\n Method name: ${this.callContext.methodName}`,`httpDetails`in this.callContext&&(t+=`\n HTTP details: ${JSON.stringify(this.callContext.httpDetails,Qe(e.verbosity),2)}`)),t}},$e=class e extends Error{get code(){return this.cause.code}set code(e){this.cause.code=e}get kind(){return this.cause.kind}set kind(e){this.cause.kind=e}get isCertified(){return this.code.isCertified}constructor(t,n){super(t.toString()),this.name=`AgentError`,this.cause={code:t,kind:n},Object.setPrototypeOf(this,e.prototype)}hasCode(e){return this.code instanceof e}toString(){return`${this.name} (${this.kind}): ${this.message}`}},et=class extends $e{static fromCode(e){return new this(e)}},tt=class e extends et{constructor(t){super(t,Ye.Trust),this.name=`TrustError`,Object.setPrototypeOf(this,e.prototype)}},A=class e extends et{constructor(t){super(t,Ye.Protocol),this.name=`ProtocolError`,Object.setPrototypeOf(this,e.prototype)}},nt=class e extends et{constructor(t){super(t,Ye.Reject),this.name=`RejectError`,Object.setPrototypeOf(this,e.prototype)}},rt=class e extends et{constructor(t){super(t,Ye.Transport),this.name=`TransportError`,Object.setPrototypeOf(this,e.prototype)}},it=class e extends et{constructor(t){super(t,Ye.External),this.name=`ExternalError`,Object.setPrototypeOf(this,e.prototype)}},j=class e extends et{constructor(t){super(t,Ye.Input),this.name=`InputError`,Object.setPrototypeOf(this,e.prototype)}},M=class e extends et{constructor(t){super(t,Ye.Unknown),this.name=`UnknownError`,Object.setPrototypeOf(this,e.prototype)}},at=class e extends k{constructor(t,n){super(),this.reason=t,this.error=n,this.name=`CertificateVerificationErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let e=this.reason;return this.error&&(e+=`: ${Gt(this.error)}`),`Certificate verification error: "${e}"`}},ot=class e extends k{constructor(t,n,r,i,a){super(),this.maxAgeInMinutes=t,this.certificateTime=n,this.currentTime=r,this.timeDiffMsecs=i,this.ageType=a,this.name=`CertificateTimeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`}},st=class e extends k{constructor(){super(),this.name=`CertificateHasTooManyDelegationsErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Certificate has too many delegations`}},ct=class e extends k{constructor(t,n){super(),this.canisterId=t,this.subnetId=n,this.name=`CertificateNotAuthorizedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`}},lt=class e extends k{constructor(t){super(),this.subnetId=t,this.name=`CertificateNotAuthorizedForSubnetErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate is not authorized for subnet ${this.subnetId.toText()}`}},ut=class e extends k{constructor(t,n){super(),this.message=t,this.lookupStatus=n,this.name=`LookupErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}},dt=class e extends k{constructor(t){super(),this.message=t,this.name=`MalformedLookupFoundValueErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},ft=class e extends k{constructor(t){super(),this.message=t,this.name=`MissingLookupValueErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},pt=class e extends k{constructor(t,n){super(),this.expectedLength=t,this.actualLength=n,this.name=`DerKeyLengthMismatchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}},mt=class e extends k{constructor(t,n){super(),this.expectedPrefix=t,this.actualPrefix=n,this.name=`DerPrefixMismatchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${w(this.expectedPrefix)}, but got ${w(this.actualPrefix)}`}},ht=class e extends k{constructor(t,n){super(),this.expectedLength=t,this.actualLength=n,this.name=`DerDecodeLengthMismatchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}},gt=class e extends k{constructor(t){super(),this.error=t,this.name=`DerDecodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},_t=class e extends k{constructor(t){super(),this.error=t,this.name=`DerEncodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},vt=class e extends k{constructor(t,n){super(),this.error=t,this.input=n,this.name=`CborDecodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${Gt(this.error)}, input: ${w(this.input)}`}},yt=class e extends k{constructor(t,n){super(),this.error=t,this.value=n,this.name=`CborEncodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${Gt(this.error)}, input: ${this.value}`}},bt=class e extends k{constructor(t,n,r){super(),this.message=t,this.requestId=n,this.status=r,this.name=`TimeoutWaitingForResponseErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let e=`${this.message}\n`;return this.requestId&&(e+=` Request ID: ${w(this.requestId)}\n`),this.status&&(e+=` Request status: ${this.status}\n`),e}},xt=class e extends k{constructor(t,n,r){super(),this.maxIngressExpiryInMinutes=t,this.requestId=n,this.retryTimes=r,this.name=`CertificateOutdatedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let e=`Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?\n Request ID: ${w(this.requestId)}\n`;return this.retryTimes!==void 0&&(e+=` Retried ${this.retryTimes} times.`),e}},St=class e extends k{constructor(t,n,r,i){super(!0),this.requestId=t,this.rejectCode=n,this.rejectMessage=r,this.rejectErrorCode=i,this.name=`CertifiedRejectErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:\n Request ID: ${w(this.requestId)}\n Reject code: ${this.rejectCode}\n Reject text: ${this.rejectMessage}\n Error code: ${this.rejectErrorCode}\n`}},Ct=class e extends k{constructor(t,n,r,i,a){super(),this.requestId=t,this.rejectCode=n,this.rejectMessage=r,this.rejectErrorCode=i,this.signatures=a,this.name=`UncertifiedRejectErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:\n Request ID: ${w(this.requestId)}\n Reject code: ${this.rejectCode}\n Reject text: ${this.rejectMessage}\n Error code: ${this.rejectErrorCode}\n`}},wt=class e extends k{constructor(t,n,r,i){super(),this.requestId=t,this.rejectCode=n,this.rejectMessage=r,this.rejectErrorCode=i,this.name=`UncertifiedRejectUpdateErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:\n Request ID: ${w(this.requestId)}\n Reject code: ${this.rejectCode}\n Reject text: ${this.rejectMessage}\n Error code: ${this.rejectErrorCode}\n`}},Tt=class e extends k{constructor(t){super(),this.requestId=t,this.name=`RequestStatusDoneNoReplyErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Call was marked as done but we never saw the reply:\n Request ID: ${w(this.requestId)}\n`}},Et=class e extends k{constructor(t){super(),this.shouldFetchRootKey=t,this.name=`MissingRootKeyErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.shouldFetchRootKey===void 0?`Agent is missing root key`:`Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`}},Dt=class e extends k{constructor(t){super(),this.value=t,this.name=`HashValueErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}},Ot=class e extends k{constructor(){super(),this.name=`IdentityInvalidErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`This identity has expired due this application's security policy. Please refresh your authentication.`}},kt=class e extends k{constructor(t,n){super(),this.message=t,this.providedIngressExpiryInMinutes=n,this.name=`IngressExpiryInvalidErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}},At=class e extends k{constructor(){super(),this.name=`MissingFetchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"No fetch implementation available. Provide a `fetch` function in HttpAgentOptions or ensure `globalThis.fetch` is defined."}},jt=class e extends k{constructor(){super(),this.name=`CreateHttpAgentErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to create agent from provided agent`}},Mt=class e extends k{constructor(t,n){super(),this.signatureCount=t,this.maxExpected=n,this.name=`ExcessiveSignaturesErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contains ${this.signatureCount} signatures, which exceeds the subnet size of ${this.maxExpected}. This suggests a malformed or malicious response.`}},Nt=class e extends k{constructor(t){super(),this.error=t,this.name=`MalformedSignatureErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},Pt=class e extends k{constructor(){super(),this.name=`MalformedPublicKeyErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Read state response contained a malformed public key`}},Ft=class e extends k{constructor(t){super(),this.nodeId=t,this.name=`QuerySignatureVerificationFailedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},It=class e extends k{constructor(t){super(),this.error=t,this.name=`UnexpectedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${Gt(this.error)}`}},Lt=class e extends k{constructor(t,n,r,i){super(),this.status=t,this.requestId=n,this.response=r,this.rawCertificate=i,this.name=`UnexpectedV4StatusErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected request status in v4 sync response: "${this.status}"\n Request ID (hex): ${w(this.requestId)}\n Response: ${JSON.stringify(this.response,(e,t)=>t instanceof Uint8Array?`hex(${t.length}):${w(t)}`:t,2)}`}},Rt=class e extends k{constructor(t){super(),this.error=t,this.name=`HashTreeDecodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},zt=class e extends k{constructor(t,n,r,i){super(),this.status=t,this.statusText=n,this.headers=r,this.bodyText=i,this.name=`HttpErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let e=`HTTP request failed:
|
|
2
|
+
Status: ${this.status} (${this.statusText})\n Headers: ${JSON.stringify(this.headers,Qe(k.verbosity))}\n`;return this.bodyText&&(e+=` Body: ${this.bodyText}\n`),e}},Bt=class e extends k{constructor(){super(),this.name=`HttpV4ApiNotSupportedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`HTTP request failed: v4 API is not supported`}},Vt=class e extends k{constructor(t){super(),this.error=t,this.name=`HttpFetchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${Gt(this.error)}`}},Ht=class e extends k{constructor(t){super(),this.receivedCanisterId=t,this.name=`MissingCanisterIdErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Canister ID is required, but received ${typeof this.receivedCanisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`}},Ut=class e extends k{constructor(t){super(),this.request=t,this.name=`InvalidReadStateRequestErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},Wt=class e extends k{constructor(t){super(),this.error=t,this.name=`ExpiryJsonDeserializeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function Gt(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e,Qe(k.verbosity))}catch{return String(e)}}var Kt=Error(`unreachable`);function N(...e){let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}var qt=class{save(){return this._view}restore(e){if(!(e instanceof Uint8Array))throw Error(`Checkpoint must be a Uint8Array`);this._view=e}constructor(e,t=e?.byteLength||0){if(e&&!(e instanceof Uint8Array))try{e=Jt(e)}catch{throw Error(`Buffer must be a Uint8Array`)}if(t<0||!Number.isInteger(t))throw Error(`Length must be a non-negative integer`);if(e&&t>e.byteLength)throw Error(`Length cannot exceed buffer length`);this._buffer=e||new Uint8Array,this._view=new Uint8Array(this._buffer.buffer,0,t)}get buffer(){return this._view.slice()}get byteLength(){return this._view.byteLength}read(e){let t=this._view.subarray(0,e);return this._view=this._view.subarray(e),t.slice()}readUint8(){if(this._view.byteLength===0)return;let e=this._view[0];return this._view=this._view.subarray(1),e}write(e){if(!(e instanceof Uint8Array))throw Error(`Buffer must be a Uint8Array`);let t=this._view.byteLength;this._view.byteOffset+this._view.byteLength+e.byteLength>=this._buffer.byteLength?this.alloc(e.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+e.byteLength),this._view.set(e,t)}get end(){return this._view.byteLength===0}alloc(e){if(e<=0||!Number.isInteger(e))throw Error(`Amount must be a positive integer`);let t=new Uint8Array((this._buffer.byteLength+e)*1.2|0),n=new Uint8Array(t.buffer,0,this._view.byteLength+e);n.set(this._view),this._buffer=t,this._view=n}};function Jt(e){if(!e)throw Error(`Input cannot be null or undefined`);return e instanceof Uint8Array?e:e instanceof ArrayBuffer||Array.isArray(e)?new Uint8Array(e):`buffer`in e?Jt(e.buffer):new Uint8Array(e)}function Yt(e,t){if(e.byteLength!==t.byteLength)return e.byteLength-t.byteLength;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]-t[n];return 0}function Xt(e){if(!(e instanceof Uint8Array))throw Error(`Input must be a Uint8Array`);return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Zt(e){let t=new TextEncoder().encode(e),n=0;for(let e of t)n=(n*223+e)%2**32;return n}function Qt(e){if(/^_\d+_$/.test(e)||/^_0x[0-9a-fA-F]+_$/.test(e)){let t=+e.slice(1,-1);if(Number.isSafeInteger(t)&&t>=0&&t<2**32)return t}return Zt(e)}function $t(e){let t=BigInt(e);if(e<=0)throw RangeError(`Input must be positive`);return t.toString(2).length-1}function en(e){let t=BigInt(e);if(e<0)throw RangeError(`Input must be non-negative`);return BigInt(1)<<t}function tn(){throw Error(`unexpected end of buffer`)}function nn(e,t){return e.byteLength<t&&tn(),e.read(t)}function rn(e){let t=e.readUint8();return t===void 0&&tn(),t}function P(e){if(typeof e==`number`&&(e=BigInt(e)),e<BigInt(0))throw Error(`Cannot leb encode negative values.`);let t=(e===BigInt(0)?0:$t(e))+1,n=new qt(new Uint8Array(t),0);for(;;){let t=Number(e&BigInt(127));if(e/=BigInt(128),e===BigInt(0)){n.write(new Uint8Array([t]));break}n.write(new Uint8Array([t|128]))}return n.buffer}function F(e){let t=BigInt(1),n=BigInt(0),r;do r=rn(e),n+=BigInt(r&127).valueOf()*t,t*=BigInt(128);while(r>=128);return n}function I(e){typeof e==`number`&&(e=BigInt(e));let t=e<BigInt(0);t&&(e=-e-BigInt(1));let n=(e===BigInt(0)?0:$t(e))+1,r=new qt(new Uint8Array(n),0);for(;;){let n=i(e);if(e/=BigInt(128),t&&e===BigInt(0)&&n&64||!t&&e===BigInt(0)&&!(n&64)){r.write(new Uint8Array([n]));break}r.write(new Uint8Array([n|128]))}function i(e){let n=e%BigInt(128);return Number(t?BigInt(128)-n-BigInt(1):n)}return r.buffer}function an(e){let t=new Uint8Array(e.buffer),n=0;for(;n<t.byteLength;n++)if(t[n]<128){if(!(t[n]&64))return F(e);break}let r=new Uint8Array(nn(e,n+1)),i=BigInt(0);for(let e=r.byteLength-1;e>=0;e--)i=i*BigInt(128)+BigInt(128-(r[e]&127)-1);return-i-BigInt(1)}function on(e,t){if(BigInt(e)<BigInt(0))throw Error(`Cannot write negative values.`);return sn(e,t)}function sn(e,t){e=BigInt(e);let n=new qt(new Uint8Array(Math.min(1,t)),0),r=0,i=BigInt(256),a=BigInt(0),o=Number(e%i);for(n.write(new Uint8Array([o]));++r<t;)e<0&&a===BigInt(0)&&o!==0&&(a=BigInt(1)),o=Number((e/i-a)%BigInt(256)),n.write(new Uint8Array([o])),i*=BigInt(256);return n.buffer}function cn(e,t){if(t<=0||!Number.isInteger(t))throw Error(`Byte length must be a positive integer`);let n=BigInt(rn(e)),r=BigInt(1),i=0;for(;++i<t;){r*=BigInt(256);let t=BigInt(rn(e));n+=r*t}return n}function ln(e,t){if(t<=0||!Number.isInteger(t))throw Error(`Byte length must be a positive integer`);let n=cn(e,t),r=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return n>=r&&(n-=r*BigInt(2)),n}var un=n({Bool:()=>qn,BoolClass:()=>Cn,CandidDecodeError:()=>dn,ConstructType:()=>bn,Empty:()=>Wn,EmptyClass:()=>xn,FixedIntClass:()=>An,FixedNatClass:()=>jn,Float32:()=>Qn,Float64:()=>$n,FloatClass:()=>kn,Func:()=>hr,FuncClass:()=>Bn,Int:()=>Xn,Int16:()=>tr,Int32:()=>nr,Int64:()=>rr,Int8:()=>er,IntClass:()=>Dn,Nat:()=>Zn,Nat16:()=>ar,Nat32:()=>or,Nat64:()=>sr,Nat8:()=>ir,NatClass:()=>On,Null:()=>Jn,NullClass:()=>wn,Opt:()=>dr,OptClass:()=>Nn,PrimitiveType:()=>yn,Principal:()=>cr,PrincipalClass:()=>zn,Rec:()=>mr,RecClass:()=>Ln,Record:()=>fr,RecordClass:()=>Pn,Reserved:()=>Gn,ReservedClass:()=>Tn,Service:()=>gr,ServiceClass:()=>Vn,Text:()=>Yn,TextClass:()=>En,Tuple:()=>lr,TupleClass:()=>Fn,Type:()=>vn,Unknown:()=>Kn,UnknownClass:()=>Sn,Variant:()=>pr,VariantClass:()=>In,Vec:()=>ur,VecClass:()=>Mn,Visitor:()=>_n,decode:()=>Un,encode:()=>Hn,resetSubtypeCache:()=>yr,subtype:()=>Sr}),dn=class e extends Error{constructor(t){super(t),this.name=`CandidDecodeError`,Object.setPrototypeOf(this,e.prototype)}},L;(function(e){e[e.Null=-1]=`Null`,e[e.Bool=-2]=`Bool`,e[e.Nat=-3]=`Nat`,e[e.Int=-4]=`Int`,e[e.Float32=-13]=`Float32`,e[e.Float64=-14]=`Float64`,e[e.Text=-15]=`Text`,e[e.Reserved=-16]=`Reserved`,e[e.Empty=-17]=`Empty`,e[e.Opt=-18]=`Opt`,e[e.Vector=-19]=`Vector`,e[e.Record=-20]=`Record`,e[e.Variant=-21]=`Variant`,e[e.Func=-22]=`Func`,e[e.Service=-23]=`Service`,e[e.Principal=-24]=`Principal`})(L||={});var fn=`DIDL`,pn=new TextEncoder().encode(fn),mn=400;function hn(e,t,n){return e.map((e,r)=>n(e,t[r]))}var gn=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(e){return this._idx.has(e.name)}add(e,t){let n=this._typs.length;this._idx.set(e.name,n),this._idxRefCount.set(n,1),this._typs.push(t)}merge(e,t){let n=this._idx.get(e.name),r=this._idx.get(t);if(n===void 0)throw Error(`Missing type index for ${e}`);if(r===void 0)throw Error(`Missing type index for ${t}`);this._typs[n]=this._typs[r];let i=this._getIdxRefCount(n),a=this._getIdxRefCount(r);this._idxRefCount.set(n,i+a),this._idx.set(t,n),this._idxRefCount.set(r,0),this._compactFromEnd()}_getIdxRefCount(e){return this._idxRefCount.get(e)||0}_compactFromEnd(){for(;this._typs.length>0;){let e=this._typs.length-1;if(this._getIdxRefCount(e)>0)break;this._typs.pop(),this._idxRefCount.delete(e)}}encode(){return N(P(this._typs.length),N(...this._typs))}indexOf(e){if(!this._idx.has(e))throw Error(`Missing type index for ${e}`);return I(this._idx.get(e)||0)}},_n=class{visitType(e,t){throw Error(`Not implemented`)}visitPrimitive(e,t){return this.visitType(e,t)}visitEmpty(e,t){return this.visitPrimitive(e,t)}visitBool(e,t){return this.visitPrimitive(e,t)}visitNull(e,t){return this.visitPrimitive(e,t)}visitReserved(e,t){return this.visitPrimitive(e,t)}visitText(e,t){return this.visitPrimitive(e,t)}visitNumber(e,t){return this.visitPrimitive(e,t)}visitInt(e,t){return this.visitNumber(e,t)}visitNat(e,t){return this.visitNumber(e,t)}visitFloat(e,t){return this.visitPrimitive(e,t)}visitFixedInt(e,t){return this.visitNumber(e,t)}visitFixedNat(e,t){return this.visitNumber(e,t)}visitPrincipal(e,t){return this.visitPrimitive(e,t)}visitConstruct(e,t){return this.visitType(e,t)}visitVec(e,t,n){return this.visitConstruct(e,n)}visitOpt(e,t,n){return this.visitConstruct(e,n)}visitRecord(e,t,n){return this.visitConstruct(e,n)}visitTuple(e,t,n){let r=t.map((e,t)=>[`_${t}_`,e]);return this.visitRecord(e,r,n)}visitVariant(e,t,n){return this.visitConstruct(e,n)}visitRec(e,t,n){return this.visitConstruct(t,n)}visitFunc(e,t){return this.visitConstruct(e,t)}visitService(e,t){return this.visitConstruct(e,t)}},R;(function(e){e.EmptyClass=`__IDL_EmptyClass__`,e.UnknownClass=`__IDL_UnknownClass__`,e.BoolClass=`__IDL_BoolClass__`,e.NullClass=`__IDL_NullClass__`,e.ReservedClass=`__IDL_ReservedClass__`,e.TextClass=`__IDL_TextClass__`,e.IntClass=`__IDL_IntClass__`,e.NatClass=`__IDL_NatClass__`,e.FloatClass=`__IDL_FloatClass__`,e.FixedIntClass=`__IDL_FixedIntClass__`,e.FixedNatClass=`__IDL_FixedNatClass__`,e.VecClass=`__IDL_VecClass__`,e.OptClass=`__IDL_OptClass__`,e.RecordClass=`__IDL_RecordClass__`,e.TupleClass=`__IDL_TupleClass__`,e.VariantClass=`__IDL_VariantClass__`,e.RecClass=`__IDL_RecClass__`,e.PrincipalClass=`__IDL_PrincipalClass__`,e.FuncClass=`__IDL_FuncClass__`,e.ServiceClass=`__IDL_ServiceClass__`})(R||={});var vn=class{display(){return this.name}valueToString(e){return z(e)}buildTypeTable(e){e.has(this)||this._buildTypeTableImpl(e)}},yn=class extends vn{checkType(e){if(this.name!==e.name)throw Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`);return e}_buildTypeTableImpl(e){}},bn=class extends vn{checkType(e){if(e instanceof Ln){let t=e.getType();if(t===void 0)throw new dn(`Type mismatch: cannot decode from uninitialized recursive type`);return t}throw Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`)}encodeType(e){return e.indexOf(this.name)}},xn=class extends yn{get typeName(){return R.EmptyClass}static[Symbol.hasInstance](e){return e.typeName===R.EmptyClass}accept(e,t){return e.visitEmpty(this,t)}covariant(e){throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(){throw Error(`Empty cannot appear as a function argument`)}valueToString(){throw Error(`Empty cannot appear as a value`)}encodeType(){return I(L.Empty)}decodeValue(){throw Error(`Empty cannot appear as an output`)}get name(){return`empty`}},Sn=class extends vn{get typeName(){return R.UnknownClass}static[Symbol.hasInstance](e){return e.typeName===R.UnknownClass}checkType(e){throw Error(`Method not implemented for unknown.`)}accept(e,t){throw e.visitType(this,t)}covariant(e){throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(){throw Error(`Unknown cannot appear as a function argument`)}valueToString(){throw Error(`Unknown cannot appear as a value`)}encodeType(){throw Error(`Unknown cannot be serialized`)}decodeValue(e,t){let n=t.decodeValue(e,t);Object(n)!==n&&(n=Object(n));let r;return r=t instanceof Ln?()=>t.getType():()=>t,Object.defineProperty(n,"type",{value:r,writable:!0,enumerable:!1,configurable:!0}),n}_buildTypeTableImpl(){throw Error(`Unknown cannot be serialized`)}get name(){return`Unknown`}},Cn=class extends yn{get typeName(){return R.BoolClass}static[Symbol.hasInstance](e){return e.typeName===R.BoolClass}accept(e,t){return e.visitBool(this,t)}covariant(e){if(typeof e==`boolean`)return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){return new Uint8Array([+!!e])}encodeType(){return I(L.Bool)}decodeValue(e,t){switch(this.checkType(t),rn(e)){case 0:return!1;case 1:return!0;default:throw Error(`Boolean value out of range`)}}get name(){return`bool`}},wn=class extends yn{get typeName(){return R.NullClass}static[Symbol.hasInstance](e){return e.typeName===R.NullClass}accept(e,t){return e.visitNull(this,t)}covariant(e){if(e===null)return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(){return new Uint8Array}encodeType(){return I(L.Null)}decodeValue(e,t){return this.checkType(t),null}get name(){return`null`}},Tn=class extends yn{get typeName(){return R.ReservedClass}static[Symbol.hasInstance](e){return e.typeName===R.ReservedClass}accept(e,t){return e.visitReserved(this,t)}covariant(e){return!0}encodeValue(){return new Uint8Array}encodeType(){return I(L.Reserved)}decodeValue(e,t){return t.name!==this.name&&t.decodeValue(e,t),null}get name(){return`reserved`}},En=class extends yn{get typeName(){return R.TextClass}static[Symbol.hasInstance](e){return e.typeName===R.TextClass}accept(e,t){return e.visitText(this,t)}covariant(e){if(typeof e==`string`)return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){let t=new TextEncoder().encode(e);return N(P(t.byteLength),t)}encodeType(){return I(L.Text)}decodeValue(e,t){this.checkType(t);let n=F(e),r=nn(e,Number(n));return new TextDecoder(`utf8`,{fatal:!0}).decode(r)}get name(){return`text`}valueToString(e){return`"${e}"`}},Dn=class extends yn{get typeName(){return R.IntClass}static[Symbol.hasInstance](e){return e.typeName===R.IntClass}accept(e,t){return e.visitInt(this,t)}covariant(e){if(typeof e==`bigint`||Number.isInteger(e))return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){return I(e)}encodeType(){return I(L.Int)}decodeValue(e,t){return this.checkType(t),an(e)}get name(){return`int`}valueToString(e){return e.toString()}},On=class extends yn{get typeName(){return R.NatClass}static[Symbol.hasInstance](e){return e.typeName===R.NatClass}accept(e,t){return e.visitNat(this,t)}covariant(e){if(typeof e==`bigint`&&e>=BigInt(0)||Number.isInteger(e)&&e>=0)return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){return P(e)}encodeType(){return I(L.Nat)}decodeValue(e,t){return this.checkType(t),F(e)}get name(){return`nat`}valueToString(e){return e.toString()}},kn=class extends yn{get typeName(){return R.FloatClass}static[Symbol.hasInstance](e){return e.typeName===R.FloatClass}constructor(e){if(super(),this._bits=e,e!==32&&e!==64)throw Error(`not a valid float type`)}accept(e,t){return e.visitFloat(this,t)}covariant(e){if(typeof e==`number`||e instanceof Number)return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){let t=new ArrayBuffer(this._bits/8),n=new DataView(t);return this._bits===32?n.setFloat32(0,e,!0):n.setFloat64(0,e,!0),new Uint8Array(t)}encodeType(){return I(this._bits===32?L.Float32:L.Float64)}decodeValue(e,t){this.checkType(t);let n=Xt(nn(e,this._bits/8));return this._bits===32?n.getFloat32(0,!0):n.getFloat64(0,!0)}get name(){return`float${this._bits}`}valueToString(e){return e.toString()}},An=class extends yn{get typeName(){return R.FixedIntClass}static[Symbol.hasInstance](e){return e.typeName===R.FixedIntClass}constructor(e){super(),this._bits=e}accept(e,t){return e.visitFixedInt(this,t)}covariant(e){let t=en(this._bits-1)*BigInt(-1),n=en(this._bits-1)-BigInt(1);if(typeof e==`bigint`){if(e>=t&&e<=n)return!0}else if(Number.isInteger(e)){let r=BigInt(e);if(r>=t&&r<=n)return!0}throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){return sn(e,this._bits/8)}encodeType(){return I(-9-(Math.log2(this._bits)-3))}decodeValue(e,t){this.checkType(t);let n=ln(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(e){return e.toString()}},jn=class extends yn{get typeName(){return R.FixedNatClass}static[Symbol.hasInstance](e){return e.typeName===R.FixedNatClass}constructor(e){super(),this._bits=e}accept(e,t){return e.visitFixedNat(this,t)}covariant(e){let t=en(this._bits);if(typeof e==`bigint`&&e>=BigInt(0)){if(e<t)return!0}else if(Number.isInteger(e)&&e>=0&&BigInt(e)<t)return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){return on(e,this._bits/8)}encodeType(){return I(-5-(Math.log2(this._bits)-3))}decodeValue(e,t){this.checkType(t);let n=cn(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(e){return e.toString()}},Mn=class e extends bn{get typeName(){return R.VecClass}static[Symbol.hasInstance](e){return e.typeName===R.VecClass}constructor(e){super(),this._type=e,this._blobOptimization=!1,e instanceof jn&&e._bits===8&&(this._blobOptimization=!0)}accept(e,t){return e.visitVec(this,this._type,t)}covariant(e){let t=this._type instanceof jn||this._type instanceof An?this._type._bits:0;if(ArrayBuffer.isView(e)&&t==e.BYTES_PER_ELEMENT*8||Array.isArray(e)&&e.every((e,t)=>{try{return this._type.covariant(e)}catch(e){throw Error(`Invalid ${this.display()} argument: \n\nindex ${t} -> ${e.message}`,{cause:e})}}))return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){let t=P(e.length);if(this._blobOptimization)return N(t,new Uint8Array(e));if(ArrayBuffer.isView(e)){if(e instanceof Int16Array||e instanceof Uint16Array){let n=new DataView(new ArrayBuffer(e.length*2));for(let t=0;t<e.length;t++)e instanceof Int16Array?n.setInt16(t*2,e[t],!0):n.setUint16(t*2,e[t],!0);return N(t,new Uint8Array(n.buffer))}if(e instanceof Int32Array||e instanceof Uint32Array){let n=new DataView(new ArrayBuffer(e.length*4));for(let t=0;t<e.length;t++)e instanceof Int32Array?n.setInt32(t*4,e[t],!0):n.setUint32(t*4,e[t],!0);return N(t,new Uint8Array(n.buffer))}if(e instanceof BigInt64Array||e instanceof BigUint64Array){let n=new DataView(new ArrayBuffer(e.length*8));for(let t=0;t<e.length;t++)e instanceof BigInt64Array?n.setBigInt64(t*8,e[t],!0):n.setBigUint64(t*8,e[t],!0);return N(t,new Uint8Array(n.buffer))}return N(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}let n=new qt(new Uint8Array(t.byteLength+e.length),0);n.write(t);for(let t of e){let e=this._type.encodeValue(t);n.write(new Uint8Array(e))}return n.buffer}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let t=I(L.Vector),n=this._type.encodeType(e);e.add(this,N(t,n))}decodeValue(t,n){let r=this.checkType(n);if(!(r instanceof e))throw new dn(`Expected type '${this.display()}', but received non-vector type '${r.display()}'`);let i=Number(F(t));if(this._type instanceof jn){if(this._type._bits==8)return new Uint8Array(t.read(i));if(this._type._bits==16){let e=t.read(i*2);return new Uint16Array(e.buffer,e.byteOffset,i)}if(this._type._bits==32){let e=t.read(i*4);return new Uint32Array(e.buffer,e.byteOffset,i)}if(this._type._bits==64)return new BigUint64Array(t.read(i*8).buffer)}if(this._type instanceof An){if(this._type._bits==8)return new Int8Array(t.read(i));if(this._type._bits==16){let e=t.read(i*2),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Int16Array(i);for(let e=0;e<i;e++)r[e]=n.getInt16(e*2,!0);return r}if(this._type._bits==32){let e=t.read(i*4),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Int32Array(i);for(let e=0;e<i;e++)r[e]=n.getInt32(e*4,!0);return r}if(this._type._bits==64){let e=t.read(i*8),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new BigInt64Array(i);for(let e=0;e<i;e++)r[e]=n.getBigInt64(e*8,!0);return r}}let a=[];for(let e=0;e<i;e++)a.push(this._type.decodeValue(t,r._type));return a}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(e){return`vec {${e.map(e=>this._type.valueToString(e)).join(`; `)}}`}},Nn=class e extends bn{get typeName(){return R.OptClass}static[Symbol.hasInstance](e){return e.typeName===R.OptClass}constructor(e){super(),this._type=e}accept(e,t){return e.visitOpt(this,this._type,t)}covariant(e){try{if(Array.isArray(e)&&(e.length===0||e.length===1&&this._type.covariant(e[0])))return!0}catch(t){throw Error(`Invalid ${this.display()} argument: ${z(e)} \n\n-> ${t.message}`,{cause:t})}throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){return e.length===0?new Uint8Array([0]):N(new Uint8Array([1]),this._type.encodeValue(e[0]))}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let t=I(L.Opt),n=this._type.encodeType(e);e.add(this,N(t,n))}decodeValue(t,n){if(n instanceof wn||n instanceof Tn)return[];let r=n;if(n instanceof Ln){let e=n.getType();if(e===void 0)throw new dn(`Type mismatch: cannot decode from uninitialized recursive type`);r=e}if(r instanceof e)switch(rn(t)){case 0:return[];case 1:{let e=t.save();try{return[this._type.decodeValue(t,r._type)]}catch{return t.restore(e),r._type.decodeValue(t,r._type),[]}}default:throw new dn(`Invalid option value: expected 0 (None) or 1 (Some) for type '${this.display()}'`)}else if(this._type instanceof wn||this._type instanceof e||this._type instanceof Tn)return r.decodeValue(t,r),[];else{let e=t.save();try{return[this._type.decodeValue(t,n)]}catch{return t.restore(e),r.decodeValue(t,n),[]}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(e){return e.length===0?`null`:`opt ${this._type.valueToString(e[0])}`}},Pn=class e extends bn{get typeName(){return R.RecordClass}static[Symbol.hasInstance](e){return e.typeName===R.RecordClass||e.typeName===R.TupleClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((e,t)=>Qt(e[0])-Qt(t[0]))}accept(e,t){return e.visitRecord(this,this._fields,t)}tryAsTuple(){let e=[];for(let t=0;t<this._fields.length;t++){let[n,r]=this._fields[t];if(n!==`_${t}_`)return null;e.push(r)}return e}covariant(e){if(typeof e==`object`&&this._fields.every(([t,n])=>{if(!e.hasOwnProperty(t))throw Error(`Record is missing key "${t}".`);try{return n.covariant(e[t])}catch(e){throw Error(`Invalid ${this.display()} argument: \n\nfield ${t} -> ${e.message}`,{cause:e})}}))return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){let t=this._fields.map(([t])=>e[t]);return N(...hn(this._fields,t,([,e],t)=>e.encodeValue(t)))}_buildTypeTableImpl(e){this._fields.forEach(([t,n])=>n.buildTypeTable(e));let t=I(L.Record),n=P(this._fields.length),r=this._fields.map(([t,n])=>N(P(Qt(t)),n.encodeType(e)));e.add(this,N(t,n,N(...r)))}decodeValue(t,n){let r=this.checkType(n);if(!(r instanceof e))throw new dn(`Expected type '${this.display()}', but received non-record type '${r.display()}'`);let i={},a=0,o=0;for(;o<r._fields.length;){let[e,n]=r._fields[o];if(a>=this._fields.length){n.decodeValue(t,n),o++;continue}let[s,c]=this._fields[a],l=Qt(this._fields[a][0]),u=Qt(e);if(l===u)i[s]=c.decodeValue(t,n),a++,o++;else if(u>l){if(c instanceof Nn||c instanceof Tn)i[s]=[],a++;else throw new dn(`Cannot find required field '${s}' in record, expected fields: [${this._fields.map(([e])=>e).join(`, `)}], received fields: [${r._fields.map(([e])=>e).join(`, `)}]`)}else n.decodeValue(t,n),o++}for(let[e,t]of this._fields.slice(a))if(t instanceof Nn||t instanceof Tn)i[e]=[];else throw new dn(`Cannot find required field '${e}' in record, expected fields: [${this._fields.map(([e])=>e).join(`, `)}], received fields: [${r._fields.map(([e])=>e).join(`, `)}]`);return i}get fieldsAsObject(){let e={};for(let[t,n]of this._fields)e[Qt(t)]=n;return e}get name(){return`record {${this._fields.map(([e,t])=>`${e}:${t.name}`).join(`; `)}}`}display(){return`record {${this._fields.map(([e,t])=>`${e}:${t.display()}`).join(`; `)}}`}valueToString(e){let t=this._fields.map(([t])=>e[t]);return`record {${hn(this._fields,t,([e,t],n)=>`${e}=${t.valueToString(n)}`).join(`; `)}}`}},Fn=class e extends Pn{get typeName(){return R.TupleClass}static[Symbol.hasInstance](e){return e.typeName===R.TupleClass}constructor(e){let t={};e.forEach((e,n)=>t[`_${n}_`]=e),super(t),this._components=e}accept(e,t){return e.visitTuple(this,this._components,t)}covariant(e){if(Array.isArray(e)&&e.length>=this._fields.length&&this._components.every((t,n)=>{try{return t.covariant(e[n])}catch(e){throw Error(`Invalid ${this.display()} argument: \n\nindex ${n} -> ${e.message}`,{cause:e})}}))return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){return N(...hn(this._components,e,(e,t)=>e.encodeValue(t)))}decodeValue(t,n){let r=this.checkType(n);if(!(r instanceof e))throw new dn(`Expected type '${this.display()}', but received non-tuple type '${r.display()}'`);if(r._components.length<this._components.length)throw new dn(`Tuple mismatch: expected ${this._components.length} components, but received ${r._components.length}`);let i=[];for(let[e,n]of r._components.entries())e>=this._components.length?n.decodeValue(t,n):i.push(this._components[e].decodeValue(t,n));return i}display(){return`record {${this._components.map(e=>e.display()).join(`; `)}}`}valueToString(e){return`record {${hn(this._components,e,(e,t)=>e.valueToString(t)).join(`; `)}}`}},In=class e extends bn{get typeName(){return R.VariantClass}static[Symbol.hasInstance](e){return e.typeName===R.VariantClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((e,t)=>Qt(e[0])-Qt(t[0]))}accept(e,t){return e.visitVariant(this,this._fields,t)}covariant(e){if(typeof e==`object`&&Object.entries(e).length===1&&this._fields.every(([t,n])=>{try{return!e.hasOwnProperty(t)||n.covariant(e[t])}catch(e){throw Error(`Invalid ${this.display()} argument: \n\nvariant ${t} -> ${e.message}`,{cause:e})}}))return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){for(let t=0;t<this._fields.length;t++){let[n,r]=this._fields[t];if(e.hasOwnProperty(n))return N(P(t),r.encodeValue(e[n]))}throw Error(`Variant has no data: ${e}`)}_buildTypeTableImpl(e){this._fields.forEach(([,t])=>{t.buildTypeTable(e)});let t=I(L.Variant),n=P(this._fields.length),r=this._fields.map(([t,n])=>N(P(Qt(t)),n.encodeType(e)));e.add(this,N(t,n,...r))}decodeValue(t,n){let r=this.checkType(n);if(!(r instanceof e))throw new dn(`Expected type '${this.display()}', but received non-variant type '${r.display()}'`);let i=Number(F(t));if(i>=r._fields.length)throw Error(`Invalid variant index: ${i}`);let[a,o]=r._fields[i];for(let[e,n]of this._fields)if(Qt(a)===Qt(e)){let r=n.decodeValue(t,o);return{[e]:r}}throw new dn(`Cannot find field hash ${a} in variant, expected fields: [${this._fields.map(([e])=>e).join(`, `)}]`)}get name(){return`variant {${this._fields.map(([e,t])=>`${e}:${t.name}`).join(`; `)}}`}display(){return`variant {${this._fields.map(([e,t])=>e+(t.name===`null`?``:`:${t.display()}`)).join(`; `)}}`}valueToString(e){for(let[t,n]of this._fields)if(e.hasOwnProperty(t)){let r=n.valueToString(e[t]);return r===`null`?`variant {${t}}`:`variant {${t}=${r}}`}throw Error(`Variant has no data: ${e}`)}get alternativesAsObject(){let e={};for(let[t,n]of this._fields)e[Qt(t)]=n;return e}},Ln=class e extends bn{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return R.RecClass}static{this._counter=0}static[Symbol.hasInstance](e){return e.typeName===R.RecClass}accept(e,t){if(!this._type)throw Error(`Recursive type uninitialized.`);return e.visitRec(this,this._type,t)}fill(e){this._type=e}getType(){return this._type}covariant(e){if(this._type&&this._type.covariant(e))return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){if(!this._type)throw Error(`Recursive type uninitialized.`);return this._type.encodeValue(e)}_buildTypeTableImpl(e){if(!this._type)throw Error(`Recursive type uninitialized.`);e.add(this,new Uint8Array([])),this._type.buildTypeTable(e),e.merge(this,this._type.name)}decodeValue(e,t){if(!this._type)throw Error(`Recursive type uninitialized.`);return this._type.decodeValue(e,t)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error(`Recursive type uninitialized.`);return`μ${this.name}.${this._type.name}`}valueToString(e){if(!this._type)throw Error(`Recursive type uninitialized.`);return this._type.valueToString(e)}};function Rn(e){if(rn(e)!==1)throw Error(`Cannot decode principal`);let t=Number(F(e));return O.fromUint8Array(new Uint8Array(nn(e,t)))}var zn=class extends yn{get typeName(){return R.PrincipalClass}static[Symbol.hasInstance](e){return e.typeName===R.PrincipalClass}accept(e,t){return e.visitPrincipal(this,t)}covariant(e){if(e&&e._isPrincipal)return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){let t=e.toUint8Array(),n=P(t.byteLength);return N(new Uint8Array([1]),n,t)}encodeType(){return I(L.Principal)}decodeValue(e,t){return this.checkType(t),Rn(e)}get name(){return`principal`}valueToString(e){return`${this.name} "${e.toText()}"`}},Bn=class extends bn{get typeName(){return R.FuncClass}static[Symbol.hasInstance](e){return e.typeName===R.FuncClass}static argsToString(e,t){if(e.length!==t.length)throw Error(`arity mismatch`);return`(${e.map((e,n)=>e.valueToString(t[n])).join(`, `)})`}constructor(e,t,n=[]){super(),this.argTypes=e,this.retTypes=t,this.annotations=n}accept(e,t){return e.visitFunc(this,t)}covariant(e){if(Array.isArray(e)&&e.length===2&&e[0]&&e[0]._isPrincipal&&typeof e[1]==`string`)return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue([e,t]){let n=e.toUint8Array(),r=P(n.byteLength),i=N(new Uint8Array([1]),r,n),a=new TextEncoder().encode(t),o=P(a.byteLength);return N(new Uint8Array([1]),i,o,a)}_buildTypeTableImpl(e){this.argTypes.forEach(t=>t.buildTypeTable(e)),this.retTypes.forEach(t=>t.buildTypeTable(e));let t=I(L.Func),n=P(this.argTypes.length),r=N(...this.argTypes.map(t=>t.encodeType(e))),i=P(this.retTypes.length),a=N(...this.retTypes.map(t=>t.encodeType(e))),o=P(this.annotations.length),s=N(...this.annotations.map(e=>this.encodeAnnotation(e)));e.add(this,N(t,n,r,i,a,o,s))}decodeValue(e,t){let n=t instanceof Ln?t.getType()??t:t;if(!Sr(n,this))throw Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(rn(e)!==1)throw Error(`Cannot decode function reference`);let r=Rn(e),i=nn(e,Number(F(e)));return[r,new TextDecoder(`utf8`,{fatal:!0}).decode(i)]}get name(){return`(${this.argTypes.map(e=>e.name).join(`, `)}) -> (${this.retTypes.map(e=>e.name).join(`, `)})${` ${this.annotations.join(` `)}`}`}valueToString([e,t]){return`func "${e.toText()}".${t}`}display(){return`(${this.argTypes.map(e=>e.display()).join(`, `)}) → (${this.retTypes.map(e=>e.display()).join(`, `)})${` ${this.annotations.join(` `)}`}`}encodeAnnotation(e){if(e===`query`)return new Uint8Array([1]);if(e===`oneway`)return new Uint8Array([2]);if(e===`composite_query`)return new Uint8Array([3]);throw Error(`Illegal function annotation`)}},Vn=class extends bn{get typeName(){return R.ServiceClass}static[Symbol.hasInstance](e){return e.typeName===R.ServiceClass}constructor(e){super(),this._fields=Object.entries(e).sort((e,t)=>e[0]<t[0]?-1:+(e[0]>t[0]))}accept(e,t){return e.visitService(this,t)}covariant(e){if(e&&e._isPrincipal)return!0;throw Error(`Invalid ${this.display()} argument: ${z(e)}`)}encodeValue(e){let t=e.toUint8Array(),n=P(t.length);return N(new Uint8Array([1]),n,t)}_buildTypeTableImpl(e){this._fields.forEach(([t,n])=>n.buildTypeTable(e));let t=I(L.Service),n=P(this._fields.length),r=this._fields.map(([t,n])=>{let r=new TextEncoder().encode(t);return N(P(r.length),r,n.encodeType(e))});e.add(this,N(t,n,...r))}decodeValue(e,t){let n=t instanceof Ln?t.getType()??t:t;if(!Sr(n,this))throw Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return Rn(e)}get name(){return`service {${this._fields.map(([e,t])=>`${e}:${t.name}`).join(`; `)}}`}valueToString(e){return`service "${e.toText()}"`}fieldsAsObject(){let e={};for(let[t,n]of this._fields)e[t]=n;return e}};function z(e){let t=JSON.stringify(e,(e,t)=>typeof t==`bigint`?`BigInt(${t})`:t);return t&&t.length>mn?`${t.substring(0,397)}...`:t}function Hn(e,t){if(t.length<e.length)throw Error(`Wrong number of message arguments`);let n=new gn;return e.forEach(e=>e.buildTypeTable(n)),N(pn,n.encode(),P(t.length),N(...e.map(e=>e.encodeType(n))),N(...hn(e,t,(e,t)=>{try{e.covariant(t)}catch(e){throw Error(`${e.message}\n\n`)}return e.encodeValue(t)})))}function Un(e,t){let n=new qt(t);if(t.byteLength<4)throw Error(`Message length smaller than magic number`);let r=nn(n,4),i=new TextDecoder().decode(r);if(i!==fn)throw Error(`Wrong magic number: ${JSON.stringify(i)}`);function a(e){let t=[],n=Number(F(e));for(let r=0;r<n;r++){let n=Number(an(e));switch(n){case L.Opt:case L.Vector:{let r=Number(an(e));t.push([n,r]);break}case L.Record:case L.Variant:{let r=[],i=Number(F(e)),a;for(;i--;){let t=Number(F(e));if(t>=2**32)throw Error(`field id out of 32-bit range`);if(typeof a==`number`&&a>=t)throw Error(`field id collision or not sorted`);a=t;let n=Number(an(e));r.push([t,n])}t.push([n,r]);break}case L.Func:{let r=[],i=Number(F(e));for(;i--;)r.push(Number(an(e)));let a=[],o=Number(F(e));for(;o--;)a.push(Number(an(e)));let s=[],c=Number(F(e));for(;c--;)switch(Number(F(e))){case 1:s.push(`query`);break;case 2:s.push(`oneway`);break;case 3:s.push(`composite_query`);break;default:throw Error(`unknown annotation`)}t.push([n,[r,a,s]]);break}case L.Service:{let r=Number(F(e)),i=[];for(;r--;){let t=Number(F(e)),n=new TextDecoder().decode(nn(e,t)),r=an(e);i.push([n,r])}t.push([n,i]);break}default:throw Error(`Illegal op_code: ${n}`)}}let r=[],i=Number(F(e));for(let t=0;t<i;t++)r.push(Number(an(e)));return[t,r]}let[o,s]=a(n);if(s.length<e.length)throw Error(`Wrong number of return values`);let c=o.map(e=>mr());function l(e){if(e<-24)throw Error(`future value not supported`);if(e<0)switch(e){case-1:return Jn;case-2:return qn;case-3:return Zn;case-4:return Xn;case-5:return ir;case-6:return ar;case-7:return or;case-8:return sr;case-9:return er;case-10:return tr;case-11:return nr;case-12:return rr;case-13:return Qn;case-14:return $n;case-15:return Yn;case-16:return Gn;case-17:return Wn;case-24:return cr;default:throw Error(`Illegal op_code: ${e}`)}if(e>=o.length)throw Error(`type index out of range`);return c[e]}function u(e){switch(e[0]){case L.Vector:return ur(l(e[1]));case L.Opt:return dr(l(e[1]));case L.Record:{let t={};for(let[n,r]of e[1]){let e=`_${n}_`;t[e]=l(r)}let n=fr(t),r=n.tryAsTuple();return Array.isArray(r)?lr(...r):n}case L.Variant:{let t={};for(let[n,r]of e[1]){let e=`_${n}_`;t[e]=l(r)}return pr(t)}case L.Func:{let[t,n,r]=e[1];return hr(t.map(e=>l(e)),n.map(e=>l(e)),r)}case L.Service:{let t={},n=e[1];for(let[e,r]of n){let n=l(r);if(n instanceof Ln&&(n=n.getType()),!(n instanceof Bn))throw Error(`Illegal service definition: services can only contain functions`);t[e]=n}return gr(t)}default:throw Error(`Illegal op_code: ${e[0]}`)}}o.forEach((e,t)=>{if(e[0]===L.Func){let n=u(e);c[t].fill(n)}}),o.forEach((e,t)=>{if(e[0]!==L.Func){let n=u(e);c[t].fill(n)}}),yr();let d=s.map(e=>l(e));try{let t=e.map((e,t)=>e.decodeValue(n,d[t]));for(let t=e.length;t<d.length;t++)d[t].decodeValue(n,d[t]);if(n.byteLength>0)throw Error(`decode: Left-over bytes`);return t}finally{yr()}}var Wn=new xn,Gn=new Tn,Kn=new Sn,qn=new Cn,Jn=new wn,Yn=new En,Xn=new Dn,Zn=new On,Qn=new kn(32),$n=new kn(64),er=new An(8),tr=new An(16),nr=new An(32),rr=new An(64),ir=new jn(8),ar=new jn(16),or=new jn(32),sr=new jn(64),cr=new zn;function lr(...e){return new Fn(e)}function ur(e){return new Mn(e)}function dr(e){return new Nn(e)}function fr(e){return new Pn(e)}function pr(e){return new In(e)}function mr(){return new Ln}function hr(e,t,n=[]){return new Bn(e,t,n)}function gr(e){return new Vn(e)}var _r=class e{constructor(e=new Map){this.rels=e}copy(){let t=new Map;for(let[e,n]of this.rels.entries()){let r=new Map(n);t.set(e,r)}return new e(t)}known(e,t){return this.rels.get(e.name)?.get(t.name)}addNegative(e,t){this.addNames(e.name,t.name,!1)}add(e,t){this.addNames(e.name,t.name,!0)}display(){let e=``;for(let[t,n]of this.rels)for(let[r,i]of n)e+=`${t} ${i?`:<`:`!<:`} ${r}\n`;return e}addNames(e,t,n){let r=this.rels.get(e);if(r==null){let r=new Map;r.set(t,n),this.rels.set(e,r)}else r.set(t,n)}},vr=new _r;function yr(){vr=new _r}function br(e,t){let n=new Set(e.annotations),r=new Set(t.annotations);if(n.size!==r.size)return!1;for(let e of n)if(!r.has(e))return!1;return!0}function xr(e){return e instanceof Nn||e instanceof wn||e instanceof Tn}function Sr(e,t){let n=Cr(vr.copy(),e,t);return n?vr.add(e,t):vr.addNegative(e,t),n}function Cr(e,t,n){if(t.name===n.name)return!0;let r=e.known(t,n);if(r!==void 0)return r;if(e.add(t,n),n instanceof Tn||t instanceof xn||t instanceof On&&n instanceof Dn)return!0;if(t instanceof Mn&&n instanceof Mn)return Cr(e,t._type,n._type);if(n instanceof Nn)return!0;if(t instanceof Pn&&n instanceof Pn){let r=t.fieldsAsObject;for(let[t,i]of n._fields){let n=r[Qt(t)];if(!n){if(!xr(i))return!1}else if(!Cr(e,n,i))return!1}return!0}if(t instanceof Bn&&n instanceof Bn){if(!br(t,n))return!1;for(let r=0;r<t.argTypes.length;r++){let i=t.argTypes[r];if(r<n.argTypes.length){if(!Cr(e,n.argTypes[r],i))return!1}else if(!xr(i))return!1}for(let r=0;r<n.retTypes.length;r++){let i=n.retTypes[r];if(r<t.retTypes.length){if(!Cr(e,t.retTypes[r],i))return!1}else if(!xr(i))return!1}return!0}if(t instanceof In&&n instanceof In){let r=n.alternativesAsObject;for(let[n,i]of t._fields){let t=r[Qt(n)];if(!t||!Cr(e,i,t))return!1}return!0}if(t instanceof Vn&&n instanceof Vn){let r=t.fieldsAsObject();for(let[t,i]of n._fields){let n=r[t];if(!n||!Cr(e,n,i))return!1}return!0}return t instanceof Ln?Cr(e,t.getType(),n):n instanceof Ln&&Cr(e,t,n.getType())}var wr=class{constructor(e,t){this.idl=e,this.ui=t,this.label=null,this.value=void 0;let n=document.createElement(`span`);n.className=`status`,this.status=n,t.input&&(t.input.addEventListener(`blur`,()=>{t.input.value!==``&&this.parse()}),t.input.addEventListener(`input`,()=>{n.style.display=`none`,t.input.classList.remove(`reject`)}))}isRejected(){return this.value===void 0}parse(e={}){if(this.ui.form){let t=this.ui.form.parse(e);return this.value=t,t}if(this.ui.input){let t=this.ui.input;try{let n=this.ui.parse(this.idl,e,t.value);if(!this.idl.covariant(n))throw Error(`${t.value} is not of type ${this.idl.display()}`);return this.status.style.display=`none`,this.value=n,n}catch(e){t.classList.add(`reject`),this.status.style.display=`block`,this.status.innerHTML=`InputError: ${e.message}`,this.value=void 0;return}}return null}render(e){let t=document.createElement(`span`);if(this.label){let e=document.createElement(`label`);e.innerText=this.label,t.appendChild(e)}this.ui.input&&(t.appendChild(this.ui.input),t.appendChild(this.status)),this.ui.form&&this.ui.form.render(t),e.appendChild(t)}},Tr=class{constructor(e){this.ui=e,this.form=[]}renderForm(e){this.ui.container?(this.form.forEach(e=>e.render(this.ui.container)),e.appendChild(this.ui.container)):this.form.forEach(t=>t.render(e))}render(e){if(this.ui.open&&this.ui.event){e.appendChild(this.ui.open);let t=this;t.ui.open.addEventListener(t.ui.event,()=>{if(t.ui.container)t.ui.container.innerHTML=``;else{let e=t.ui.open.nextElementSibling;e&&e.parentNode.removeChild(e)}t.generateForm(),t.renderForm(e)})}else this.generateForm(),this.renderForm(e)}},Er=class extends Tr{constructor(e,t){super(t),this.fields=e,this.ui=t}generateForm(){this.form=this.fields.map(([e,t])=>{let n=this.ui.render(t);return n.label=this.ui.labelMap&&this.ui.labelMap.hasOwnProperty(e)?`${this.ui.labelMap[e]} `:`${e} `,n})}parse(e){let t={};if(this.fields.forEach(([n,r],i)=>{let a=this.form[i].parse(e);t[n]=a}),!this.form.some(e=>e.isRejected()))return t}},Dr=class extends Tr{constructor(e,t){super(t),this.components=e,this.ui=t}generateForm(){this.form=this.components.map(e=>this.ui.render(e))}parse(e){let t=[];if(this.components.forEach((n,r)=>{let i=this.form[r].parse(e);t.push(i)}),!this.form.some(e=>e.isRejected()))return t}},Or=class extends Tr{constructor(e,t){super(t),this.fields=e,this.ui=t}generateForm(){let e=this.ui.open.selectedIndex,[t,n]=this.fields[e],r=this.ui.render(n);this.form=[r]}parse(e){let t=this.ui.open,n=t.options[t.selectedIndex].value,r=this.form[0].parse(e);if(r===void 0)return;let i={};return i[n]=r,i}},kr=class extends Tr{constructor(e,t){super(t),this.ty=e,this.ui=t}generateForm(){if(this.ui.open.checked){let e=this.ui.render(this.ty);this.form=[e]}else this.form=[]}parse(e){if(this.form.length===0)return[];let t=this.form[0].parse(e);if(t!==void 0)return[t]}},Ar=class extends Tr{constructor(e,t){super(t),this.ty=e,this.ui=t}generateForm(){let e=+this.ui.open.value;this.form=[];for(let t=0;t<e;t++){let e=this.ui.render(this.ty);this.form.push(e)}}parse(e){let t=this.form.map(t=>t.parse(e));if(!this.form.some(e=>e.isRejected()))return t}},jr={parse:Hr},Mr={render:Ur},Nr=(e,t)=>new wr(e,{...jr,...t}),Pr=(e,t)=>new Er(e,{...Mr,...t}),Fr=(e,t)=>new Dr(e,{...Mr,...t}),Ir=(e,t)=>new Or(e,{...Mr,...t}),Lr=(e,t)=>new kr(e,{...Mr,...t}),Rr=(e,t)=>new Ar(e,{...Mr,...t}),zr=class extends _n{visitType(e,t){let n=document.createElement(`input`);return n.classList.add(`argument`),n.placeholder=e.display(),Nr(e,{input:n})}visitNull(e,t){return Nr(e,{})}visitRecord(e,t,n){let r={};if(t.length>1){let e=document.createElement(`div`);e.classList.add(`popup-form`),r={container:e}}return Nr(e,{form:Pr(t,r)})}visitTuple(e,t,n){let r={};if(t.length>1){let e=document.createElement(`div`);e.classList.add(`popup-form`),r={container:e}}return Nr(e,{form:Fr(t,r)})}visitVariant(e,t,n){let r=document.createElement(`select`);for(let[e,n]of t){let t=new Option(e);r.add(t)}return r.selectedIndex=-1,r.classList.add(`open`),Nr(e,{form:Ir(t,{open:r,event:`change`})})}visitOpt(e,t,n){let r=document.createElement(`input`);return r.type=`checkbox`,r.classList.add(`open`),Nr(e,{form:Lr(t,{open:r,event:`change`})})}visitVec(e,t,n){let r=document.createElement(`input`);r.type=`number`,r.min=`0`,r.max=`100`,r.style.width=`8rem`,r.placeholder=`len`,r.classList.add(`open`);let i=document.createElement(`div`);return i.classList.add(`popup-form`),Nr(e,{form:Rr(t,{open:r,event:`change`,container:i})})}visitRec(e,t,n){return Ur(t)}},Br=class extends _n{visitNull(e,t){return null}visitBool(e,t){if(t===`true`)return!0;if(t===`false`)return!1;throw Error(`Cannot parse ${t} as boolean`)}visitText(e,t){return t}visitFloat(e,t){return parseFloat(t)}visitFixedInt(e,t){return e._bits<=32?parseInt(t,10):BigInt(t)}visitFixedNat(e,t){return e._bits<=32?parseInt(t,10):BigInt(t)}visitNumber(e,t){return BigInt(t)}visitPrincipal(e,t){return O.fromText(t)}visitService(e,t){return O.fromText(t)}visitFunc(e,t){let n=t.split(`.`,2);return[O.fromText(n[0]),n[1]]}},Vr=class extends _n{visitNull(e,t){return null}visitBool(e,t){return Math.random()<.5}visitText(e,t){return Math.random().toString(36).substring(6)}visitFloat(e,t){return Math.random()}visitInt(e,t){return BigInt(this.generateNumber(!0))}visitNat(e,t){return BigInt(this.generateNumber(!1))}visitFixedInt(e,t){let n=this.generateNumber(!0);return e._bits<=32?n:BigInt(t)}visitFixedNat(e,t){let n=this.generateNumber(!1);return e._bits<=32?n:BigInt(t)}generateNumber(e){let t=Math.floor(Math.random()*100);return e&&Math.random()<.5?-t:t}};function Hr(e,t,n){return t.random&&n===``?e.accept(new Vr,n):e.accept(new Br,n)}function Ur(e){return e.accept(new zr,null)}function Wr(e,t,n){return e.accept(new Gr,{input:t,value:n})}var Gr=class extends _n{visitType(e,t){t.input.ui.input.value=e.valueToString(t.value)}visitNull(e,t){}visitText(e,t){t.input.ui.input.value=t.value}visitRec(e,t,n){Wr(t,n.input,n.value)}visitOpt(e,t,n){if(n.value.length!==0){let e=n.input.ui.form,r=e.ui.open;r.checked=!0,r.dispatchEvent(new Event(e.ui.event)),Wr(t,e.form[0],n.value[0])}}visitRecord(e,t,n){let r=n.input.ui.form;t.forEach(([e,t],i)=>{Wr(t,r.form[i],n.value[e])})}visitTuple(e,t,n){let r=n.input.ui.form;t.forEach((e,t)=>{Wr(e,r.form[t],n.value[t])})}visitVariant(e,t,n){let r=n.input.ui.form,i=Object.entries(n.value)[0];t.forEach(([e,t],n)=>{if(e===i[0]){let e=r.ui.open;e.selectedIndex=n,e.dispatchEvent(new Event(r.ui.event)),Wr(t,r.form[0],i[1])}})}visitVec(e,t,n){let r=n.input.ui.form,i=n.value.length,a=r.ui.open;a.value=i,a.dispatchEvent(new Event(r.ui.event)),n.value.forEach((e,n)=>{Wr(t,r.form[n],e)})}};function Kr(e){if(!e)throw Error(`Input cannot be null or undefined`);return e instanceof Uint8Array?e:e instanceof ArrayBuffer||Array.isArray(e)?new Uint8Array(e):`buffer`in e?Kr(e.buffer):new Uint8Array(e)}function qr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Jr(e){if(typeof e==`string`)return Yr(e);if(typeof e==`number`)return He(P(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return He(Kr(e));if(Array.isArray(e))return He(E(...e.map(Jr)));if(e&&typeof e==`object`&&e._isPrincipal)return He(e.toUint8Array());if(typeof e==`object`&&e&&typeof e.toHash==`function`)return Jr(e.toHash());if(typeof e==`object`)return Zr(e);if(typeof e==`bigint`)return He(P(e));throw j.fromCode(new Dt(e))}var Yr=e=>He(new TextEncoder().encode(e));function Xr(e){return Zr(e)}function Zr(e){return He(E(...Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>[Yr(e),Jr(t)]).sort(([e],[t])=>Yt(e,t)).map(e=>E(...e))))}var Qr=new TextEncoder().encode(`\ric-state-root`);new TextEncoder().encode(`
|
|
3
|
+
ic-request`);var $r=new TextEncoder().encode(`\vic-response`);new TextEncoder().encode(`ic-request-auth-delegation`);var ei=class{getPrincipal(){return O.anonymous()}async transformRequest(e){return{...e,body:{content:e.body}}}},ti=class extends Error{constructor(e){super(e),this.name=`DecodingError`}},ni=55799,ri=Symbol(`CBOR_STOP_CODE`),ii=(e=>(e[e.False=20]=`False`,e[e.True=21]=`True`,e[e.Null=22]=`Null`,e[e.Undefined=23]=`Undefined`,e[e.Break=31]=`Break`,e))(ii||{}),B=(e=>(e[e.UnsignedInteger=0]=`UnsignedInteger`,e[e.NegativeInteger=1]=`NegativeInteger`,e[e.ByteString=2]=`ByteString`,e[e.TextString=3]=`TextString`,e[e.Array=4]=`Array`,e[e.Map=5]=`Map`,e[e.Tag=6]=`Tag`,e[e.Simple=7]=`Simple`,e))(B||{}),ai=23,oi=255,si=65535,ci=4294967295,li=BigInt(`0xffffffffffffffff`),ui=(e=>(e[e.Value=23]=`Value`,e[e.OneByte=24]=`OneByte`,e[e.TwoBytes=25]=`TwoBytes`,e[e.FourBytes=26]=`FourBytes`,e[e.EightBytes=27]=`EightBytes`,e[e.Indefinite=31]=`Indefinite`,e))(ui||{}),di=!1;function fi(e){return e==null}function pi(e,t){let n=new Uint8Array(t);return n.set(e),n}var mi=new TextDecoder;function hi(e){return(e&224)>>5}function gi(e){return e&31}var _i=new Uint8Array,vi,yi=0;function bi(e,t){_i=e,yi=0;let n=xi(t);return t?.(n)??n}function xi(e){let[t,n]=Si();switch(t){case B.UnsignedInteger:return Ei(n);case B.NegativeInteger:return Di(n);case B.ByteString:return Oi(n);case B.TextString:return ki(n);case B.Array:return Ci(n,e);case B.Map:return Ti(n,e);case B.Tag:return Ai(n,e);case B.Simple:return wi(n)}throw new ti(`Unsupported major type: ${t}`)}function Si(){let e=_i.at(yi);if(fi(e))throw new ti(`Provided CBOR data is empty`);let t=hi(e),n=gi(e);return yi++,[t,n]}function Ci(e,t){let n=Ei(e);if(n===1/0){let e=[],n=xi(t);for(;n!==ri;)e.push(t?.(n)??n),n=xi(t);return e}let r=Array(n);for(let e=0;e<n;e++){let n=xi(t);r[e]=t?.(n)??n}return r}function wi(e){switch(e){case ii.False:return!1;case ii.True:return!0;case ii.Null:return null;case ii.Undefined:return;case ii.Break:return ri}throw new ti(`Unrecognized simple type: ${e.toString(2)}`)}function Ti(e,t){let n=Ei(e),r={};if(n===1/0){let[e,n]=Si();for(;e!==B.Simple&&n!==ii.Break;){let i=ki(n),a=xi(t);r[i]=t?.(a,i)??a,[e,n]=Si()}return r}for(let e=0;e<n;e++){let[e,n]=Si();if(e!==B.TextString)throw new ti(`Map keys must be text strings`);let i=ki(n),a=xi(t);r[i]=t?.(a,i)??a}return r}function Ei(e){if(e<=ui.Value)return e;switch(vi=new DataView(_i.buffer,_i.byteOffset+yi),e){case ui.OneByte:return yi++,vi.getUint8(0);case ui.TwoBytes:return yi+=2,vi.getUint16(0,di);case ui.FourBytes:return yi+=4,vi.getUint32(0,di);case ui.EightBytes:return yi+=8,vi.getBigUint64(0,di);case ui.Indefinite:return 1/0;default:throw new ti(`Unsupported integer info: ${e.toString(2)}`)}}function Di(e){let t=Ei(e);return typeof t==`number`?-1-t:-1n-t}function Oi(e){let t=Ei(e);if(t>2**53-1)throw new ti(`Byte length is too large`);let n=Number(t);return yi+=n,_i.slice(yi-n,yi)}function ki(e){let t=Oi(e);return mi.decode(t)}function Ai(e,t){let n=Ei(e);if(n===ni)return xi(t);throw new ti(`Unsupported tag: ${n}.`)}var ji=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},Mi=2048,Ni=100,Pi=new TextEncoder;function Fi(e){return e<<5}var Ii=new Uint8Array(Mi),Li=new DataView(Ii.buffer),V=0,Ri=[];function zi(e,t){return V=0,ea(ni,t?.(e)??e,t),Ii.slice(0,V)}function Bi(e){let t=Ii.length*2;for(;t<e;)t*=2;Ii=pi(Ii,t),Li=new DataView(Ii.buffer)}function Vi(e,t){if(e===!1||e===!0||e==null)Gi(e);else if(typeof e==`number`||typeof e==`bigint`)Zi(e);else if(typeof e==`string`)Qi(e);else if(e instanceof Uint8Array)$i(e);else if(e instanceof ArrayBuffer)$i(new Uint8Array(e));else if(Array.isArray(e))Hi(e,t);else if(typeof e==`object`)Ui(e,t);else throw new ji(`Unsupported type: ${typeof e}`)}function Hi(e,t){Wi(B.Array,e.length),e.forEach((e,n)=>{Vi(t?.(e,n.toString())??e,t)})}function Ui(e,t){Ri=Object.entries(e),Wi(B.Map,Ri.length),Ri.forEach(([e,n])=>{Qi(e),Vi(t?.(n,e)??n,t)})}function Wi(e,t){if(V>Ii.length-Ni&&Bi(V+Ni),t<=ai)Li.setUint8(V++,Fi(e)|Number(t));else if(t<=oi)Li.setUint8(V++,Fi(e)|ui.OneByte),Li.setUint8(V,Number(t)),V+=1;else if(t<=si)Li.setUint8(V++,Fi(e)|ui.TwoBytes),Li.setUint16(V,Number(t),di),V+=2;else if(t<=ci)Li.setUint8(V++,Fi(e)|ui.FourBytes),Li.setUint32(V,Number(t),di),V+=4;else if(t<=li)Li.setUint8(V++,Fi(e)|ui.EightBytes),Li.setBigUint64(V,BigInt(t),di),V+=8;else throw new ji(`Value too large to encode: ${t}`)}function Gi(e){Wi(B.Simple,Ki(e))}function Ki(e){if(e===!1)return ii.False;if(e===!0)return ii.True;if(e===null)return ii.Null;if(e===void 0)return ii.Undefined;throw new ji(`Unrecognized simple value: ${e.toString()}`)}function qi(e,t){Wi(e,t.length),V>Ii.length-t.length&&Bi(V+t.length),Ii.set(t,V),V+=t.length}function Ji(e,t){Wi(e,t)}function Yi(e){Ji(B.UnsignedInteger,e)}function Xi(e){Ji(B.NegativeInteger,typeof e==`bigint`?-1n-e:-1-e)}function Zi(e){e>=0?Yi(e):Xi(e)}function Qi(e){qi(B.TextString,Pi.encode(e))}function $i(e){qi(B.ByteString,e)}function ea(e,t,n){Wi(B.Tag,e),Vi(t,n)}var ta=`__expiry__`,na=BigInt(1e3),ra=BigInt(1e6),ia=BigInt(60)*na,aa=BigInt(1)*ia;function oa(e){return e/na*na}function sa(e){return e/ia*ia}var ca=class e{constructor(e){this.__expiry__=e,this._isExpiry=!0}static fromDeltaInMilliseconds(t,n=0){let r=BigInt(Date.now())+BigInt(n),i=r+BigInt(t),a=sa(i),o;return o=a>=r+aa?a:oa(i),new e(o*ra)}toBigInt(){return this.__expiry__}toHash(){return P(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[ta]:this.toString()}}static fromJSON(t){let n=JSON.parse(t);if(n.__expiry__)try{let t=BigInt(n[ta]);return new e(t)}catch(e){throw new j(new Wt(`Not a valid BigInt: ${e}`))}throw new j(new Wt(`The input does not contain the key ${ta}`))}static isExpiry(t){return t instanceof e||typeof t==`object`&&!!t&&`_isExpiry`in t&&t._isExpiry===!0&&`__expiry__`in t&&typeof t.__expiry__==`bigint`}};function la(e){return typeof e==`object`&&!!e&&`toCborValue`in e}function ua(e){try{return zi(e,e=>O.isPrincipal(e)?e.toUint8Array():ca.isExpiry(e)?e.toBigInt():la(e)?e.toCborValue():e)}catch(t){throw j.fromCode(new yt(t,e))}}function da(e){try{return bi(e)}catch(t){throw j.fromCode(new vt(t,e))}}var fa=()=>{if(typeof window<`u`&&window.crypto&&window.crypto.getRandomValues){let e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if(typeof crypto<`u`&&crypto.getRandomValues){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return typeof crypto<`u`&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)},pa;(function(e){e.Query=`read`,e.ReadState=`read_state`,e.Call=`call`})(pa||={});var ma;(function(e){e.Call=`call`})(ma||={});var ha;(function(e){e.Query=`query`,e.ReadState=`read_state`})(ha||={});var ga;(function(e){e.Received=`received`,e.Processing=`processing`,e.Replied=`replied`,e.Rejected=`rejected`,e.Unknown=`unknown`,e.Done=`done`})(ga||={});function _a(){let e=new ArrayBuffer(16),t=new DataView(e),n=fa(),r=fa(),i=fa(),a=fa();return t.setUint32(0,n),t.setUint32(4,r),t.setUint32(8,i),t.setUint32(12,a),Object.assign(new Uint8Array(e),{__nonce__:void 0})}function va(e=_a){return async t=>{let n=t.request.headers;t.request.headers=n,t.endpoint===pa.Call&&(t.body.nonce=e())}}function ya(e){let t=[];return e.forEach((e,n)=>{t.push([n,e])}),t}var ba=BigInt(0),xa=BigInt(1);function Sa(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}"`;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function Ca(e,t,n=``){let r=g(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function wa(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?ba:BigInt(`0x`+e)}function Ta(e){return wa(w(e))}function Ea(e){return v(e),wa(w(Uint8Array.from(e).reverse()))}function H(e,t){return ie(e.toString(16).padStart(t*2,`0`))}function Da(e,t){return H(e,t).reverse()}function U(e,t,n){let r;if(typeof t==`string`)try{r=ie(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(g(t))r=Uint8Array.from(t);else throw Error(e+` must be hex string or Uint8Array`);let i=r.length;if(typeof n==`number`&&i!==n)throw Error(e+` of length `+n+` expected, got `+i);return r}function Oa(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function ka(e){return Uint8Array.from(e)}var Aa=e=>typeof e==`bigint`&&ba<=e;function ja(e,t,n){return Aa(e)&&Aa(t)&&Aa(n)&&t<=e&&e<n}function Ma(e,t,n,r){if(!ja(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function Na(e){let t=0;for(;e>ba;e>>=xa,t+=1);return t}function Pa(e,t){return e>>BigInt(t)&xa}var Fa=e=>(xa<<BigInt(e))-xa;function Ia(e){return typeof e==`function`&&Number.isSafeInteger(e.outputLen)}function La(e,t,n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}var Ra=()=>{throw Error(`not implemented`)};function za(e){let t=new WeakMap;return(n,...r)=>{let i=t.get(n);if(i!==void 0)return i;let a=e(n,...r);return t.set(n,a),a}}var W=BigInt(0),G=BigInt(1),Ba=BigInt(2),Va=BigInt(3),Ha=BigInt(4),Ua=BigInt(5),Wa=BigInt(7),Ga=BigInt(8),Ka=BigInt(9),qa=BigInt(16);function K(e,t){let n=e%t;return n>=W?n:t+n}function Ja(e,t,n){let r=e;for(;t-->W;)r*=r,r%=n;return r}function Ya(e,t){if(e===W)throw Error(`invert: expected non-zero number`);if(t<=W)throw Error(`invert: expected positive modulus, got `+t);let n=K(e,t),r=t,i=W,a=G,o=G,s=W;for(;n!==W;){let e=r/n,t=r%n,c=i-o*e,l=a-s*e;r=n,n=t,i=o,a=s,o=c,s=l}if(r!==G)throw Error(`invert: does not exist`);return K(i,t)}function Xa(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function Za(e,t){let n=(e.ORDER+G)/Ha,r=e.pow(t,n);return Xa(e,r,t),r}function Qa(e,t){let n=(e.ORDER-Ua)/Ga,r=e.mul(t,Ba),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,Ba),i),s=e.mul(a,e.sub(o,e.ONE));return Xa(e,s,t),s}function $a(e){let t=lo(e),n=eo(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+Wa)/qa;return(e,t)=>{let n=e.pow(t,o),s=e.mul(n,r),c=e.mul(n,i),l=e.mul(n,a),u=e.eql(e.sqr(s),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,s,u),s=e.cmov(l,c,d);let f=e.eql(e.sqr(s),t),p=e.cmov(n,s,f);return Xa(e,p,t),p}}function eo(e){if(e<Va)throw Error(`sqrt is not defined for small field`);let t=e-G,n=0;for(;t%Ba===W;)t/=Ba,n++;let r=Ba,i=lo(e);for(;so(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return Za;let a=i.pow(r,t),o=(t+G)/Ba;return function(e,r){if(e.is0(r))return r;if(so(e,r)!==1)throw Error(`Cannot find square root`);let i=n,s=e.mul(e.ONE,a),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw Error(`Cannot find square root`);let r=G<<BigInt(i-t-1),a=e.pow(s,r);i=t,s=e.sqr(a),c=e.mul(c,s),l=e.mul(l,a)}return l}}function to(e){return e%Ha===Va?Za:e%Ga===Ua?Qa:e%qa===Ka?$a(e):eo(e)}var no=(e,t)=>(K(e,t)&G)===G,ro=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function io(e){return La(e,ro.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function ao(e,t,n){if(n<W)throw Error(`invalid exponent, negatives unsupported`);if(n===W)return e.ONE;if(n===G)return t;let r=e.ONE,i=t;for(;n>W;)n&G&&(r=e.mul(r,i)),i=e.sqr(i),n>>=G;return r}function oo(e,t,n=!1){let r=Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),a=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),a),r}function so(e,t){let n=(e.ORDER-G)/Ba,r=e.pow(t,n),i=e.eql(r,e.ONE),a=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!a&&!o)throw Error(`invalid Legendre symbol result`);return i?1:a?0:-1}function co(e,t){t!==void 0&&_(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function lo(e,t,n=!1,r={}){if(e<=W)throw Error(`invalid field: expected ORDER > 0, got `+e);let i,a,o=!1,s;if(typeof t==`object`&&t){if(r.sqrt||n)throw Error(`cannot specify opts in two arguments`);let e=t;e.BITS&&(i=e.BITS),e.sqrt&&(a=e.sqrt),typeof e.isLE==`boolean`&&(n=e.isLE),typeof e.modFromBytes==`boolean`&&(o=e.modFromBytes),s=e.allowedLengths}else typeof t==`number`&&(i=t),r.sqrt&&(a=r.sqrt);let{nBitLength:c,nByteLength:l}=co(e,i);if(l>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);let u,d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:Fa(c),ZERO:W,ONE:G,allowedLengths:s,create:t=>K(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof t);return W<=t&&t<e},is0:e=>e===W,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&G)===G,neg:t=>K(-t,e),eql:(e,t)=>e===t,sqr:t=>K(t*t,e),add:(t,n)=>K(t+n,e),sub:(t,n)=>K(t-n,e),mul:(t,n)=>K(t*n,e),pow:(e,t)=>ao(d,e,t),div:(t,n)=>K(t*Ya(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Ya(t,e),sqrt:a||(t=>(u||=to(e),u(d,t))),toBytes:e=>n?Da(e,l):H(e,l),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw Error(`Field.fromBytes: expected `+s+` bytes, got `+t.length);let e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw Error(`Field.fromBytes: expected `+l+` bytes, got `+t.length);let i=n?Ea(t):Ta(t);if(o&&(i=K(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>oo(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function uo(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function fo(e){let t=uo(e);return t+Math.ceil(t/2)}function po(e,t,n=!1){let r=e.length,i=uo(t),a=fo(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=K(n?Ea(e):Ta(e),t-G)+G;return n?Da(o,i):H(o,i)}var mo=BigInt(0),ho=BigInt(1);function go(e,t){let n=t.negate();return e?n:t}function _o(e,t){let n=oo(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function vo(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function yo(e,t){vo(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:Fa(e),maxNumber:i,shiftBy:BigInt(e)}}function bo(e,t,n){let{windowSize:r,mask:i,maxNumber:a,shiftBy:o}=n,s=Number(e&i),c=e>>o;s>r&&(s-=a,c+=ho);let l=t*r,u=l+Math.abs(s)-1,d=s===0,f=s<0,p=t%2!=0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function xo(e,t){if(!Array.isArray(e))throw Error(`array expected`);e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function So(e,t){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,n)=>{if(!t.isValid(e))throw Error(`invalid scalar at index `+n)})}var Co=new WeakMap,wo=new WeakMap;function To(e){return wo.get(e)||1}function Eo(e){if(e!==mo)throw Error(`invalid wNAF`)}var Do=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>mo;)t&ho&&(n=n.add(r)),r=r.double(),t>>=ho;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=yo(t,this.bits),i=[],a=e,o=a;for(let e=0;e<n;e++){o=a,i.push(o);for(let e=1;e<r;e++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw Error(`invalid scalar`);let r=this.ZERO,i=this.BASE,a=yo(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=bo(n,e,a);n=o,c?i=i.add(go(u,t[d])):r=r.add(go(l,t[s]))}return Eo(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=yo(e,this.bits);for(let e=0;e<i.windows&&n!==mo;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=bo(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return Eo(n),r}getPrecomputes(e,t,n){let r=Co.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),Co.set(t,r))),r}cached(e,t,n){let r=To(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=To(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){vo(t,this.bits),wo.set(e,t),Co.delete(e)}hasCache(e){return To(e)!==1}};function Oo(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>mo||r>mo;)n&ho&&(a=a.add(i)),r&ho&&(o=o.add(i)),i=i.double(),n>>=ho,r>>=ho;return{p1:a,p2:o}}function ko(e,t,n,r){xo(n,e),So(r,t);let i=n.length,a=r.length;if(i!==a)throw Error(`arrays of points and scalars must have equal length`);let o=e.ZERO,s=Na(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=Fa(c),u=Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c,f=o;for(let e=d;e>=0;e-=c){u.fill(o);for(let t=0;t<a;t++){let i=r[t],a=Number(i>>BigInt(e)&l);u[a]=u[a].add(n[t])}let t=o;for(let e=u.length-1,n=o;e>0;e--)n=n.add(u[e]),t=t.add(n);if(f=f.add(t),e!==0)for(let e=0;e<c;e++)f=f.double()}return f}function Ao(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return io(t),t}return lo(e,{isLE:n})}function jo(e,t,n={},r){if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(typeof n==`bigint`&&n>mo))throw Error(`CURVE.${e} must be positive bigint`)}let i=Ao(t.p,n.Fp,r),a=Ao(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}var Mo=Ta;function No(e,t){if(Fo(e),Fo(t),e<0||e>=1<<8*t)throw Error(`invalid I2OSP input: `+e);let n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function Po(e,t){let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function Fo(e){if(!Number.isSafeInteger(e))throw Error(`number expected`)}function Io(e){if(!g(e)&&typeof e!=`string`)throw Error(`DST must be Uint8Array or string`);return typeof e==`string`?T(e):e}function Lo(e,t,n,r){v(e),Fo(n),t=Io(t),t.length>255&&(t=r(E(T(`H2C-OVERSIZE-DST-`),t)));let{outputLen:i,blockLen:a}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw Error(`expand_message_xmd: invalid lenInBytes`);let s=E(t,No(t.length,1)),c=No(0,a),l=No(n,2),u=Array(o),d=r(E(c,e,l,No(0,1),s));u[0]=r(E(d,No(1,1),s));for(let e=1;e<=o;e++){let t=[Po(d,u[e-1]),No(e+1,1),s];u[e]=r(E(...t))}return E(...u).slice(0,n)}function Ro(e,t,n,r,i){if(v(e),Fo(n),t=Io(t),t.length>255){let e=Math.ceil(2*r/8);t=i.create({dkLen:e}).update(T(`H2C-OVERSIZE-DST-`)).update(t).digest()}if(n>65535||t.length>255)throw Error(`expand_message_xof: invalid lenInBytes`);return i.create({dkLen:n}).update(e).update(No(n,2)).update(t).update(No(t.length,1)).digest()}function zo(e,t,n){La(n,{p:`bigint`,m:`number`,k:`number`,hash:`function`});let{p:r,k:i,m:a,hash:o,expand:s,DST:c}=n;if(!Ia(n.hash))throw Error(`expected valid hash`);v(e),Fo(t);let l=r.toString(2).length,u=Math.ceil((l+i)/8),d=t*a*u,f;if(s===`xmd`)f=Lo(e,c,d,o);else if(s===`xof`)f=Ro(e,c,d,i,o);else if(s===`_internal_pass`)f=e;else throw Error(`expand must be "xmd" or "xof"`);let p=Array(t);for(let e=0;e<t;e++){let t=Array(a);for(let n=0;n<a;n++){let i=u*(n+e*a),o=f.subarray(i,i+u);t[n]=K(Mo(o),r)}p[e]=t}return p}function Bo(e,t){let n=t.map(e=>Array.from(e).reverse());return(t,r)=>{let[i,a,o,s]=n.map(n=>n.reduce((n,r)=>e.add(e.mul(n,t),r))),[c,l]=oo(e,[a,s],!0);return t=e.mul(i,c),r=e.mul(r,e.mul(o,l)),{x:t,y:r}}}var Vo=T(`HashToScalar-`);function Ho(e,t,n){if(typeof t!=`function`)throw Error(`mapToCurve() must be defined`);function r(n){return e.fromAffine(t(n))}function i(t){let n=t.clearCofactor();return n.equals(e.ZERO)?e.ZERO:(n.assertValidity(),n)}return{defaults:n,hashToCurve(e,t){let a=zo(e,2,Object.assign({},n,t)),o=r(a[0]),s=r(a[1]);return i(o.add(s))},encodeToCurve(e,t){let a=n.encodeDST?{DST:n.encodeDST}:{};return i(r(zo(e,1,Object.assign({},n,a,t))[0]))},mapToCurve(e){if(!Array.isArray(e))throw Error(`expected array of bigints`);for(let t of e)if(typeof t!=`bigint`)throw Error(`expected array of bigints`);return i(r(e))},hashToScalar(t,r){let i=e.Fn.ORDER;return zo(t,1,Object.assign({},n,{p:i,m:1,DST:Vo},r))[0][0]}}}var Uo=(e,t)=>(e+(e>=0?t:-t)/qo)/t;function Wo(e,t,n){let[[r,i],[a,o]]=t,s=Uo(o*e,n),c=Uo(-i*e,n),l=e-s*r-c*a,u=-s*i-c*o,d=l<Go,f=u<Go;d&&(l=-l),f&&(u=-u);let p=Fa(Math.ceil(Na(n)/2))+Ko;if(l<Go||l>=p||u<Go||u>=p)throw Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}var Go=BigInt(0),Ko=BigInt(1),qo=BigInt(2),Jo=BigInt(3),Yo=BigInt(4);function Xo(e,t){let{BYTES:n}=e,r;if(typeof t==`bigint`)r=t;else{let i=U(`private key`,t);try{r=e.fromBytes(i)}catch{throw Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw Error(`invalid private key: out of range [1..N-1]`);return r}function Zo(e,t={}){let n=jo(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;La(t,{},{allowInfinityPoint:`boolean`,clearCofactor:`function`,isTorsionFree:`function`,fromBytes:`function`,toBytes:`function`,endo:`object`,wrapPrivateKey:`boolean`});let{endo:c}=t;if(c&&(!r.is0(a.a)||typeof c.beta!=`bigint`||!Array.isArray(c.basises)))throw Error(`invalid endo: expected "beta": bigint and "basises": array`);let l=ts(r,i);function u(){if(!r.isOdd)throw Error(`compression is not supported: Field does not have .isOdd()`)}function d(e,t,n){let{x:i,y:a}=t.toAffine(),o=r.toBytes(i);return Sa(n,`isCompressed`),n?(u(),E(Qo(!r.isOdd(a)),o)):E(Uint8Array.of(4),o,r.toBytes(a))}function f(e){Ca(e,void 0,`Point`);let{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,a=e[0],o=e.subarray(1);if(i===t&&(a===2||a===3)){let e=r.fromBytes(o);if(!r.isValid(e))throw Error(`bad point: is not on curve, wrong x`);let t=h(e),n;try{n=r.sqrt(t)}catch(e){let t=e instanceof Error?`: `+e.message:``;throw Error(`bad point: is not on curve, sqrt error`+t)}u();let i=r.isOdd(n);return(a&1)==1!==i&&(n=r.neg(n)),{x:e,y:n}}if(i===n&&a===4){let e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.subarray(e,e*2));if(!g(t,n))throw Error(`bad point: is not on curve`);return{x:t,y:n}}throw Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}let p=t.toBytes||d,m=t.fromBytes||f;function h(e){let t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,a.a)),a.b)}function g(e,t){let n=r.sqr(t),i=h(e);return r.eql(n,i)}if(!g(a.Gx,a.Gy))throw Error(`bad curve params: generator point`);let _=r.mul(r.pow(a.a,Jo),Yo),v=r.mul(r.sqr(a.b),BigInt(27));if(r.is0(r.add(_,v)))throw Error(`bad curve params: a or b`);function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw Error(`bad point coordinate ${e}`);return t}function b(e){if(!(e instanceof C))throw Error(`ProjectivePoint expected`)}function x(e){if(!c||!c.basises)throw Error(`no endo`);return Wo(e,c.basises,i.ORDER)}let ee=za((e,t)=>{let{X:n,Y:i,Z:a}=e;if(r.eql(a,r.ONE))return{x:n,y:i};let o=e.is0();t??=o?r.ONE:r.inv(a);let s=r.mul(n,t),c=r.mul(i,t),l=r.mul(a,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw Error(`invZ was invalid`);return{x:s,y:c}}),S=za(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw Error(`bad point: ZERO`)}let{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error(`bad point: x or y not field elements`);if(!g(n,i))throw Error(`bad point: equation left != right`);if(!e.isTorsionFree())throw Error(`bad point: not in prime-order subgroup`);return!0});function te(e,t,n,i,a){return n=new C(r.mul(n.X,e),n.Y,n.Z),t=go(i,t),n=go(a,n),t.add(n)}class C{constructor(e,t,n){this.X=y(`x`,e),this.Y=y(`y`,t,!0),this.Z=y(`z`,n),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){let{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error(`invalid affine point`);if(e instanceof C)throw Error(`projective point not allowed`);return r.is0(t)&&r.is0(n)?C.ZERO:new C(t,n,r.ONE)}static fromBytes(e){let t=C.fromAffine(m(Ca(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return C.fromBytes(U(`pointHex`,e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return re.createCache(this,e),t||this.multiply(Jo),this}assertValidity(){S(this)}hasEvenY(){let{y:e}=this.toAffine();if(!r.isOdd)throw Error(`Field doesn't support isOdd`);return!r.isOdd(e)}equals(e){b(e);let{X:t,Y:n,Z:i}=this,{X:a,Y:o,Z:s}=e,c=r.eql(r.mul(t,s),r.mul(a,i)),l=r.eql(r.mul(n,s),r.mul(o,i));return c&&l}negate(){return new C(this.X,r.neg(this.Y),this.Z)}double(){let{a:e,b:t}=a,n=r.mul(t,Jo),{X:i,Y:o,Z:s}=this,c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),f=r.mul(o,o),p=r.mul(s,s),m=r.mul(i,o);return m=r.add(m,m),u=r.mul(i,s),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,p),l=r.add(c,l),c=r.sub(f,l),l=r.add(f,l),l=r.mul(c,l),c=r.mul(m,c),u=r.mul(n,u),p=r.mul(e,p),m=r.sub(d,p),m=r.mul(e,m),m=r.add(m,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,p),d=r.mul(d,m),l=r.add(l,d),p=r.mul(o,s),p=r.add(p,p),d=r.mul(p,m),c=r.sub(c,d),u=r.mul(p,f),u=r.add(u,u),u=r.add(u,u),new C(c,l,u)}add(e){b(e);let{X:t,Y:n,Z:i}=this,{X:o,Y:s,Z:c}=e,l=r.ZERO,u=r.ZERO,d=r.ZERO,f=a.a,p=r.mul(a.b,Jo),m=r.mul(t,o),h=r.mul(n,s),g=r.mul(i,c),_=r.add(t,n),v=r.add(o,s);_=r.mul(_,v),v=r.add(m,h),_=r.sub(_,v),v=r.add(t,i);let y=r.add(o,c);return v=r.mul(v,y),y=r.add(m,g),v=r.sub(v,y),y=r.add(n,i),l=r.add(s,c),y=r.mul(y,l),l=r.add(h,g),y=r.sub(y,l),d=r.mul(f,v),l=r.mul(p,g),d=r.add(l,d),l=r.sub(h,d),d=r.add(h,d),u=r.mul(l,d),h=r.add(m,m),h=r.add(h,m),g=r.mul(f,g),v=r.mul(p,v),h=r.add(h,g),g=r.sub(m,g),g=r.mul(f,g),v=r.add(v,g),m=r.mul(h,v),u=r.add(u,m),m=r.mul(y,v),l=r.mul(_,l),l=r.sub(l,m),m=r.mul(_,h),d=r.mul(y,d),d=r.add(d,m),new C(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(C.ZERO)}multiply(e){let{endo:n}=t;if(!i.isValidNot0(e))throw Error(`invalid scalar: out of range`);let r,a,o=e=>re.cached(this,e,e=>_o(C,e));if(n){let{k1neg:t,k1:i,k2neg:s,k2:c}=x(e),{p:l,f:u}=o(i),{p:d,f}=o(c);a=u.add(f),r=te(n.beta,l,d,t,s)}else{let{p:t,f:n}=o(e);r=t,a=n}return _o(C,[r,a])[0]}multiplyUnsafe(e){let{endo:n}=t,r=this;if(!i.isValid(e))throw Error(`invalid scalar: out of range`);if(e===Go||r.is0())return C.ZERO;if(e===Ko)return r;if(re.hasCache(this))return this.multiply(e);if(n){let{k1neg:t,k1:i,k2neg:a,k2:o}=x(e),{p1:s,p2:c}=Oo(C,r,i,o);return te(n.beta,s,c,t,a)}return re.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){let r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return ee(this,e)}isTorsionFree(){let{isTorsionFree:e}=t;return o===Ko?!0:e?e(C,this):re.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:e}=t;return o===Ko?this:e?e(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Sa(e,`isCompressed`),this.assertValidity(),p(C,this,e)}toHex(e=!0){return w(this.toBytes(e))}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return _o(C,e)}static msm(e,t){return ko(C,i,e,t)}static fromPrivateKey(e){return C.BASE.multiply(Xo(i,e))}}C.BASE=new C(a.Gx,a.Gy,r.ONE),C.ZERO=new C(r.ZERO,r.ONE,r.ZERO),C.Fp=r,C.Fn=i;let ne=i.BITS,re=new Do(C,t.endo?Math.ceil(ne/2):ne);return C.BASE.precompute(8),C}function Qo(e){return Uint8Array.of(e?2:3)}function $o(e,t){let n=e.ORDER,r=Go;for(let e=n-Ko;e%qo===Go;e/=qo)r+=Ko;let i=r,a=qo<<i-Ko-Ko,o=a*qo,s=(n-Ko)/o,c=(s-Ko)/qo,l=o-Ko,u=a,d=e.pow(t,s),f=e.pow(t,(s+Ko)/qo),p=(t,n)=>{let r=d,a=e.pow(n,l),o=e.sqr(a);o=e.mul(o,n);let s=e.mul(t,o);s=e.pow(s,c),s=e.mul(s,a),a=e.mul(s,n),o=e.mul(s,t);let p=e.mul(o,a);s=e.pow(p,u);let m=e.eql(s,e.ONE);a=e.mul(o,f),s=e.mul(p,r),o=e.cmov(a,o,m),p=e.cmov(s,p,m);for(let t=i;t>Ko;t--){let n=t-qo;n=qo<<n-Ko;let i=e.pow(p,n),s=e.eql(i,e.ONE);a=e.mul(o,r),r=e.mul(r,r),i=e.mul(p,r),o=e.cmov(a,o,s),p=e.cmov(i,p,s)}return{isValid:m,value:o}};if(e.ORDER%Yo===Jo){let n=(e.ORDER-Jo)/Yo,r=e.sqrt(e.neg(t));p=(t,i)=>{let a=e.sqr(i),o=e.mul(t,i);a=e.mul(a,o);let s=e.pow(a,n);s=e.mul(s,o);let c=e.mul(s,r),l=e.mul(e.sqr(s),i),u=e.eql(l,t);return{isValid:u,value:e.cmov(c,s,u)}}}return p}function es(e,t){io(e);let{A:n,B:r,Z:i}=t;if(!e.isValid(n)||!e.isValid(r)||!e.isValid(i))throw Error(`mapToCurveSimpleSWU: invalid opts`);let a=$o(e,i);if(!e.isOdd)throw Error(`Field does not have .isOdd()`);return t=>{let o,s,c,l,u,d,f,p;o=e.sqr(t),o=e.mul(o,i),s=e.sqr(o),s=e.add(s,o),c=e.add(s,e.ONE),c=e.mul(c,r),l=e.cmov(i,e.neg(s),!e.eql(s,e.ZERO)),l=e.mul(l,n),s=e.sqr(c),d=e.sqr(l),u=e.mul(d,n),s=e.add(s,u),s=e.mul(s,c),d=e.mul(d,l),u=e.mul(d,r),s=e.add(s,u),f=e.mul(o,c);let{isValid:m,value:h}=a(s,d);p=e.mul(o,t),p=e.mul(p,h),f=e.cmov(f,c,m),p=e.cmov(p,h,m);let g=e.isOdd(t)===e.isOdd(p);p=e.cmov(e.neg(p),p,g);let _=oo(e,[l],!0)[0];return f=e.mul(f,_),{x:f,y:p}}}function ts(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function ns(e){let{CURVE:t,curveOpts:n}=rs(e);return as(e,Zo(t,n))}function rs(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:lo(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}function is(e,t,n){function r(r){let i=e.sqr(r),a=e.mul(i,r);return e.add(e.add(a,e.mul(r,t)),n)}return r}function as(e,t){let{Fp:n,Fn:r}=t;function i(e){return ja(e,Ko,r.ORDER)}let a=is(n,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:e=>Xo(r,e),weierstrassEquation:a,isWithinCurveOrder:i})}var os=BigInt(0),ss=BigInt(1),cs=BigInt(2),ls=BigInt(3);function us(e){let t=[];for(;e>ss;e>>=ss)(e&ss)===os?t.unshift(0):(e&ls)===ls?(t.unshift(-1),e+=ss):t.unshift(1);return t}function ds(e){if(!Array.isArray(e)||e.length===0)throw Error(`expected non-empty array`)}function fs(e,t,n,r){let{Fp2:i,Fp12:a}=e,{twistType:o,ateLoopSize:s,xNegative:c,postPrecompute:l}=r,u;if(o===`multiplicative`)u=(e,t,n,r,o,s)=>a.mul014(r,e,i.mul(t,o),i.mul(n,s));else if(o===`divisive`)u=(e,t,n,r,o,s)=>a.mul034(r,i.mul(n,s),i.mul(t,o),e);else throw Error(`bls: unknown twist type`);let d=i.div(i.ONE,i.mul(i.ONE,cs));function f(e,t,n,r){let a=i.sqr(n),o=i.sqr(r),s=i.mulByB(i.mul(o,ls)),c=i.mul(s,ls),l=i.sub(i.sub(i.sqr(i.add(n,r)),o),a),u=i.sub(s,a),f=i.mul(i.sqr(t),ls),p=i.neg(l);return e.push([u,f,p]),t=i.mul(i.mul(i.mul(i.sub(a,c),t),n),d),n=i.sub(i.sqr(i.mul(i.add(a,c),d)),i.mul(i.sqr(s),ls)),r=i.mul(a,l),{Rx:t,Ry:n,Rz:r}}function p(e,t,n,r,a,o){let s=i.sub(n,i.mul(o,r)),c=i.sub(t,i.mul(a,r)),l=i.sub(i.mul(s,a),i.mul(c,o)),u=i.neg(s),d=c;e.push([l,u,d]);let f=i.sqr(c),p=i.mul(f,c),m=i.mul(f,t),h=i.add(i.sub(p,i.mul(m,cs)),i.mul(i.sqr(s),r));return t=i.mul(c,h),n=i.sub(i.mul(i.sub(m,h),s),i.mul(p,n)),r=i.mul(r,p),{Rx:t,Ry:n,Rz:r}}let m=us(s),h=za(e=>{let{x:t,y:n}=e.toAffine(),r=t,a=n,o=i.neg(n),s=r,c=a,u=i.ONE,d=[];for(let e of m){let t=[];({Rx:s,Ry:c,Rz:u}=f(t,s,c,u)),e&&({Rx:s,Ry:c,Rz:u}=p(t,s,c,u,r,e===-1?o:a)),d.push(t)}if(l){let e=d[d.length-1];l(s,c,u,r,a,p.bind(null,e))}return d});function g(e,t=!1){let n=a.ONE;if(e.length){let t=e[0][0].length;for(let r=0;r<t;r++){n=a.sqr(n);for(let[t,i,a]of e)for(let[e,o,s]of t[r])n=u(e,o,s,n,i,a)}}return c&&(n=a.conjugate(n)),t?a.finalExponentiate(n):n}function _(e,r=!0){let i=[];_o(t,e.map(({g1:e})=>e)),_o(n,e.map(({g2:e})=>e));for(let{g1:t,g2:n}of e){if(t.is0()||n.is0())throw Error(`pairing is not available for ZERO point`);t.assertValidity(),n.assertValidity();let e=t.toAffine();i.push([h(n),e.x,e.y])}return g(i,r)}function v(e,t,n=!0){return _([{g1:e,g2:t}],n)}return{Fp12:a,millerLoopBatch:g,pairing:v,pairingBatch:_,calcPairingPrecomputes:h}}function ps(e,t,n,r,i){let{Fp12:a,pairingBatch:o}=e;function s(e){return e instanceof t.Point?e:t.Point.fromHex(e)}function c(e){return e instanceof n.Point?e:n.Point.fromHex(e)}function l(e){if(!(e instanceof n.Point))throw Error(`expected valid message hashed to ${i?`G1`:`G2`} curve`);return e}let u=i?(e,t)=>({g1:t,g2:e}):(e,t)=>({g1:e,g2:t});return{getPublicKey(e){let n=Xo(t.Point.Fn,e);return t.Point.BASE.multiply(n)},sign(e,n,r){if(r!=null)throw Error(`sign() expects 2 arguments`);let i=Xo(t.Point.Fn,n);return l(e).assertValidity(),e.multiply(i)},verify(e,n,r,i){if(i!=null)throw Error(`verify() expects 3 arguments`);e=c(e),r=s(r);let d=r.negate(),f=t.Point.BASE,p=l(n),m=e,h=o([u(d,p),u(f,m)]);return a.eql(h,a.ONE)},verifyBatch(e,n,r){if(ds(n),r.length!==n.length)throw Error(`amount of public keys and messages should be equal`);let i=c(e),l=n,d=r.map(s),f=new Map;for(let e=0;e<d.length;e++){let t=d[e],n=l[e],r=f.get(n);r===void 0&&(r=[],f.set(n,r)),r.push(t)}let p=[],m=t.Point.BASE;try{for(let[e,t]of f){let n=t.reduce((e,t)=>e.add(t));p.push(u(n,e))}return p.push(u(m.negate(),i)),a.eql(o(p),a.ONE)}catch{return!1}},aggregatePublicKeys(e){ds(e),e=e.map(e=>s(e));let n=e.reduce((e,t)=>e.add(t),t.Point.ZERO);return n.assertValidity(),n},aggregateSignatures(e){ds(e),e=e.map(e=>c(e));let t=e.reduce((e,t)=>e.add(t),n.Point.ZERO);return t.assertValidity(),t},hash(e,t){v(e);let r=t?{DST:t}:void 0;return n.hashToCurve(e,r)},Signature:r}}function ms(e){let{Fp:t,Fr:n,Fp2:r,Fp6:i,Fp12:a}=e.fields,o=ns(e.G1),s=Object.assign(o,Ho(o.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=ns(e.G2),l=Object.assign(c,Ho(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),u=fs(e.fields,s.Point,l.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:d,pairing:f,pairingBatch:p,calcPairingPrecomputes:m}=u,h=ps(u,s,l,e.G2.Signature,!1),g=ps(u,l,s,e.G1.ShortSignature,!0),_=e.randomBytes||ce,v=()=>{let e=fo(n.ORDER);return po(_(e),n.ORDER)},y={randomSecretKey:v,randomPrivateKey:v,calcPairingPrecomputes:m},{ShortSignature:b}=e.G1,{Signature:x}=e.G2;function ee(e,t){return e instanceof s.Point?e:g.hash(U(`point`,e),t?.DST)}function S(e,t){return e instanceof l.Point?e:h.hash(U(`point`,e),t?.DST)}function te(e){return h.getPublicKey(e).toBytes(!0)}function C(e){return g.getPublicKey(e).toBytes(!0)}function w(e,t,n){let r=S(e,n),i=h.sign(r,t);return e instanceof l.Point?i:x.toBytes(i)}function ne(e,t,n){let r=ee(e,n),i=g.sign(r,t);return e instanceof s.Point?i:b.toBytes(i)}function re(e,t,n,r){let i=S(t,r);return h.verify(e,i,n)}function ie(e,t,n,r){let i=ee(t,r);return g.verify(e,i,n)}function T(e){let t=h.aggregatePublicKeys(e);return e[0]instanceof s.Point?t:t.toBytes(!0)}function ae(e){let t=h.aggregateSignatures(e);return e[0]instanceof l.Point?t:x.toBytes(t)}function E(e){let t=g.aggregateSignatures(e);return e[0]instanceof s.Point?t:b.toBytes(t)}function oe(e,t,n,r){let i=t.map(e=>S(e,r));return h.verifyBatch(e,i,n)}return s.Point.BASE.precompute(4),{longSignatures:h,shortSignatures:g,millerLoopBatch:d,pairing:f,pairingBatch:p,verifyBatch:oe,fields:{Fr:n,Fp:t,Fp2:r,Fp6:i,Fp12:a},params:{ateLoopSize:e.params.ateLoopSize,twistType:e.params.twistType,r:e.params.r,G1b:e.G1.b,G2b:e.G2.b},utils:y,getPublicKey:te,getPublicKeyForShortSignatures:C,sign:w,signShortSignature:ne,verify:re,verifyShortSignature:ie,aggregatePublicKeys:T,aggregateSignatures:ae,aggregateShortSignatures:E,G1:s,G2:l,Signature:x,ShortSignature:b}}var hs=BigInt(0),gs=BigInt(1),_s=BigInt(2),vs=BigInt(3);function ys(e,t,n,r,i=1,a){let o=BigInt(a===void 0?r:a),s=n**BigInt(r),c=[];for(let a=0;a<i;a++){let i=BigInt(a+1),l=[];for(let a=0,c=gs;a<r;a++){let r=(i*c-i)/o%s;l.push(e.pow(t,r)),c*=n}c.push(l)}return c}function bs(e,t,n){let r=t.pow(n,(e.ORDER-gs)/vs),i=t.pow(n,(e.ORDER-gs)/_s);function a(e,n){return[t.mul(t.frobeniusMap(e,1),r),t.mul(t.frobeniusMap(n,1),i)]}let o=t.pow(n,(e.ORDER**_s-gs)/vs),s=t.pow(n,(e.ORDER**_s-gs)/_s);if(!t.eql(s,t.neg(t.ONE)))throw Error(`psiFrobenius: PSI2_Y!==-1`);function c(e,n){return[t.mul(e,o),t.neg(n)]}let l=e=>(t,n)=>{let r=n.toAffine(),i=e(r.x,r.y);return t.fromAffine({x:i[0],y:i[1]})};return{psi:a,psi2:c,G2psi:l(a),G2psi2:l(c),PSI_X:r,PSI_Y:i,PSI2_X:o,PSI2_Y:s}}var xs=(e,t)=>{if(t.length!==2)throw Error(`invalid tuple`);let n=t.map(t=>e.create(t));return{c0:n[0],c1:n[1]}},Ss=class{constructor(e,t={}){this.MASK=gs;let n=e.ORDER,r=n*n;this.Fp=e,this.ORDER=r,this.BITS=Na(r),this.BYTES=Math.ceil(Na(r)/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,_s),this.NONRESIDUE=xs(e,t.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=ys(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=t.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return xs(this.Fp,e)}create(e){return e}isValid({c0:e,c1:t}){function n(e,t){return typeof e==`bigint`&&hs<=e&&e<t}return n(e,this.ORDER)&&n(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:n,c1:r}){return this.Fp.eql(e,n)&&this.Fp.eql(t,r)}neg({c0:e,c1:t}){return{c0:this.Fp.neg(e),c1:this.Fp.neg(t)}}pow(e,t){return ao(this,e,t)}invertBatch(e){return oo(this,e)}add(e,t){let{c0:n,c1:r}=e,{c0:i,c1:a}=t;return{c0:this.Fp.add(n,i),c1:this.Fp.add(r,a)}}sub({c0:e,c1:t},{c0:n,c1:r}){return{c0:this.Fp.sub(e,n),c1:this.Fp.sub(t,r)}}mul({c0:e,c1:t},n){let{Fp:r}=this;if(typeof n==`bigint`)return{c0:r.mul(e,n),c1:r.mul(t,n)};let{c0:i,c1:a}=n,o=r.mul(e,i),s=r.mul(t,a);return{c0:r.sub(o,s),c1:r.sub(r.mul(r.add(e,t),r.add(i,a)),r.add(o,s))}}sqr({c0:e,c1:t}){let{Fp:n}=this,r=n.add(e,t),i=n.sub(e,t),a=n.add(e,e);return{c0:n.mul(r,i),c1:n.mul(a,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:n}=this;return this.mul(e,typeof t==`bigint`?n.inv(n.create(t)):this.inv(t))}inv({c0:e,c1:t}){let{Fp:n}=this,r=n.inv(n.create(e*e+t*t));return{c0:n.mul(r,n.create(e)),c1:n.mul(r,n.create(-t))}}sqrt(e){let{Fp:t}=this,n=this,{c0:r,c1:i}=e;if(t.is0(i))return so(t,r)===1?n.create({c0:t.sqrt(r),c1:t.ZERO}):n.create({c0:t.ZERO,c1:t.sqrt(t.div(r,this.Fp_NONRESIDUE))});let a=t.sqrt(t.sub(t.sqr(r),t.mul(t.sqr(i),this.Fp_NONRESIDUE))),o=t.mul(t.add(a,r),this.Fp_div2);so(t,o)===-1&&(o=t.sub(o,a));let s=t.sqrt(o),c=n.create({c0:s,c1:t.div(t.mul(i,this.Fp_div2),s)});if(!n.eql(n.sqr(c),e))throw Error(`Cannot find square root`);let l=c,u=n.neg(l),{re:d,im:f}=n.reim(l),{re:p,im:m}=n.reim(u);return f>m||f===m&&d>p?l:u}isOdd(e){let{re:t,im:n}=this.reim(e),r=t%_s,i=t===hs,a=n%_s;return BigInt(r||i&&a)==gs}fromBytes(e){let{Fp:t}=this;if(e.length!==this.BYTES)throw 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 E(this.Fp.toBytes(e),this.Fp.toBytes(t))}cmov({c0:e,c1:t},{c0:n,c1:r},i){return{c0:this.Fp.cmov(e,n,i),c1:this.Fp.cmov(t,r,i)}}reim({c0:e,c1:t}){return{re:e,im:t}}Fp4Square(e,t){let n=this,r=n.sqr(e),i=n.sqr(t);return{first:n.add(n.mulByNonresidue(i),r),second:n.sub(n.sub(n.sqr(n.add(e,t)),r),i)}}mulByNonresidue({c0:e,c1:t}){return this.mul({c0:e,c1:t},this.NONRESIDUE)}frobeniusMap({c0:e,c1:t},n){return{c0:e,c1:this.Fp.mul(t,this.FROBENIUS_COEFFICIENTS[n%2])}}},Cs=class{constructor(e){this.MASK=gs,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,n=ys(e,e.NONRESIDUE,t.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=n[0],this.FROBENIUS_COEFFICIENTS_2=n[1],Object.seal(this)}add({c0:e,c1:t,c2:n},{c0:r,c1:i,c2:a}){let{Fp2:o}=this;return{c0:o.add(e,r),c1:o.add(t,i),c2:o.add(n,a)}}sub({c0:e,c1:t,c2:n},{c0:r,c1:i,c2:a}){let{Fp2:o}=this;return{c0:o.sub(e,r),c1:o.sub(t,i),c2:o.sub(n,a)}}mul({c0:e,c1:t,c2:n},r){let{Fp2:i}=this;if(typeof r==`bigint`)return{c0:i.mul(e,r),c1:i.mul(t,r),c2:i.mul(n,r)};let{c0:a,c1:o,c2:s}=r,c=i.mul(e,a),l=i.mul(t,o),u=i.mul(n,s);return{c0:i.add(c,i.mulByNonresidue(i.sub(i.mul(i.add(t,n),i.add(o,s)),i.add(l,u)))),c1:i.add(i.sub(i.mul(i.add(e,t),i.add(a,o)),i.add(c,l)),i.mulByNonresidue(u)),c2:i.sub(i.add(l,i.mul(i.add(e,n),i.add(a,s))),i.add(c,u))}}sqr({c0:e,c1:t,c2:n}){let{Fp2:r}=this,i=r.sqr(e),a=r.mul(r.mul(e,t),_s),o=r.mul(r.mul(t,n),_s),s=r.sqr(n);return{c0:r.add(r.mulByNonresidue(o),i),c1:r.add(r.mulByNonresidue(s),a),c2:r.sub(r.sub(r.add(r.add(a,r.sqr(r.add(r.sub(e,t),n))),o),i),s)}}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:n}){let{Fp2:r}=this;return r.isValid(e)&&r.isValid(t)&&r.isValid(n)}is0({c0:e,c1:t,c2:n}){let{Fp2:r}=this;return r.is0(e)&&r.is0(t)&&r.is0(n)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:t,c2:n}){let{Fp2:r}=this;return{c0:r.neg(e),c1:r.neg(t),c2:r.neg(n)}}eql({c0:e,c1:t,c2:n},{c0:r,c1:i,c2:a}){let{Fp2:o}=this;return o.eql(e,r)&&o.eql(t,i)&&o.eql(n,a)}sqrt(e){return Ra()}div(e,t){let{Fp2:n}=this,{Fp:r}=n;return this.mul(e,typeof t==`bigint`?r.inv(r.create(t)):this.inv(t))}pow(e,t){return ao(this,e,t)}invertBatch(e){return oo(this,e)}inv({c0:e,c1:t,c2:n}){let{Fp2:r}=this,i=r.sub(r.sqr(e),r.mulByNonresidue(r.mul(n,t))),a=r.sub(r.mulByNonresidue(r.sqr(n)),r.mul(e,t)),o=r.sub(r.sqr(t),r.mul(e,n)),s=r.inv(r.add(r.mulByNonresidue(r.add(r.mul(n,a),r.mul(t,o))),r.mul(e,i)));return{c0:r.mul(s,i),c1:r.mul(s,a),c2:r.mul(s,o)}}fromBytes(e){let{Fp2:t}=this;if(e.length!==this.BYTES)throw Error(`fromBytes invalid length=`+e.length);let n=t.BYTES;return{c0:t.fromBytes(e.subarray(0,n)),c1:t.fromBytes(e.subarray(n,n*2)),c2:t.fromBytes(e.subarray(2*n))}}toBytes({c0:e,c1:t,c2:n}){let{Fp2:r}=this;return E(r.toBytes(e),r.toBytes(t),r.toBytes(n))}cmov({c0:e,c1:t,c2:n},{c0:r,c1:i,c2:a},o){let{Fp2:s}=this;return{c0:s.cmov(e,r,o),c1:s.cmov(t,i,o),c2:s.cmov(n,a,o)}}fromBigSix(e){let{Fp2:t}=this;if(!Array.isArray(e)||e.length!==6)throw 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:n},r){let{Fp2:i}=this;return{c0:i.frobeniusMap(e,r),c1:i.mul(i.frobeniusMap(t,r),this.FROBENIUS_COEFFICIENTS_1[r%6]),c2:i.mul(i.frobeniusMap(n,r),this.FROBENIUS_COEFFICIENTS_2[r%6])}}mulByFp2({c0:e,c1:t,c2:n},r){let{Fp2:i}=this;return{c0:i.mul(e,r),c1:i.mul(t,r),c2:i.mul(n,r)}}mulByNonresidue({c0:e,c1:t,c2:n}){let{Fp2:r}=this;return{c0:r.mulByNonresidue(n),c1:e,c2:t}}mul1({c0:e,c1:t,c2:n},r){let{Fp2:i}=this;return{c0:i.mulByNonresidue(i.mul(n,r)),c1:i.mul(e,r),c2:i.mul(t,r)}}mul01({c0:e,c1:t,c2:n},r,i){let{Fp2:a}=this,o=a.mul(e,r),s=a.mul(t,i);return{c0:a.add(a.mulByNonresidue(a.sub(a.mul(a.add(t,n),i),s)),o),c1:a.sub(a.sub(a.mul(a.add(r,i),a.add(e,t)),o),s),c2:a.add(a.sub(a.mul(a.add(e,n),r),o),s)}}},ws=class{constructor(e,t){this.MASK=gs;let{Fp2:n}=e,{Fp:r}=n;this.Fp6=e,this.ORDER=n.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=ys(n,n.NONRESIDUE,r.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:n}=this;return n.isValid(e)&&n.isValid(t)}is0({c0:e,c1:t}){let{Fp6:n}=this;return n.is0(e)&&n.is0(t)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:t}){let{Fp6:n}=this;return{c0:n.neg(e),c1:n.neg(t)}}eql({c0:e,c1:t},{c0:n,c1:r}){let{Fp6:i}=this;return i.eql(e,n)&&i.eql(t,r)}sqrt(e){Ra()}inv({c0:e,c1:t}){let{Fp6:n}=this,r=n.inv(n.sub(n.sqr(e),n.mulByNonresidue(n.sqr(t))));return{c0:n.mul(e,r),c1:n.neg(n.mul(t,r))}}div(e,t){let{Fp6:n}=this,{Fp2:r}=n,{Fp:i}=r;return this.mul(e,typeof t==`bigint`?i.inv(i.create(t)):this.inv(t))}pow(e,t){return ao(this,e,t)}invertBatch(e){return oo(this,e)}add({c0:e,c1:t},{c0:n,c1:r}){let{Fp6:i}=this;return{c0:i.add(e,n),c1:i.add(t,r)}}sub({c0:e,c1:t},{c0:n,c1:r}){let{Fp6:i}=this;return{c0:i.sub(e,n),c1:i.sub(t,r)}}mul({c0:e,c1:t},n){let{Fp6:r}=this;if(typeof n==`bigint`)return{c0:r.mul(e,n),c1:r.mul(t,n)};let{c0:i,c1:a}=n,o=r.mul(e,i),s=r.mul(t,a);return{c0:r.add(o,r.mulByNonresidue(s)),c1:r.sub(r.mul(r.add(e,t),r.add(i,a)),r.add(o,s))}}sqr({c0:e,c1:t}){let{Fp6:n}=this,r=n.mul(e,t);return{c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(t),e),n.add(e,t)),r),n.mulByNonresidue(r)),c1:n.add(r,r)}}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 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:n}=this;return E(n.toBytes(e),n.toBytes(t))}cmov({c0:e,c1:t},{c0:n,c1:r},i){let{Fp6:a}=this;return{c0:a.cmov(e,n,i),c1:a.cmov(t,r,i)}}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:n}=this,{Fp2:r}=n,{c0:i,c1:a,c2:o}=n.frobeniusMap(e.c1,t),s=this.FROBENIUS_COEFFICIENTS[t%12];return{c0:n.frobeniusMap(e.c0,t),c1:n.create({c0:r.mul(i,s),c1:r.mul(a,s),c2:r.mul(o,s)})}}mulByFp2({c0:e,c1:t},n){let{Fp6:r}=this;return{c0:r.mulByFp2(e,n),c1:r.mulByFp2(t,n)}}conjugate({c0:e,c1:t}){return{c0:e,c1:this.Fp6.neg(t)}}mul014({c0:e,c1:t},n,r,i){let{Fp6:a}=this,{Fp2:o}=a,s=a.mul01(e,n,r),c=a.mul1(t,i);return{c0:a.add(a.mulByNonresidue(c),s),c1:a.sub(a.sub(a.mul01(a.add(t,e),n,o.add(r,i)),s),c)}}mul034({c0:e,c1:t},n,r,i){let{Fp6:a}=this,{Fp2:o}=a,s=a.create({c0:o.mul(e.c0,n),c1:o.mul(e.c1,n),c2:o.mul(e.c2,n)}),c=a.mul01(t,r,i),l=a.mul01(a.add(e,t),o.add(n,r),i);return{c0:a.add(a.mulByNonresidue(c),s),c1:a.sub(l,a.add(s,c))}}_cyclotomicSquare({c0:e,c1:t}){let{Fp6:n}=this,{Fp2:r}=n,{c0:i,c1:a,c2:o}=e,{c0:s,c1:c,c2:l}=t,{first:u,second:d}=r.Fp4Square(i,c),{first:f,second:p}=r.Fp4Square(s,o),{first:m,second:h}=r.Fp4Square(a,l),g=r.mulByNonresidue(h);return{c0:n.create({c0:r.add(r.mul(r.sub(u,i),_s),u),c1:r.add(r.mul(r.sub(f,a),_s),f),c2:r.add(r.mul(r.sub(m,o),_s),m)}),c1:n.create({c0:r.add(r.mul(r.add(g,s),_s),g),c1:r.add(r.mul(r.add(d,c),_s),d),c2:r.add(r.mul(r.add(p,l),_s),p)})}}_cyclotomicExp(e,t){let n=this.ONE;for(let r=this.X_LEN-1;r>=0;r--)n=this._cyclotomicSquare(n),Pa(t,r)&&(n=this.mul(n,e));return n}};function Ts(e){let t=lo(e.ORDER),n=new Ss(t,e),r=new Cs(n);return{Fp:t,Fp2:n,Fp6:r,Fp12:new ws(r,e)}}var q=BigInt(0),Es=BigInt(1),Ds=BigInt(2),Os=BigInt(3),ks=BigInt(4),As=BigInt(`0xd201000000010000`),js=Na(As),Ms={p:BigInt(`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab`),n:BigInt(`0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001`),h:BigInt(`0x396c8c005555e1568c00aaab0000aaab`),a:q,b:ks,Gx:BigInt(`0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb`),Gy:BigInt(`0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1`)},Ns=lo(Ms.n,{modFromBytes:!0,isLE:!0}),{Fp:J,Fp2:Y,Fp6:Ps,Fp12:X}=Ts({ORDER:Ms.p,X_LEN:js,FP2_NONRESIDUE:[Es,Es],Fp2mulByB:({c0:e,c1:t})=>{let n=J.mul(e,ks),r=J.mul(t,ks);return{c0:J.sub(n,r),c1:J.add(n,r)}},Fp12finalExponentiate:e=>{let t=As,n=X.div(X.frobeniusMap(e,6),e),r=X.mul(X.frobeniusMap(n,2),n),i=X.conjugate(X._cyclotomicExp(r,t)),a=X.mul(X.conjugate(X._cyclotomicSquare(r)),i),o=X.conjugate(X._cyclotomicExp(a,t)),s=X.conjugate(X._cyclotomicExp(o,t)),c=X.mul(X.conjugate(X._cyclotomicExp(s,t)),X._cyclotomicSquare(i)),l=X.conjugate(X._cyclotomicExp(c,t)),u=X.frobeniusMap(X.mul(i,s),2),d=X.frobeniusMap(X.mul(o,r),3),f=X.frobeniusMap(X.mul(c,X.conjugate(r)),1),p=X.mul(X.mul(l,X.conjugate(a)),r);return X.mul(X.mul(X.mul(u,d),f),p)}}),{G2psi:Fs,G2psi2:Is}=bs(J,Y,Y.div(Y.ONE,Y.NONRESIDUE)),Ls=Object.freeze({DST:`BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_`,encodeDST:`BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_`,p:J.ORDER,m:2,k:128,expand:`xmd`,hash:He}),Rs={p:Y.ORDER,n:Ms.n,h:BigInt(`0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5`),a:Y.ZERO,b:Y.fromBigTuple([ks,ks]),Gx:Y.fromBigTuple([BigInt(`0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8`),BigInt(`0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e`)]),Gy:Y.fromBigTuple([BigInt(`0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801`),BigInt(`0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be`)])},zs=Vs(J.toBytes(q),{infinity:!0,compressed:!0});function Bs(e){e=e.slice();let t=e[0]&224,n=!!(t>>7&1),r=!!(t>>6&1),i=!!(t>>5&1);return e[0]&=31,{compressed:n,infinity:r,sort:i,value:e}}function Vs(e,t){if(e[0]&224)throw Error(`setMask: non-empty mask`);return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function Hs(e,t,n){let{BYTES:r,ORDER:i}=J,a=t.is0(),{x:o,y:s}=t.toAffine();if(n){if(a)return zs.slice();let e=!!(s*Ds/i);return Vs(H(o,r),{compressed:!0,sort:e})}return a?E(Uint8Array.of(64),new Uint8Array(2*r-1)):E(H(o,r),H(s,r))}function Us(e){e.assertValidity();let{BYTES:t,ORDER:n}=J,{x:r,y:i}=e.toAffine();if(e.is0())return zs.slice();let a=!!(i*Ds/n);return Vs(H(r,t),{compressed:!0,sort:a})}function Ws(e){let{compressed:t,infinity:n,sort:r,value:i}=Bs(e),{BYTES:a,ORDER:o}=J;if(i.length===48&&t){let e=Ta(i),t=J.create(e&Fa(J.BITS));if(n){if(t!==q)throw Error(`invalid G1 point: non-empty, at infinity, with compression`);return{x:q,y:q}}let a=J.add(J.pow(t,Os),J.create(Ms.b)),s=J.sqrt(a);if(!s)throw Error(`invalid G1 point: compressed point`);return s*Ds/o!==BigInt(r)&&(s=J.neg(s)),{x:J.create(t),y:J.create(s)}}if(i.length===96&&!t){let e=Ta(i.subarray(0,a)),t=Ta(i.subarray(a));if(n){if(e!==q||t!==q)throw Error(`G1: non-empty point at infinity`);return Xs.G1.Point.ZERO.toAffine()}return{x:J.create(e),y:J.create(t)}}throw Error(`invalid G1 point: expected 48/96 bytes`)}function Gs(e){let{infinity:t,sort:n,value:r}=Bs(U(`signatureHex`,e,48)),i=J.ORDER,a=Xs.G1.Point,o=Ta(r);if(t)return a.ZERO;let s=J.create(o&Fa(J.BITS)),c=J.add(J.pow(s,Os),J.create(Ms.b)),l=J.sqrt(c);if(!l)throw Error(`invalid G1 point: compressed`);let u=BigInt(n);l*Ds/i!==u&&(l=J.neg(l));let d=a.fromAffine({x:s,y:l});return d.assertValidity(),d}function Ks(e,t,n){let{BYTES:r,ORDER:i}=J,a=t.is0(),{x:o,y:s}=t.toAffine();if(n){if(a)return E(zs,H(q,r));let e=!!(s.c1===q?s.c0*Ds/i:s.c1*Ds/i);return E(Vs(H(o.c1,r),{compressed:!0,sort:e}),H(o.c0,r))}{if(a)return E(Uint8Array.of(64),new Uint8Array(4*r-1));let{re:e,im:t}=Y.reim(o),{re:n,im:i}=Y.reim(s);return E(H(t,r),H(e,r),H(i,r),H(n,r))}}function qs(e){e.assertValidity();let{BYTES:t}=J;if(e.is0())return E(zs,H(q,t));let{x:n,y:r}=e.toAffine(),{re:i,im:a}=Y.reim(n),{re:o,im:s}=Y.reim(r),c=!!((s>q?s*Ds:o*Ds)/J.ORDER&Es),l=i;return E(Vs(H(a,t),{sort:c,compressed:!0}),H(l,t))}function Js(e){let{BYTES:t,ORDER:n}=J,{compressed:r,infinity:i,sort:a,value:o}=Bs(e);if(!r&&!i&&a||!r&&i&&a||a&&i&&r)throw Error(`invalid encoding flag: `+(e[0]&224));let s=(e,t,n)=>Ta(e.slice(t,n));if(o.length===96&&r){if(i){if(o.reduce((e,t)=>e===0?t:t+1,0)>0)throw Error(`invalid G2 point: compressed`);return{x:Y.ZERO,y:Y.ZERO}}let e=s(o,0,t),r=s(o,t,2*t),c=Y.create({c0:J.create(r),c1:J.create(e)}),l=Y.add(Y.pow(c,Os),Rs.b),u=Y.sqrt(l),d=u.c1===q?u.c0*Ds/n:u.c1*Ds/n?Es:q;return u=a&&d>0?u:Y.neg(u),{x:c,y:u}}if(o.length===192&&!r){if(i){if(o.reduce((e,t)=>e===0?t:t+1,0)>0)throw Error(`invalid G2 point: uncompressed`);return{x:Y.ZERO,y:Y.ZERO}}let e=s(o,0*t,1*t),n=s(o,1*t,2*t),r=s(o,2*t,3*t),a=s(o,3*t,4*t);return{x:Y.fromBigTuple([n,e]),y:Y.fromBigTuple([a,r])}}throw Error(`invalid G2 point: expected 96/192 bytes`)}function Ys(e){let{ORDER:t}=J,{infinity:n,sort:r,value:i}=Bs(U(`signatureHex`,e)),a=Xs.G2.Point,o=i.length/2;if(o!==48&&o!==96)throw Error(`invalid compressed signature length, expected 96/192 bytes`);let s=Ta(i.slice(0,o)),c=Ta(i.slice(o));if(n)return a.ZERO;let l=J.create(s&Fa(J.BITS)),u=J.create(c),d=Y.create({c0:u,c1:l}),f=Y.add(Y.pow(d,Os),Rs.b),p=Y.sqrt(f);if(!p)throw Error(`Failed to find a square root`);let{re:m,im:h}=Y.reim(p),g=BigInt(r),_=h>q&&h*Ds/t!==g,v=h===q&&m*Ds/t!==g;(_||v)&&(p=Y.neg(p));let y=a.fromAffine({x:d,y:p});return y.assertValidity(),y}var Xs=ms({fields:{Fp:J,Fp2:Y,Fp6:Ps,Fp12:X,Fr:Ns},G1:{...Ms,Fp:J,htfDefaults:{...Ls,m:1,DST:`BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_`},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(e,t)=>{let n=BigInt(`0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe`),r=new e(J.mul(t.X,n),t.Y,t.Z);return t.multiplyUnsafe(As).negate().multiplyUnsafe(As).equals(r)},clearCofactor:(e,t)=>t.multiplyUnsafe(As).add(t),mapToCurve:tc,fromBytes:Ws,toBytes:Hs,ShortSignature:{fromBytes(e){return v(e),Gs(e)},fromHex(e){return Gs(e)},toBytes(e){return Us(e)},toRawBytes(e){return Us(e)},toHex(e){return w(Us(e))}}},G2:{...Rs,Fp:Y,hEff:BigInt(`0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551`),htfDefaults:{...Ls},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:nc,isTorsionFree:(e,t)=>t.multiplyUnsafe(As).negate().equals(Fs(e,t)),clearCofactor:(e,t)=>{let n=As,r=t.multiplyUnsafe(n).negate(),i=Fs(e,t),a=t.double();return a=Is(e,a),a=a.subtract(i),i=r.add(i),i=i.multiplyUnsafe(n).negate(),a=a.add(i),a=a.subtract(r),a.subtract(t)},fromBytes:Js,toBytes:Ks,Signature:{fromBytes(e){return v(e),Ys(e)},fromHex(e){return Ys(e)},toBytes(e){return qs(e)},toRawBytes(e){return qs(e)},toHex(e){return w(qs(e))}}},params:{ateLoopSize:As,r:Ms.n,xNegative:!0,twistType:`multiplicative`},htfDefaults:Ls,hash:He}),Zs=Bo(Y,[[[`0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6`,`0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6`],[`0x0`,`0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a`],[`0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e`,`0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d`],[`0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1`,`0x0`]],[[`0x0`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63`],[`0xc`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f`],[`0x1`,`0x0`]],[[`0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706`,`0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706`],[`0x0`,`0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be`],[`0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c`,`0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f`],[`0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10`,`0x0`]],[[`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb`],[`0x0`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3`],[`0x12`,`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99`],[`0x1`,`0x0`]]].map(e=>e.map(e=>Y.fromBigTuple(e.map(BigInt))))),Qs=Bo(J,[[`0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7`,`0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb`,`0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0`,`0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861`,`0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9`,`0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983`,`0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84`,`0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e`,`0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317`,`0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e`,`0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b`,`0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229`],[`0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c`,`0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff`,`0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19`,`0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8`,`0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e`,`0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5`,`0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a`,`0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e`,`0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641`,`0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a`,`0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001`],[`0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33`,`0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696`,`0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6`,`0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb`,`0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb`,`0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0`,`0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2`,`0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29`,`0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587`,`0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30`,`0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132`,`0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e`,`0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8`,`0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133`,`0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b`,`0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604`],[`0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1`,`0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d`,`0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2`,`0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416`,`0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d`,`0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac`,`0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c`,`0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9`,`0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a`,`0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55`,`0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8`,`0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092`,`0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc`,`0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7`,`0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f`,`0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001`]].map(e=>e.map(e=>BigInt(e)))),$s=es(J,{A:J.create(BigInt(`0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d`)),B:J.create(BigInt(`0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0`)),Z:J.create(BigInt(11))}),ec=es(Y,{A:Y.create({c0:J.create(q),c1:J.create(BigInt(240))}),B:Y.create({c0:J.create(BigInt(1012)),c1:J.create(BigInt(1012))}),Z:Y.create({c0:J.create(BigInt(-2)),c1:J.create(BigInt(-1))})});function tc(e){let{x:t,y:n}=$s(J.create(e[0]));return Qs(t,n)}function nc(e){let{x:t,y:n}=ec(Y.fromBigTuple(e));return Zs(t,n)}function rc(e,t,n){let r=typeof e==`string`?e:w(e),i=typeof t==`string`?t:w(t),a=typeof n==`string`?n:w(n);return Xs.verifyShortSignature(i,a,r)}var ic=BigInt(1e6),ac=e=>F(new qt(e)),oc=e=>{let t=ac(e)/ic;return new Date(Number(t))},sc=6e4,cc=1440,lc=5,uc=5,dc=30*cc,Z;(function(e){e[e.Empty=0]=`Empty`,e[e.Fork=1]=`Fork`,e[e.Labeled=2]=`Labeled`,e[e.Leaf=3]=`Leaf`,e[e.Pruned=4]=`Pruned`})(Z||={});function fc(e,t){for(let n=0;n<e.length;n++)if(e[n]>t[n])return!0;return!1}var pc=class e{#e=!1;#t=void 0;static async create(t){let n=e.createUnverified(t);return await n.verify(),n}static createUnverified(t){return new e(t.certificate,t.rootKey,t.principal,t.blsVerify??rc,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(e,t,n,r,i=lc,a=!1,o){this._rootKey=t,this._principal=n,this._blsVerify=r,this._maxAgeInMinutes=i,this.#e=a,this.cert=da(e),o&&`getTimeDiffMsecs`in o&&`hasSyncedTime`in o&&`syncTime`in o&&`syncTimeWithSubnet`in o&&(this.#t=o)}lookup_path(e){return Tc(e,this.cert.tree)}lookup_subtree(e){return Ec(e,this.cert.tree)}async verify(){let e=await bc(this.cert.tree),t=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,r=vc(t),i=E(Qr,e),a=yc(this.lookup_path([`time`]));if(!a)throw A.fromCode(new at(`Certificate does not contain a time`));if(!this.#e){let e=this.#t?.getTimeDiffMsecs()??0,t=this._maxAgeInMinutes*sc,n=new Date,r=n.getTime()+e,i=r-t,o=r+uc*sc,s=oc(a),c=s.getTime()<i,l=s.getTime()>o;if((c||l)&&this.#t&&!this.#t.hasSyncedTime())return await this._syncTime(),await this.verify();if(c)throw tt.fromCode(new ot(this._maxAgeInMinutes,s,n,e,`past`));if(l)throw this.#t?.hasSyncedTime()?M.fromCode(new It(`System time has been synced with the IC network, but certificate is still too far in the future.`)):tt.fromCode(new ot(5,s,n,e,`future`))}try{if(!await this._blsVerify(r,n,i))throw tt.fromCode(new at(`Invalid signature`))}catch(e){throw tt.fromCode(new at(`Signature verification failed`,e))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let n=e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,principal:this._principal,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:dc,agent:this.#t});if(n.cert.delegation)throw A.fromCode(new st);await n.verify();let r;if(hc(this._principal)){let e=this._principal.canisterId;if(r=O.fromUint8Array(t.subnet_id),!Ac({canisterId:e,subnetId:r,tree:n.cert.tree}))throw tt.fromCode(new ct(e,r))}else if(mc(this._principal))r=this._principal.subnetId;else throw Kt;let i=yc(n.lookup_path([`subnet`,r.toUint8Array(),`public_key`]));if(!i)throw mc(this._principal)?tt.fromCode(new lt(r)):tt.fromCode(new ft(`Could not find subnet key for subnet ID ${r.toText()}`));return i}async _syncTime(){this.#t&&(hc(this._principal)?await this.#t.syncTime(this._principal.canisterId):await this.#t.syncTimeWithSubnet(this._principal.subnetId))}};function mc(e){return`subnetId`in e}function hc(e){return`canisterId`in e}var gc=ie(`308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100`),_c=96;function vc(e){let t=gc.byteLength+_c;if(e.byteLength!==t)throw A.fromCode(new pt(t,e.byteLength));let n=e.slice(0,gc.byteLength);if(!qr(n,gc))throw A.fromCode(new mt(gc,n));return e.slice(gc.byteLength)}function yc(e){if(e.status===Cc.Found&&e.value instanceof Uint8Array)return e.value}async function bc(e){switch(e[0]){case Z.Empty:return He(xc(`ic-hashtree-empty`));case Z.Pruned:return e[1];case Z.Leaf:return He(E(xc(`ic-hashtree-leaf`),e[1]));case Z.Labeled:return He(E(xc(`ic-hashtree-labeled`),e[1],await bc(e[2])));case Z.Fork:return He(E(xc(`ic-hashtree-fork`),await bc(e[1]),await bc(e[2])));default:throw Kt}}function xc(e){return E(new Uint8Array([e.length]),new TextEncoder().encode(e))}function Sc(e){return typeof e[0]==`string`?T(e[0]):e[0]}var Cc;(function(e){e.Unknown=`Unknown`,e.Absent=`Absent`,e.Found=`Found`,e.Error=`Error`})(Cc||={});var wc;(function(e){e.Absent=`Absent`,e.Unknown=`Unknown`,e.Found=`Found`})(wc||={});var Q;(function(e){e.Absent=`Absent`,e.Unknown=`Unknown`,e.Found=`Found`,e.Less=`Less`,e.Greater=`Greater`})(Q||={});function Tc(e,t){if(e.length===0)switch(t[0]){case Z.Empty:return{status:Cc.Absent};case Z.Leaf:if(!t[1])throw M.fromCode(new Rt(`Invalid tree structure for leaf`));if(t[1]instanceof Uint8Array)return{status:Cc.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw Kt;case Z.Pruned:return{status:Cc.Unknown};case Z.Labeled:case Z.Fork:return{status:Cc.Error};default:throw Kt}let n=Oc(Sc(e),t);switch(n.status){case Q.Found:return Tc(e.slice(1),n.value);case Q.Absent:case Q.Greater:case Q.Less:return{status:Cc.Absent};case Q.Unknown:return{status:Cc.Unknown};default:throw Kt}}function Ec(e,t){if(e.length===0)return{status:wc.Found,value:t};let n=Oc(Sc(e),t);switch(n.status){case Q.Found:return Ec(e.slice(1),n.value);case Q.Unknown:return{status:wc.Unknown};case Q.Absent:case Q.Greater:case Q.Less:return{status:wc.Absent};default:throw Kt}}function Dc(e){switch(e[0]){case Z.Empty:return[];case Z.Fork:return Dc(e[1]).concat(Dc(e[2]));default:return[e]}}function Oc(e,t){switch(t[0]){case Z.Labeled:return fc(e,t[1])?{status:Q.Greater}:qr(e,t[1])?{status:Q.Found,value:t[2]}:{status:Q.Less};case Z.Fork:{let n=Oc(e,t[1]);switch(n.status){case Q.Greater:{let n=Oc(e,t[2]);return n.status===Q.Less?{status:Q.Absent}:n}case Q.Unknown:{let n=Oc(e,t[2]);return n.status===Q.Less?{status:Q.Unknown}:n}default:return n}}case Z.Pruned:return{status:Q.Unknown};default:return{status:Q.Absent}}}function kc(e,t){switch(t[0]){case Z.Empty|Z.Pruned:return[];case Z.Leaf:return[e];case Z.Fork:return kc(e,t[1]).concat(kc(e,t[2]));case Z.Labeled:{let n=t[1],r=t[2];return kc([...e,n],r)}default:throw Kt}}function Ac(e){let t=Nc(jc(e)),{canisterId:n}=e;return t.some(e=>e[0].ltEq(n)&&e[1].gtEq(n))}function jc(e){let{subnetId:t,tree:n,canisterId:r}=e,i=Ec([`canister_ranges`,t.toUint8Array()],n);if(i.status!==wc.Found)return Mc(t,n);let a=i.value,o=Pc(a);if(o.length===0)throw A.fromCode(new ct(r,t));o.sort(Yt);let s=o[Fc(o,r)];return Ic(s,a)}function Mc(e,t){let n=Tc([`subnet`,e.toUint8Array(),`canister_ranges`],t);if(n.status!==Cc.Found)throw A.fromCode(new ut(`Could not find canister ranges for subnet ${e.toText()}`,n.status));return n.value}function Nc(e){return da(e).map(e=>[O.fromUint8Array(e[0]),O.fromUint8Array(e[1])])}function Pc(e){let t=[];for(let n of kc([],e)){let e=n[0];if(!e)throw A.fromCode(new at(`Path is invalid`));t.push(e)}return t}function Fc(e,t){let n=t.toUint8Array(),r=0,i=e.length-1;for(;r<i;){let t=Math.floor((r+i)/2);Yt(e[t],n)<=0?i=t:r=t+1}return r}function Ic(e,t){let n=Tc([e],t);if(n.status!==Cc.Found)throw A.fromCode(new ut(`Could not find canister range for shard ${e.toString()}`,n.status));return n.value}function Lc(e,t){return e.delegation?O.fromUint8Array(e.delegation.subnet_id):O.selfAuthenticating(t)}var Rc=O.fromText(`tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe`);function zc(e,t){switch(t){case`raw`:return e;case`leb128`:return ac(e);case`cbor`:return da(e);case`hex`:return w(e);case`utf-8`:return new TextDecoder().decode(e)}}function Bc(e){return da(e).map(e=>O.fromUint8Array(e))}function Vc(e,t){let n=typeof e==`string`?T(e):e;return[T(`canister`),t,T(`metadata`),n]}function Hc(e){return typeof e==`object`&&!!e&&`key`in e&&`path`in e}function Uc(e,t){let n=Ec([`subnet`,t.toUint8Array(),`node`],e.tree);if(n.status!==wc.Found)throw A.fromCode(new ut(`Node not found`,n.status));if(n.value instanceof Uint8Array)throw M.fromCode(new Rt(`Invalid node tree`));let r=Dc(n.value),i=new Map;return r.forEach(e=>{let t=O.from(e[1]).toText(),n=Tc([`public_key`],e[2]);if(n.status!==Cc.Found)throw A.fromCode(new ut(`Public key not found`,n.status));let r=n.value;if(r.byteLength!==44)throw A.fromCode(new pt(44,r.byteLength));i.set(t,r)}),i}var Wc=async e=>{let{agent:t,paths:n,disableCertificateTimeVerification:r=!1}=e,i=O.from(e.canisterId),a=[...new Set(n)],o=new Map,s=a.map((e,n)=>{let s=Kc(e,i);return(async()=>{try{if(t.rootKey===null)throw it.fromCode(new Et);let e=t.rootKey,c=await t.readState(i,{paths:[s]}),{path:l,data:u}=((t,n)=>n===`subnet`?{path:n,data:Gc(c.certificate,i,e)}:{path:n,data:yc(t.lookup_path(s))})(await pc.create({certificate:c.certificate,rootKey:e,principal:{canisterId:i},disableTimeVerification:r,agent:t}),a[n]);if(!u)typeof l==`string`?o.set(l,null):o.set(l.key,null);else switch(l){case`time`:o.set(l,oc(u));break;case`controllers`:o.set(l,Bc(u));break;case`module_hash`:o.set(l,w(u));break;case`subnet`:o.set(l,u);break;case`candid`:o.set(l,new TextDecoder().decode(u));break;default:Hc(l)&&o.set(l.key,zc(u,l.decodeStrategy))}}catch(t){if(t instanceof $e&&(t.hasCode(at)||t.hasCode(ot)))throw t;Hc(e)?o.set(e.key,null):o.set(e,null)}})()});return await Promise.all(s),o},Gc=(e,t,n)=>{if(!t._isPrincipal)throw j.fromCode(new It(`Invalid canisterId`));let r=da(e),{delegation:i}=r,a;a=i&&i.subnet_id?O.fromUint8Array(new Uint8Array(i.subnet_id)):!i&&n!==void 0?O.selfAuthenticating(new Uint8Array(n)):Rc;let o=Uc(r,a);return{subnetId:a.toText(),nodeKeys:o}},Kc=(e,t)=>{let n=t.toUint8Array();switch(e){case`time`:return[T(`time`)];case`controllers`:return[T(`canister`),n,T(`controllers`)];case`module_hash`:return[T(`canister`),n,T(`module_hash`)];case`subnet`:return[T(`subnet`)];case`candid`:return[T(`canister`),n,T(`metadata`),T(`candid:service`)];default:if(Hc(e))return typeof e.path==`string`||e.path instanceof Uint8Array?Vc(e.path,n):e.path}throw M.fromCode(new It(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))};async function qc(e){let{agent:t,paths:n,disableCertificateTimeVerification:r=!1}=e,i=O.from(e.subnetId),a=[...new Set(n)],o=new Map,s=a.map((e,n)=>{let s=Jc(e,i);return(async()=>{try{if(t.rootKey===null)throw it.fromCode(new Et);let e=t.rootKey,c=await t.readSubnetState(i,{paths:[s]}),{path:l,data:u}=((e,t)=>t===`nodeKeys`?{path:t,data:Uc(e.cert,i)}:{path:t,data:yc(e.lookup_path(s))})(await pc.create({certificate:c.certificate,rootKey:e,principal:{subnetId:i},disableTimeVerification:r,agent:t}),a[n]);if(!u)typeof l==`string`?o.set(l,null):o.set(l.key,null);else switch(l){case`time`:o.set(l,oc(u));break;case`canisterRanges`:o.set(l,Nc(u));break;case`publicKey`:o.set(l,u);break;case`nodeKeys`:o.set(l,u);break;default:Hc(l)&&o.set(l.key,zc(u,l.decodeStrategy))}}catch(t){if(t instanceof $e&&(t.hasCode(at)||t.hasCode(ot)))throw t;Hc(e)?o.set(e.key,null):o.set(e,null)}})()});return await Promise.all(s),o}function Jc(e,t){let n=t.toUint8Array();switch(e){case`time`:return[T(`time`)];case`canisterRanges`:return[T(`canister_ranges`),n];case`publicKey`:return[T(`subnet`),n,T(`public_key`)];case`nodeKeys`:return[T(`subnet`),n,T(`node`)];default:if(Hc(e)){if(typeof e.path==`string`||e.path instanceof Uint8Array){let t=typeof e.path==`string`?T(e.path):e.path;return[T(`subnet`),n,t]}return e.path}}throw M.fromCode(new It(`Error while encoding your path for subnet status. Please ensure that your path ${e} was formatted correctly.`))}function Yc(e,t,n){let r=new Uint8Array(yc(e.lookup_path([...t,`reject_code`])))[0],i=new TextDecoder().decode(yc(e.lookup_path([...t,`reject_message`]))),a=yc(e.lookup_path([...t,`error_code`]));return new St(n,r,i,a?new TextDecoder().decode(a):void 0)}var Xc=BigInt(0),$=BigInt(1),Zc=BigInt(2),Qc=BigInt(8);function $c(e,t,n,r){let i=e.sqr(n),a=e.sqr(r),o=e.add(e.mul(t.a,i),a),s=e.add(e.ONE,e.mul(t.d,e.mul(i,a)));return e.eql(o,s)}function el(e,t={}){let n=jo(`edwards`,e,t,t.FpFnLE),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o}=a;La(t,{},{uvRatio:`function`});let s=Zc<<BigInt(i.BYTES*8)-$,c=e=>r.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch{return{isValid:!1,value:Xc}}});if(!$c(r,a,a.Gx,a.Gy))throw Error(`bad curve params: generator point`);function u(e,t,n=!1){let r=n?$:Xc;return Ma(`coordinate `+e,t,r,s),t}function d(e){if(!(e instanceof m))throw Error(`ExtendedPoint expected`)}let f=za((e,t)=>{let{X:n,Y:i,Z:a}=e,o=e.is0();t??=o?Qc:r.inv(a);let s=c(n*t),l=c(i*t),u=r.mul(a,t);if(o)return{x:Xc,y:$};if(u!==$)throw Error(`invZ was invalid`);return{x:s,y:l}}),p=za(e=>{let{a:t,d:n}=a;if(e.is0())throw Error(`bad point: ZERO`);let{X:r,Y:i,Z:o,T:s}=e,l=c(r*r),u=c(i*i),d=c(o*o),f=c(d*d),p=c(l*t);if(c(d*c(p+u))!==c(f+c(n*c(l*u))))throw Error(`bad point: equation left != right (1)`);if(c(r*i)!==c(o*s))throw Error(`bad point: equation left != right (2)`);return!0});class m{constructor(e,t,n,r){this.X=u(`x`,e),this.Y=u(`y`,t),this.Z=u(`z`,n,!0),this.T=u(`t`,r),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){if(e instanceof m)throw Error(`extended point not allowed`);let{x:t,y:n}=e||{};return u(`x`,t),u(`y`,n),new m(t,n,$,c(t*n))}static fromBytes(e,t=!1){let n=r.BYTES,{a:i,d:o}=a;e=ka(Ca(e,n,`point`)),Sa(t,`zip215`);let u=ka(e),d=e[n-1];u[n-1]=d&-129;let f=Ea(u);Ma(`point.y`,f,Xc,t?s:r.ORDER);let p=c(f*f),h=c(p-$),g=c(o*p-i),{isValid:_,value:v}=l(h,g);if(!_)throw Error(`bad point: invalid y coordinate`);let y=(v&$)===$,b=!!(d&128);if(!t&&v===Xc&&b)throw Error(`bad point: x=0 and x_0=1`);return b!==y&&(v=c(-v)),m.fromAffine({x:v,y:f})}static fromHex(e,t=!1){return m.fromBytes(U(`point`,e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return h.createCache(this,e),t||this.multiply(Zc),this}assertValidity(){p(this)}equals(e){d(e);let{X:t,Y:n,Z:r}=this,{X:i,Y:a,Z:o}=e,s=c(t*o),l=c(i*r),u=c(n*o),f=c(a*r);return s===l&&u===f}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:e}=a,{X:t,Y:n,Z:r}=this,i=c(t*t),o=c(n*n),s=c(Zc*c(r*r)),l=c(e*i),u=t+n,d=c(c(u*u)-i-o),f=l+o,p=f-s,h=l-o,g=c(d*p),_=c(f*h),v=c(d*h),y=c(p*f);return new m(g,_,y,v)}add(e){d(e);let{a:t,d:n}=a,{X:r,Y:i,Z:o,T:s}=this,{X:l,Y:u,Z:f,T:p}=e,h=c(r*l),g=c(i*u),_=c(s*n*p),v=c(o*f),y=c((r+i)*(l+u)-h-g),b=v-_,x=v+_,ee=c(g-t*h),S=c(y*b),te=c(x*ee),C=c(y*ee),w=c(b*x);return new m(S,te,w,C)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw Error(`invalid scalar: expected 1 <= sc < curve.n`);let{p:t,f:n}=h.cached(this,e,e=>_o(m,e));return _o(m,[t,n])[0]}multiplyUnsafe(e,t=m.ZERO){if(!i.isValid(e))throw Error(`invalid scalar: expected 0 <= sc < curve.n`);return e===Xc?m.ZERO:this.is0()||e===$?this:h.unsafe(this,e,e=>_o(m,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return h.unsafe(this,a.n).is0()}toAffine(e){return f(this,e)}clearCofactor(){return o===$?this:this.multiplyUnsafe(o)}toBytes(){let{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&$?128:0,n}toHex(){return w(this.toBytes())}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return _o(m,e)}static msm(e,t){return ko(m,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}m.BASE=new m(a.Gx,a.Gy,$,c(a.Gx*a.Gy)),m.ZERO=new m(Xc,$,$,Xc),m.Fp=r,m.Fn=i;let h=new Do(m,i.BITS);return m.BASE.precompute(8),m}var tl=class{constructor(e){this.ep=e}static fromBytes(e){Ra()}static fromHex(e){Ra()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return w(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function nl(e,t,n={}){if(typeof t!=`function`)throw Error(`"hash" function param is required`);La(n,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,mapToCurve:`function`});let{prehash:r}=n,{BASE:i,Fp:a,Fn:o}=e,s=n.randomBytes||ce,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(Sa(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e});function u(e){return o.create(Ea(e))}function d(e){let n=b.secretKey;e=U(`private key`,e,n);let r=U(`hashed private key`,t(e),2*n),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}function f(e){let{head:t,prefix:n,scalar:r}=d(e),a=i.multiply(r);return{head:t,prefix:n,scalar:r,point:a,pointBytes:a.toBytes()}}function p(e){return f(e).pointBytes}function m(e=Uint8Array.of(),...n){let i=E(...n);return u(t(l(i,U(`context`,e),!!r)))}function h(e,t,n={}){e=U(`message`,e),r&&(e=r(e));let{prefix:a,scalar:s,pointBytes:c}=f(t),l=m(n.context,a,e),u=i.multiply(l).toBytes(),d=m(n.context,u,c,e),p=o.create(l+d*s);if(!o.isValid(p))throw Error(`sign failed: invalid s`);return Ca(E(u,o.toBytes(p)),b.signature,`result`)}let _={zip215:!0};function v(t,n,a,o=_){let{context:s,zip215:c}=o,l=b.signature;t=U(`signature`,t,l),n=U(`message`,n),a=U(`publicKey`,a,b.publicKey),c!==void 0&&Sa(c,`zip215`),r&&(n=r(n));let u=l/2,d=t.subarray(0,u),f=Ea(t.subarray(u,l)),p,h,g;try{p=e.fromBytes(a,c),h=e.fromBytes(d,c),g=i.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let v=m(s,h.toBytes(),p.toBytes(),n);return h.add(p.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()}let y=a.BYTES,b={secretKey:y,publicKey:y,signature:2*y,seed:y};function x(e=s(b.seed)){return Ca(e,b.seed,`seed`)}function ee(e){let t=C.randomSecretKey(e);return{secretKey:t,publicKey:p(t)}}function S(e){return g(e)&&e.length===o.BYTES}function te(t,n){try{return!!e.fromBytes(t,n)}catch{return!1}}let C={getExtendedPublicKey:f,randomSecretKey:x,isValidSecretKey:S,isValidPublicKey:te,toMontgomery(t){let{y:n}=e.fromBytes(t),r=b.publicKey,i=r===32;if(!i&&r!==57)throw Error(`only defined for 25519 and 448`);let o=i?a.div($+n,$-n):a.div(n-$,n+$);return a.toBytes(o)},toMontgomerySecret(e){let n=b.secretKey;Ca(e,n);let r=t(e.subarray(0,n));return c(r).subarray(0,n)},randomPrivateKey:x,precompute(t=8,n=e.BASE){return n.precompute(t,!1)}};return Object.freeze({keygen:ee,getPublicKey:p,sign:h,verify:v,utils:C,Point:e,lengths:b})}function rl(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n={Fp:e.Fp,Fn:lo(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}function il(e,t){let n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function al(e){let{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=rl(e);return il(e,nl(el(t,n),r,i))}var ol=BigInt(0),sl=BigInt(1),cl=BigInt(2),ll=BigInt(5),ul=BigInt(8),dl=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),fl={p:dl,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:ul,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function pl(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=dl,o=e*e%a*e%a,s=Ja(Ja(o,cl,a)*o%a,sl,a)*e%a,c=Ja(s,ll,a)*s%a,l=Ja(c,t,a)*c%a,u=Ja(l,n,a)*l%a,d=Ja(u,r,a)*u%a;return{pow_p_5_8:Ja(Ja(Ja(Ja(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,cl,a)*e%a,b2:o}}function ml(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var hl=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function gl(e,t){let n=dl,r=K(t*t*t,n),i=pl(e*K(r*r*t,n)).pow_p_5_8,a=K(e*r*i,n),o=K(t*a*a,n),s=a,c=K(a*hl,n),l=o===e,u=o===K(-e,n),d=o===K(-e*hl,n);return l&&(a=s),(u||d)&&(a=c),no(a,n)&&(a=K(-a,n)),{isValid:l||u,value:a}}var _l=lo(fl.p,{isLE:!0}),vl=lo(fl.n,{isLE:!0}),yl=al({...fl,Fp:_l,hash:We,adjustScalarBytes:ml,uvRatio:gl}),bl=hl,xl=BigInt(`25063068953384623474111414158702152701244531502492656460079210482610430750235`),Sl=BigInt(`54469307008909316920995813868745141605393597292927456921205312896311721017578`),Cl=BigInt(`1159843021668779879193775521855586647937357759715417654439879720876111806838`),wl=BigInt(`40440834346308536858101042469323190826248399146238708352240133220865137265952`),Tl=e=>gl(sl,e),El=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),Dl=e=>yl.Point.Fp.create(Ea(e)&El);function Ol(e){let{d:t}=fl,n=dl,r=e=>_l.create(e),i=r(bl*e*e),a=r((i+sl)*Cl),o=BigInt(-1),s=r((o-t*i)*r(i+t)),{isValid:c,value:l}=gl(a,s),u=r(l*e);no(u,n)||(u=r(-u)),c||(l=u),c||(o=i);let d=r(o*(i-sl)*wl-s),f=l*l,p=r((l+l)*s),m=r(d*xl),h=r(sl-f),g=r(sl+f);return new yl.Point(r(p*g),r(h*m),r(m*g),r(p*h))}function kl(e){v(e,64);let t=Ol(Dl(e.subarray(0,32))),n=Ol(Dl(e.subarray(32,64)));return new Al(t.add(n))}var Al=class e extends tl{constructor(e){super(e)}static fromAffine(t){return new e(yl.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw Error(`RistrettoPoint expected`)}init(t){return new e(t)}static hashToCurve(e){return kl(U(`ristrettoHash`,e,64))}static fromBytes(t){v(t,32);let{a:n,d:r}=fl,i=dl,a=e=>_l.create(e),o=Dl(t);if(!Oa(_l.toBytes(o),t)||no(o,i))throw Error(`invalid ristretto255 encoding 1`);let s=a(o*o),c=a(sl+n*s),l=a(sl-n*s),u=a(c*c),d=a(l*l),f=a(n*r*u-d),{isValid:p,value:m}=Tl(a(f*d)),h=a(m*l),g=a(m*h*f),_=a((o+o)*h);no(_,i)&&(_=a(-_));let y=a(c*g),b=a(_*y);if(!p||no(b,i)||y===ol)throw Error(`invalid ristretto255 encoding 2`);return new e(new yl.Point(_,y,sl,b))}static fromHex(t){return e.fromBytes(U(`ristrettoHex`,t,32))}static msm(t,n){return ko(e,yl.Point.Fn,t,n)}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep,i=dl,a=e=>_l.create(e),o=a(a(n+t)*a(n-t)),s=a(e*t),{value:c}=Tl(a(o*a(s*s))),l=a(c*o),u=a(c*s),d=a(l*u*r),f;if(no(r*d,i)){let n=a(t*bl),r=a(e*bl);e=n,t=r,f=a(l*Sl)}else f=u;no(e*d,i)&&(t=a(-t));let p=a((n-t)*f);return no(p,i)&&(p=a(-p)),_l.toBytes(p)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:r,Y:i}=e.ep,a=e=>_l.create(e),o=a(t*i)===a(n*r),s=a(n*i)===a(t*r);return o||s}is0(){return this.equals(e.ZERO)}};Al.BASE=new Al(yl.Point.BASE),Al.ZERO=new Al(yl.Point.ZERO),Al.Fp=_l,Al.Fn=vl;function jl(e){if(!Number.isFinite(e)||e<=0)throw Error(`expirationTime must be a positive finite number, got ${e}`)}var Ml=class{#e;#t;#n=null;constructor(e){if(globalThis.indexedDB===void 0)throw Error(`IndexedDBExpirableStore requires IndexedDB, which is not available in this environment`);jl(e.expirationTime),this.#e=e.dbName,this.#t=e.storeName,this.expirationTime=e.expirationTime}#r(){return this.#n||=this.#i().catch(e=>{throw this.#n=null,e}),this.#n}async#i(){let e=await this.#a();if(e.objectStoreNames.contains(this.#t))return e;let t=e.version+1;return e.close(),this.#a(t)}#a(e){let t=this.#t;return new Promise((n,r)=>{let i=globalThis.indexedDB.open(this.#e,e);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(t)||e.createObjectStore(t,{keyPath:`key`})},i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>{e.close(),this.#n=null},n(e)},i.onerror=()=>r(i.error)})}async get(e){let t=await this.#r();return new Promise((n,r)=>{let i=t.transaction(this.#t,`readonly`).objectStore(this.#t).get(e);i.onsuccess=()=>{let t=i.result;t?Date.now()-t.timestamp>this.expirationTime?this.delete(e).then(()=>n(void 0),()=>n(void 0)):n(t.value):n(void 0)},i.onerror=()=>r(i.error)})}async set(e,t){await this.#o();let n=await this.#r();return new Promise((r,i)=>{let a=n.transaction(this.#t,`readwrite`),o=a.objectStore(this.#t),s={key:e,value:t,timestamp:Date.now()};o.put(s),a.oncomplete=()=>r(),a.onerror=()=>i(a.error)})}async delete(e){let t=await this.#r();return new Promise((n,r)=>{let i=t.transaction(this.#t,`readwrite`);i.objectStore(this.#t).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async#o(){let e=await this.#r(),t=Date.now();return new Promise((n,r)=>{let i=e.transaction(this.#t,`readwrite`),a=i.objectStore(this.#t).openCursor();a.onsuccess=()=>{let e=a.result;if(!e)return;let n=e.value;t-n.timestamp>this.expirationTime&&e.delete(),e.continue()},i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}},Nl=class{#e;constructor(e){jl(e.expirationTime),this.expirationTime=e.expirationTime,this.#e=new Map}get(e){let t=this.#e.get(e);return t?Date.now()-t.timestamp>this.expirationTime?(this.#e.delete(e),Promise.resolve(void 0)):Promise.resolve(t.value):Promise.resolve(void 0)}set(e,t){return this.#t(),this.#e.set(e,{value:t,timestamp:Date.now()}),Promise.resolve()}delete(e){return this.#e.delete(e),Promise.resolve()}#t(){let e=Date.now();for(let[t,n]of this.#e)e-n.timestamp>this.expirationTime&&this.#e.delete(t)}};function Pl(e){return globalThis.indexedDB===void 0?new Nl({expirationTime:e.expirationTime}):new Ml(e)}var Fl=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw j.fromCode(new _t(`Length too long (> 4 bytes)`))},Il=(e,t,n)=>{if(n<=127)return e[t]=n,1;if(n<=255)return e[t]=129,e[t+1]=n,2;if(n<=65535)return e[t]=130,e[t+1]=n>>8,e[t+2]=n,3;if(n<=16777215)return e[t]=131,e[t+1]=n>>16,e[t+2]=n>>8,e[t+3]=n,4;throw j.fromCode(new _t(`Length too long (> 4 bytes)`))},Ll=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw j.fromCode(new gt(`Invalid length 0`));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw j.fromCode(new gt(`Length too long (> 4 bytes)`))},Rl=(e,t)=>{let n=Ll(e,t);if(n===1)return e[t];if(n===2)return e[t+1];if(n===3)return(e[t+1]<<8)+e[t+2];if(n===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw j.fromCode(new gt(`Length too long (> 4 bytes)`))};Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]);var zl=Uint8Array.from([48,5,6,3,43,101,112]);Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),Uint8Array.from([48,29,6,13,43,6,1,4,1,130,220,124,5,3,1,2,1,6,12,43,6,1,4,1,130,220,124,5,3,2,1]);function Bl(e,t){let n=2+Fl(e.byteLength+1),r=t.byteLength+n+e.byteLength,i=0,a=new Uint8Array(1+Fl(r)+r);return a[i++]=48,i+=Il(a,i,r),a.set(t,i),i+=t.byteLength,a[i++]=3,i+=Il(a,i,e.byteLength+1),a[i++]=0,a.set(new Uint8Array(e),i),a}var Vl=(e,t)=>{let n=0,r=(e,t)=>{if(i[n++]!==e)throw j.fromCode(new gt(`Expected ${t} at offset ${n}`))},i=new Uint8Array(e);if(r(48,`sequence`),n+=Ll(i,n),!qr(i.slice(n,n+t.byteLength),t))throw j.fromCode(new gt(`Not the expected OID.`));n+=t.byteLength,r(3,`bit string`);let a=Rl(i,n)-1;n+=Ll(i,n),r(0,`0 padding`);let o=i.slice(n);if(a!==o.length)throw j.fromCode(new ht(a,o.length));return o},Hl=class e{static from(e){return this.fromDer(e.toDer())}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(e){return Bl(e,zl)}static derDecode(e){let t=Vl(e,zl);if(t.length!==this.RAW_KEY_LENGTH)throw j.fromCode(new gt(`An Ed25519 public key must be exactly 32 bytes long`));return t}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw j.fromCode(new gt(`An Ed25519 public key must be exactly 32 bytes long`));this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}},Ul=class{constructor(){this.observers=[]}subscribe(e){this.observers.push(e)}unsubscribe(e){this.observers=this.observers.filter(t=>t!==e)}notify(e,...t){this.observers.forEach(n=>n(e,...t))}},Wl=class extends Ul{constructor(){super()}print(e,...t){this.notify({message:e,level:`info`},...t)}warn(e,...t){this.notify({message:e,level:`warn`},...t)}error(e,t,...n){this.notify({message:e,level:`error`,error:t},...n)}},Gl=.5,Kl=1.5,ql=500,Jl=6e4,Yl=9e5,Xl=10,Zl=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c=0;static{this.default={initialInterval:ql,randomizationFactor:Gl,multiplier:Kl,maxInterval:Jl,maxElapsedTime:Yl,maxIterations:Xl,date:Date}}constructor(t=e.default){let{initialInterval:n=ql,randomizationFactor:r=Gl,multiplier:i=Kl,maxInterval:a=Jl,maxElapsedTime:o=Yl,maxIterations:s=Xl,date:c=Date}=t;this.#e=n,this.#t=r,this.#n=i,this.#r=a,this.#s=c,this.#i=c.now(),this.#a=o,this.#o=s}get ellapsedTimeInMsec(){return this.#s.now()-this.#i}get currentInterval(){return this.#e}get count(){return this.#c}get randomValueFromInterval(){let e=this.#t*this.#e,t=this.#e-e,n=this.#e+e;return Math.random()*(n-t)+t}incrementCurrentInterval(){return this.#e=Math.min(this.#e*this.#n,this.#r),this.#c++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#a||this.#c>=this.#o?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}},Ql=3e5;function $l(){return iu(tu(eu(),1e3),ru(1e3,1.2),nu(Ql))}function eu(){let e=!0;return async()=>e?(e=!1,!0):!1}function tu(e,t){return async(n,r,i)=>{if(await e(n,r,i))return new Promise(e=>setTimeout(e,t))}}function nu(e){let t=Date.now()+e;return async(n,r,i)=>{if(Date.now()>t)throw A.fromCode(new bt(`Request timed out after ${e} msec`,r,i))}}function ru(e,t){let n=e;return()=>new Promise(e=>setTimeout(()=>{n*=t,e()},n))}function iu(...e){return async(t,n,r)=>{for(let i of e)await i(t,n,r)}}var au={preSignReadStateRequest:!1};function ou(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function su(e,t){return typeof e==`object`&&!!e&&ou(e,t)}function cu(e,t){return ou(e,t)&&typeof e[t]==`function`}function lu(e){return su(e,`body`)&&su(e.body,`content`)&&e.body.content.request_type===ha.ReadState&&su(e.body.content,`ingress_expiry`)&&typeof e.body.content.ingress_expiry==`object`&&e.body.content.ingress_expiry!==null&&cu(e.body.content.ingress_expiry,`toHash`)}async function uu(e,t,n,r={}){let i=[T(`request_status`),n],a,o;if(r.preSignReadStateRequest??!1?(o=await du({paths:[i],agent:e,pollingOptions:r}),a=await e.readState(t,{paths:[i]},void 0,o)):a=await e.readState(t,{paths:[i]}),e.rootKey==null)throw it.fromCode(new Et);let s=await pc.create({certificate:a.certificate,rootKey:e.rootKey,principal:{canisterId:t},blsVerify:r.blsVerify,agent:e}),c=yc(s.lookup_path([...i,T(`status`)])),l;switch(l=c===void 0?ga.Unknown:new TextDecoder().decode(c),l){case ga.Replied:return{reply:yc(s.lookup_path([...i,`reply`])),certificate:s,rawCertificate:a.certificate};case ga.Received:case ga.Unknown:case ga.Processing:{let i=r.strategy??$l();return await i(t,n,l),uu(e,t,n,{...r,strategy:i,request:o})}case ga.Rejected:throw nt.fromCode(Yc(s,i,n));case ga.Done:throw M.fromCode(new Tt(n))}throw Kt}async function du(e){let{paths:t,agent:n,pollingOptions:r}=e;if(r.request&&lu(r.request))return r.request;let i=await n.createReadStateRequest?.({paths:t},void 0);if(!lu(i))throw j.fromCode(new Ut(i));return i}var fu=6e4,pu=1e6,mu=0,hu=`308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae`,gu=`ic0.app`,_u=`.ic0.app`,vu=`icp0.io`,yu=`.icp0.io`,bu=`icp-api.io`,xu=`.icp-api.io`,Su=200,Cu=202,wu=404;function Tu(e){let t;if(e!==void 0)t=!e.match(/^[a-z]+:/)&&typeof window<`u`?new URL(`${window.location.protocol}//${e}`):new URL(e);else{let e=[`ic0.app`,`icp0.io`,`127.0.0.1`,`localhost`],n=[`.github.dev`,`.gitpod.io`],r=typeof window<`u`?window.location:void 0,i=r?.hostname,a;i&&typeof i==`string`&&(a=n.some(e=>i.endsWith(e))?i:e.find(e=>i.endsWith(e))),t=r&&a?new URL(`${r.protocol}//${a}${r.port?`:${r.port}`:``}`):new URL(`https://icp-api.io`)}return t.toString()}var Eu=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;get#h(){return this.#p*fu}#g;#_;#v;#y;constructor(e={}){if(this.#e=null,this.#t=!1,this.#n=mu,this.#r=!1,this.#i=null,this.#a=!1,this._isAgent=!0,this.config={},this.log=new Wl,this.#g=[],this.#_=[],this.#v=new Map,this.#y=!0,this.#w=(e,t)=>{if(this.#y===!1)return e;let{status:n,signatures:r=[],requestId:i}=e,a=t.size;if(r.length>a)throw A.fromCode(new Mt(r.length,a));for(let a of r){let{timestamp:r,identity:s}=a,c=O.fromUint8Array(s).toText(),l;if(n===o.Replied){let{reply:t}=e;l=Zr({status:n,reply:t,timestamp:BigInt(r),request_id:i})}else if(n===o.Rejected){let{reject_code:t,reject_message:a,error_code:o}=e;l=Zr({status:n,reject_code:t,reject_message:a,error_code:o,timestamp:BigInt(r),request_id:i})}else throw M.fromCode(new It(`Unknown status: ${n}`));let u=E($r,l),d=t.get(c);if(!d)throw A.fromCode(new Pt);let f=Hl.fromDer(d).rawKey;if(!yl.verify(a.signature,u,f))throw tt.fromCode(new Ft(c))}return e},this.config=e,e.fetch)this.#s=e.fetch;else{let e=globalThis.fetch;if(typeof e!=`function`)throw j.fromCode(new At);this.#s=e.bind(globalThis)}this.#c=e.fetchOptions,this.#l=e.callOptions,this.#t=e.shouldFetchRootKey??!1,this.#a=e.shouldSyncTime??!1,this.rootKey=e.rootKey?e.rootKey:this.#t?null:ie(hu);let t=Tu(e.host);this.host=new URL(t),this.host.hostname.endsWith(_u)?this.host.hostname=gu:this.host.hostname.endsWith(yu)?this.host.hostname=vu:this.host.hostname.endsWith(xu)&&(this.host.hostname=bu),e.verifyQuerySignatures!==void 0&&(this.#y=e.verifyQuerySignatures),this.#m=e.subnetNodeKeyExpirableStore??Pl({dbName:`icp-sdk-${this.host.host}`,storeName:`subnetNodeKeys`,expirationTime:5*fu}),this.#d=e.retryTimes??3;let n=()=>new Zl({maxIterations:this.#d});if(this.#f=e.backoffStrategy||n,e.credentials){let{name:t,password:n}=e.credentials;this.#u=`${t}${n?`:${n}`:``}`}if(this.#o=Promise.resolve(e.identity||new ei),e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes>5)throw j.fromCode(new kt(`The maximum ingress expiry time is 5 minutes.`,e.ingressExpiryInMinutes));if(e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes<=0)throw j.fromCode(new kt(`Ingress expiry time must be greater than 0.`,e.ingressExpiryInMinutes));this.#p=e.ingressExpiryInMinutes||5,this.addTransform(`update`,va(_a)),e.useQueryNonces&&this.addTransform(`query`,va(_a)),e.logToConsole&&this.log.subscribe(e=>{e.level===`error`?console.error(e.message):e.level===`warn`?console.warn(e.message):console.log(e.message)})}static createSync(e={}){return new this({...e})}static async create(t={}){let n=e.createSync(t);return await n.#D(),n}static async from(t){try{return`config`in t?await e.create(t.config):await e.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw j.fromCode(new jt)}}isLocal(){let e=this.host.hostname;return e===`127.0.0.1`||e.endsWith(`127.0.0.1`)}addTransform(e,t,n=t.priority||0){if(e===`update`){let e=this.#_.findIndex(e=>(e.priority||0)<n);this.#_.splice(e>=0?e:this.#_.length,0,Object.assign(t,{priority:n}))}else if(e===`query`){let e=this.#g.findIndex(e=>(e.priority||0)<n);this.#g.splice(e>=0?e:this.#g.length,0,Object.assign(t,{priority:n}))}}async getPrincipal(){if(!this.#o)throw it.fromCode(new Ot);return(await this.#o).getPrincipal()}async call(e,t,n){let r=t.callSync??!0,i=await(n??this.#o);if(!i)throw it.fromCode(new Ot);let a=O.from(e),o=t.effectiveCanisterId?O.from(t.effectiveCanisterId):a;await this.#D(o);let s=i.getPrincipal(),c=Du(this.#p,this.#n),l={request_type:ma.Call,canister_id:a,method_name:t.methodName,arg:t.arg,sender:s,ingress_expiry:c},u=await this._transform({request:{body:null,method:`POST`,headers:{"Content-Type":`application/cbor`,...this.#u?{Authorization:`Basic ${btoa(this.#u)}`}:{}}},endpoint:pa.Call,body:l}),d;d=t?.nonce?f(t.nonce):u.body.nonce?f(u.body.nonce):void 0,l.nonce=d;function f(e){return Object.assign(e,{__nonce__:void 0})}u=await i.transformRequest(u);let p=Xr(u.body.content??l),m=ua(u.body),h=this.#f();try{let e=r?()=>{let e=new URL(`/api/v4/canister/${o.toText()}/call`,this.host);return this.log.print(`fetching "${e.pathname}" with request:`,u),this.#s(e,{...this.#l,...u.request,body:m})}:()=>{let e=new URL(`/api/v2/canister/${o.toText()}/call`,this.host);return this.log.print(`fetching "${e.pathname}" with request:`,u),this.#s(e,{...this.#l,...u.request,body:m})},{responseBodyBytes:t,...n}=await this.#C({requestFn:e,backoff:h,tries:0}),i=t.byteLength>0?da(t):null;return{requestId:p,response:{...n,body:i},requestDetails:l}}catch(r){let i;if(r instanceof $e){if(r.hasCode(Bt))return this.log.warn(`v4 api not supported. Fall back to v2`),this.call(e,{...t,callSync:!1},n);if(r.hasCode(kt)&&!this.#r)return await this.syncTime(a),this.call(a,t,n);r.code.requestContext={requestId:p,senderPubKey:u.body.sender_pubkey,senderSignature:u.body.sender_sig,ingressExpiry:u.body.content.ingress_expiry},i=r}else i=M.fromCode(new It(r));throw this.log.error(`Error while making call: ${i.message}`,i),i}}async update(e,t,n={}){let r=O.from(t.effectiveCanisterId),{requestId:i,response:a,requestDetails:o}=await this.call(e,t),{body:l,...u}=a;if(c(l))return this.#b(l,a,i,r,t.methodName,u,o,n,t.onPollingStarted);if(s(l)&&this.#x(l,i,r,t.methodName,u),a.status===Cu)return t.onPollingStarted?.(),{...await uu(this,r,i,n),requestDetails:o,callResponse:a};let d=new It(`Unexpected response from call: status ${a.status} with unrecognized body`);throw d.callContext={canisterId:r,methodName:t.methodName,httpDetails:u},M.fromCode(d)}async#b(e,t,n,r,i,a,o,s,c){if(this.rootKey==null)throw it.fromCode(new Et);let l=e.certificate,u=await pc.create({certificate:l,rootKey:this.rootKey,principal:{canisterId:r},blsVerify:s.blsVerify,agent:this}),d=[T(`request_status`),n],f=yc(u.lookup_path([...d,T(`status`)])),p=f?new TextDecoder().decode(f):void 0;switch(p){case ga.Replied:return{reply:yc(u.lookup_path([...d,`reply`])),certificate:u,rawCertificate:l,requestDetails:o,callResponse:t};case ga.Rejected:{let e=Yc(u,d,n);throw e.callContext={canisterId:r,methodName:i,httpDetails:a},nt.fromCode(e)}case void 0:return this.log.warn(`v4 sync response certificate does not contain request ID ${w(n)} status. Falling back to polling.`),c?.(),{...await uu(this,r,n,s),requestDetails:o,callResponse:t};default:{let e=new Lt(p,n,t,l);throw e.callContext={canisterId:r,methodName:i,httpDetails:a},M.fromCode(e)}}}#x(e,t,n,r,i){let{reject_code:a,reject_message:o,error_code:s}=e,c=new wt(t,a,o,s);throw c.callContext={canisterId:n,methodName:r,httpDetails:i},nt.fromCode(c)}async#S(e){let{ecid:t,transformedRequest:n,body:r,requestId:i,backoff:a,tries:o}=e,s=o===0?0:a.next(),c=new URL(`/api/v3/canister/${t.toString()}/query`,this.host);if(this.log.print(`fetching "${c.pathname}" with tries:`,{tries:o,backoff:a,delay:s}),s===null)throw M.fromCode(new bt(`Backoff strategy exhausted after ${o} attempts.`,i));s>0&&await new Promise(e=>setTimeout(e,s));let l;try{this.log.print(`fetching "${c.pathname}" with request:`,n),l=await this.#s(c,{...this.#c,...n.request,body:r})}catch(t){if(o<this.#d)return this.log.warn(`Caught exception while attempting to make query:\n ${t}\n Retrying query.`),await this.#S({...e,tries:o+1});throw rt.fromCode(new Vt(t))}let u=ya(l.headers);if(l.status!==Su){let t=await l.text();if(Ou(t))throw j.fromCode(new kt(t,this.#p));if(o<this.#d)return await this.#S({...e,tries:o+1});throw A.fromCode(new zt(l.status,l.statusText,u,t))}let d={...da(Kr(await l.arrayBuffer())),httpDetails:{ok:l.ok,status:l.status,statusText:l.statusText,headers:u},requestId:i};if(!this.#y)return d;let f=d.signatures?.[0]?.timestamp;if(!f)throw A.fromCode(new Nt(`Timestamp not found in query response. This suggests a malformed or malicious response.`));let p=Number(BigInt(f)/BigInt(pu));if(Date.now()+this.#n-p>this.#h){if(o<this.#d)return this.log.warn(`Timestamp is older than the max ingress expiry. Retrying query.`,{requestId:i,signatureTimestampMs:p}),await this.syncTime(t),await this.#S({...e,tries:o+1});throw tt.fromCode(new xt(this.#p,i,o))}return d}async#C(e){let{requestFn:t,backoff:n,tries:r}=e,i=r===0?0:n.next();if(i===null)throw A.fromCode(new bt(`Retry strategy exhausted after ${r} attempts.`));i>0&&await new Promise(e=>setTimeout(e,i));let a,o=new Uint8Array;try{a=await t(),a.status===Su&&(o=Kr(await a.clone().arrayBuffer()))}catch(e){if(r<this.#d)return this.log.warn(`Caught exception while attempting to make request:\n ${e}\n Retrying request.`),await this.#C({requestFn:t,backoff:n,tries:r+1});throw rt.fromCode(new Vt(e))}let s=ya(a.headers);if(a.status===Su||a.status===Cu)return{ok:a.ok,status:a.status,statusText:a.statusText,responseBodyBytes:o,headers:s};let c=await a.text();if(a.status===wu&&a.url.includes(`api/v4`))throw A.fromCode(new Bt);if(Ou(c))throw j.fromCode(new kt(c,this.#p));if(r<this.#d)return await this.#C({requestFn:t,backoff:n,tries:r+1});throw A.fromCode(new zt(a.status,a.statusText,s,c))}async query(e,t,n){let r=this.#f(),i=t.effectiveCanisterId?O.from(t.effectiveCanisterId):O.from(e);await this.#D(i),this.log.print(`ecid ${i.toString()}`),this.log.print(`canisterId ${e.toString()}`);let a,o=await(n??this.#o);if(!o)throw it.fromCode(new Ot);let s=O.from(e),c=o.getPrincipal(),l=Du(this.#p,this.#n),u={request_type:ha.Query,canister_id:s,method_name:t.methodName,arg:t.arg,sender:c,ingress_expiry:l};a=await this._transform({request:{method:`POST`,headers:{"Content-Type":`application/cbor`,...this.#u?{Authorization:`Basic ${btoa(this.#u)}`}:{}}},endpoint:pa.Query,body:u}),a=await o.transformRequest(a);let d=Xr(a.body.content??u),f=ua(a.body),p={canister:s.toText(),ecid:i,transformedRequest:a,body:f,requestId:d,backoff:r,tries:0},m=async()=>{let e=await this.#S(p);return{requestDetails:u,...e}};try{if(!this.#y)return await m();let[e,t]=await Promise.all([m(),this.fetchSubnetKeys(i)]);try{return this.#w(e,t)}catch{this.log.warn(`Query response verification failed. Retrying with fresh subnet keys.`),await this.#m.delete(i.toString());let t=await this.fetchSubnetKeys(i);return this.#w(e,t)}}catch(r){let o;if(r instanceof $e){if(r.hasCode(kt)&&!this.#r)return await this.syncTime(i),this.query(e,t,n);r.code.requestContext={requestId:d,senderPubKey:a.body.sender_pubkey,senderSignature:a.body.sender_sig,ingressExpiry:a.body.content.ingress_expiry},o=r}else o=M.fromCode(new It(r));throw this.log.error(`Error while making query: ${o.message}`,o),o}}#w;async createReadStateRequest(e,t){await this.#D();let n=await(t??this.#o);if(!n)throw it.fromCode(new Ot);let r=n.getPrincipal(),i=await this._transform({request:{method:`POST`,headers:{"Content-Type":`application/cbor`,...this.#u?{Authorization:`Basic ${btoa(this.#u)}`}:{}}},endpoint:pa.ReadState,body:{request_type:ha.ReadState,paths:e.paths,sender:r,ingress_expiry:Du(this.#p,this.#n)}});return n.transformRequest(i)}async readState(e,t,n,r){await this.#O();let i=O.from(e);function a(e){for(let t of e.paths){let[e,n]=t;if(qr(e,new TextEncoder().encode(`request_status`)))return n}}let o,s;if(r)o=r;else{s=a(t);let e=await this.#o;if(!e)throw it.fromCode(new Ot);o=await this.createReadStateRequest(t,e)}let c=new URL(`/api/v3/canister/${i.toString()}/read_state`,this.host);return await this.#T(c,{canisterId:i},o,s)}async readSubnetState(e,t){await this.#O();let n=O.from(e),r=new URL(`/api/v3/subnet/${n.toString()}/read_state`,this.host),i=await this.createReadStateRequest(t,this.#o??void 0);return await this.#T(r,{subnetId:n},i)}async#T(e,t,n,r){let i=this.#f();try{let{responseBodyBytes:t}=await this.#C({requestFn:()=>this.#s(e,{...this.#c,...n.request,body:ua(n.body)}),backoff:i,tries:0});return da(t)}catch(i){let a;if(i instanceof $e){if(i.hasCode(kt)&&!this.#r){if(`canisterId`in t)await this.syncTime(t.canisterId);else if(`subnetId`in t)await this.syncTimeWithSubnet(t.subnetId);else throw Kt;return await this.#T(e,t,n,r)}i.code.requestContext={requestId:r??Xr(n),senderPubKey:n.body.sender_pubkey,senderSignature:n.body.sender_sig,ingressExpiry:n.body.content.ingress_expiry},a=i}else a=M.fromCode(new It(i));throw this.log.error(`Error while making read state: ${a.message}`,a),a}}parseTimeFromResponse(e){let t;if(e.certificate){let n=da(e.certificate);if(n&&`tree`in n)t=n.tree;else throw A.fromCode(new Rt(`Could not decode time from response`));let r=Tc([`time`],t);if(r.status!==Cc.Found)throw A.fromCode(new ut(`Time was not found in the response or was not in its expected format.`,r.status));if(!(r.value instanceof Uint8Array)&&!ArrayBuffer.isView(r))throw A.fromCode(new dt(`Time was not in its expected format.`));let i=oc(r.value);return this.log.print(`Time from response:`,i),this.log.print(`Time from response in milliseconds:`,i.getTime()),i.getTime()}return this.log.warn(`No certificate found in response`),0}async syncTime(t){this.#i=this.#i??(async()=>{await this.#O();let n=Date.now();try{t||this.log.print(`Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai`);let r=t??O.from(`ryjl3-tyaaa-aaaaa-aaaba-cai`),i=e.createSync({identity:new ei,host:this.host.toString(),fetch:this.#s,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),a=await Promise.all([,,,].fill(null).map(async()=>{let e=(await Wc({canisterId:r,agent:i,paths:[`time`],disableCertificateTimeVerification:!0})).get(`time`);if(e instanceof Date)return e.getTime()},[]));this.#E(n,a)}catch(e){let t=e instanceof $e?e:M.fromCode(new It(e));throw this.log.error(`Caught exception while attempting to sync time`,t),t}})(),await this.#i.finally(()=>{this.#i=null})}async syncTimeWithSubnet(t){await this.#O();let n=Date.now();try{let r=e.createSync({identity:new ei,host:this.host.toString(),fetch:this.#s,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),i=await Promise.all([,,,].fill(null).map(async()=>{let e=(await qc({subnetId:t,agent:r,paths:[`time`],disableCertificateTimeVerification:!0})).get(`time`);if(e instanceof Date)return e.getTime()},[]));this.#E(n,i)}catch(e){let t=e instanceof $e?e:M.fromCode(new It(e));throw this.log.error(`Caught exception while attempting to sync time with subnet`,t),t}}#E(e,t){let n=t.reduce((e,t)=>typeof t==`number`&&t>e?t:e,0);n>0&&(this.#n=n-e,this.#r=!0,this.log.notify({message:`Syncing time: offset of ${this.#n}`,level:`info`}))}async status(){let e=this.#u?{Authorization:`Basic ${btoa(this.#u)}`}:{},t=new URL(`/api/v2/status`,this.host);this.log.print(`fetching "${t.pathname}"`);let n=this.#f(),{responseBodyBytes:r}=await this.#C({backoff:n,requestFn:()=>this.#s(t,{headers:e,...this.#c}),tries:0});return da(r)}async fetchRootKey(){return this.#e=this.#e??(async()=>{let e=await this.status();return this.rootKey=e.root_key,this.rootKey})(),await this.#e.finally(()=>{this.#e=null})}async#D(e){await Promise.all([this.#O(),this.#k(e)])}async#O(){if(!this.rootKey){if(this.rootKey===null&&this.host.toString()!==`https://icp-api.io`&&this.#t)await this.fetchRootKey();else throw it.fromCode(new Et(this.#t))}}async#k(e){this.#a&&!this.hasSyncedTime()&&await this.syncTime(e)}invalidateIdentity(){this.#o=null}replaceIdentity(e){this.#o=Promise.resolve(e)}async fetchSubnetKeys(e){let t=O.from(e),n=await this.#m.get(t.toText());if(n)return n;let r=this.#v.get(t.toText());if(r)return r;let i=this.#A(t).finally(()=>{this.#v.delete(t.toText())});return this.#v.set(t.toText(),i),i}async#A(e){await this.#D(e);let t=this.rootKey,n=await this.readState(e,{paths:[[T(`subnet`)]]}),r=await pc.create({certificate:n.certificate,rootKey:t,principal:{canisterId:e},agent:this});if(!r.cert.delegation){let n=O.selfAuthenticating(t);if(!Ac({canisterId:e,subnetId:n,tree:r.cert.tree}))throw tt.fromCode(new ct(e,n))}let i=Lc(r.cert,t),a=Uc(r.cert,i);return await this.#m.set(e.toText(),a),a}async getSubnetIdFromCanister(e){let t=O.from(e);await this.#D(t);let n=await this.readState(t,{paths:[[T(`time`)]]});return Lc((await pc.create({certificate:n.certificate,rootKey:this.rootKey,principal:{canisterId:t},agent:this})).cert,this.rootKey)}_transform(e){let t=Promise.resolve(e);if(e.endpoint===pa.Call)for(let e of this.#_)t=t.then(t=>e(t).then(e=>e||t));else for(let e of this.#g)t=t.then(t=>e(t).then(e=>e||t));return t}getTimeDiffMsecs(){return this.#n}hasSyncedTime(){return this.#r}};function Du(e,t){let n=e*fu;return ca.fromDeltaInMilliseconds(n,t)}function Ou(e){return e.includes(`Invalid request expiry: `)}var ku=Symbol.for(`ic-agent-metadata`),Au=class{static agentOf(e){return e[ku].config.agent}static interfaceOf(e){return e[ku].service}static canisterIdOf(e){return O.from(e[ku].config.canisterId)}static createActorClass(e,t){let n=e({IDL:un});class r extends Au{constructor(e){if(!e.canisterId)throw j.fromCode(new Ht(e.canisterId));let r=typeof e.canisterId==`string`?O.fromText(e.canisterId):e.canisterId;super({config:{...Mu,...e,canisterId:r},service:n});for(let[r,i]of n._fields)t?.httpDetails&&i.annotations.push(Nu),t?.certificate&&i.annotations.push(Pu),this[r]=Fu(this,r,i,e.blsVerify)}}return r}static createActor(e,t){if(!t.canisterId)throw j.fromCode(new Ht(t.canisterId));return new(this.createActorClass(e))(t)}static createActorWithHttpDetails(e,t){return new(this.createActorClass(e,{httpDetails:!0}))(t)}static createActorWithExtendedDetails(e,t,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(e,n))(t)}constructor(e){this[ku]=Object.freeze(e)}};function ju(e,t){let n=Un(e,t);switch(n.length){case 0:return;case 1:return n[0];default:return n}}var Mu={pollingOptions:au,queryStrategy:`query`},Nu=`http-details`,Pu=`certificate`;function Fu(e,t,n,r){let i,a=n.annotations.includes(`query`)||n.annotations.includes(`composite_query`),s=e[ku].config.queryStrategy;i=a&&s===`query`?async(r,...i)=>{r={...r,...e[ku].config.queryTransform?.(t,i,{...e[ku].config,...r})};let a=r.agent||e[ku].config.agent||new Eu,s=O.from(r.canisterId||e[ku].config.canisterId),c=Hn(n.argTypes,i),l=await a.query(s,{methodName:t,arg:c,effectiveCanisterId:r.effectiveCanisterId}),u={...l.httpDetails,requestDetails:l.requestDetails};switch(l.status){case o.Rejected:{let e=new Ct(l.requestId,l.reject_code,l.reject_message,l.error_code,l.signatures);throw e.callContext={canisterId:s,methodName:t,httpDetails:u},nt.fromCode(e)}case o.Replied:return n.annotations.includes(`http-details`)?{httpDetails:u,result:ju(n.retTypes,l.reply.arg)}:ju(n.retTypes,l.reply.arg)}}:async(i,...a)=>{i={...i,...e[ku].config.callTransform?.(t,a,{...e[ku].config,...i})};let o=i.agent||e[ku].config.agent||Eu.createSync(),{canisterId:s,effectiveCanisterId:c,pollingOptions:l}={...Mu,...e[ku].config,...i},u=O.from(s),d=c===void 0?u:O.from(c),f=Hn(n.argTypes,a),p,m,h,g;try{({reply:p,certificate:m,callResponse:h,requestDetails:g}=await o.update(u,{methodName:t,arg:f,effectiveCanisterId:d,nonce:i.nonce},{...l,blsVerify:r}))}catch(e){if(e instanceof nt){let n=Object.create(Object.getPrototypeOf(e.code),Object.getOwnPropertyDescriptors(e.code));throw n.callContext={...e.code.callContext,canisterId:u,methodName:t},nt.fromCode(n)}throw e}let _=n.annotations.includes(Nu),v=n.annotations.includes(Pu),y={...h,requestDetails:g};return _&&v?{httpDetails:y,certificate:m,result:ju(n.retTypes,p)}:v?{certificate:m,result:ju(n.retTypes,p)}:_?{httpDetails:y,result:ju(n.retTypes,p)}:ju(n.retTypes,p)};let c=(...e)=>i({},...e);return c.withOptions=e=>(...t)=>i(e,...t),c}var Iu=({IDL:e})=>e.Service({get_fiat_rates:e.Func([],[e.Opt(e.Record({rates:e.Vec(e.Tuple(e.Text,e.Float64)),lastUpdated:e.Int}))],[`query`]),get_fiat_rate:e.Func([e.Text],[e.Opt(e.Float64)],[`query`]),get_pybara_admin_config:e.Func([],[e.Record({supported_tokens:e.Vec(e.Text),supported_wallets:e.Vec(e.Text),supported_plugins:e.Vec(e.Text),decimals:e.Vec(e.Tuple(e.Text,e.Nat8)),transfer_fees:e.Vec(e.Tuple(e.Text,e.Nat)),minimums:e.Vec(e.Tuple(e.Text,e.Nat))})],[`query`])}),Lu=({IDL:e})=>{let t=e.Record({id:e.Nat,site_url:e.Text,nanoid:e.Text,registered_at:e.Int,is_founder_rate:e.Bool,commission_bps:e.Nat}),n=e.Record({identity:t,is_allowed:e.Bool,issues_tax_receipts:e.Bool});return e.Service({get_merchant:e.Func([e.Text],[e.Opt(n)],[`query`]),get_recipient:e.Func([e.Text],[e.Opt(n)],[`query`])})},Ru=`https://icp-api.io`,zu=class{constructor(e){this.agent=null,this.adminCoreActor=null,this.adminRegsActor=null,this.adminConfig=null,this.merchantDataCache=new Map,this.recipientDataCache=new Map,this.merchantDataInFlight=new Map,this.recipientDataInFlight=new Map,this.adminCoreCanisterId=e.adminCoreCanisterId,this.adminRegsCanisterId=e.adminCoreCanisterId===i.staging.admin_core?i.staging.admin_regs:i.prod.admin_regs,this.debug=e.debug??!1}async init(){this.agent=await Eu.create({host:Ru}),this.adminCoreActor=Au.createActor(Iu,{agent:this.agent,canisterId:this.adminCoreCanisterId})}async getFiatRates(){let e=await this.getAdminActor();try{let t=(await e.get_fiat_rates())[0];if(t){let e={};return t.rates.forEach(([t,n])=>{e[t]=n}),e}return await this.fetchFiatRatesFallback()}catch(e){return this.debug&&console.warn(`🧩 ⚠️ Canister fiat rates failed, using fallback:`,e),await this.fetchFiatRatesFallback()}}async getFiatRate(e){if(e===`USD`)return 1;let t=await this.getAdminActor();try{let n=await t.get_fiat_rate(e);return n.length>0?n[0]??null:(await this.getFiatRates())[e]??null}catch(t){return this.debug&&console.warn(`🧩 ⚠️ Failed to get ${e}/USD rate:`,t),(await this.fetchFiatRatesFallback())[e]??null}}async getPybaraAdminConfig(){if(this.adminConfig)return this.adminConfig;let e=await this.getAdminActor();try{let t=await e.get_pybara_admin_config(),n={},r={},i={};t.decimals.forEach(([e,t])=>{n[e]=Number(t)}),t.minimums.forEach(([e,t])=>{r[e]=Number(t)}),t.transfer_fees&&Array.isArray(t.transfer_fees)&&t.transfer_fees.forEach(([e,t])=>{i[e]=t.toString()});let a={supported_tokens:t.supported_tokens||[],supported_wallets:t.supported_wallets||[],supported_plugins:t.supported_plugins||[],decimals:n,minimums:r,transfer_fees:i};return this.adminConfig=a,a}catch(e){throw this.debug&&console.error(`🧩 ❌ Get Pybara admin config failed:`,e),e}}async getMerchantDataWithCache(e){let t=Date.now(),n=this.merchantDataCache.get(e);if(n&&t-n.timestamp<3e5)return this.validateMerchantAccess(n.data),n.data;let r=this.merchantDataInFlight.get(e);if(r)return r;let i=this.fetchMerchantData(e,t);this.merchantDataInFlight.set(e,i);try{return await i}finally{this.merchantDataInFlight.delete(e)}}async fetchMerchantData(e,t){let n=(await(await this.getRegsActor()).get_merchant(e))?.[0]??null;return this.merchantDataCache.set(e,{data:n,timestamp:t}),this.validateMerchantAccess(n),n}async getRecipientDataWithCache(e){let t=Date.now(),n=this.recipientDataCache.get(e);if(n&&t-n.timestamp<3e5)return this.validateRecipientAccess(n.data),n.data;let r=this.recipientDataInFlight.get(e);if(r)return r;let i=this.fetchRecipientData(e,t);this.recipientDataInFlight.set(e,i);try{return await i}finally{this.recipientDataInFlight.delete(e)}}async fetchRecipientData(e,t){let n=(await(await this.getRegsActor()).get_recipient(e))?.[0]??null;return this.recipientDataCache.set(e,{data:n,timestamp:t}),this.validateRecipientAccess(n),n}async validatePlugin(e,t){this.adminConfig||await this.getPybaraAdminConfig();let n=this.adminConfig?.supported_plugins||[],r=t?`${e.toLowerCase()}-${t}`:e.toLowerCase();if(!n.includes(r))throw Error(`Plugin disabled by Pybara Administration: ${r}. Please contact Pybara support.`)}async getAgent(){if(this.agent||await this.init(),!this.agent)throw Error(`Agent initialization failed`);return this.agent}async getAdminActor(){return this.adminCoreActor||=Au.createActor(Iu,{agent:await this.getAgent(),canisterId:this.adminCoreCanisterId}),this.adminCoreActor}async getRegsActor(){return this.adminRegsActor||=Au.createActor(Lu,{agent:await this.getAgent(),canisterId:this.adminRegsCanisterId}),this.adminRegsActor}async fetchFiatRatesFallback(){try{let e=await fetch(`https://api.frankfurter.app/latest?from=USD`);if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json(),n={USD:1};for(let[e,r]of Object.entries(t.rates))n[e]=1/r;return n}catch(e){throw this.debug&&console.error(`🧩 ❌ Fiat rates fallback also failed:`,e),Error(`Unable to fetch fiat exchange rates from any source`)}}validateMerchantAccess(e){if(e&&!e.is_allowed)throw Error(`Merchant suspended by Pybara Administration`)}validateRecipientAccess(e){if(e&&!e.is_allowed)throw Error(`Donation recipient suspended by Pybara Administration`)}},Bu={Z_INDEX:999999,BACKGROUND:`rgba(0, 0, 0, 0.7)`},Vu={OVERLAY_FADE_IN_MS:200,PANEL_OPEN_MS:300,PANEL_CLOSE_MS:200,OVERLAY_FADE_OUT_DELAY_MS:50,OVERLAY_FADE_OUT_MS:150},Hu=0,Uu=0,Wu=0;function Gu(e){e.preventDefault()}function Ku(e){e.preventDefault()}function qu(e){e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||[`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&e.preventDefault()}function Ju(){window.scrollTo(Uu,Wu)}function Yu(){Hu===0&&(Uu=window.scrollX,Wu=window.scrollY,window.addEventListener(`wheel`,Gu,{passive:!1}),window.addEventListener(`touchmove`,Ku,{passive:!1}),window.addEventListener(`keydown`,qu),window.addEventListener(`scroll`,Ju)),Hu+=1}function Xu(){Hu!==0&&(--Hu,Hu===0&&(window.removeEventListener(`wheel`,Gu),window.removeEventListener(`touchmove`,Ku),window.removeEventListener(`keydown`,qu),window.removeEventListener(`scroll`,Ju)))}function Zu(){return window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}var Qu=[`DESTINATION_REFUSED`,`INVALID_BENEFICIARY`,`INVALID_CHECKOUT`,`NO_WALLET_AVAILABLE`,`RATE_UNAVAILABLE`,`SITE_MISMATCH`];function $u(e){return Qu.includes(e)?e:`UNKNOWN`}var ed=class extends Error{constructor(e,t){super(t),this.name=`EmbeddedError`,this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};function td(e){return typeof e==`object`&&!!e&&typeof e.type==`string`&&e.type.startsWith(`pybara_embedded_`)}var nd=class{constructor(e){this.overlay=null,this.iframe=null,this.spinner=null,this.handleMessage=null,this.handleEscapeKey=null,this.closable=!0,this.iframeLoaded=!1,this.pendingPaymentData=null,this.config=e,this.walletOrigin=new URL(e.walletUrl).origin,this.createIframe()}createIframe(){let e=document.createElement(`div`);e.className=`pybara-checkout-overlay`,e.style.cssText=`
|
|
4
4
|
position: fixed;
|
|
5
5
|
top: 0;
|
|
6
6
|
left: 0;
|
|
@@ -33,7 +33,7 @@ ic-request`);var ei=new TextEncoder().encode(`\vic-response`);new TextEncoder().
|
|
|
33
33
|
<svg viewBox="0 0 50 50" width="50" height="50">
|
|
34
34
|
<circle cx="25" cy="25" r="20" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-dasharray="80" stroke-dashoffset="20"/>
|
|
35
35
|
</svg>
|
|
36
|
-
`,n.querySelector(`svg`)?.animate([{transform:`rotate(0deg)`},{transform:`rotate(360deg)`}],{duration:1e3,iterations:1/0}),t.addEventListener(`load`,()=>{this.iframeLoaded=!0,this.pendingPaymentData&&=(this.sendInitMessage(this.pendingPaymentData),null)},{once:!0}),this.handleMessage=e=>{if(e.origin===this.walletOrigin&&e.source===t.contentWindow&&td(e.data))switch(e.data.type){case`pybara_embedded_result`:this.config.onSuccess?.({blockIndex:e.data.blockIndex,reference:e.data.reference,payerPrincipal:e.data.payerPrincipal,token:e.data.token});break;case`pybara_embedded_error`:this.close(),this.config.onError?.(new ed($u(e.data.code),e.data.message));break;case`pybara_embedded_closed`:this.close(),this.config.onClose?.();break;case`pybara_embedded_resize`:t.style.height!==`${e.data.height}px`&&(t.style.height=`${e.data.height}px`),this.spinner&&(this.spinner.remove(),this.spinner=null,Zu()||t.animate([{transform:`translateY(20px)`,opacity:0},{transform:`none`,opacity:1}],{duration:Vu.PANEL_OPEN_MS,easing:`ease`}));break;case`pybara_embedded_closable`:this.closable=e.data.closable}},window.addEventListener(`message`,this.handleMessage),this.handleEscapeKey=e=>{e.key===`Escape`&&this.closable&&(this.close(),this.config.onClose?.())},document.addEventListener(`keydown`,this.handleEscapeKey),e.appendChild(n),e.appendChild(t),document.body.appendChild(e),this.overlay=e,this.iframe=t,this.spinner=n}sendInitMessage(e){let t={type:`pybara_embedded_init`,beneficiary:e.modalData.beneficiary,salt:e.modalData.salt
|
|
36
|
+
`,n.querySelector(`svg`)?.animate([{transform:`rotate(0deg)`},{transform:`rotate(360deg)`}],{duration:1e3,iterations:1/0}),t.addEventListener(`load`,()=>{this.iframeLoaded=!0,this.pendingPaymentData&&=(this.sendInitMessage(this.pendingPaymentData),null)},{once:!0}),this.handleMessage=e=>{if(e.origin===this.walletOrigin&&e.source===t.contentWindow&&td(e.data))switch(e.data.type){case`pybara_embedded_result`:this.config.onSuccess?.({blockIndex:e.data.blockIndex,reference:e.data.reference,payerPrincipal:e.data.payerPrincipal,token:e.data.token});break;case`pybara_embedded_error`:this.close(),this.config.onError?.(new ed($u(e.data.code),e.data.message));break;case`pybara_embedded_closed`:this.close(),this.config.onClose?.();break;case`pybara_embedded_resize`:t.style.height!==`${e.data.height}px`&&(t.style.height=`${e.data.height}px`),this.spinner&&(this.spinner.remove(),this.spinner=null,Zu()||t.animate([{transform:`translateY(20px)`,opacity:0},{transform:`none`,opacity:1}],{duration:Vu.PANEL_OPEN_MS,easing:`ease`}));break;case`pybara_embedded_closable`:this.closable=e.data.closable}},window.addEventListener(`message`,this.handleMessage),this.handleEscapeKey=e=>{e.key===`Escape`&&this.closable&&(this.close(),this.config.onClose?.())},document.addEventListener(`keydown`,this.handleEscapeKey),e.appendChild(n),e.appendChild(t),document.body.appendChild(e),this.overlay=e,this.iframe=t,this.spinner=n}sendInitMessage(e){let t={type:`pybara_embedded_init`,beneficiary:e.modalData.beneficiary,salt:e.modalData.salt,...e.modalData.amountUSD===void 0?{}:{amountUSD:e.modalData.amountUSD},reference:e.modalData.reference,context:this.config.context,...e.recurring?{recurring:e.recurring}:{},...e.sdkFields?{sdkFields:e.sdkFields}:{},...e.checkout?{checkout:e.checkout}:{},...this.config.thankYouMessage?{thankYouMessage:this.config.thankYouMessage}:{}};this.iframe?.contentWindow?.postMessage(t,this.walletOrigin)}open(){this.overlay&&this.overlay.style.display!==`flex`&&(Yu(),this.overlay.style.display=`flex`,Zu()||this.overlay.animate([{opacity:0},{opacity:1}],{duration:Vu.OVERLAY_FADE_IN_MS,easing:`ease`}))}show(e){this.open(),this.iframeLoaded?this.sendInitMessage(e):this.pendingPaymentData=e}renderTerminalState(e){this.close(),Yu();let t=document.createElement(`div`);t.className=`pybara-checkout-overlay`,t.style.cssText=`
|
|
37
37
|
position: fixed;
|
|
38
38
|
top: 0;
|
|
39
39
|
left: 0;
|
|
@@ -55,4 +55,4 @@ ic-request`);var ei=new TextEncoder().encode(`\vic-response`);new TextEncoder().
|
|
|
55
55
|
text-align: center;
|
|
56
56
|
font-family: system-ui, sans-serif;
|
|
57
57
|
user-select: text;
|
|
58
|
-
`,n.textContent=e,t.appendChild(n),t.addEventListener(`click`,e=>{e.target===t&&(t.remove(),Xu(),this.config.onClose?.())}),document.body.appendChild(t),this.overlay=t}close(){this.handleMessage&&=(window.removeEventListener(`message`,this.handleMessage),null),this.handleEscapeKey&&=(document.removeEventListener(`keydown`,this.handleEscapeKey),null),Xu();let e=this.overlay,t=this.iframe;this.overlay=null,this.iframe=null,this.spinner=null,this.iframeLoaded=!1,this.pendingPaymentData=null,this.closable=!0,e&&(e.style.display===`none`||Zu()?e.remove():(e.style.pointerEvents=`none`,t?.animate([{transform:`scale(1)`,opacity:1},{transform:`scale(0.95)`,opacity:0}],{duration:Vu.PANEL_CLOSE_MS,easing:`ease-out`,fill:`forwards`}),e.animate([{opacity:1},{opacity:0}],{duration:Vu.OVERLAY_FADE_OUT_MS,delay:Vu.OVERLAY_FADE_OUT_DELAY_MS,easing:`ease-out`,fill:`forwards`}).finished.then(()=>e.remove(),()=>e.remove())))}},rd={
|
|
58
|
+
`,n.textContent=e,t.appendChild(n),t.addEventListener(`click`,e=>{e.target===t&&(t.remove(),Xu(),this.config.onClose?.())}),document.body.appendChild(t),this.overlay=t}close(){this.handleMessage&&=(window.removeEventListener(`message`,this.handleMessage),null),this.handleEscapeKey&&=(document.removeEventListener(`keydown`,this.handleEscapeKey),null),Xu();let e=this.overlay,t=this.iframe;this.overlay=null,this.iframe=null,this.spinner=null,this.iframeLoaded=!1,this.pendingPaymentData=null,this.closable=!0,e&&(e.style.display===`none`||Zu()?e.remove():(e.style.pointerEvents=`none`,t?.animate([{transform:`scale(1)`,opacity:1},{transform:`scale(0.95)`,opacity:0}],{duration:Vu.PANEL_CLOSE_MS,easing:`ease-out`,fill:`forwards`}),e.animate([{opacity:1},{opacity:0}],{duration:Vu.OVERLAY_FADE_OUT_MS,delay:Vu.OVERLAY_FADE_OUT_DELAY_MS,easing:`ease-out`,fill:`forwards`}).finished.then(()=>e.remove(),()=>e.remove())))}},rd={widget:`donate-widget`,recurring:`donate-widget-recurring`};function id(e,t){let n=e=>{let t=/^(\d+)-(\d+)$/.exec(e);return t?[Number(t[1]),Number(t[2])]:null},r=n(e),i=n(t);return!r||!i?!1:r[0]>i[0]||r[0]===i[0]&&r[1]>=i[1]}async function ad(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status} from ${e}`);return await t.json()}async function od(e,t,n){let r=i[e],a=`https://${r.admin_core}.raw.icp0.io/widget-config`,o=`https://${r.admin_regs}.raw.icp0.io/widget-terms?site_url=${encodeURIComponent(t)}&principal=${encodeURIComponent(n)}`,s,c;try{[s,c]=await Promise.all([ad(a),ad(o)])}catch(e){return{show:!1,reason:`could not read the widget's configuration (${e instanceof Error?e.message:String(e)})`}}let l=s.kill_switch?.plugins??{};return l[rd.widget]?.enabled===!0?!c.signed||!c.version?{show:!1,reason:`${t} has not accepted the widget's terms in Pybara Wallet (Manage › Sites › Add a site without a plugin)`}:id(c.version,`1-0`)?{show:!0,recurring:l[rd.recurring]?.enabled===!0}:{show:!1,reason:`this widget version requires terms 1-0, and ${t} accepted ${c.version}: accept the new terms in Pybara Wallet (Manage › Sites)`}:{show:!1,reason:`the widget is switched off by Pybara for now`}}var sd=class extends Error{constructor(e,t){super(t),this.name=`PybaraError`,this.code=e}},cd=/^(0|[1-9]\d*)(\.\d+)?$/,ld=/^[a-z0-9-]{1,64}$/,ud=class{constructor(e){this.adminClient=null,this.modal=null,this.gateOutcome=null,this.isOpen=!1,this.completedPayment=!1,this.activePayment=null,this.config=pd(e),this.ready=this.init()}get gate(){return this.gateOutcome}async open(e){if(await this.ready,this.gateOutcome&&!this.gateOutcome.show)throw new sd(`GATE_REFUSED`,this.gateOutcome.reason??`This site cannot accept Pybara payments yet.`);let t=dd(e.amount);if(t===null)throw new sd(`INVALID_CONFIG`,`open(): "amount" must be a decimal string in the currency's major units, e.g. "12.34", or a positive number — got ${JSON.stringify(e.amount)}`);let n=e.currency??this.config.currency;if(!n)throw new sd(`INVALID_CONFIG`,`open(): "currency" is required — pass it to open(), or set it once in Pybara.checkout()`);if(!/^[A-Z]{3}$/.test(n))throw new sd(`INVALID_CONFIG`,`open(): "currency" must be an uppercase ISO 4217 code, e.g. "EUR" — got ${JSON.stringify(n)}`);if(e.durationMonths!=null&&!e.frequency)throw new sd(`INVALID_CONFIG`,`open(): "durationMonths" needs a "frequency"`);let r=e.frequency?{frequency:e.frequency,...e.durationMonths==null?{}:{durationMonths:e.durationMonths}}:void 0;if(r&&this.gateOutcome&&this.gateOutcome.show&&!this.gateOutcome.recurring)throw new sd(`GATE_REFUSED`,`Recurring payments are temporarily unavailable.`);if(this.isOpen)return;this.isOpen=!0;let i=!1;try{await this.adminClient?.getRecipientDataWithCache(this.config.siteUrl)}catch(e){this.config.debug&&console.warn(`🧩 pybara-js: recipient access validation failed:`,e),i=!0}this.modal||this.initCheckoutModal();let a=this.modal;if(!a)throw this.isOpen=!1,new sd(`CHECKOUT_FAILED`,`The checkout modal could not be initialised.`);if(i)this.isOpen=!1,a.renderTerminalState(`This recipient is currently unable to accept donations.`),this.initCheckoutModal();else{this.activePayment=e;try{a.show({modalData:{beneficiary:this.config.recipientPrincipal,salt:md(),reference:this.config.siteName},recurring:r,checkout:this.checkoutFor(e,t,n)})}catch(e){throw this.isOpen=!1,this.activePayment=null,hd(e)}}}close(){this.modal?.close()}async init(){let e=this.config.staging?`staging`:`prod`,t=this.config.debug;t&&console.log(`🧩 pybara-js: initializing checkout…`),this.preconnectWallet(e),this.initCheckoutModal();let n=new zu({adminCoreCanisterId:i[e].admin_core,debug:t});this.adminClient=n;let r=(async()=>{try{await n.init(),await n.getPybaraAdminConfig(),t&&console.log(`🧩 pybara-js: admin client ready`),n.getRecipientDataWithCache(this.config.siteUrl).catch(e=>{t&&console.warn(`🧩 pybara-js: recipient prewarm failed:`,e)})}catch(e){t&&console.error(`🧩 pybara-js: admin client init failed:`,e)}})(),a=(async()=>{this.config.pluginVersion||(this.gateOutcome=await od(e,this.config.siteUrl,this.config.recipientPrincipal),!this.gateOutcome.show&&t&&console.warn(`🧩 pybara-js: gate refused —`,this.gateOutcome.reason))})();await Promise.all([r,a])}initCheckoutModal(){let e=this.config.staging?`staging`:`prod`,t=this.config,n=this;this.modal=new nd({walletUrl:r[e],context:`donation`,thankYouMessage:t.thankYouMessage,onSuccess:e=>{n.completedPayment=!0;let r=n.activePayment,i=r?.frequency!=null,a={blockIndex:e.blockIndex,reference:e.reference,token:e.token,recurring:i,frequency:r?.frequency,durationMonths:i?r?.durationMonths??void 0:void 0,isUnlimited:i&&r?.durationMonths==null,payerPrincipal:e.payerPrincipal,recipientPrincipal:t.recipientPrincipal};r?.onSuccess?.(a)},onError:e=>{n.isOpen=!1;let t=n.activePayment;n.activePayment=null,t?.onError?.(hd(e)),n.modal=null,n.initCheckoutModal()},onClose:()=>{n.isOpen=!1;let e=n.activePayment;n.activePayment=null,e?.onClose?.(),n.completedPayment&&t.thankYouRedirectUrl?window.location.href=t.thankYouRedirectUrl:(n.completedPayment=!1,n.modal=null,n.initCheckoutModal())}})}checkoutFor(e,t,n){let r=this.config;return{v:1,amount:t,currency:n,site:{url:r.siteUrl,name:r.siteName,country:r.siteCountry},platform:r.platform??`pybara-js`,pluginVersion:r.pluginVersion,siteTerms:{version:r.recipientTosVersion,acceptedAt:r.recipientTosAcceptedAt},notify:{email:r.notifyEmail,enabled:r.notifyDonations},donation:{donor:{email:e.donorEmail,firstName:e.donorFirstName,lastName:e.donorLastName,company:e.donorCompany,country:e.donorCountry,address:{line1:e.donorAddressLine1,line2:e.donorAddressLine2,city:e.donorAddressCity,state:e.donorAddressState,postalCode:e.donorAddressPostalCode,country:e.donorAddressCountry},tos:{version:e.donorTosVersion,acceptedAt:e.donorTosAcceptedAt}},message:e.donorMessage,isAnonymous:e.donorIsAnonymous,wantsTaxReceipt:e.wantsTaxReceipt}}}preconnectWallet(e){let t=document.createElement(`link`);t.rel=`preconnect`,t.href=new URL(r[e]).origin,t.crossOrigin=`anonymous`,document.head.appendChild(t)}};function dd(e){let t=typeof e==`number`&&Number.isFinite(e)?String(e):e;return typeof t!=`string`||!cd.test(t)||!/[1-9]/.test(t)?null:t}function fd(e){let t=e.trim();if(!t)return null;let n;try{n=new URL(t.includes(`://`)?t:`https://${t}`)}catch{return null}return n.protocol!==`https:`&&n.protocol!==`http:`?null:n.origin+n.pathname.replace(/\/+$/,``)}function pd(e){if(!e.recipientPrincipal)throw new sd(`INVALID_CONFIG`,`Pybara.checkout: "recipientPrincipal" is required`);if(!e.siteUrl)throw new sd(`INVALID_CONFIG`,`Pybara.checkout: "siteUrl" is required`);let t=fd(e.siteUrl);if(!t)throw new sd(`INVALID_CONFIG`,`Pybara.checkout: "siteUrl" is not a valid http(s) URL: ${e.siteUrl}`);if(!e.siteName)throw new sd(`INVALID_CONFIG`,`Pybara.checkout: "siteName" is required`);if(e.currency!=null&&!/^[A-Z]{3}$/.test(e.currency))throw new sd(`INVALID_CONFIG`,`Pybara.checkout: "currency" must be an uppercase ISO 4217 code, e.g. "EUR" — got ${JSON.stringify(e.currency)}`);if(e.platform!=null&&!ld.test(e.platform))throw new sd(`INVALID_CONFIG`,`Pybara.checkout: "platform" must be a lowercase slug (a-z, 0-9, -), at most 64 characters`);return{...e,siteUrl:t,staging:e.staging??!1,debug:e.debug??!1}}function md(){let e=crypto.getRandomValues(new Uint8Array(16));return btoa(String.fromCharCode(...e))}function hd(e){return e instanceof Error?e:Error(String(e))}function gd(e){return new ud(e)}return e.Pybara={checkout:gd},e.PybaraCheckout=ud,e.PybaraError=sd,e.checkout=gd,e})({});
|