@pybara/donate-widget 0.0.0-stage → 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +143 -2
- package/dist/config.d.ts +32 -0
- package/dist/i18n/en.d.ts +38 -0
- package/dist/i18n/index.d.ts +10 -0
- package/dist/index.d.ts +14 -0
- package/dist/pybara-donate.iife.js +464 -0
- package/dist/pybara-donate.js +8640 -0
- package/dist/types.d.ts +119 -0
- package/dist/ui/amount-selector.d.ts +28 -0
- package/dist/ui/recurring-options.d.ts +33 -0
- package/dist/ui/styles.d.ts +8 -0
- package/dist/widget.d.ts +55 -0
- package/package.json +64 -4
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
var PybaraDonate=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function n(e,n,r){t(e,n),n.set(e,r)}function r(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}function i(e,t,n){return e.set(r(e,t),n),n}function a(e,t){return e.get(r(e,t))}function o(e,n){t(e,n),n.add(e)}var s,c,l,u,d,f,p,m,h,g,_,v,y,b,ee,te,x,ne,re,ie,ae,oe,se,ce,le,ue,de,fe,pe,me,he,ge,_e,ve,ye,be,xe,Se,S,Ce,we,Te,Ee,De,Oe,ke,Ae,je=Object.defineProperty,Me=(e,t)=>{let n={};for(var r in e)je(n,r,{get:e[r],enumerable:!0});return t||je(n,Symbol.toStringTag,{value:`Module`}),n},Ne={prod:`https://pybara.io`,staging:`https://staging.pybara.io`},Pe={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`}};(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`})(ke||(ke={})),function(e){e.Replied=`replied`,e.Rejected=`rejected`}(Ae||(Ae={}));var Fe=`abcdefghijklmnopqrstuvwxyz234567`,Ie=Object.create(null);for(let e=0;e<32;e++)Ie[Fe[e]]=e;Ie[0]=Ie.o,Ie[1]=Ie.i;var Le=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]),Re=typeof globalThis==`object`&&`crypto`in globalThis?globalThis.crypto:void 0;function ze(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function Be(e,...t){if(!ze(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 Ve(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 He(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ue(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function We(e,t){return e<<32-t|e>>>t}var Ge=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Ke=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function C(e){if(Be(e),Ge)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Ke[e[n]];return t}var qe=48,Je=57,Ye=65,Xe=70,Ze=97,Qe=102;function $e(e){return e>=qe&&e<=Je?e-qe:e>=Ye&&e<=Xe?e-(Ye-10):e>=Ze&&e<=Qe?e-(Ze-10):void 0}function et(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(Ge)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=$e(e.charCodeAt(i)),a=$e(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]=16*n+a}return r}function w(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function tt(e){return typeof e==`string`&&(e=w(e)),Be(e),e}function T(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];Be(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 nt=class{};function rt(e){let t=t=>e().update(tt(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function it(e=32){if(Re&&typeof Re.getRandomValues==`function`)return Re.getRandomValues(new Uint8Array(e));if(Re&&typeof Re.randomBytes==`function`)return Uint8Array.from(Re.randomBytes(e));throw Error(`crypto.getRandomValues must be defined`)}function at(e,t,n){return e&t^~e&n}function ot(e,t,n){return e&t^e&n^t&n}var st=class extends nt{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=Ue(this.buffer)}update(e){Ve(this),Be(e=tt(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=Ue(e);for(;r<=i-a;a+=r)this.process(t,a);continue}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){Ve(this),function(e,t){Be(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,He(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;(function(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)})(n,r-8,BigInt(8*this.length),i),this.process(n,0);let o=Ue(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||(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()}},ct=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lt=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),E=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ut=BigInt(2**32-1),dt=BigInt(32);function ft(e,t=!1){return t?{h:Number(e&ut),l:Number(e>>dt&ut)}:{h:0|Number(e>>dt&ut),l:0|Number(e&ut)}}var pt=(e,t,n)=>e>>>n,mt=(e,t,n)=>e<<32-n|t>>>n,ht=(e,t,n)=>e>>>n|t<<32-n,gt=(e,t,n)=>e<<32-n|t>>>n,_t=(e,t,n)=>e<<64-n|t>>>n-32,vt=(e,t,n)=>e>>>n-32|t<<64-n;function yt(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}var bt,xt,St=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Ct=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,wt=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Tt=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Et=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Dt=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,Ot=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]),kt=new Uint32Array(64),At=class extends st{constructor(e=32){super(64,e,8,!1),this.A=0|ct[0],this.B=0|ct[1],this.C=0|ct[2],this.D=0|ct[3],this.E=0|ct[4],this.F=0|ct[5],this.G=0|ct[6],this.H=0|ct[7]}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=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|a,this.G=0|o,this.H=0|s}process(e,t){for(let n=0;n<16;n++,t+=4)kt[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=kt[e-15],n=kt[e-2],r=We(t,7)^We(t,18)^t>>>3,i=We(n,17)^We(n,19)^n>>>10;kt[e]=i+kt[e-7]+r+kt[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=l+(We(o,6)^We(o,11)^We(o,25))+at(o,s,c)+Ot[e]+kt[e]|0,u=(We(n,2)^We(n,13)^We(n,22))+ot(n,r,i)|0;l=c,c=s,s=o,o=a+t|0,a=i,i=r,r=n,n=t+u|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(){He(kt)}destroy(){this.set(0,0,0,0,0,0,0,0),He(this.buffer)}},jt=class extends At{constructor(){super(28),this.A=0|lt[0],this.B=0|lt[1],this.C=0|lt[2],this.D=0|lt[3],this.E=0|lt[4],this.F=0|lt[5],this.G=0|lt[6],this.H=0|lt[7]}},Mt=function(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}=ft(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}(`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))),Nt=Mt[0],Pt=Mt[1],Ft=new Uint32Array(80),It=new Uint32Array(80),Lt=class extends st{constructor(e=64){super(128,e,16,!1),this.Ah=0|E[0],this.Al=0|E[1],this.Bh=0|E[2],this.Bl=0|E[3],this.Ch=0|E[4],this.Cl=0|E[5],this.Dh=0|E[6],this.Dl=0|E[7],this.Eh=0|E[8],this.El=0|E[9],this.Fh=0|E[10],this.Fl=0|E[11],this.Gh=0|E[12],this.Gl=0|E[13],this.Hh=0|E[14],this.Hl=0|E[15]}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=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|a,this.Dh=0|o,this.Dl=0|s,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|d,this.Gh=0|f,this.Gl=0|p,this.Hh=0|m,this.Hl=0|h}process(e,t){for(let n=0;n<16;n++,t+=4)Ft[n]=e.getUint32(t),It[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=0|Ft[e-15],n=0|It[e-15],r=ht(t,n,1)^ht(t,n,8)^pt(t,0,7),i=gt(t,n,1)^gt(t,n,8)^mt(t,n,7),a=0|Ft[e-2],o=0|It[e-2],s=ht(a,o,19)^_t(a,o,61)^pt(a,0,6),c=wt(i,gt(a,o,19)^vt(a,o,61)^mt(a,o,6),It[e-7],It[e-16]),l=Tt(c,r,s,Ft[e-7],Ft[e-16]);Ft[e]=0|l,It[e]=0|c}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=ht(u,d,14)^ht(u,d,18)^_t(u,d,41),v=gt(u,d,14)^gt(u,d,18)^vt(u,d,41),y=u&f^~u&m,b=Et(_,v,d&p^~d&h,Pt[e],It[e]),ee=Dt(b,g,t,y,Nt[e],Ft[e]),te=0|b,x=ht(n,r,28)^_t(n,r,34)^_t(n,r,39),ne=gt(n,r,28)^vt(n,r,34)^vt(n,r,39),re=n&i^n&o^i&o,ie=r&a^r&s^a&s;g=0|m,_=0|h,m=0|f,h=0|p,f=0|u,p=0|d,{h:u,l:d}=yt(0|c,0|l,0|ee,0|te),c=0|o,l=0|s,o=0|i,s=0|a,i=0|n,a=0|r;let ae=St(te,ne,ie);n=Ct(ae,ee,x,re),r=0|ae}({h:n,l:r}=yt(0|this.Ah,0|this.Al,0|n,0|r)),{h:i,l:a}=yt(0|this.Bh,0|this.Bl,0|i,0|a),{h:o,l:s}=yt(0|this.Ch,0|this.Cl,0|o,0|s),{h:c,l}=yt(0|this.Dh,0|this.Dl,0|c,0|l),{h:u,l:d}=yt(0|this.Eh,0|this.El,0|u,0|d),{h:f,l:p}=yt(0|this.Fh,0|this.Fl,0|f,0|p),{h:m,l:h}=yt(0|this.Gh,0|this.Gl,0|m,0|h),{h:g,l:_}=yt(0|this.Hh,0|this.Hl,0|g,0|_),this.set(n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}roundClean(){He(Ft,It)}destroy(){He(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Rt=rt(()=>new At),zt=rt(()=>new jt),Bt=rt(()=>new Lt),Vt=`__principal__`,D=class e{static anonymous(){return new this(new Uint8Array([4]))}static managementCanister(){return this.fromText(`aaaaa-aa`)}static selfAuthenticating(e){let t=zt(e);return new this(new Uint8Array([...t,2]))}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(et(e))}static fromText(e){let t=e;if(e.includes(`__principal__`)){let n=JSON.parse(e);`__principal__`in n&&(t=n[Vt])}let n=function(e){let t=0,n=0,r=new Uint8Array(4*e.length/3|0),i=0;function a(e){let a=Ie[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)}(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&&!0===t._isPrincipal&&`_arr`in t&&t._arr instanceof Uint8Array}constructor(e){this._arr=e,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===4}toUint8Array(){return this._arr}toHex(){return C(this._arr).toUpperCase()}toText(){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,function(e){let t=-1;for(let n=0;n<e.length;n++)t=Le[255&(e[n]^t)]^t>>>8;return(-1^t)>>>0}(this._arr));let t=new Uint8Array(e),n=function(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+=Fe[n>>3],t+=5),0)}for(let t=0;t<e.length;)t+=i(e[t]);return r+(t<0?Fe[n>>3]:``)}(new Uint8Array([...t,...this._arr])).match(/.{1,5}/g);if(!n)throw Error();return n.join(`-`)}toString(){return this.toText()}toJSON(){return{[Vt]: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`}};(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`})(bt||(bt={})),function(e){e.Normal=`normal`,e.Verbose=`verbose`}(xt||(xt={}));var Ht=new Set([`arg`,`certificate`,`nonce`]);function Ut(e){return(t,n)=>n instanceof Uint8Array?e===xt.Normal&&Ht.has(t)?`<${n.length} bytes, set ErrorCode.verbosity = ErrorVerbosity.Verbose to display>`:`hex(${n.length}):${C(n)}`:n}var O=(s=class e{constructor(e=!1){this.isCertified=e}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`\nRequest context:\n Request ID (hex): ${this.requestContext.requestId?C(this.requestContext.requestId):`undefined`}\n Sender pubkey (hex): ${C(this.requestContext.senderPubKey)}\n Sender signature (hex): ${C(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,Ut(e.verbosity),2)}`)),t}},s.verbosity=xt.Normal,s),Wt=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}`}},Gt=class extends Wt{static fromCode(e){return new this(e)}},Kt=class e extends Gt{constructor(t){super(t,bt.Trust),this.name=`TrustError`,Object.setPrototypeOf(this,e.prototype)}},k=class e extends Gt{constructor(t){super(t,bt.Protocol),this.name=`ProtocolError`,Object.setPrototypeOf(this,e.prototype)}},qt=class e extends Gt{constructor(t){super(t,bt.Reject),this.name=`RejectError`,Object.setPrototypeOf(this,e.prototype)}},Jt=class e extends Gt{constructor(t){super(t,bt.Transport),this.name=`TransportError`,Object.setPrototypeOf(this,e.prototype)}},Yt=class e extends Gt{constructor(t){super(t,bt.External),this.name=`ExternalError`,Object.setPrototypeOf(this,e.prototype)}},A=class e extends Gt{constructor(t){super(t,bt.Input),this.name=`InputError`,Object.setPrototypeOf(this,e.prototype)}},j=class e extends Gt{constructor(t){super(t,bt.Unknown),this.name=`UnknownError`,Object.setPrototypeOf(this,e.prototype)}},Xt=class e extends O{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+=`: ${Ln(this.error)}`),`Certificate verification error: "${e}"`}},Zt=class e extends O{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`}},Qt=class e extends O{constructor(){super(),this.name=`CertificateHasTooManyDelegationsErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Certificate has too many delegations`}},$t=class e extends O{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()}`}},en=class e extends O{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()}`}},tn=class e extends O{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}`}},nn=class e extends O{constructor(t){super(),this.message=t,this.name=`MalformedLookupFoundValueErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},rn=class e extends O{constructor(t){super(),this.message=t,this.name=`MissingLookupValueErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},an=class e extends O{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`}},on=class e extends O{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: ${C(this.expectedPrefix)}, but got ${C(this.actualPrefix)}`}},sn=class e extends O{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}`}},cn=class e extends O{constructor(t){super(),this.error=t,this.name=`DerDecodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},ln=class e extends O{constructor(t){super(),this.error=t,this.name=`DerEncodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},un=class e extends O{constructor(t,n){super(),this.error=t,this.input=n,this.name=`CborDecodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${Ln(this.error)}, input: ${C(this.input)}`}},dn=class e extends O{constructor(t,n){super(),this.error=t,this.value=n,this.name=`CborEncodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${Ln(this.error)}, input: ${this.value}`}},fn=class e extends O{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: ${C(this.requestId)}\n`),this.status&&(e+=` Request status: ${this.status}\n`),e}},pn=class e extends O{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: ${C(this.requestId)}\n`;return this.retryTimes!==void 0&&(e+=` Retried ${this.retryTimes} times.`),e}},mn=class e extends O{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: ${C(this.requestId)}\n Reject code: ${this.rejectCode}\n Reject text: ${this.rejectMessage}\n Error code: ${this.rejectErrorCode}\n`}},hn=class e extends O{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: ${C(this.requestId)}\n Reject code: ${this.rejectCode}\n Reject text: ${this.rejectMessage}\n Error code: ${this.rejectErrorCode}\n`}},gn=class e extends O{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: ${C(this.requestId)}\n Reject code: ${this.rejectCode}\n Reject text: ${this.rejectMessage}\n Error code: ${this.rejectErrorCode}\n`}},_n=class e extends O{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: ${C(this.requestId)}\n`}},vn=class e extends O{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.`}},yn=class e extends O{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}`}},bn=class e extends O{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.`}},xn=class e extends O{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.`}},Sn=class e extends O{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."}},Cn=class e extends O{constructor(){super(),this.name=`CreateHttpAgentErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to create agent from provided agent`}},wn=class e extends O{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.`}},Tn=class e extends O{constructor(t){super(),this.error=t,this.name=`MalformedSignatureErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},En=class e extends O{constructor(){super(),this.name=`MalformedPublicKeyErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Read state response contained a malformed public key`}},Dn=class e extends O{constructor(t){super(),this.nodeId=t,this.name=`QuerySignatureVerificationFailedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},On=class e extends O{constructor(t){super(),this.error=t,this.name=`UnexpectedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${Ln(this.error)}`}},kn=class e extends O{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): ${C(this.requestId)}\n Response: ${JSON.stringify(this.response,(e,t)=>t instanceof Uint8Array?`hex(${t.length}):${C(t)}`:t,2)}`}},An=class e extends O{constructor(t){super(),this.error=t,this.name=`HashTreeDecodeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},jn=class e extends O{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:\n Status: ${this.status} (${this.statusText})\n Headers: ${JSON.stringify(this.headers,Ut(O.verbosity))}\n`;return this.bodyText&&(e+=` Body: ${this.bodyText}\n`),e}},Mn=class e extends O{constructor(){super(),this.name=`HttpV4ApiNotSupportedErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`HTTP request failed: v4 API is not supported`}},Nn=class e extends O{constructor(t){super(),this.error=t,this.name=`HttpFetchErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${Ln(this.error)}`}},Pn=class e extends O{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.`}},Fn=class e extends O{constructor(t){super(),this.request=t,this.name=`InvalidReadStateRequestErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},In=class e extends O{constructor(t){super(),this.error=t,this.name=`ExpiryJsonDeserializeErrorCode`,Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function Ln(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e,Ut(O.verbosity))}catch{return String(e)}}var Rn=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 zn=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=Bn(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(1.2*(this._buffer.byteLength+e)|0),n=new Uint8Array(t.buffer,0,this._view.byteLength+e);n.set(this._view),this._buffer=t,this._view=n}};function Bn(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?Bn(e.buffer):new Uint8Array(e)}function Vn(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 Hn(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 function(e){let t=new TextEncoder().encode(e),n=0;for(let e of t)n=(223*n+e)%2**32;return n}(e)}function Un(e){let t=BigInt(e);if(e<=0)throw RangeError(`Input must be positive`);return t.toString(2).length-1}function Wn(e){let t=BigInt(e);if(e<0)throw RangeError(`Input must be non-negative`);return BigInt(1)<<t}function Gn(){throw Error(`unexpected end of buffer`)}function Kn(e,t){return e.byteLength<t&&Gn(),e.read(t)}function qn(e){let t=e.readUint8();return t===void 0&&Gn(),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:Un(e))+1,n=new zn(new Uint8Array(t),0);for(;;){let t=Number(e&BigInt(127));if((e/=BigInt(128))===BigInt(0)){n.write(new Uint8Array([t]));break}n.write(new Uint8Array([128|t]))}return n.buffer}function P(e){let t,n=BigInt(1),r=BigInt(0);do t=qn(e),r+=BigInt(127&t).valueOf()*n,n*=BigInt(128);while(t>=128);return r}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:Un(e))+1,r=new zn(new Uint8Array(n),0);for(;;){let n=i(e);if(e/=BigInt(128),t&&e===BigInt(0)&&64&n||!t&&e===BigInt(0)&&!(64&n)){r.write(new Uint8Array([n]));break}r.write(new Uint8Array([128|n]))}function i(e){let n=e%BigInt(128);return Number(t?BigInt(128)-n-BigInt(1):n)}return r.buffer}function Jn(e){let t=new Uint8Array(e.buffer),n=0;for(;n<t.byteLength;n++)if(t[n]<128){if(!(64&t[n]))return P(e);break}let r=new Uint8Array(Kn(e,n+1)),i=BigInt(0);for(let e=r.byteLength-1;e>=0;e--)i=i*BigInt(128)+BigInt(128-(127&r[e])-1);return-i-BigInt(1)}function Yn(e,t){e=BigInt(e);let n=new zn(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 Xn(e,t){if(t<=0||!Number.isInteger(t))throw Error(`Byte length must be a positive integer`);let n=BigInt(qn(e)),r=BigInt(1),i=0;for(;++i<t;)r*=BigInt(256),n+=r*BigInt(qn(e));return n}var I,Zn=Me({Bool:()=>Nr,BoolClass:()=>lr,CandidDecodeError:()=>Qn,ConstructType:()=>or,Empty:()=>Ar,EmptyClass:()=>sr,FixedIntClass:()=>gr,FixedNatClass:()=>_r,Float32:()=>Rr,Float64:()=>zr,FloatClass:()=>hr,Func:()=>ti,FuncClass:()=>Er,Int:()=>Ir,Int16:()=>Vr,Int32:()=>Hr,Int64:()=>Ur,Int8:()=>Br,IntClass:()=>pr,Nat:()=>Lr,Nat16:()=>Gr,Nat32:()=>Kr,Nat64:()=>qr,Nat8:()=>Wr,NatClass:()=>mr,Null:()=>Pr,NullClass:()=>ur,Opt:()=>Zr,OptClass:()=>yr,PrimitiveType:()=>ar,Principal:()=>Jr,PrincipalClass:()=>Tr,Rec:()=>ei,RecClass:()=>Cr,Record:()=>Qr,RecordClass:()=>br,Reserved:()=>jr,ReservedClass:()=>dr,Service:()=>ni,ServiceClass:()=>Dr,Text:()=>Fr,TextClass:()=>fr,Tuple:()=>Yr,TupleClass:()=>xr,Type:()=>ir,Unknown:()=>Mr,UnknownClass:()=>cr,Variant:()=>$r,VariantClass:()=>Sr,Vec:()=>Xr,VecClass:()=>vr,Visitor:()=>rr,decode:()=>kr,encode:()=>Or,resetSubtypeCache:()=>ai,subtype:()=>si}),Qn=class e extends Error{constructor(t){super(t),this.name=`CandidDecodeError`,Object.setPrototypeOf(this,e.prototype)}};(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||(I={}));var $n=`DIDL`,er=new TextEncoder().encode($n);function tr(e,t,n){return e.map((e,r)=>n(e,t[r]))}var L,nr=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)}},rr=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)}};(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||(L={}));var ir=class{display(){return this.name}valueToString(e){return R(e)}buildTypeTable(e){e.has(this)||this._buildTypeTableImpl(e)}},ar=class extends ir{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){}},or=class extends ir{checkType(e){if(e instanceof Cr){let t=e.getType();if(t===void 0)throw new Qn(`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)}},sr=class extends ar{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`}},cr=class extends ir{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,r=t.decodeValue(e,t);return Object(r)!==r&&(r=Object(r)),n=t instanceof Cr?()=>t.getType():()=>t,Object.defineProperty(r,"type",{value:n,writable:!0,enumerable:!1,configurable:!0}),r}_buildTypeTableImpl(){throw Error(`Unknown cannot be serialized`)}get name(){return`Unknown`}},lr=class extends ar{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),qn(e)){case 0:return!1;case 1:return!0;default:throw Error(`Boolean value out of range`)}}get name(){return`bool`}},ur=class extends ar{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`}},dr=class extends ar{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`}},fr=class extends ar{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=Kn(e,Number(n));return new TextDecoder(`utf8`,{fatal:!0}).decode(r)}get name(){return`text`}valueToString(e){return`"${e}"`}},pr=class extends ar{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),Jn(e)}get name(){return`int`}valueToString(e){return e.toString()}},mr=class extends ar{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()}},hr=class extends ar{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=function(e){if(!(e instanceof Uint8Array))throw Error(`Input must be a Uint8Array`);return new DataView(e.buffer,e.byteOffset,e.byteLength)}(Kn(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()}},gr=class extends ar{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=Wn(this._bits-1)*BigInt(-1),n=Wn(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 Yn(e,this._bits/8)}encodeType(){return F(-9-(Math.log2(this._bits)-3))}decodeValue(e,t){this.checkType(t);let n=function(e,t){if(t<=0||!Number.isInteger(t))throw Error(`Byte length must be a positive integer`);let n=Xn(e,t),r=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return n>=r&&(n-=r*BigInt(2)),n}(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(e){return e.toString()}},_r=class extends ar{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=Wn(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 function(e,t){if(BigInt(e)<BigInt(0))throw Error(`Cannot write negative values.`);return Yn(e,t)}(e,this._bits/8)}encodeType(){return F(-5-(Math.log2(this._bits)-3))}decodeValue(e,t){this.checkType(t);let n=Xn(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(e){return e.toString()}},vr=class e extends or{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 _r&&e._bits===8&&(this._blobOptimization=!0)}accept(e,t){return e.visitVec(this,this._type,t)}covariant(e){let t=this._type instanceof _r||this._type instanceof gr?this._type._bits:0;if(ArrayBuffer.isView(e)&&t==8*e.BYTES_PER_ELEMENT||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(2*e.length));for(let t=0;t<e.length;t++)e instanceof Int16Array?n.setInt16(2*t,e[t],!0):n.setUint16(2*t,e[t],!0);return M(t,new Uint8Array(n.buffer))}if(e instanceof Int32Array||e instanceof Uint32Array){let n=new DataView(new ArrayBuffer(4*e.length));for(let t=0;t<e.length;t++)e instanceof Int32Array?n.setInt32(4*t,e[t],!0):n.setUint32(4*t,e[t],!0);return M(t,new Uint8Array(n.buffer))}if(e instanceof BigInt64Array||e instanceof BigUint64Array){let n=new DataView(new ArrayBuffer(8*e.length));for(let t=0;t<e.length;t++)e instanceof BigInt64Array?n.setBigInt64(8*t,e[t],!0):n.setBigUint64(8*t,e[t],!0);return M(t,new Uint8Array(n.buffer))}return M(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}let n=new zn(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 Qn(`Expected type '${this.display()}', but received non-vector type '${r.display()}'`);let i=Number(P(t));if(this._type instanceof _r){if(this._type._bits==8)return new Uint8Array(t.read(i));if(this._type._bits==16){let e=t.read(2*i);return new Uint16Array(e.buffer,e.byteOffset,i)}if(this._type._bits==32){let e=t.read(4*i);return new Uint32Array(e.buffer,e.byteOffset,i)}if(this._type._bits==64)return new BigUint64Array(t.read(8*i).buffer)}if(this._type instanceof gr){if(this._type._bits==8)return new Int8Array(t.read(i));if(this._type._bits==16){let e=t.read(2*i),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Int16Array(i);for(let e=0;e<i;e++)r[e]=n.getInt16(2*e,!0);return r}if(this._type._bits==32){let e=t.read(4*i),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Int32Array(i);for(let e=0;e<i;e++)r[e]=n.getInt32(4*e,!0);return r}if(this._type._bits==64){let e=t.read(8*i),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new BigInt64Array(i);for(let e=0;e<i;e++)r[e]=n.getBigInt64(8*e,!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(`; `)}}`}},yr=class e extends or{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 ur||n instanceof dr)return[];let r=n;if(n instanceof Cr){let e=n.getType();if(e===void 0)throw new Qn(`Type mismatch: cannot decode from uninitialized recursive type`);r=e}if(r instanceof e)switch(qn(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 Qn(`Invalid option value: expected 0 (None) or 1 (Some) for type '${this.display()}'`)}else{if(this._type instanceof ur||this._type instanceof e||this._type instanceof dr)return r.decodeValue(t,r),[];{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])}`}},br=class e extends or{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)=>Hn(e[0])-Hn(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(...tr(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(Hn(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 Qn(`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=Hn(this._fields[a][0]),u=Hn(e);if(l===u)i[s]=c.decodeValue(t,n),a++,o++;else if(u>l){if(!(c instanceof yr||c instanceof dr))throw new Qn(`Cannot find required field '${s}' in record, expected fields: [${this._fields.map(([e])=>e).join(`, `)}], received fields: [${r._fields.map(([e])=>e).join(`, `)}]`);i[s]=[],a++}else n.decodeValue(t,n),o++}for(let[e,t]of this._fields.slice(a)){if(!(t instanceof yr||t instanceof dr))throw new Qn(`Cannot find required field '${e}' in record, expected fields: [${this._fields.map(([e])=>e).join(`, `)}], received fields: [${r._fields.map(([e])=>e).join(`, `)}]`);i[e]=[]}return i}get fieldsAsObject(){let e={};for(let[t,n]of this._fields)e[Hn(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 {${tr(this._fields,t,([e,t],n)=>`${e}=${t.valueToString(n)}`).join(`; `)}}`}},xr=class e extends br{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(...tr(this._components,e,(e,t)=>e.encodeValue(t)))}decodeValue(t,n){let r=this.checkType(n);if(!(r instanceof e))throw new Qn(`Expected type '${this.display()}', but received non-tuple type '${r.display()}'`);if(r._components.length<this._components.length)throw new Qn(`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 {${tr(this._components,e,(e,t)=>e.valueToString(t)).join(`; `)}}`}},Sr=class e extends or{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)=>Hn(e[0])-Hn(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(Hn(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 Qn(`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(Hn(a)===Hn(e)){let r=n.decodeValue(t,o);return{[e]:r}}throw new Qn(`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[Hn(t)]=n;return e}},Cr=(Oe=Symbol.hasInstance,c=class e extends or{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return L.RecClass}static[Oe](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)}},c._counter=0,c);function wr(e){if(qn(e)!==1)throw Error(`Cannot decode principal`);let t=Number(P(e));return D.fromUint8Array(new Uint8Array(Kn(e,t)))}var Tr=class extends ar{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),wr(e)}get name(){return`principal`}valueToString(e){return`${this.name} "${e.toText()}"`}},Er=class extends or{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 Cr?t.getType()??t:t;if(!si(n,this))throw Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(qn(e)!==1)throw Error(`Cannot decode function reference`);let r=wr(e),i=Kn(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`)}},Dr=class extends or{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 Cr?t.getType()??t:t;if(!si(n,this))throw Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return wr(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>400?`${t.substring(0,397)}...`:t}function Or(e,t){if(t.length<e.length)throw Error(`Wrong number of message arguments`);let n=new nr;return e.forEach(e=>e.buildTypeTable(n)),M(er,n.encode(),N(t.length),M(...e.map(e=>e.encodeType(n))),M(...tr(e,t,(e,t)=>{try{e.covariant(t)}catch(e){throw Error(`${e.message}\n\n`)}return e.encodeValue(t)})))}function kr(e,t){let n=new zn(t);if(t.byteLength<4)throw Error(`Message length smaller than magic number`);let r=Kn(n,4),i=new TextDecoder().decode(r);if(i!==$n)throw Error(`Wrong magic number: ${JSON.stringify(i)}`);let[a,o]=function(e){let t=[],n=Number(P(e));for(let r=0;r<n;r++){let n=Number(Jn(e));switch(n){case I.Opt:case I.Vector:{let r=Number(Jn(e));t.push([n,r]);break}case I.Record:case I.Variant:{let r=[],i,a=Number(P(e));for(;a--;){let t=Number(P(e));if(t>=2**32)throw Error(`field id out of 32-bit range`);if(typeof i==`number`&&i>=t)throw Error(`field id collision or not sorted`);i=t;let n=Number(Jn(e));r.push([t,n])}t.push([n,r]);break}case I.Func:{let r=[],i=Number(P(e));for(;i--;)r.push(Number(Jn(e)));let a=[],o=Number(P(e));for(;o--;)a.push(Number(Jn(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(Kn(e,t)),r=Jn(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(Jn(e)));return[t,r]}(n);if(o.length<e.length)throw Error(`Wrong number of return values`);let s=a.map(e=>ei());function c(e){if(e<-24)throw Error(`future value not supported`);if(e<0)switch(e){case-1:return Pr;case-2:return Nr;case-3:return Lr;case-4:return Ir;case-5:return Wr;case-6:return Gr;case-7:return Kr;case-8:return qr;case-9:return Br;case-10:return Vr;case-11:return Hr;case-12:return Ur;case-13:return Rr;case-14:return zr;case-15:return Fr;case-16:return jr;case-17:return Ar;case-24:return Jr;default:throw Error(`Illegal op_code: ${e}`)}if(e>=a.length)throw Error(`type index out of range`);return s[e]}function l(e){switch(e[0]){case I.Vector:return Xr(c(e[1]));case I.Opt:return Zr(c(e[1]));case I.Record:{let t={};for(let[n,r]of e[1])t[`_${n}_`]=c(r);let n=Qr(t),r=n.tryAsTuple();return Array.isArray(r)?Yr(...r):n}case I.Variant:{let t={};for(let[n,r]of e[1])t[`_${n}_`]=c(r);return $r(t)}case I.Func:{let[t,n,r]=e[1];return ti(t.map(e=>c(e)),n.map(e=>c(e)),r)}case I.Service:{let t={},n=e[1];for(let[e,r]of n){let n=c(r);if(n instanceof Cr&&(n=n.getType()),!(n instanceof Er))throw Error(`Illegal service definition: services can only contain functions`);t[e]=n}return ni(t)}default:throw Error(`Illegal op_code: ${e[0]}`)}}a.forEach((e,t)=>{if(e[0]===I.Func){let n=l(e);s[t].fill(n)}}),a.forEach((e,t)=>{if(e[0]!==I.Func){let n=l(e);s[t].fill(n)}}),ai();let u=o.map(e=>c(e));try{let t=e.map((e,t)=>e.decodeValue(n,u[t]));for(let t=e.length;t<u.length;t++)u[t].decodeValue(n,u[t]);if(n.byteLength>0)throw Error(`decode: Left-over bytes`);return t}finally{ai()}}var Ar=new sr,jr=new dr,Mr=new cr,Nr=new lr,Pr=new ur,Fr=new fr,Ir=new pr,Lr=new mr,Rr=new hr(32),zr=new hr(64),Br=new gr(8),Vr=new gr(16),Hr=new gr(32),Ur=new gr(64),Wr=new _r(8),Gr=new _r(16),Kr=new _r(32),qr=new _r(64),Jr=new Tr;function Yr(...e){return new xr(e)}function Xr(e){return new vr(e)}function Zr(e){return new yr(e)}function Qr(e){return new br(e)}function $r(e){return new Sr(e)}function ei(){return new Cr}function ti(e,t,n=[]){return new Er(e,t,n)}function ni(e){return new Dr(e)}var ri=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)}},ii=new ri;function ai(){ii=new ri}function oi(e){return e instanceof yr||e instanceof ur||e instanceof dr}function si(e,t){let n=ci(ii.copy(),e,t);return n?ii.add(e,t):ii.addNegative(e,t),n}function ci(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 dr||t instanceof sr||t instanceof mr&&n instanceof pr)return!0;if(t instanceof vr&&n instanceof vr)return ci(e,t._type,n._type);if(n instanceof yr)return!0;if(t instanceof br&&n instanceof br){let r=t.fieldsAsObject;for(let[t,i]of n._fields){let n=r[Hn(t)];if(n){if(!ci(e,n,i))return!1}else if(!oi(i))return!1}return!0}if(t instanceof Er&&n instanceof Er){if(!function(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}(t,n))return!1;for(let r=0;r<t.argTypes.length;r++){let i=t.argTypes[r];if(r<n.argTypes.length){if(!ci(e,n.argTypes[r],i))return!1}else if(!oi(i))return!1}for(let r=0;r<n.retTypes.length;r++){let i=n.retTypes[r];if(r<t.retTypes.length){if(!ci(e,t.retTypes[r],i))return!1}else if(!oi(i))return!1}return!0}if(t instanceof Sr&&n instanceof Sr){let r=n.alternativesAsObject;for(let[n,i]of t._fields){let t=r[Hn(n)];if(!t||!ci(e,i,t))return!1}return!0}if(t instanceof Dr&&n instanceof Dr){let r=t.fieldsAsObject();for(let[t,i]of n._fields){let n=r[t];if(!n||!ci(e,n,i))return!1}return!0}return t instanceof Cr?ci(e,t.getType(),n):n instanceof Cr&&ci(e,t,n.getType())}function li(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?li(e.buffer):new Uint8Array(e)}function ui(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 di(e){if(typeof e==`string`)return fi(e);if(typeof e==`number`)return Rt(N(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return Rt(li(e));if(Array.isArray(e))return Rt(T(...e.map(di)));if(e&&typeof e==`object`&&e._isPrincipal)return Rt(e.toUint8Array());if(typeof e==`object`&&e&&typeof e.toHash==`function`)return di(e.toHash());if(typeof e==`object`)return mi(e);if(typeof e==`bigint`)return Rt(N(e));throw A.fromCode(new yn(e))}var fi=e=>Rt(new TextEncoder().encode(e));function pi(e){return mi(e)}function mi(e){return Rt(T(...Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>[fi(e),di(t)]).sort(([e],[t])=>Vn(e,t)).map(e=>T(...e))))}var hi=new TextEncoder().encode(`\ric-state-root`),gi=(new TextEncoder().encode(`
|
|
2
|
+
ic-request`),new TextEncoder().encode(`\vic-response`)),_i=(new TextEncoder().encode(`ic-request-auth-delegation`),class{getPrincipal(){return D.anonymous()}async transformRequest(e){return{...e,body:{content:e.body}}}}),vi=class extends Error{constructor(e){super(e),this.name=`DecodingError`}},yi=55799,bi=Symbol(`CBOR_STOP_CODE`),xi=(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))(xi||{}),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||{}),Si=BigInt(`0xffffffffffffffff`),Ci=(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))(Ci||{}),wi=!1,Ti=new TextDecoder,Ei,Di=new Uint8Array,Oi=0;function ki(e){let[t,n]=Ai();switch(t){case z.UnsignedInteger:return ji(n);case z.NegativeInteger:return function(e){let t=ji(e);return typeof t==`number`?-1-t:-1n-t}(n);case z.ByteString:return Mi(n);case z.TextString:return Ni(n);case z.Array:return function(e,t){let n=ji(e);if(n===1/0){let e=[],n=ki(t);for(;n!==bi;)e.push(t?.(n)??n),n=ki(t);return e}let r=Array(n);for(let e=0;e<n;e++){let n=ki(t);r[e]=t?.(n)??n}return r}(n,e);case z.Map:return function(e,t){let n=ji(e),r={};if(n===1/0){let[e,n]=Ai();for(;e!==z.Simple&&n!==xi.Break;){let i=Ni(n),a=ki(t);r[i]=t?.(a,i)??a,[e,n]=Ai()}return r}for(let e=0;e<n;e++){let[e,n]=Ai();if(e!==z.TextString)throw new vi(`Map keys must be text strings`);let i=Ni(n),a=ki(t);r[i]=t?.(a,i)??a}return r}(n,e);case z.Tag:return function(e,t){let n=ji(e);if(n===yi)return ki(t);throw new vi(`Unsupported tag: ${n}.`)}(n,e);case z.Simple:return function(e){switch(e){case xi.False:return!1;case xi.True:return!0;case xi.Null:return null;case xi.Undefined:return;case xi.Break:return bi}throw new vi(`Unrecognized simple type: ${e.toString(2)}`)}(n)}throw new vi(`Unsupported major type: ${t}`)}function Ai(){let e=Di.at(Oi);if(function(e){return e==null}(e))throw new vi(`Provided CBOR data is empty`);let t=function(e){return(224&e)>>5}(e),n=function(e){return 31&e}(e);return Oi++,[t,n]}function ji(e){if(e<=Ci.Value)return e;switch(Ei=new DataView(Di.buffer,Di.byteOffset+Oi),e){case Ci.OneByte:return Oi++,Ei.getUint8(0);case Ci.TwoBytes:return Oi+=2,Ei.getUint16(0,wi);case Ci.FourBytes:return Oi+=4,Ei.getUint32(0,wi);case Ci.EightBytes:return Oi+=8,Ei.getBigUint64(0,wi);case Ci.Indefinite:return 1/0;default:throw new vi(`Unsupported integer info: ${e.toString(2)}`)}}function Mi(e){let t=ji(e);if(t>2**53-1)throw new vi(`Byte length is too large`);let n=Number(t);return Oi+=n,Di.slice(Oi-n,Oi)}function Ni(e){let t=Mi(e);return Ti.decode(t)}var Pi=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},Fi=new TextEncoder;function Ii(e){return e<<5}var Li=new Uint8Array(2048),Ri=new DataView(Li.buffer),B=0,zi=[];function Bi(e,t){return B=0,function(e,t,n){Ui(z.Tag,e),Hi(t,n)}(yi,t?.(e)??e,t),Li.slice(0,B)}function Vi(e){let t=2*Li.length;for(;t<e;)t*=2;Li=function(e,t){let n=new Uint8Array(t);return n.set(e),n}(Li,t),Ri=new DataView(Li.buffer)}function Hi(e,t){if(!1!==e&&!0!==e&&e!=null){if(typeof e!=`number`&&typeof e!=`bigint`){if(typeof e!=`string`){if(e instanceof Uint8Array)qi(e);else if(e instanceof ArrayBuffer)qi(new Uint8Array(e));else if(Array.isArray(e))(function(e,t){Ui(z.Array,e.length),e.forEach((e,n)=>{Hi(t?.(e,n.toString())??e,t)})})(e,t);else{if(typeof e!=`object`)throw new Pi(`Unsupported type: `+typeof e);(function(e,t){zi=Object.entries(e),Ui(z.Map,zi.length),zi.forEach(([e,n])=>{Ki(e),Hi(t?.(n,e)??n,t)})})(e,t)}}else Ki(e)}else(function(e){e>=0?function(e){Gi(z.UnsignedInteger,e)}(e):function(e){Gi(z.NegativeInteger,typeof e==`bigint`?-1n-e:-1-e)}(e)})(e)}else(function(e){Ui(z.Simple,function(e){if(!1===e)return xi.False;if(!0===e)return xi.True;if(e===null)return xi.Null;if(e===void 0)return xi.Undefined;throw new Pi(`Unrecognized simple value: ${e.toString()}`)}(e))})(e)}function Ui(e,t){if(B>Li.length-100&&Vi(B+100),!(t<=23)){if(t<=255)return Ri.setUint8(B++,Ii(e)|Ci.OneByte),Ri.setUint8(B,Number(t)),void(B+=1);if(t<=65535)return Ri.setUint8(B++,Ii(e)|Ci.TwoBytes),Ri.setUint16(B,Number(t),wi),void(B+=2);if(t<=4294967295)return Ri.setUint8(B++,Ii(e)|Ci.FourBytes),Ri.setUint32(B,Number(t),wi),void(B+=4);if(t<=Si)return Ri.setUint8(B++,Ii(e)|Ci.EightBytes),Ri.setBigUint64(B,BigInt(t),wi),void(B+=8);throw new Pi(`Value too large to encode: ${t}`)}Ri.setUint8(B++,Ii(e)|Number(t))}function Wi(e,t){Ui(e,t.length),B>Li.length-t.length&&Vi(B+t.length),Li.set(t,B),B+=t.length}function Gi(e,t){Ui(e,t)}function Ki(e){Wi(z.TextString,Fi.encode(e))}function qi(e){Wi(z.ByteString,e)}var Ji=`__expiry__`,Yi=BigInt(1e3),Xi=BigInt(1e6),Zi=BigInt(60)*Yi,Qi=BigInt(1)*Zi,$i=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=i/Zi*Zi,o;return o=a>=r+Qi?a:function(e){return e/Yi*Yi}(i),new e(o*Xi)}toBigInt(){return this.__expiry__}toHash(){return N(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[Ji]:this.toString()}}static fromJSON(t){let n=JSON.parse(t);if(n.__expiry__)try{let t=BigInt(n[Ji]);return new e(t)}catch(e){throw new A(new In(`Not a valid BigInt: ${e}`))}throw new A(new In(`The input does not contain the key ${Ji}`))}static isExpiry(t){return t instanceof e||typeof t==`object`&&!!t&&`_isExpiry`in t&&!0===t._isExpiry&&`__expiry__`in t&&typeof t.__expiry__==`bigint`}};function ea(e){try{return Bi(e,e=>D.isPrincipal(e)?e.toUint8Array():$i.isExpiry(e)?e.toBigInt():function(e){return typeof e==`object`&&!!e&&`toCborValue`in e}(e)?e.toCborValue():e)}catch(t){throw A.fromCode(new dn(t,e))}}function ta(e){try{return function(e,t){Di=e,Oi=0;let n=ki(t);return t?.(n)??n}(e)}catch(t){throw A.fromCode(new un(t,e))}}var na,ra,ia,aa,oa=()=>{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(4294967295*Math.random())};function sa(){let e=new ArrayBuffer(16),t=new DataView(e),n=oa(),r=oa(),i=oa(),a=oa();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 ca(e=sa){return async t=>{let n=t.request.headers;t.request.headers=n,t.endpoint===na.Call&&(t.body.nonce=e())}}function la(e){let t=[];return e.forEach((e,n)=>{t.push([n,e])}),t}(function(e){e.Query=`read`,e.ReadState=`read_state`,e.Call=`call`})(na||(na={})),function(e){e.Call=`call`}(ra||(ra={})),function(e){e.Query=`query`,e.ReadState=`read_state`}(ia||(ia={})),function(e){e.Received=`received`,e.Processing=`processing`,e.Replied=`replied`,e.Rejected=`rejected`,e.Unknown=`unknown`,e.Done=`done`}(aa||(aa={}));var ua=BigInt(0),da=BigInt(1);function fa(e,t=``){if(typeof e!=`boolean`)throw Error((t&&`"${t}"`)+`expected boolean, got type=`+typeof e);return e}function pa(e,t,n=``){let r=ze(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t)throw Error((n&&`"${n}" `)+`expected Uint8Array`+(a?` of length ${t}`:``)+`, got `+(r?`length=${i}`:`type=`+typeof e));return e}function ma(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?ua:BigInt(`0x`+e)}function ha(e){return ma(C(e))}function ga(e){return Be(e),ma(C(Uint8Array.from(e).reverse()))}function V(e,t){return et(e.toString(16).padStart(2*t,`0`))}function _a(e,t){return V(e,t).reverse()}function H(e,t,n){let r;if(typeof t==`string`)try{r=et(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else{if(!ze(t))throw Error(e+` must be hex string or Uint8Array`);r=Uint8Array.from(t)}let i=r.length;if(typeof n==`number`&&i!==n)throw Error(e+` of length `+n+` expected, got `+i);return r}function va(e){return Uint8Array.from(e)}var ya=e=>typeof e==`bigint`&&ua<=e;function ba(e,t,n){return ya(e)&&ya(t)&&ya(n)&&t<=e&&e<n}function xa(e,t,n,r){if(!ba(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function Sa(e){let t=0;for(;e>ua;e>>=da,t+=1);return t}function Ca(e,t){return e>>BigInt(t)&da}var wa=e=>(da<<BigInt(e))-da;function Ta(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 Ea=()=>{throw Error(`not implemented`)};function Da(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),Oa=BigInt(2),ka=BigInt(3),Aa=BigInt(4),ja=BigInt(5),Ma=BigInt(7),Na=BigInt(8),Pa=BigInt(9),Fa=BigInt(16);function G(e,t){let n=e%t;return n>=U?n:t+n}function Ia(e,t,n){let r=e;for(;t-->U;)r*=r,r%=n;return r}function La(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 Ra(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function za(e,t){let n=(e.ORDER+W)/Aa,r=e.pow(t,n);return Ra(e,r,t),r}function Ba(e,t){let n=(e.ORDER-ja)/Na,r=e.mul(t,Oa),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,Oa),i),s=e.mul(a,e.sub(o,e.ONE));return Ra(e,s,t),s}function Va(e){if(e<ka)throw Error(`sqrt is not defined for small field`);let t=e-W,n=0;for(;t%Oa===U;)t/=Oa,n++;let r=Oa,i=Xa(e);for(;Ja(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+W)/Oa;return function(e,r){if(e.is0(r))return r;if(Ja(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 Ha(e){return e%Aa===ka?za:e%Na===ja?Ba:e%Fa===Pa?function(e){let t=Xa(e),n=Va(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+Ma)/Fa;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 Ra(e,p,t),p}}(e):Va(e)}var Ua=(e,t)=>(G(e,t)&W)===W,Wa=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function Ga(e){return Ta(e,Wa.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function Ka(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 qa(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 Ja(e,t){let n=(e.ORDER-W)/Oa,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 Ya(e,t){t!==void 0&&function(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Xa(e,t,n=!1,r={}){if(e<=U)throw Error(`invalid field: expected ORDER > 0, got `+e);let i,a,o,s=!1;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`&&(s=e.modFromBytes),o=e.allowedLengths}else typeof t==`number`&&(i=t),r.sqrt&&(a=r.sqrt);let{nBitLength:c,nByteLength:l}=Ya(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:wa(c),ZERO:U,ONE:W,allowedLengths:o,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)=>Ka(d,e,t),div:(t,n)=>G(t*La(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>La(t,e),sqrt:a||(t=>(u||(u=Ha(e)),u(d,t))),toBytes:e=>n?_a(e,l):V(e,l),fromBytes:(t,r=!0)=>{if(o){if(!o.includes(t.length)||t.length>l)throw Error(`Field.fromBytes: expected `+o+` 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?ga(t):ha(t);if(s&&(i=G(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>qa(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function Za(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function Qa(e){let t=Za(e);return t+Math.ceil(t/2)}var $a=BigInt(0),eo=BigInt(1);function to(e,t){let n=t.negate();return e?n:t}function no(e,t){let n=qa(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function ro(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function io(e,t){ro(e,t);let n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:wa(e),maxNumber:n,shiftBy:BigInt(e)}}function ao(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+=eo);let l=t*r;return{nextN:c,offset:l+Math.abs(s)-1,isZero:s===0,isNeg:s<0,isNegF:t%2!=0,offsetF:l}}var oo=new WeakMap,so=new WeakMap;function co(e){return so.get(e)||1}function lo(e){if(e!==$a)throw Error(`invalid wNAF`)}var uo=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>$a;)t&eo&&(n=n.add(r)),r=r.double(),t>>=eo;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=io(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=io(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=ao(n,e,a);n=o,c?i=i.add(to(u,t[d])):r=r.add(to(l,t[s]))}return lo(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=io(e,this.bits);for(let e=0;e<i.windows&&n!==$a;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=ao(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return lo(n),r}getPrecomputes(e,t,n){let r=oo.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),oo.set(t,r))),r}cached(e,t,n){let r=co(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=co(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){ro(t,this.bits),so.set(e,t),oo.delete(e)}hasCache(e){return co(e)!==1}};function fo(e,t,n,r){(function(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)})})(n,e),function(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)})}(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=Sa(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=wa(c),u=Array(Number(l)+1).fill(o),d=o;for(let e=Math.floor((t.BITS-1)/c)*c;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(d=d.add(t),e!==0)for(let e=0;e<c;e++)d=d.double()}return d}function po(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return Ga(t),t}return Xa(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>$a))throw Error(`CURVE.${e} must be positive bigint`)}let i=po(t.p,n.Fp,r),a=po(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{CURVE:t=Object.freeze(Object.assign({},t)),Fp:i,Fn:a}}var ho=ha;function go(e,t){if(vo(e),vo(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]=255&e,e>>>=8;return new Uint8Array(n)}function _o(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 vo(e){if(!Number.isSafeInteger(e))throw Error(`number expected`)}function yo(e){if(!ze(e)&&typeof e!=`string`)throw Error(`DST must be Uint8Array or string`);return typeof e==`string`?w(e):e}function bo(e,t,n){Ta(n,{p:`bigint`,m:`number`,k:`number`,hash:`function`});let{p:r,k:i,m:a,hash:o,expand:s,DST:c}=n;if(typeof(l=n.hash)!=`function`||!Number.isSafeInteger(l.outputLen))throw Error(`expected valid hash`);var l;Be(e),vo(t);let u=r.toString(2).length,d=Math.ceil((u+i)/8),f=t*a*d,p;if(s===`xmd`)p=function(e,t,n,r){Be(e),vo(n),(t=yo(t)).length>255&&(t=r(T(w(`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=T(t,go(t.length,1)),c=go(0,a),l=go(n,2),u=Array(o),d=r(T(c,e,l,go(0,1),s));u[0]=r(T(d,go(1,1),s));for(let e=1;e<=o;e++){let t=[_o(d,u[e-1]),go(e+1,1),s];u[e]=r(T(...t))}return T(...u).slice(0,n)}(e,c,f,o);else if(s===`xof`)p=function(e,t,n,r,i){if(Be(e),vo(n),(t=yo(t)).length>255){let e=Math.ceil(2*r/8);t=i.create({dkLen:e}).update(w(`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(go(n,2)).update(t).update(go(t.length,1)).digest()}(e,c,f,i,o);else{if(s!==`_internal_pass`)throw Error(`expand must be "xmd" or "xof"`);p=e}let m=Array(t);for(let e=0;e<t;e++){let t=Array(a);for(let n=0;n<a;n++){let i=d*(n+e*a),o=p.subarray(i,i+d);t[n]=G(ho(o),r)}m[e]=t}return m}function xo(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]=qa(e,[a,s],!0);return t=e.mul(i,c),r=e.mul(r,e.mul(o,l)),{x:t,y:r}}}var So=w(`HashToScalar-`);function Co(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:So},r))[0][0]}}}var wo=(e,t)=>(e+(e>=0?t:-t)/Eo)/t,To=BigInt(0),K=BigInt(1),Eo=BigInt(2),Do=BigInt(3),Oo=BigInt(4);function ko(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 Ao(e,t={}){let n=mo(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;Ta(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=function(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}(r,i);function u(){if(!r.isOdd)throw Error(`compression is not supported: Field does not have .isOdd()`)}let d=t.toBytes||function(e,t,n){let{x:i,y:a}=t.toAffine(),o=r.toBytes(i);return fa(n,`isCompressed`),n?(u(),T(function(e){return Uint8Array.of(e?2:3)}(!r.isOdd(a)),o)):T(Uint8Array.of(4),o,r.toBytes(a))},f=t.fromBytes||function(e){pa(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){if(i===n&&a===4){let e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.subarray(e,2*e));if(!m(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 e=r.fromBytes(o);if(!r.isValid(e))throw Error(`bad point: is not on curve, wrong x`);let t=p(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)}return u(),!(1&~a)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function p(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 m(e,t){let n=r.sqr(t),i=p(e);return r.eql(n,i)}if(!m(a.Gx,a.Gy))throw Error(`bad curve params: generator point`);let h=r.mul(r.pow(a.a,Do),Oo),g=r.mul(r.sqr(a.b),BigInt(27));if(r.is0(r.add(h,g)))throw Error(`bad curve params: a or b`);function _(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw Error(`bad point coordinate ${e}`);return t}function v(e){if(!(e instanceof x))throw Error(`ProjectivePoint expected`)}function y(e){if(!c||!c.basises)throw Error(`no endo`);return function(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<To,f=u<To;d&&(l=-l),f&&(u=-u);let p=wa(Math.ceil(Sa(n)/2))+K;if(l<To||l>=p||u<To||u>=p)throw Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}(e,c.basises,i.ORDER)}let b=Da((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??(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}}),ee=Da(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(!m(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 x(r.mul(n.X,e),n.Y,n.Z),t=to(i,t),n=to(a,n),t.add(n)}class x{constructor(e,t,n){this.X=_(`x`,e),this.Y=_(`y`,t,!0),this.Z=_(`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 x)throw Error(`projective point not allowed`);return r.is0(t)&&r.is0(n)?x.ZERO:new x(t,n,r.ONE)}static fromBytes(e){let t=x.fromAffine(f(pa(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return x.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(Do),this}assertValidity(){ee(this)}hasEvenY(){let{y:e}=this.toAffine();if(!r.isOdd)throw Error(`Field doesn't support isOdd`);return!r.isOdd(e)}equals(e){v(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 x(this.X,r.neg(this.Y),this.Z)}double(){let{a:e,b:t}=a,n=r.mul(t,Do),{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 x(c,l,u)}add(e){v(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,Do),m=r.mul(t,o),h=r.mul(n,s),g=r.mul(i,c),_=r.add(t,n),y=r.add(o,s);_=r.mul(_,y),y=r.add(m,h),_=r.sub(_,y),y=r.add(t,i);let b=r.add(o,c);return y=r.mul(y,b),b=r.add(m,g),y=r.sub(y,b),b=r.add(n,i),l=r.add(s,c),b=r.mul(b,l),l=r.add(h,g),b=r.sub(b,l),d=r.mul(f,y),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),y=r.mul(p,y),h=r.add(h,g),g=r.sub(m,g),g=r.mul(f,g),y=r.add(y,g),m=r.mul(h,y),u=r.add(u,m),m=r.mul(b,y),l=r.mul(_,l),l=r.sub(l,m),m=r.mul(_,h),d=r.mul(b,d),d=r.add(d,m),new x(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(x.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=>no(x,e));if(n){let{k1neg:t,k1:i,k2neg:s,k2:c}=y(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 no(x,[r,a])[0]}multiplyUnsafe(e){let{endo:n}=t,r=this;if(!i.isValid(e))throw Error(`invalid scalar: out of range`);if(e===To||r.is0())return x.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}=y(e),{p1:s,p2:c}=function(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>$a||r>$a;)n&eo&&(a=a.add(i)),r&eo&&(o=o.add(i)),i=i.double(),n>>=eo,r>>=eo;return{p1:a,p2:o}}(x,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 b(this,e)}isTorsionFree(){let{isTorsionFree:e}=t;return o===K||(e?e(x,this):re.unsafe(this,s).is0())}clearCofactor(){let{clearCofactor:e}=t;return o===K?this:e?e(x,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return fa(e,`isCompressed`),this.assertValidity(),d(x,this,e)}toHex(e=!0){return C(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 no(x,e)}static msm(e,t){return fo(x,i,e,t)}static fromPrivateKey(e){return x.BASE.multiply(ko(i,e))}}x.BASE=new x(a.Gx,a.Gy,r.ONE),x.ZERO=new x(r.ZERO,r.ONE,r.ZERO),x.Fp=r,x.Fn=i;let ne=i.BITS,re=new uo(x,t.endo?Math.ceil(ne/2):ne);return x.BASE.precompute(8),x}function jo(e,t){Ga(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=function(e,t){let n=e.ORDER,r=To;for(let e=n-K;e%Eo===To;e/=Eo)r+=K;let i=r,a=Eo<<i-K-K,o=a*Eo,s=(n-K)/o,c=(s-K)/Eo,l=o-K,u=a,d=e.pow(t,s),f=e.pow(t,(s+K)/Eo),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-Eo;n=Eo<<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%Oo===Do){let n=(e.ORDER-Do)/Oo,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}(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 _=qa(e,[l],!0)[0];return f=e.mul(f,_),{x:f,y:p}}}function Mo(e){let{CURVE:t,curveOpts:n}=function(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:Xa(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}}}(e);return function(e,t){let{Fp:n,Fn:r}=t;function i(e){return ba(e,K,r.ORDER)}let a=function(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}(n,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:e=>ko(r,e),weierstrassEquation:a,isWithinCurveOrder:i})}(e,Ao(t,n))}var No=BigInt(0),Po=BigInt(1),Fo=BigInt(2),Io=BigInt(3);function Lo(e){if(!Array.isArray(e)||e.length===0)throw Error(`expected non-empty array`)}function Ro(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`)throw Error(`bls: unknown twist type`);u=(e,t,n,r,o,s)=>a.mul034(r,i.mul(n,s),i.mul(t,o),e)}let d=i.div(i.ONE,i.mul(i.ONE,Fo));function f(e,t,n,r){let a=i.sqr(n),o=i.sqr(r),s=i.mulByB(i.mul(o,Io)),c=i.mul(s,Io),l=i.sub(i.sub(i.sqr(i.add(n,r)),o),a),u=i.sub(s,a),f=i.mul(i.sqr(t),Io),p=i.neg(l);return e.push([u,f,p]),{Rx:t=i.mul(i.mul(i.mul(i.sub(a,c),t),n),d),Ry:n=i.sub(i.sqr(i.mul(i.add(a,c),d)),i.mul(i.sqr(s),Io)),Rz:r=i.mul(a,l)}}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,Fo)),i.mul(i.sqr(s),r));return{Rx:t=i.mul(c,h),Ry:n=i.sub(i.mul(i.sub(m,h),s),i.mul(p,n)),Rz:r=i.mul(r,p)}}let m=function(e){let t=[];for(;e>Po;e>>=Po)(e&Po)===No?t.unshift(0):(e&Io)===Io?(t.unshift(-1),e+=Po):t.unshift(1);return t}(s),h=Da(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=[];no(t,e.map(({g1:e})=>e)),no(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)}return{Fp12:a,millerLoopBatch:g,pairing:function(e,t,n=!0){return _([{g1:e,g2:t}],n)},pairingBatch:_,calcPairingPrecomputes:h}}function zo(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=ko(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=ko(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);let d=(r=s(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(Lo(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){Lo(e);let n=(e=e.map(e=>s(e))).reduce((e,t)=>e.add(t),t.Point.ZERO);return n.assertValidity(),n},aggregateSignatures(e){Lo(e);let t=(e=e.map(e=>c(e))).reduce((e,t)=>e.add(t),n.Point.ZERO);return t.assertValidity(),t},hash(e,t){Be(e);let r=t?{DST:t}:void 0;return n.hashToCurve(e,r)},Signature:r}}var Bo=BigInt(0),Vo=BigInt(1),Ho=BigInt(2),Uo=BigInt(3);function Wo(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=Vo;a<r;a++){let r=(i*c-i)/o%s;l.push(e.pow(t,r)),c*=n}c.push(l)}return c}var Go=(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]}},Ko=class{constructor(e,t={}){this.MASK=Vo;let n=e.ORDER,r=n*n;this.Fp=e,this.ORDER=r,this.BITS=Sa(r),this.BYTES=Math.ceil(Sa(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,Ho),this.NONRESIDUE=Go(e,t.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=Wo(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=t.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return Go(this.Fp,e)}create(e){return e}isValid({c0:e,c1:t}){function n(e,t){return typeof e==`bigint`&&Bo<=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 Ka(this,e,t)}invertBatch(e){return qa(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 Ja(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);Ja(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);return BigInt(t%Ho||t===Bo&&n%Ho)==Vo}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 T(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])}}},qo=class{constructor(e){this.MASK=Vo,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=Wo(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),Ho),o=r.mul(r.mul(t,n),Ho),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 Ea()}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 Ka(this,e,t)}invertBatch(e){return qa(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,2*n)),c2:t.fromBytes(e.subarray(2*n))}}toBytes({c0:e,c1:t,c2:n}){let{Fp2:r}=this;return T(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)}}},Jo=class{constructor(e,t){this.MASK=Vo;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=Wo(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){Ea()}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 Ka(this,e,t)}invertBatch(e){return qa(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 T(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),Ho),u),c1:r.add(r.mul(r.sub(f,a),Ho),f),c2:r.add(r.mul(r.sub(m,o),Ho),m)}),c1:n.create({c0:r.add(r.mul(r.add(g,s),Ho),g),c1:r.add(r.mul(r.add(d,c),Ho),d),c2:r.add(r.mul(r.add(p,l),Ho),p)})}}_cyclotomicExp(e,t){let n=this.ONE;for(let r=this.X_LEN-1;r>=0;r--)n=this._cyclotomicSquare(n),Ca(t,r)&&(n=this.mul(n,e));return n}},q=BigInt(0),Yo=BigInt(1),Xo=BigInt(2),Zo=BigInt(3),Qo=BigInt(4),$o=BigInt(`0xd201000000010000`),es=Sa($o),ts={p:BigInt(`0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab`),n:BigInt(`0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001`),h:BigInt(`0x396c8c005555e1568c00aaab0000aaab`),a:q,b:Qo,Gx:BigInt(`0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb`),Gy:BigInt(`0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1`)},ns=Xa(ts.n,{modFromBytes:!0,isLE:!0}),{Fp:J,Fp2:Y,Fp6:rs,Fp12:X}=function(e){let t=Xa(e.ORDER),n=new Ko(t,e),r=new qo(n);return{Fp:t,Fp2:n,Fp6:r,Fp12:new Jo(r,e)}}({ORDER:ts.p,X_LEN:es,FP2_NONRESIDUE:[Yo,Yo],Fp2mulByB:({c0:e,c1:t})=>{let n=J.mul(e,Qo),r=J.mul(t,Qo);return{c0:J.sub(n,r),c1:J.add(n,r)}},Fp12finalExponentiate:e=>{let t=$o,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:is,G2psi2:as}=function(e,t,n){let r=t.pow(n,(e.ORDER-Vo)/Uo),i=t.pow(n,(e.ORDER-Vo)/Ho);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**Ho-Vo)/Uo),s=t.pow(n,(e.ORDER**Ho-Vo)/Ho);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}}(J,Y,Y.div(Y.ONE,Y.NONRESIDUE)),os=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:Rt}),ss={p:Y.ORDER,n:ts.n,h:BigInt(`0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5`),a:Y.ZERO,b:Y.fromBigTuple([Qo,Qo]),Gx:Y.fromBigTuple([BigInt(`0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8`),BigInt(`0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e`)]),Gy:Y.fromBigTuple([BigInt(`0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801`),BigInt(`0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be`)])},cs=us(J.toBytes(q),{infinity:!0,compressed:!0});function ls(e){let t=224&(e=e.slice())[0],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 us(e,t){if(224&e[0])throw Error(`setMask: non-empty mask`);return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function ds(e){e.assertValidity();let{BYTES:t,ORDER:n}=J,{x:r,y:i}=e.toAffine();if(e.is0())return cs.slice();let a=!!(i*Xo/n);return us(V(r,t),{compressed:!0,sort:a})}function fs(e){let{infinity:t,sort:n,value:r}=ls(H(`signatureHex`,e,48)),i=J.ORDER,a=hs.G1.Point,o=ha(r);if(t)return a.ZERO;let s=J.create(o&wa(J.BITS)),c=J.add(J.pow(s,Zo),J.create(ts.b)),l=J.sqrt(c);if(!l)throw Error(`invalid G1 point: compressed`);let u=BigInt(n);l*Xo/i!==u&&(l=J.neg(l));let d=a.fromAffine({x:s,y:l});return d.assertValidity(),d}function ps(e){e.assertValidity();let{BYTES:t}=J;if(e.is0())return T(cs,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*Xo:o*Xo)/J.ORDER&Yo),l=i;return T(us(V(a,t),{sort:c,compressed:!0}),V(l,t))}function ms(e){let{ORDER:t}=J,{infinity:n,sort:r,value:i}=ls(H(`signatureHex`,e)),a=hs.G2.Point,o=i.length/2;if(o!==48&&o!==96)throw Error(`invalid compressed signature length, expected 96/192 bytes`);let s=ha(i.slice(0,o)),c=ha(i.slice(o));if(n)return a.ZERO;let l=J.create(s&wa(J.BITS)),u=J.create(c),d=Y.create({c0:u,c1:l}),f=Y.add(Y.pow(d,Zo),ss.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*Xo/t!==g||h===q&&m*Xo/t!==g)&&(p=Y.neg(p));let _=a.fromAffine({x:d,y:p});return _.assertValidity(),_}var hs=function(e){let{Fp:t,Fr:n,Fp2:r,Fp6:i,Fp12:a}=e.fields,o=Mo(e.G1),s=Object.assign(o,Co(o.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=Mo(e.G2),l=Object.assign(c,Co(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),u=Ro(e.fields,s.Point,l.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:d,pairing:f,pairingBatch:p,calcPairingPrecomputes:m}=u,h=zo(u,s,l,e.G2.Signature,!1),g=zo(u,l,s,e.G1.ShortSignature,!0),_=e.randomBytes||it,v=()=>{let e=Qa(n.ORDER);return function(e,t,n=!1){let r=e.length,i=Za(t),a=Qa(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=G(n?ga(e):ha(e),t-W)+W;return n?_a(o,i):V(o,i)}(_(e),n.ORDER)},y={randomSecretKey:v,randomPrivateKey:v,calcPairingPrecomputes:m},{ShortSignature:b}=e.G1,{Signature:ee}=e.G2;function te(e,t){return e instanceof s.Point?e:g.hash(H(`point`,e),t?.DST)}function x(e,t){return e instanceof l.Point?e:h.hash(H(`point`,e),t?.DST)}return s.Point.BASE.precompute(4),{longSignatures:h,shortSignatures:g,millerLoopBatch:d,pairing:f,pairingBatch:p,verifyBatch:function(e,t,n,r){let i=t.map(e=>x(e,r));return h.verifyBatch(e,i,n)},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:function(e){return h.getPublicKey(e).toBytes(!0)},getPublicKeyForShortSignatures:function(e){return g.getPublicKey(e).toBytes(!0)},sign:function(e,t,n){let r=x(e,n),i=h.sign(r,t);return e instanceof l.Point?i:ee.toBytes(i)},signShortSignature:function(e,t,n){let r=te(e,n),i=g.sign(r,t);return e instanceof s.Point?i:b.toBytes(i)},verify:function(e,t,n,r){let i=x(t,r);return h.verify(e,i,n)},verifyShortSignature:function(e,t,n,r){let i=te(t,r);return g.verify(e,i,n)},aggregatePublicKeys:function(e){let t=h.aggregatePublicKeys(e);return e[0]instanceof s.Point?t:t.toBytes(!0)},aggregateSignatures:function(e){let t=h.aggregateSignatures(e);return e[0]instanceof l.Point?t:ee.toBytes(t)},aggregateShortSignatures:function(e){let t=g.aggregateSignatures(e);return e[0]instanceof s.Point?t:b.toBytes(t)},G1:s,G2:l,Signature:ee,ShortSignature:b}}({fields:{Fp:J,Fp2:Y,Fp6:rs,Fp12:X,Fr:ns},G1:{...ts,Fp:J,htfDefaults:{...os,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($o).negate().multiplyUnsafe($o).equals(r)},clearCofactor:(e,t)=>t.multiplyUnsafe($o).add(t),mapToCurve:function(e){let{x:t,y:n}=vs(J.create(e[0]));return _s(t,n)},fromBytes:function(e){let{compressed:t,infinity:n,sort:r,value:i}=ls(e),{BYTES:a,ORDER:o}=J;if(i.length===48&&t){let e=ha(i),t=J.create(e&wa(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,Zo),J.create(ts.b)),s=J.sqrt(a);if(!s)throw Error(`invalid G1 point: compressed point`);return s*Xo/o!==BigInt(r)&&(s=J.neg(s)),{x:J.create(t),y:J.create(s)}}if(i.length!==96||t)throw Error(`invalid G1 point: expected 48/96 bytes`);{let e=ha(i.subarray(0,a)),t=ha(i.subarray(a));if(n){if(e!==q||t!==q)throw Error(`G1: non-empty point at infinity`);return hs.G1.Point.ZERO.toAffine()}return{x:J.create(e),y:J.create(t)}}},toBytes:function(e,t,n){let{BYTES:r,ORDER:i}=J,a=t.is0(),{x:o,y:s}=t.toAffine();if(n){if(a)return cs.slice();let e=!!(s*Xo/i);return us(V(o,r),{compressed:!0,sort:e})}return a?T(Uint8Array.of(64),new Uint8Array(2*r-1)):T(V(o,r),V(s,r))},ShortSignature:{fromBytes:e=>(Be(e),fs(e)),fromHex:e=>fs(e),toBytes:e=>ds(e),toRawBytes:e=>ds(e),toHex:e=>C(ds(e))}},G2:{...ss,Fp:Y,hEff:BigInt(`0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551`),htfDefaults:{...os},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:function(e){let{x:t,y:n}=ys(Y.fromBigTuple(e));return gs(t,n)},isTorsionFree:(e,t)=>t.multiplyUnsafe($o).negate().equals(is(e,t)),clearCofactor:(e,t)=>{let n=$o,r=t.multiplyUnsafe(n).negate(),i=is(e,t),a=t.double();return a=as(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:function(e){let{BYTES:t,ORDER:n}=J,{compressed:r,infinity:i,sort:a,value:o}=ls(e);if(!r&&!i&&a||!r&&i&&a||a&&i&&r)throw Error(`invalid encoding flag: `+(224&e[0]));let s=(e,t,n)=>ha(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,Zo),ss.b),u=Y.sqrt(l),d=u.c1===q?u.c0*Xo/n:u.c1*Xo/n?Yo:q;return u=a&&d>0?u:Y.neg(u),{x:c,y:u}}if(o.length!==192||r)throw Error(`invalid G2 point: expected 96/192 bytes`);{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])}}},toBytes:function(e,t,n){let{BYTES:r,ORDER:i}=J,a=t.is0(),{x:o,y:s}=t.toAffine();if(n){if(a)return T(cs,V(q,r));let e=!!(s.c1===q?s.c0*Xo/i:s.c1*Xo/i);return T(us(V(o.c1,r),{compressed:!0,sort:e}),V(o.c0,r))}{if(a)return T(Uint8Array.of(64),new Uint8Array(4*r-1));let{re:e,im:t}=Y.reim(o),{re:n,im:i}=Y.reim(s);return T(V(t,r),V(e,r),V(i,r),V(n,r))}},Signature:{fromBytes:e=>(Be(e),ms(e)),fromHex:e=>ms(e),toBytes:e=>ps(e),toRawBytes:e=>ps(e),toHex:e=>C(ps(e))}},params:{ateLoopSize:$o,r:ts.n,xNegative:!0,twistType:`multiplicative`},htfDefaults:os,hash:Rt}),gs=xo(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))))),_s=xo(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)))),vs=jo(J,{A:J.create(BigInt(`0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d`)),B:J.create(BigInt(`0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0`)),Z:J.create(BigInt(11))}),ys=jo(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 bs(e,t,n){let r=typeof e==`string`?e:C(e),i=typeof t==`string`?t:C(t),a=typeof n==`string`?n:C(n);return hs.verifyShortSignature(i,a,r)}var Z,xs=BigInt(1e6),Ss=e=>P(new zn(e)),Cs=e=>{let t=Ss(e)/xs;return new Date(Number(t))};(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||(Z={}));var ws=(l=new WeakMap,u=new WeakMap,class e{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??bs,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(e,t,r,a,o=5,s=!1,c){n(this,l,!1),n(this,u,void 0),this._rootKey=t,this._principal=r,this._blsVerify=a,this._maxAgeInMinutes=o,i(l,this,s),this.cert=ta(e),c&&`getTimeDiffMsecs`in c&&`hasSyncedTime`in c&&`syncTime`in c&&`syncTimeWithSubnet`in c&&i(u,this,c)}lookup_path(e){return Fs(e,this.cert.tree)}lookup_subtree(e){return Is(e,this.cert.tree)}async verify(){let e=await Ms(this.cert.tree),t=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,r=function(e){let t=ks.byteLength+As;if(e.byteLength!==t)throw k.fromCode(new an(t,e.byteLength));let n=e.slice(0,ks.byteLength);if(!ui(n,ks))throw k.fromCode(new on(ks,n));return e.slice(ks.byteLength)}(t),i=T(hi,e),o=js(this.lookup_path([`time`]));if(!o)throw k.fromCode(new Xt(`Certificate does not contain a time`));if(!a(l,this)){let e=a(u,this)?.getTimeDiffMsecs()??0,t=6e4*this._maxAgeInMinutes,n=new Date,r=n.getTime()+e,i=r-t,s=r+3e5,c=Cs(o),l=c.getTime()<i,d=c.getTime()>s;if((l||d)&&a(u,this)&&!a(u,this).hasSyncedTime())return await this._syncTime(),await this.verify();if(l)throw Kt.fromCode(new Zt(this._maxAgeInMinutes,c,n,e,`past`));if(d)throw a(u,this)?.hasSyncedTime()?j.fromCode(new On(`System time has been synced with the IC network, but certificate is still too far in the future.`)):Kt.fromCode(new Zt(5,c,n,e,`future`))}try{if(!await this._blsVerify(r,n,i))throw Kt.fromCode(new Xt(`Invalid signature`))}catch(e){throw Kt.fromCode(new Xt(`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:a(l,this),maxAgeInMinutes:43200,agent:a(u,this)});if(n.cert.delegation)throw k.fromCode(new Qt);let r;if(await n.verify(),Es(this._principal)){let e=this._principal.canisterId;if(r=D.fromUint8Array(t.subnet_id),!Bs({canisterId:e,subnetId:r,tree:n.cert.tree}))throw Kt.fromCode(new $t(e,r))}else{if(!Ts(this._principal))throw Rn;r=this._principal.subnetId}let i=js(n.lookup_path([`subnet`,r.toUint8Array(),`public_key`]));if(!i)throw Ts(this._principal)?Kt.fromCode(new en(r)):Kt.fromCode(new rn(`Could not find subnet key for subnet ID ${r.toText()}`));return i}async _syncTime(){a(u,this)&&(Es(this._principal)?await a(u,this).syncTime(this._principal.canisterId):await a(u,this).syncTimeWithSubnet(this._principal.subnetId))}});function Ts(e){return`subnetId`in e}function Es(e){return`canisterId`in e}var Ds,Os,Q,ks=et(`308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100`),As=96;function js(e){if(e.status===Ds.Found)return e.value instanceof Uint8Array?e.value:void 0}async function Ms(e){switch(e[0]){case Z.Empty:return Rt(Ns(`ic-hashtree-empty`));case Z.Pruned:return e[1];case Z.Leaf:return Rt(T(Ns(`ic-hashtree-leaf`),e[1]));case Z.Labeled:return Rt(T(Ns(`ic-hashtree-labeled`),e[1],await Ms(e[2])));case Z.Fork:return Rt(T(Ns(`ic-hashtree-fork`),await Ms(e[1]),await Ms(e[2])));default:throw Rn}}function Ns(e){return T(new Uint8Array([e.length]),new TextEncoder().encode(e))}function Ps(e){return typeof e[0]==`string`?w(e[0]):e[0]}function Fs(e,t){if(e.length===0)switch(t[0]){case Z.Empty:return{status:Ds.Absent};case Z.Leaf:if(!t[1])throw j.fromCode(new An(`Invalid tree structure for leaf`));if(t[1]instanceof Uint8Array)return{status:Ds.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw Rn;case Z.Pruned:return{status:Ds.Unknown};case Z.Labeled:case Z.Fork:return{status:Ds.Error};default:throw Rn}let n=Rs(Ps(e),t);switch(n.status){case Q.Found:return Fs(e.slice(1),n.value);case Q.Absent:case Q.Greater:case Q.Less:return{status:Ds.Absent};case Q.Unknown:return{status:Ds.Unknown};default:throw Rn}}function Is(e,t){if(e.length===0)return{status:Os.Found,value:t};let n=Rs(Ps(e),t);switch(n.status){case Q.Found:return Is(e.slice(1),n.value);case Q.Unknown:return{status:Os.Unknown};case Q.Absent:case Q.Greater:case Q.Less:return{status:Os.Absent};default:throw Rn}}function Ls(e){switch(e[0]){case Z.Empty:return[];case Z.Fork:return Ls(e[1]).concat(Ls(e[2]));default:return[e]}}function Rs(e,t){switch(t[0]){case Z.Labeled:return function(e,t){for(let n=0;n<e.length;n++)if(e[n]>t[n])return!0;return!1}(e,t[1])?{status:Q.Greater}:ui(e,t[1])?{status:Q.Found,value:t[2]}:{status:Q.Less};case Z.Fork:{let n=Rs(e,t[1]);switch(n.status){case Q.Greater:{let n=Rs(e,t[2]);return n.status===Q.Less?{status:Q.Absent}:n}case Q.Unknown:{let n=Rs(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 zs(e,t){switch(t[0]){case Z.Empty|Z.Pruned:return[];case Z.Leaf:return[e];case Z.Fork:return zs(e,t[1]).concat(zs(e,t[2]));case Z.Labeled:{let n=t[1],r=t[2];return zs([...e,n],r)}default:throw Rn}}function Bs(e){let t=Vs(function(e){let{subnetId:t,tree:n,canisterId:r}=e,i=Is([`canister_ranges`,t.toUint8Array()],n);if(i.status!==Os.Found)return function(e,t){let n=Fs([`subnet`,e.toUint8Array(),`canister_ranges`],t);if(n.status!==Ds.Found)throw k.fromCode(new tn(`Could not find canister ranges for subnet ${e.toText()}`,n.status));return n.value}(t,n);let a=i.value,o=function(e){let t=[];for(let n of zs([],e)){let e=n[0];if(!e)throw k.fromCode(new Xt(`Path is invalid`));t.push(e)}return t}(a);if(o.length===0)throw k.fromCode(new $t(r,t));return o.sort(Vn),function(e,t){let n=Fs([e],t);if(n.status!==Ds.Found)throw k.fromCode(new tn(`Could not find canister range for shard ${e.toString()}`,n.status));return n.value}(o[function(e,t){let n=t.toUint8Array(),r=0,i=e.length-1;for(;r<i;){let t=Math.floor((r+i)/2);Vn(e[t],n)<=0?i=t:r=t+1}return r}(o,r)],a)}(e)),{canisterId:n}=e;return t.some(e=>e[0].ltEq(n)&&e[1].gtEq(n))}function Vs(e){return ta(e).map(e=>[D.fromUint8Array(e[0]),D.fromUint8Array(e[1])])}function Hs(e,t){return e.delegation?D.fromUint8Array(e.delegation.subnet_id):D.selfAuthenticating(t)}(function(e){e.Unknown=`Unknown`,e.Absent=`Absent`,e.Found=`Found`,e.Error=`Error`})(Ds||(Ds={})),function(e){e.Absent=`Absent`,e.Unknown=`Unknown`,e.Found=`Found`}(Os||(Os={})),function(e){e.Absent=`Absent`,e.Unknown=`Unknown`,e.Found=`Found`,e.Less=`Less`,e.Greater=`Greater`}(Q||(Q={}));var Us=D.fromText(`tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe`);function Ws(e,t){switch(t){case`raw`:return e;case`leb128`:return Ss(e);case`cbor`:return ta(e);case`hex`:return C(e);case`utf-8`:return new TextDecoder().decode(e)}}function Gs(e){return typeof e==`object`&&!!e&&`key`in e&&`path`in e}function Ks(e,t){let n=Is([`subnet`,t.toUint8Array(),`node`],e.tree);if(n.status!==Os.Found)throw k.fromCode(new tn(`Node not found`,n.status));if(n.value instanceof Uint8Array)throw j.fromCode(new An(`Invalid node tree`));let r=Ls(n.value),i=new Map;return r.forEach(e=>{let t=D.from(e[1]).toText(),n=Fs([`public_key`],e[2]);if(n.status!==Ds.Found)throw k.fromCode(new tn(`Public key not found`,n.status));let r=n.value;if(r.byteLength!==44)throw k.fromCode(new an(44,r.byteLength));i.set(t,r)}),i}var qs=async e=>{let{agent:t,paths:n,disableCertificateTimeVerification:r=!1}=e,i=D.from(e.canisterId),a=[...new Set(n)],o=new Map,s=a.map((e,n)=>{let s=Ys(e,i);return(async()=>{try{if(t.rootKey===null)throw Yt.fromCode(new vn);let e=t.rootKey,c=await t.readState(i,{paths:[s]}),{path:l,data:u}=((t,n)=>n===`subnet`?{path:n,data:Js(c.certificate,i,e)}:{path:n,data:js(t.lookup_path(s))})(await ws.create({certificate:c.certificate,rootKey:e,principal:{canisterId:i},disableTimeVerification:r,agent:t}),a[n]);if(u)switch(l){case`time`:o.set(l,Cs(u));break;case`controllers`:o.set(l,ta(u).map(e=>D.fromUint8Array(e)));break;case`module_hash`:o.set(l,C(u));break;case`subnet`:o.set(l,u);break;case`candid`:o.set(l,new TextDecoder().decode(u));break;default:Gs(l)&&o.set(l.key,Ws(u,l.decodeStrategy))}else typeof l==`string`?o.set(l,null):o.set(l.key,null)}catch(t){if(t instanceof Wt&&(t.hasCode(Xt)||t.hasCode(Zt)))throw t;Gs(e)?o.set(e.key,null):o.set(e,null)}})()});return await Promise.all(s),o},Js=(e,t,n)=>{if(!t._isPrincipal)throw A.fromCode(new On(`Invalid canisterId`));let r=ta(e),{delegation:i}=r,a;a=i&&i.subnet_id?D.fromUint8Array(new Uint8Array(i.subnet_id)):i||n===void 0?Us:D.selfAuthenticating(new Uint8Array(n));let o=Ks(r,a);return{subnetId:a.toText(),nodeKeys:o}},Ys=(e,t)=>{let n=t.toUint8Array();switch(e){case`time`:return[w(`time`)];case`controllers`:return[w(`canister`),n,w(`controllers`)];case`module_hash`:return[w(`canister`),n,w(`module_hash`)];case`subnet`:return[w(`subnet`)];case`candid`:return[w(`canister`),n,w(`metadata`),w(`candid:service`)];default:if(Gs(e))return typeof e.path==`string`||e.path instanceof Uint8Array?function(e,t){let n=typeof e==`string`?w(e):e;return[w(`canister`),t,w(`metadata`),n]}(e.path,n):e.path}throw j.fromCode(new On(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))};async function Xs(e){let{agent:t,paths:n,disableCertificateTimeVerification:r=!1}=e,i=D.from(e.subnetId),a=[...new Set(n)],o=new Map,s=a.map((e,n)=>{let s=function(e,t){let n=t.toUint8Array();switch(e){case`time`:return[w(`time`)];case`canisterRanges`:return[w(`canister_ranges`),n];case`publicKey`:return[w(`subnet`),n,w(`public_key`)];case`nodeKeys`:return[w(`subnet`),n,w(`node`)];default:if(Gs(e)){if(typeof e.path==`string`||e.path instanceof Uint8Array){let t=typeof e.path==`string`?w(e.path):e.path;return[w(`subnet`),n,t]}return e.path}}throw j.fromCode(new On(`Error while encoding your path for subnet status. Please ensure that your path ${e} was formatted correctly.`))}(e,i);return(async()=>{try{if(t.rootKey===null)throw Yt.fromCode(new vn);let e=t.rootKey,c=await t.readSubnetState(i,{paths:[s]}),{path:l,data:u}=((e,t)=>t===`nodeKeys`?{path:t,data:Ks(e.cert,i)}:{path:t,data:js(e.lookup_path(s))})(await ws.create({certificate:c.certificate,rootKey:e,principal:{subnetId:i},disableTimeVerification:r,agent:t}),a[n]);if(u)switch(l){case`time`:o.set(l,Cs(u));break;case`canisterRanges`:o.set(l,Vs(u));break;case`publicKey`:case`nodeKeys`:o.set(l,u);break;default:Gs(l)&&o.set(l.key,Ws(u,l.decodeStrategy))}else typeof l==`string`?o.set(l,null):o.set(l.key,null)}catch(t){if(t instanceof Wt&&(t.hasCode(Xt)||t.hasCode(Zt)))throw t;Gs(e)?o.set(e.key,null):o.set(e,null)}})()});return await Promise.all(s),o}function Zs(e,t,n){let r=new Uint8Array(js(e.lookup_path([...t,`reject_code`])))[0],i=new TextDecoder().decode(js(e.lookup_path([...t,`reject_message`]))),a=js(e.lookup_path([...t,`error_code`]));return new mn(n,r,i,a?new TextDecoder().decode(a):void 0)}var Qs=BigInt(0),$=BigInt(1),$s=BigInt(2),ec=BigInt(8),tc=class{constructor(e){this.ep=e}static fromBytes(e){Ea()}static fromHex(e){Ea()}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 C(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 nc(e,t,n={}){if(typeof t!=`function`)throw Error(`"hash" function param is required`);Ta(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||it,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(fa(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e});function u(e){return o.create(ga(e))}function d(e){let{head:n,prefix:r,scalar:a}=function(e){let n=g.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)}}(e),o=i.multiply(a);return{head:n,prefix:r,scalar:a,point:o,pointBytes:o.toBytes()}}function f(e){return d(e).pointBytes}function p(e=Uint8Array.of(),...n){let i=T(...n);return u(t(l(i,H(`context`,e),!!r)))}let m={zip215:!0},h=a.BYTES,g={secretKey:h,publicKey:h,signature:2*h,seed:h};function _(e=s(g.seed)){return pa(e,g.seed,`seed`)}let v={getExtendedPublicKey:d,randomSecretKey:_,isValidSecretKey:function(e){return ze(e)&&e.length===o.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch{return!1}},toMontgomery(t){let{y:n}=e.fromBytes(t),r=g.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=g.secretKey;pa(e,n);let r=t(e.subarray(0,n));return c(r).subarray(0,n)},randomPrivateKey:_,precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({keygen:function(e){let t=v.randomSecretKey(e);return{secretKey:t,publicKey:f(t)}},getPublicKey:f,sign:function(e,t,n={}){e=H(`message`,e),r&&(e=r(e));let{prefix:a,scalar:s,pointBytes:c}=d(t),l=p(n.context,a,e),u=i.multiply(l).toBytes(),f=p(n.context,u,c,e),m=o.create(l+f*s);if(!o.isValid(m))throw Error(`sign failed: invalid s`);return pa(T(u,o.toBytes(m)),g.signature,`result`)},verify:function(t,n,a,o=m){let{context:s,zip215:c}=o,l=g.signature;t=H(`signature`,t,l),n=H(`message`,n),a=H(`publicKey`,a,g.publicKey),c!==void 0&&fa(c,`zip215`),r&&(n=r(n));let u=l/2,d=t.subarray(0,u),f=ga(t.subarray(u,l)),h,_,v;try{h=e.fromBytes(a,c),_=e.fromBytes(d,c),v=i.multiplyUnsafe(f)}catch{return!1}if(!c&&h.isSmallOrder())return!1;let y=p(s,_.toBytes(),h.toBytes(),n);return _.add(h.multiplyUnsafe(y)).subtract(v).clearCofactor().is0()},utils:v,Point:e,lengths:g})}function rc(e){let{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=function(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:Xa(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}}(e);return function(e,t){let n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(e,nc(function(e,t={}){let n=mo(`edwards`,e,t,t.FpFnLE),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o}=a;Ta(t,{},{uvRatio:`function`});let s=$s<<BigInt(8*i.BYTES)-$,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:Qs}}});if(!function(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)}(r,a,a.Gx,a.Gy))throw Error(`bad curve params: generator point`);function u(e,t,n=!1){return xa(`coordinate `+e,t,n?$:Qs,s),t}function d(e){if(!(e instanceof m))throw Error(`ExtendedPoint expected`)}let f=Da((e,t)=>{let{X:n,Y:i,Z:a}=e,o=e.is0();t??(t=o?ec:r.inv(a));let s=c(n*t),l=c(i*t),u=r.mul(a,t);if(o)return{x:Qs,y:$};if(u!==$)throw Error(`invZ was invalid`);return{x:s,y:l}}),p=Da(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=va(pa(e,n,`point`)),fa(t,`zip215`);let u=va(e),d=e[n-1];u[n-1]=-129&d;let f=ga(u);xa(`point.y`,f,Qs,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=!!(128&d);if(!t&&v===Qs&&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($s),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($s*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-_,ee=v+_,te=c(g-t*h),x=c(y*b),ne=c(ee*te),re=c(y*te),ie=c(b*ee);return new m(x,ne,ie,re)}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=>no(m,e));return no(m,[t,n])[0]}multiplyUnsafe(e,t=m.ZERO){if(!i.isValid(e))throw Error(`invalid scalar: expected 0 <= sc < curve.n`);return e===Qs?m.ZERO:this.is0()||e===$?this:h.unsafe(this,e,e=>no(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 C(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 no(m,e)}static msm(e,t){return fo(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(Qs,$,$,Qs),m.Fp=r,m.Fn=i;let h=new uo(m,i.BITS);return m.BASE.precompute(8),m}(t,n),r,i))}var ic=BigInt(0),ac=BigInt(1),oc=BigInt(2),sc=BigInt(5),cc=BigInt(8),lc=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),uc={p:lc,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:cc,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function dc(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var fc=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function pc(e,t){let n=lc,r=G(t*t*t,n),i=function(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=lc,o=e*e%a*e%a,s=Ia(Ia(o,oc,a)*o%a,ac,a)*e%a,c=Ia(s,sc,a)*s%a,l=Ia(c,t,a)*c%a,u=Ia(l,n,a)*l%a,d=Ia(u,r,a)*u%a;return{pow_p_5_8:Ia(Ia(Ia(Ia(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,oc,a)*e%a,b2:o}}(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*fc,n),l=o===e,u=o===G(-e,n),d=o===G(-e*fc,n);return l&&(a=s),(u||d)&&(a=c),Ua(a,n)&&(a=G(-a,n)),{isValid:l||u,value:a}}var mc=Xa(uc.p,{isLE:!0}),hc=Xa(uc.n,{isLE:!0}),gc=rc({...uc,Fp:mc,hash:Bt,adjustScalarBytes:dc,uvRatio:pc}),_c=fc,vc=BigInt(`25063068953384623474111414158702152701244531502492656460079210482610430750235`),yc=BigInt(`54469307008909316920995813868745141605393597292927456921205312896311721017578`),bc=BigInt(`1159843021668779879193775521855586647937357759715417654439879720876111806838`),xc=BigInt(`40440834346308536858101042469323190826248399146238708352240133220865137265952`),Sc=e=>pc(ac,e),Cc=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),wc=e=>gc.Point.Fp.create(ga(e)&Cc);function Tc(e){let{d:t}=uc,n=lc,r=e=>mc.create(e),i=r(_c*e*e),a=r((i+ac)*bc),o=BigInt(-1),s=r((o-t*i)*r(i+t)),{isValid:c,value:l}=pc(a,s),u=r(l*e);Ua(u,n)||(u=r(-u)),c||(l=u),c||(o=i);let d=r(o*(i-ac)*xc-s),f=l*l,p=r((l+l)*s),m=r(d*vc),h=r(ac-f),g=r(ac+f);return new gc.Point(r(p*g),r(h*m),r(m*g),r(p*h))}function Ec(e){Be(e,64);let t=Tc(wc(e.subarray(0,32))),n=Tc(wc(e.subarray(32,64)));return new Dc(t.add(n))}var Dc=class e extends tc{constructor(e){super(e)}static fromAffine(t){return new e(gc.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw Error(`RistrettoPoint expected`)}init(t){return new e(t)}static hashToCurve(e){return Ec(H(`ristrettoHash`,e,64))}static fromBytes(t){Be(t,32);let{a:n,d:r}=uc,i=lc,a=e=>mc.create(e),o=wc(t);if(!function(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}(mc.toBytes(o),t)||Ua(o,i))throw Error(`invalid ristretto255 encoding 1`);let s=a(o*o),c=a(ac+n*s),l=a(ac-n*s),u=a(c*c),d=a(l*l),f=a(n*r*u-d),{isValid:p,value:m}=Sc(a(f*d)),h=a(m*l),g=a(m*h*f),_=a((o+o)*h);Ua(_,i)&&(_=a(-_));let v=a(c*g),y=a(_*v);if(!p||Ua(y,i)||v===ic)throw Error(`invalid ristretto255 encoding 2`);return new e(new gc.Point(_,v,ac,y))}static fromHex(t){return e.fromBytes(H(`ristrettoHex`,t,32))}static msm(t,n){return fo(e,gc.Point.Fn,t,n)}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep,i=lc,a=e=>mc.create(e),o=a(a(n+t)*a(n-t)),s=a(e*t),{value:c}=Sc(a(o*a(s*s))),l=a(c*o),u=a(c*s),d=a(l*u*r),f;if(Ua(r*d,i)){let n=a(t*_c),r=a(e*_c);e=n,t=r,f=a(l*yc)}else f=u;Ua(e*d,i)&&(t=a(-t));let p=a((n-t)*f);return Ua(p,i)&&(p=a(-p)),mc.toBytes(p)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:r,Y:i}=e.ep,a=e=>mc.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)}};function Oc(e){if(!Number.isFinite(e)||e<=0)throw Error(`expirationTime must be a positive finite number, got ${e}`)}Dc.BASE=new Dc(gc.Point.BASE),Dc.ZERO=new Dc(gc.Point.ZERO),Dc.Fp=mc,Dc.Fn=hc;var kc=(d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakSet,class{constructor(e){if(o(this,m),n(this,d,void 0),n(this,f,void 0),n(this,p,null),globalThis.indexedDB===void 0)throw Error(`IndexedDBExpirableStore requires IndexedDB, which is not available in this environment`);Oc(e.expirationTime),i(d,this,e.dbName),i(f,this,e.storeName),this.expirationTime=e.expirationTime}async get(e){let t=await r(m,this,jc).call(this);return new Promise((n,r)=>{let i=t.transaction(a(f,this),`readonly`).objectStore(a(f,this)).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 r(m,this,Pc).call(this);let n=await r(m,this,jc).call(this);return new Promise((r,i)=>{let o=n.transaction(a(f,this),`readwrite`),s=o.objectStore(a(f,this)),c={key:e,value:t,timestamp:Date.now()};s.put(c),o.oncomplete=()=>r(),o.onerror=()=>i(o.error)})}async delete(e){let t=await r(m,this,jc).call(this);return new Promise((n,r)=>{let i=t.transaction(a(f,this),`readwrite`);i.objectStore(a(f,this)).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}}),Ac=(h=new WeakMap,g=new WeakSet,class{constructor(e){o(this,g),n(this,h,void 0),Oc(e.expirationTime),this.expirationTime=e.expirationTime,i(h,this,new Map)}get(e){let t=a(h,this).get(e);return t?Date.now()-t.timestamp>this.expirationTime?(a(h,this).delete(e),Promise.resolve(void 0)):Promise.resolve(t.value):Promise.resolve(void 0)}set(e,t){return r(g,this,Fc).call(this),a(h,this).set(e,{value:t,timestamp:Date.now()}),Promise.resolve()}delete(e){return a(h,this).delete(e),Promise.resolve()}});function jc(){return a(p,this)||i(p,this,r(m,this,Mc).call(this).catch(e=>{throw i(p,this,null),e})),a(p,this)}async function Mc(){let e=await r(m,this,Nc).call(this);if(e.objectStoreNames.contains(a(f,this)))return e;let t=e.version+1;return e.close(),r(m,this,Nc).call(this,t)}function Nc(e){let t=a(f,this);return new Promise((n,r)=>{let o=globalThis.indexedDB.open(a(d,this),e);o.onupgradeneeded=()=>{let e=o.result;e.objectStoreNames.contains(t)||e.createObjectStore(t,{keyPath:`key`})},o.onsuccess=()=>{let e=o.result;e.onversionchange=()=>{e.close(),i(p,this,null)},n(e)},o.onerror=()=>r(o.error)})}async function Pc(){let e=await r(m,this,jc).call(this),t=Date.now();return new Promise((n,r)=>{let i=e.transaction(a(f,this),`readwrite`),o=i.objectStore(a(f,this)).openCursor();o.onsuccess=()=>{let e=o.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)})}function Fc(){let e=Date.now();for(let[t,n]of a(h,this))e-n.timestamp>this.expirationTime&&a(h,this).delete(t)}var Ic=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw A.fromCode(new ln(`Length too long (> 4 bytes)`))},Lc=(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 A.fromCode(new ln(`Length too long (> 4 bytes)`))},Rc=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw A.fromCode(new cn(`Invalid length 0`));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw A.fromCode(new cn(`Length too long (> 4 bytes)`))},zc=(Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),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]);var Bc=(e,t)=>{let n=0,r=(e,t)=>{if(i[n++]!==e)throw A.fromCode(new cn(`Expected ${t} at offset ${n}`))},i=new Uint8Array(e);if(r(48,`sequence`),n+=Rc(i,n),!ui(i.slice(n,n+t.byteLength),t))throw A.fromCode(new cn(`Not the expected OID.`));n+=t.byteLength,r(3,`bit string`);let a=((e,t)=>{let n=Rc(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 A.fromCode(new cn(`Length too long (> 4 bytes)`))})(i,n)-1;n+=Rc(i,n),r(0,`0 padding`);let o=i.slice(n);if(a!==o.length)throw A.fromCode(new sn(a,o.length));return o},Vc=(_=new WeakMap,v=new WeakMap,y=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 derEncode(e){return function(e,t){let n=2+Ic(e.byteLength+1),r=t.byteLength+n+e.byteLength,i=0,a=new Uint8Array(1+Ic(r)+r);return a[i++]=48,i+=Lc(a,i,r),a.set(t,i),i+=t.byteLength,a[i++]=3,i+=Lc(a,i,e.byteLength+1),a[i++]=0,a.set(new Uint8Array(e),i),a}(e,zc)}static derDecode(e){let t=Bc(e,zc);if(t.length!==this.RAW_KEY_LENGTH)throw A.fromCode(new cn(`An Ed25519 public key must be exactly 32 bytes long`));return t}get rawKey(){return a(_,this)}get derKey(){return a(v,this)}constructor(t){if(n(this,_,void 0),n(this,v,void 0),t.byteLength!==e.RAW_KEY_LENGTH)throw A.fromCode(new cn(`An Ed25519 public key must be exactly 32 bytes long`));i(_,this,t),i(v,this,e.derEncode(t))}toDer(){return this.derKey}toRaw(){return this.rawKey}},y.RAW_KEY_LENGTH=32,y),Hc=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))}},Uc=class extends Hc{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)}},Wc=.5,Gc=1.5,Kc=500,qc=6e4,Jc=9e5,Yc=10,Xc=(b=new WeakMap,ee=new WeakMap,te=new WeakMap,x=new WeakMap,ne=new WeakMap,re=new WeakMap,ie=new WeakMap,ae=new WeakMap,oe=new WeakMap,se=class e{constructor(t=e.default){n(this,b,void 0),n(this,ee,void 0),n(this,te,void 0),n(this,x,void 0),n(this,ne,void 0),n(this,re,void 0),n(this,ie,void 0),n(this,ae,void 0),n(this,oe,0);let{initialInterval:r=Kc,randomizationFactor:a=Wc,multiplier:o=Gc,maxInterval:s=qc,maxElapsedTime:c=Jc,maxIterations:l=Yc,date:u=Date}=t;i(b,this,r),i(ee,this,a),i(te,this,o),i(x,this,s),i(ae,this,u),i(ne,this,u.now()),i(re,this,c),i(ie,this,l)}get ellapsedTimeInMsec(){return a(ae,this).now()-a(ne,this)}get currentInterval(){return a(b,this)}get count(){return a(oe,this)}get randomValueFromInterval(){let e=a(ee,this)*a(b,this),t=a(b,this)-e,n=a(b,this)+e;return Math.random()*(n-t)+t}incrementCurrentInterval(){var e;return i(b,this,Math.min(a(b,this)*a(te,this),a(x,this))),i(oe,this,(e=a(oe,this),e++,e)),a(b,this)}next(){return this.ellapsedTimeInMsec>=a(re,this)||a(oe,this)>=a(ie,this)?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}},se.default={initialInterval:Kc,randomizationFactor:Wc,multiplier:Gc,maxInterval:qc,maxElapsedTime:Jc,maxIterations:Yc,date:Date},se);function Zc(){return function(...e){return async(t,n,r)=>{for(let i of e)await i(t,n,r)}}((e=function(){let e=!0;return async()=>!!e&&(e=!1,!0)}(),t=1e3,async(n,r,i)=>{if(await e(n,r,i))return new Promise(e=>setTimeout(e,t))}),function(e,t){let n=e;return()=>new Promise(e=>setTimeout(()=>{n*=t,e()},n))}(1e3,1.2),function(e){let t=Date.now()+e;return async(n,r,i)=>{if(Date.now()>t)throw k.fromCode(new fn(`Request timed out after ${e} msec`,r,i))}}(3e5));var e,t}function Qc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function $c(e,t){return typeof e==`object`&&!!e&&Qc(e,t)}function el(e){return $c(e,`body`)&&$c(e.body,`content`)&&e.body.content.request_type===ia.ReadState&&$c(e.body.content,`ingress_expiry`)&&typeof e.body.content.ingress_expiry==`object`&&e.body.content.ingress_expiry!==null&&function(e,t){return Qc(e,t)&&typeof e[t]==`function`}(e.body.content.ingress_expiry,`toHash`)}async function tl(e,t,n,r={}){let i=[w(`request_status`),n],a,o;if(r.preSignReadStateRequest?(o=await async function(e){let{paths:t,agent:n,pollingOptions:r}=e;if(r.request&&el(r.request))return r.request;let i=await n.createReadStateRequest?.({paths:t},void 0);if(!el(i))throw A.fromCode(new Fn(i));return i}({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 Yt.fromCode(new vn);let s=await ws.create({certificate:a.certificate,rootKey:e.rootKey,principal:{canisterId:t},blsVerify:r.blsVerify,agent:e}),c=js(s.lookup_path([...i,w(`status`)])),l;switch(l=c===void 0?aa.Unknown:new TextDecoder().decode(c),l){case aa.Replied:return{reply:js(s.lookup_path([...i,`reply`])),certificate:s,rawCertificate:a.certificate};case aa.Received:case aa.Unknown:case aa.Processing:{let i=r.strategy??Zc();return await i(t,n,l),tl(e,t,n,{...r,strategy:i,request:o})}case aa.Rejected:throw qt.fromCode(Zs(s,i,n));case aa.Done:throw j.fromCode(new _n(n))}throw Rn}var nl=6e4,rl=(ce=new WeakMap,le=new WeakMap,ue=new WeakMap,de=new WeakMap,fe=new WeakMap,pe=new WeakMap,me=new WeakMap,he=new WeakMap,ge=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,be=new WeakMap,xe=new WeakMap,Se=new WeakMap,S=new WeakSet,Ce=new WeakMap,we=new WeakMap,Te=new WeakMap,Ee=new WeakMap,De=new WeakMap,class e{constructor(e={}){if(o(this,S),n(this,ce,void 0),n(this,le,void 0),n(this,ue,void 0),n(this,de,void 0),n(this,fe,void 0),n(this,pe,void 0),n(this,me,void 0),n(this,he,void 0),n(this,ge,void 0),n(this,_e,void 0),n(this,ve,void 0),n(this,ye,void 0),n(this,be,void 0),n(this,xe,void 0),n(this,Se,void 0),n(this,Ce,void 0),n(this,we,void 0),n(this,Te,void 0),n(this,Ee,void 0),n(this,De,void 0),i(ce,this,null),i(le,this,!1),i(ue,this,0),i(de,this,!1),i(fe,this,null),i(pe,this,!1),this._isAgent=!0,this.config={},this.log=new Uc,i(Ce,this,[]),i(we,this,[]),i(Te,this,new Map),i(Ee,this,!0),i(De,this,(e,t)=>{if(!1===a(Ee,this))return e;let{status:n,signatures:r=[],requestId:i}=e,o=t.size;if(r.length>o)throw k.fromCode(new wn(r.length,o));for(let a of r){let{timestamp:r,identity:o}=a,s=D.fromUint8Array(o).toText(),c;if(n===Ae.Replied){let{reply:t}=e;c=mi({status:n,reply:t,timestamp:BigInt(r),request_id:i})}else{if(n!==Ae.Rejected)throw j.fromCode(new On(`Unknown status: ${n}`));{let{reject_code:t,reject_message:a,error_code:o}=e;c=mi({status:n,reject_code:t,reject_message:a,error_code:o,timestamp:BigInt(r),request_id:i})}}let l=T(gi,c),u=t.get(s);if(!u)throw k.fromCode(new En);let d=Vc.fromDer(u).rawKey;if(!gc.verify(a.signature,l,d))throw Kt.fromCode(new Dn(s))}return e}),this.config=e,e.fetch)i(he,this,e.fetch);else{let e=globalThis.fetch;if(typeof e!=`function`)throw A.fromCode(new Sn);i(he,this,e.bind(globalThis))}i(ge,this,e.fetchOptions),i(_e,this,e.callOptions),i(le,this,e.shouldFetchRootKey??!1),i(pe,this,e.shouldSyncTime??!1),this.rootKey=e.rootKey?e.rootKey:a(le,this)?null:et(`308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae`);let t=function(e){let t;if(e!==void 0)t=e.match(/^[a-z]+:/)||typeof window>`u`?new URL(e):new URL(`${window.location.protocol}//${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()}(e.host);if(this.host=new URL(t),this.host.hostname.endsWith(`.ic0.app`)?this.host.hostname=`ic0.app`:this.host.hostname.endsWith(`.icp0.io`)?this.host.hostname=`icp0.io`:this.host.hostname.endsWith(`.icp-api.io`)&&(this.host.hostname=`icp-api.io`),e.verifyQuerySignatures!==void 0&&i(Ee,this,e.verifyQuerySignatures),i(Se,this,e.subnetNodeKeyExpirableStore??function(e){return globalThis.indexedDB===void 0?new Ac({expirationTime:e.expirationTime}):new kc(e)}({dbName:`icp-sdk-${this.host.host}`,storeName:`subnetNodeKeys`,expirationTime:3e5})),i(ye,this,e.retryTimes??3),i(be,this,e.backoffStrategy||(()=>new Xc({maxIterations:a(ye,this)}))),e.credentials){let{name:t,password:n}=e.credentials;i(ve,this,`${t}${n?`:${n}`:``}`)}if(i(me,this,Promise.resolve(e.identity||new _i)),e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes>5)throw A.fromCode(new xn(`The maximum ingress expiry time is 5 minutes.`,e.ingressExpiryInMinutes));if(e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes<=0)throw A.fromCode(new xn(`Ingress expiry time must be greater than 0.`,e.ingressExpiryInMinutes));i(xe,this,e.ingressExpiryInMinutes||5),this.addTransform(`update`,ca(sa)),e.useQueryNonces&&this.addTransform(`query`,ca(sa)),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 r(S,n,dl).call(n),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 A.fromCode(new Cn)}}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=a(we,this).findIndex(e=>(e.priority||0)<n);a(we,this).splice(e>=0?e:a(we,this).length,0,Object.assign(t,{priority:n}))}else if(e===`query`){let e=a(Ce,this).findIndex(e=>(e.priority||0)<n);a(Ce,this).splice(e>=0?e:a(Ce,this).length,0,Object.assign(t,{priority:n}))}}async getPrincipal(){if(!a(me,this))throw Yt.fromCode(new bn);return(await a(me,this)).getPrincipal()}async call(e,t,n){let i=t.callSync??!0,o=await(n??a(me,this));if(!o)throw Yt.fromCode(new bn);let s=D.from(e),c=t.effectiveCanisterId?D.from(t.effectiveCanisterId):s;await r(S,this,dl).call(this,c);let l=o.getPrincipal(),u=hl(a(xe,this),a(ue,this)),d={request_type:ra.Call,canister_id:s,method_name:t.methodName,arg:t.arg,sender:l,ingress_expiry:u},f,p=await this._transform({request:{body:null,method:`POST`,headers:{"Content-Type":`application/cbor`,...a(ve,this)?{Authorization:`Basic ${btoa(a(ve,this))}`}:{}}},endpoint:na.Call,body:d});function m(e){return Object.assign(e,{__nonce__:void 0})}f=t?.nonce?m(t.nonce):p.body.nonce?m(p.body.nonce):void 0,d.nonce=f,p=await o.transformRequest(p);let h=pi(p.body.content??d),g=ea(p.body),_=a(be,this).call(this);try{let e=i?()=>{let e=new URL(`/api/v4/canister/${c.toText()}/call`,this.host);return this.log.print(`fetching "${e.pathname}" with request:`,p),a(he,this).call(this,e,{...a(_e,this),...p.request,body:g})}:()=>{let e=new URL(`/api/v2/canister/${c.toText()}/call`,this.host);return this.log.print(`fetching "${e.pathname}" with request:`,p),a(he,this).call(this,e,{...a(_e,this),...p.request,body:g})},{responseBodyBytes:t,...n}=await r(S,this,cl).call(this,{requestFn:e,backoff:_,tries:0}),o=t.byteLength>0?ta(t):null;return{requestId:h,response:{...n,body:o},requestDetails:d}}catch(r){let i;if(r instanceof Wt){if(r.hasCode(Mn))return this.log.warn(`v4 api not supported. Fall back to v2`),this.call(e,{...t,callSync:!1},n);if(r.hasCode(xn)&&!a(de,this))return await this.syncTime(s),this.call(s,t,n);r.code.requestContext={requestId:h,senderPubKey:p.body.sender_pubkey,senderSignature:p.body.sender_sig,ingressExpiry:p.body.content.ingress_expiry},i=r}else i=j.fromCode(new On(r));throw this.log.error(`Error while making call: ${i.message}`,i),i}}async update(e,t,n={}){let i=D.from(t.effectiveCanisterId),{requestId:a,response:o,requestDetails:s}=await this.call(e,t),{body:c,...l}=o;if(function(e){return e!=null&&`certificate`in e}(c))return r(S,this,al).call(this,c,o,a,i,t.methodName,l,s,n,t.onPollingStarted);if(function(e){return e!=null&&`reject_code`in e}(c)&&r(S,this,ol).call(this,c,a,i,t.methodName,l),o.status===202)return t.onPollingStarted?.(),{...await tl(this,i,a,n),requestDetails:s,callResponse:o};let u=new On(`Unexpected response from call: status ${o.status} with unrecognized body`);throw u.callContext={canisterId:i,methodName:t.methodName,httpDetails:l},j.fromCode(u)}async query(e,t,n){let i=a(be,this).call(this),o=t.effectiveCanisterId?D.from(t.effectiveCanisterId):D.from(e),s;await r(S,this,dl).call(this,o),this.log.print(`ecid ${o.toString()}`),this.log.print(`canisterId ${e.toString()}`);let c=await(n??a(me,this));if(!c)throw Yt.fromCode(new bn);let l=D.from(e),u=c.getPrincipal(),d=hl(a(xe,this),a(ue,this)),f={request_type:ia.Query,canister_id:l,method_name:t.methodName,arg:t.arg,sender:u,ingress_expiry:d};s=await this._transform({request:{method:`POST`,headers:{"Content-Type":`application/cbor`,...a(ve,this)?{Authorization:`Basic ${btoa(a(ve,this))}`}:{}}},endpoint:na.Query,body:f}),s=await c.transformRequest(s);let p=pi(s.body.content??f),m=ea(s.body),h={canister:l.toText(),ecid:o,transformedRequest:s,body:m,requestId:p,backoff:i,tries:0},g=async()=>{let e=await r(S,this,sl).call(this,h);return{requestDetails:f,...e}};try{if(!a(Ee,this))return await g();let[e,t]=await Promise.all([g(),this.fetchSubnetKeys(o)]);try{return a(De,this).call(this,e,t)}catch{this.log.warn(`Query response verification failed. Retrying with fresh subnet keys.`),await a(Se,this).delete(o.toString());let t=await this.fetchSubnetKeys(o);return a(De,this).call(this,e,t)}}catch(r){let i;if(r instanceof Wt){if(r.hasCode(xn)&&!a(de,this))return await this.syncTime(o),this.query(e,t,n);r.code.requestContext={requestId:p,senderPubKey:s.body.sender_pubkey,senderSignature:s.body.sender_sig,ingressExpiry:s.body.content.ingress_expiry},i=r}else i=j.fromCode(new On(r));throw this.log.error(`Error while making query: ${i.message}`,i),i}}async createReadStateRequest(e,t){await r(S,this,dl).call(this);let n=await(t??a(me,this));if(!n)throw Yt.fromCode(new bn);let i=n.getPrincipal(),o=await this._transform({request:{method:`POST`,headers:{"Content-Type":`application/cbor`,...a(ve,this)?{Authorization:`Basic ${btoa(a(ve,this))}`}:{}}},endpoint:na.ReadState,body:{request_type:ia.ReadState,paths:e.paths,sender:i,ingress_expiry:hl(a(xe,this),a(ue,this))}});return n.transformRequest(o)}async readState(e,t,n,i){await r(S,this,fl).call(this);let o=D.from(e),s,c;if(i)s=i;else{c=function(e){for(let t of e.paths){let[e,n]=t;if(ui(e,new TextEncoder().encode(`request_status`)))return n}}(t);let e=await a(me,this);if(!e)throw Yt.fromCode(new bn);s=await this.createReadStateRequest(t,e)}let l=new URL(`/api/v3/canister/${o.toString()}/read_state`,this.host);return await r(S,this,ll).call(this,l,{canisterId:o},s,c)}async readSubnetState(e,t){await r(S,this,fl).call(this);let n=D.from(e),i=new URL(`/api/v3/subnet/${n.toString()}/read_state`,this.host),o=await this.createReadStateRequest(t,a(me,this)??void 0);return await r(S,this,ll).call(this,i,{subnetId:n},o)}parseTimeFromResponse(e){let t;if(e.certificate){let n=ta(e.certificate);if(!n||!(`tree`in n))throw k.fromCode(new An(`Could not decode time from response`));t=n.tree;let r=Fs([`time`],t);if(r.status!==Ds.Found)throw k.fromCode(new tn(`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 k.fromCode(new nn(`Time was not in its expected format.`));let i=Cs(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){i(fe,this,a(fe,this)??(async()=>{await r(S,this,fl).call(this);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 i=t??D.from(`ryjl3-tyaaa-aaaaa-aaaba-cai`),o=e.createSync({identity:new _i,host:this.host.toString(),fetch:a(he,this),retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),s=await Promise.all([,,,].fill(null).map(async()=>{let e=(await qs({canisterId:i,agent:o,paths:[`time`],disableCertificateTimeVerification:!0})).get(`time`);if(e instanceof Date)return e.getTime()},[]));r(S,this,ul).call(this,n,s)}catch(e){let t=e instanceof Wt?e:j.fromCode(new On(e));throw this.log.error(`Caught exception while attempting to sync time`,t),t}})()),await a(fe,this).finally(()=>{i(fe,this,null)})}async syncTimeWithSubnet(t){await r(S,this,fl).call(this);let n=Date.now();try{let i=e.createSync({identity:new _i,host:this.host.toString(),fetch:a(he,this),retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),o=await Promise.all([,,,].fill(null).map(async()=>{let e=(await Xs({subnetId:t,agent:i,paths:[`time`],disableCertificateTimeVerification:!0})).get(`time`);if(e instanceof Date)return e.getTime()},[]));r(S,this,ul).call(this,n,o)}catch(e){let t=e instanceof Wt?e:j.fromCode(new On(e));throw this.log.error(`Caught exception while attempting to sync time with subnet`,t),t}}async status(){let e=a(ve,this)?{Authorization:`Basic ${btoa(a(ve,this))}`}:{},t=new URL(`/api/v2/status`,this.host);this.log.print(`fetching "${t.pathname}"`);let n=a(be,this).call(this),{responseBodyBytes:i}=await r(S,this,cl).call(this,{backoff:n,requestFn:()=>a(he,this).call(this,t,{headers:e,...a(ge,this)}),tries:0});return ta(i)}async fetchRootKey(){return i(ce,this,a(ce,this)??(async()=>{let e=await this.status();return this.rootKey=e.root_key,this.rootKey})()),await a(ce,this).finally(()=>{i(ce,this,null)})}invalidateIdentity(){i(me,this,null)}replaceIdentity(e){i(me,this,Promise.resolve(e))}async fetchSubnetKeys(e){let t=D.from(e),n=await a(Se,this).get(t.toText());if(n)return n;let i=a(Te,this).get(t.toText());if(i)return i;let o=r(S,this,ml).call(this,t).finally(()=>{a(Te,this).delete(t.toText())});return a(Te,this).set(t.toText(),o),o}async getSubnetIdFromCanister(e){let t=D.from(e);await r(S,this,dl).call(this,t);let n=await this.readState(t,{paths:[[w(`time`)]]});return Hs((await ws.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===na.Call)for(let e of a(we,this))t=t.then(t=>e(t).then(e=>e||t));else for(let e of a(Ce,this))t=t.then(t=>e(t).then(e=>e||t));return t}getTimeDiffMsecs(){return a(ue,this)}hasSyncedTime(){return a(de,this)}});function il(){return a(xe,this)*nl}async function al(e,t,n,r,i,a,o,s,c){if(this.rootKey==null)throw Yt.fromCode(new vn);let l=e.certificate,u=await ws.create({certificate:l,rootKey:this.rootKey,principal:{canisterId:r},blsVerify:s.blsVerify,agent:this}),d=[w(`request_status`),n],f=js(u.lookup_path([...d,w(`status`)])),p=f?new TextDecoder().decode(f):void 0;switch(p){case aa.Replied:return{reply:js(u.lookup_path([...d,`reply`])),certificate:u,rawCertificate:l,requestDetails:o,callResponse:t};case aa.Rejected:{let e=Zs(u,d,n);throw e.callContext={canisterId:r,methodName:i,httpDetails:a},qt.fromCode(e)}case void 0:return this.log.warn(`v4 sync response certificate does not contain request ID ${C(n)} status. Falling back to polling.`),c?.(),{...await tl(this,r,n,s),requestDetails:o,callResponse:t};default:{let e=new kn(p,n,t,l);throw e.callContext={canisterId:r,methodName:i,httpDetails:a},j.fromCode(e)}}}function ol(e,t,n,r,i){let{reject_code:a,reject_message:o,error_code:s}=e,c=new gn(t,a,o,s);throw c.callContext={canisterId:n,methodName:r,httpDetails:i},qt.fromCode(c)}async function sl(e){let{ecid:t,transformedRequest:n,body:i,requestId:o,backoff:s,tries:c}=e,l=c===0?0:s.next(),u=new URL(`/api/v3/canister/${t.toString()}/query`,this.host);if(this.log.print(`fetching "${u.pathname}" with tries:`,{tries:c,backoff:s,delay:l}),l===null)throw j.fromCode(new fn(`Backoff strategy exhausted after ${c} attempts.`,o));let d;l>0&&await new Promise(e=>setTimeout(e,l));try{this.log.print(`fetching "${u.pathname}" with request:`,n),d=await a(he,this).call(this,u,{...a(ge,this),...n.request,body:i})}catch(t){if(c<a(ye,this))return this.log.warn(`Caught exception while attempting to make query:\n ${t}\n Retrying query.`),await r(S,this,sl).call(this,{...e,tries:c+1});throw Jt.fromCode(new Nn(t))}let f=la(d.headers);if(d.status!==200){let t=await d.text();if(gl(t))throw A.fromCode(new xn(t,a(xe,this)));if(c<a(ye,this))return await r(S,this,sl).call(this,{...e,tries:c+1});throw k.fromCode(new jn(d.status,d.statusText,f,t))}let p={...ta(li(await d.arrayBuffer())),httpDetails:{ok:d.ok,status:d.status,statusText:d.statusText,headers:f},requestId:o};if(!a(Ee,this))return p;let m=p.signatures?.[0]?.timestamp;if(!m)throw k.fromCode(new Tn(`Timestamp not found in query response. This suggests a malformed or malicious response.`));let h=Number(BigInt(m)/BigInt(1e6));if(Date.now()+a(ue,this)-h>il.call(r(S,this))){if(c<a(ye,this))return this.log.warn(`Timestamp is older than the max ingress expiry. Retrying query.`,{requestId:o,signatureTimestampMs:h}),await this.syncTime(t),await r(S,this,sl).call(this,{...e,tries:c+1});throw Kt.fromCode(new pn(a(xe,this),o,c))}return p}async function cl(e){let{requestFn:t,backoff:n,tries:i}=e,o=i===0?0:n.next();if(o===null)throw k.fromCode(new fn(`Retry strategy exhausted after ${i} attempts.`));let s;o>0&&await new Promise(e=>setTimeout(e,o));let c=new Uint8Array;try{s=await t(),s.status===200&&(c=li(await s.clone().arrayBuffer()))}catch(e){if(i<a(ye,this))return this.log.warn(`Caught exception while attempting to make request:\n ${e}\n Retrying request.`),await r(S,this,cl).call(this,{requestFn:t,backoff:n,tries:i+1});throw Jt.fromCode(new Nn(e))}let l=la(s.headers);if(s.status===200||s.status===202)return{ok:s.ok,status:s.status,statusText:s.statusText,responseBodyBytes:c,headers:l};let u=await s.text();if(s.status===404&&s.url.includes(`api/v4`))throw k.fromCode(new Mn);if(gl(u))throw A.fromCode(new xn(u,a(xe,this)));if(i<a(ye,this))return await r(S,this,cl).call(this,{requestFn:t,backoff:n,tries:i+1});throw k.fromCode(new jn(s.status,s.statusText,l,u))}async function ll(e,t,n,i){let o=a(be,this).call(this);try{let{responseBodyBytes:t}=await r(S,this,cl).call(this,{requestFn:()=>a(he,this).call(this,e,{...a(ge,this),...n.request,body:ea(n.body)}),backoff:o,tries:0});return ta(t)}catch(o){let s;if(o instanceof Wt){if(o.hasCode(xn)&&!a(de,this)){if(`canisterId`in t)await this.syncTime(t.canisterId);else{if(!(`subnetId`in t))throw Rn;await this.syncTimeWithSubnet(t.subnetId)}return await r(S,this,ll).call(this,e,t,n,i)}o.code.requestContext={requestId:i??pi(n),senderPubKey:n.body.sender_pubkey,senderSignature:n.body.sender_sig,ingressExpiry:n.body.content.ingress_expiry},s=o}else s=j.fromCode(new On(o));throw this.log.error(`Error while making read state: ${s.message}`,s),s}}function ul(e,t){let n=t.reduce((e,t)=>typeof t==`number`&&t>e?t:e,0);n>0&&(i(ue,this,n-e),i(de,this,!0),this.log.notify({message:`Syncing time: offset of ${a(ue,this)}`,level:`info`}))}async function dl(e){await Promise.all([r(S,this,fl).call(this),r(S,this,pl).call(this,e)])}async function fl(){if(!this.rootKey){if(this.rootKey!==null||this.host.toString()===`https://icp-api.io`||!a(le,this))throw Yt.fromCode(new vn(a(le,this)));await this.fetchRootKey()}}async function pl(e){a(pe,this)&&!this.hasSyncedTime()&&await this.syncTime(e)}async function ml(e){await r(S,this,dl).call(this,e);let t=this.rootKey,n=await this.readState(e,{paths:[[w(`subnet`)]]}),i=await ws.create({certificate:n.certificate,rootKey:t,principal:{canisterId:e},agent:this});if(!i.cert.delegation){let n=D.selfAuthenticating(t);if(!Bs({canisterId:e,subnetId:n,tree:i.cert.tree}))throw Kt.fromCode(new $t(e,n))}let o=Hs(i.cert,t),s=Ks(i.cert,o);return await a(Se,this).set(e.toText(),s),s}function hl(e,t){let n=e*nl;return $i.fromDeltaInMilliseconds(n,t)}function gl(e){return e.includes(`Invalid request expiry: `)}var _l=Symbol.for(`ic-agent-metadata`),vl=class{static agentOf(e){return e[_l].config.agent}static interfaceOf(e){return e[_l].service}static canisterIdOf(e){return D.from(e[_l].config.canisterId)}static createActorClass(e,t){let n=e({IDL:Zn});return class extends vl{constructor(e){if(!e.canisterId)throw A.fromCode(new Pn(e.canisterId));let r=typeof e.canisterId==`string`?D.fromText(e.canisterId):e.canisterId;super({config:{...bl,...e,canisterId:r},service:n});for(let[r,i]of n._fields)t?.httpDetails&&i.annotations.push(xl),t?.certificate&&i.annotations.push(Sl),this[r]=Cl(this,r,i,e.blsVerify)}}}static createActor(e,t){if(!t.canisterId)throw A.fromCode(new Pn(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[_l]=Object.freeze(e)}};function yl(e,t){let n=kr(e,t);switch(n.length){case 0:return;case 1:return n[0];default:return n}}var bl={pollingOptions:{preSignReadStateRequest:!1},queryStrategy:`query`},xl=`http-details`,Sl=`certificate`;function Cl(e,t,n,r){let i,a=n.annotations.includes(`query`)||n.annotations.includes(`composite_query`),o=e[_l].config.queryStrategy;i=a&&o===`query`?async(r,...i)=>{let a=(r={...r,...e[_l].config.queryTransform?.(t,i,{...e[_l].config,...r})}).agent||e[_l].config.agent||new rl,o=D.from(r.canisterId||e[_l].config.canisterId),s=Or(n.argTypes,i),c=await a.query(o,{methodName:t,arg:s,effectiveCanisterId:r.effectiveCanisterId}),l={...c.httpDetails,requestDetails:c.requestDetails};switch(c.status){case Ae.Rejected:{let e=new hn(c.requestId,c.reject_code,c.reject_message,c.error_code,c.signatures);throw e.callContext={canisterId:o,methodName:t,httpDetails:l},qt.fromCode(e)}case Ae.Replied:return n.annotations.includes(`http-details`)?{httpDetails:l,result:yl(n.retTypes,c.reply.arg)}:yl(n.retTypes,c.reply.arg)}}:async(i,...a)=>{let o=(i={...i,...e[_l].config.callTransform?.(t,a,{...e[_l].config,...i})}).agent||e[_l].config.agent||rl.createSync(),{canisterId:s,effectiveCanisterId:c,pollingOptions:l}={...bl,...e[_l].config,...i},u=D.from(s),d=c===void 0?u:D.from(c),f=Or(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 qt){let n=Object.create(Object.getPrototypeOf(e.code),Object.getOwnPropertyDescriptors(e.code));throw n.callContext={...e.code.callContext,canisterId:u,methodName:t},qt.fromCode(n)}throw e}let _=n.annotations.includes(xl),v=n.annotations.includes(Sl),y={...h,requestDetails:g};return _&&v?{httpDetails:y,certificate:m,result:yl(n.retTypes,p)}:v?{certificate:m,result:yl(n.retTypes,p)}:_?{httpDetails:y,result:yl(n.retTypes,p)}:yl(n.retTypes,p)};let s=(...e)=>i({},...e);return s.withOptions=e=>(...t)=>i(e,...t),s}var wl=({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`])}),Tl=({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});return e.Service({get_merchant:e.Func([e.Text],[e.Opt(n)],[`query`]),get_recipient:e.Func([e.Text],[e.Opt(n)],[`query`])})},El=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===Pe.staging.admin_core?Pe.staging.admin_regs:Pe.prod.admin_regs,this.debug=e.debug??!1}async init(){this.agent=await rl.create({host:`https://icp-api.io`}),this.adminCoreActor=vl.createActor(wl,{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||(this.adminCoreActor=vl.createActor(wl,{agent:await this.getAgent(),canisterId:this.adminCoreCanisterId})),this.adminCoreActor}async getRegsActor(){return this.adminRegsActor||(this.adminRegsActor=vl.createActor(Tl,{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`)}},Dl={Z_INDEX:999999,BACKGROUND:`rgba(0, 0, 0, 0.7)`},Ol={OVERLAY_FADE_IN_MS:200,PANEL_OPEN_MS:300,PANEL_CLOSE_MS:200,OVERLAY_FADE_OUT_DELAY_MS:50,OVERLAY_FADE_OUT_MS:150},kl=0,Al=0,jl=0;function Ml(e){e.preventDefault()}function Nl(e){e.preventDefault()}function Pl(e){e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||[`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&e.preventDefault()}function Fl(){window.scrollTo(Al,jl)}function Il(){kl===0&&(Al=window.scrollX,jl=window.scrollY,window.addEventListener(`wheel`,Ml,{passive:!1}),window.addEventListener(`touchmove`,Nl,{passive:!1}),window.addEventListener(`keydown`,Pl),window.addEventListener(`scroll`,Fl)),kl+=1}function Ll(){kl!==0&&(--kl,kl===0&&(window.removeEventListener(`wheel`,Ml),window.removeEventListener(`touchmove`,Nl),window.removeEventListener(`keydown`,Pl),window.removeEventListener(`scroll`,Fl)))}function Rl(){return window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}var zl=[`DESTINATION_REFUSED`,`INVALID_BENEFICIARY`,`NO_WALLET_AVAILABLE`,`SITE_MISMATCH`];function Bl(e){return zl.includes(e)?e:`UNKNOWN`}var Vl=class extends Error{constructor(e,t){super(t),this.name=`EmbeddedError`,this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};function Hl(e){return typeof e==`object`&&!!e&&typeof e.type==`string`&&e.type.startsWith(`pybara_embedded_`)}var Ul=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=`
|
|
3
|
+
position: fixed;
|
|
4
|
+
top: 0;
|
|
5
|
+
left: 0;
|
|
6
|
+
right: 0;
|
|
7
|
+
bottom: 0;
|
|
8
|
+
background: ${Dl.BACKGROUND};
|
|
9
|
+
z-index: ${Dl.Z_INDEX};
|
|
10
|
+
display: none;
|
|
11
|
+
align-items: center;
|
|
12
|
+
justify-content: center;
|
|
13
|
+
overscroll-behavior: none;
|
|
14
|
+
user-select: none;
|
|
15
|
+
`;let t=document.createElement(`iframe`);t.src=`${this.config.walletUrl}/pay?mode=embedded`,t.title=`Pybara Wallet`,t.style.cssText=`
|
|
16
|
+
width: 100%;
|
|
17
|
+
max-width: 500px;
|
|
18
|
+
height: 0;
|
|
19
|
+
max-height: 90vh;
|
|
20
|
+
border: none;
|
|
21
|
+
border-radius: 20px;
|
|
22
|
+
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
|
23
|
+
overscroll-behavior: none;
|
|
24
|
+
`;let n=document.createElement(`div`);n.setAttribute(`aria-hidden`,`true`),n.style.cssText=`
|
|
25
|
+
position: absolute;
|
|
26
|
+
inset: 0;
|
|
27
|
+
display: flex;
|
|
28
|
+
align-items: center;
|
|
29
|
+
justify-content: center;
|
|
30
|
+
pointer-events: none;
|
|
31
|
+
`,n.innerHTML=`
|
|
32
|
+
<svg viewBox="0 0 50 50" width="50" height="50">
|
|
33
|
+
<circle cx="25" cy="25" r="20" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-dasharray="80" stroke-dashoffset="20"/>
|
|
34
|
+
</svg>
|
|
35
|
+
`,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),this.pendingPaymentData=null)},{once:!0}),this.handleMessage=e=>{if(e.origin===this.walletOrigin&&e.source===t.contentWindow&&Hl(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 Vl(Bl(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,Rl()||t.animate([{transform:`translateY(20px)`,opacity:0},{transform:`none`,opacity:1}],{duration:Ol.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,amountUSD:e.modalData.amountUSD,reference:e.modalData.reference,context:this.config.context,...e.recurring?{recurring:e.recurring}:{},...e.sdkFields?{sdkFields:e.sdkFields}:{},...this.config.thankYouMessage?{thankYouMessage:this.config.thankYouMessage}:{}};this.iframe?.contentWindow?.postMessage(t,this.walletOrigin)}open(){this.overlay&&this.overlay.style.display!==`flex`&&(Il(),this.overlay.style.display=`flex`,Rl()||this.overlay.animate([{opacity:0},{opacity:1}],{duration:Ol.OVERLAY_FADE_IN_MS,easing:`ease`}))}show(e){this.open(),this.iframeLoaded?this.sendInitMessage(e):this.pendingPaymentData=e}renderTerminalState(e){this.close(),Il();let t=document.createElement(`div`);t.className=`pybara-checkout-overlay`,t.style.cssText=`
|
|
36
|
+
position: fixed;
|
|
37
|
+
top: 0;
|
|
38
|
+
left: 0;
|
|
39
|
+
right: 0;
|
|
40
|
+
bottom: 0;
|
|
41
|
+
background: ${Dl.BACKGROUND};
|
|
42
|
+
z-index: ${Dl.Z_INDEX};
|
|
43
|
+
display: flex;
|
|
44
|
+
align-items: center;
|
|
45
|
+
justify-content: center;
|
|
46
|
+
user-select: none;
|
|
47
|
+
`;let n=document.createElement(`div`);n.style.cssText=`
|
|
48
|
+
background: #fff;
|
|
49
|
+
border-radius: 12px;
|
|
50
|
+
color: #666;
|
|
51
|
+
padding: 2rem;
|
|
52
|
+
line-height: 1.4;
|
|
53
|
+
max-width: 360px;
|
|
54
|
+
text-align: center;
|
|
55
|
+
font-family: system-ui, sans-serif;
|
|
56
|
+
user-select: text;
|
|
57
|
+
`,n.textContent=e,t.appendChild(n),t.addEventListener(`click`,e=>{e.target===t&&(t.remove(),Ll(),this.config.onClose?.())}),document.body.appendChild(t),this.overlay=t}close(){this.handleMessage&&(window.removeEventListener(`message`,this.handleMessage),this.handleMessage=null),this.handleEscapeKey&&(document.removeEventListener(`keydown`,this.handleEscapeKey),this.handleEscapeKey=null),Ll();let e=this.overlay,t=this.iframe;if(this.overlay=null,this.iframe=null,this.spinner=null,this.iframeLoaded=!1,this.pendingPaymentData=null,this.closable=!0,e){if(e.style.display===`none`||Rl()){e.remove();return}e.style.pointerEvents=`none`,t?.animate([{transform:`scale(1)`,opacity:1},{transform:`scale(0.95)`,opacity:0}],{duration:Ol.PANEL_CLOSE_MS,easing:`ease-out`,fill:`forwards`}),e.animate([{opacity:1},{opacity:0}],{duration:Ol.OVERLAY_FADE_OUT_MS,delay:Ol.OVERLAY_FADE_OUT_DELAY_MS,easing:`ease-out`,fill:`forwards`}).finished.then(()=>e.remove(),()=>e.remove())}}},Wl={en:{"amount.customPlaceholder":`Custom amount`,"errors.minimumDonation":`Minimum donation is {{symbol}}{{amount}}`,"errors.minimumToken":`Minimum {{symbol}}{{amount}}`,"recurring.comingSoon":`Recurring donations coming soon`,"recurring.duration":`Duration`,"recurring.every2min":`Every 2 min (test)`,"recurring.frequency":`Frequency`,"recurring.monthly":`Monthly`,"recurring.months12":`12 months`,"recurring.months24":`24 months`,"recurring.months3":`3 months`,"recurring.months6":`6 months`,"recurring.notSupported":`Recurring donations are not yet supported. Please use one-time donation.`,"recurring.toggleLabel":`Make this a recurring donation`,"recurring.unlimited":`Unlimited`,"recurring.weekly":`Weekly`,"recurring.yearly":`Yearly`,"widget.cryptoPayments":`Crypto payments`,"widget.donateButton":`Donate`,"widget.donationFallbackName":`Donation`,"widget.errorGeneric":`Something went wrong. Please try again.`,"widget.footerText":`Zero fees for donors`},de:{"amount.customPlaceholder":`Eigener Betrag`,"errors.minimumDonation":`Mindestspende: {{symbol}}{{amount}}`,"errors.minimumToken":`Mindestens {{symbol}}{{amount}}`,"recurring.comingSoon":`Wiederkehrende Spenden demnächst verfügbar`,"recurring.duration":`Dauer`,"recurring.every2min":`2 Min. (Test)`,"recurring.frequency":`Häufigkeit`,"recurring.monthly":`Monatlich`,"recurring.months12":`12 Monate`,"recurring.months24":`24 Monate`,"recurring.months3":`3 Monate`,"recurring.months6":`6 Monate`,"recurring.notSupported":`Wiederkehrende Spenden sind noch nicht verfügbar. Bitte nutzen Sie die Einmalspende.`,"recurring.toggleLabel":`Als wiederkehrende Spende einrichten`,"recurring.unlimited":`Unbegrenzt`,"recurring.weekly":`Wöchentlich`,"recurring.yearly":`Jährlich`,"widget.cryptoPayments":`Krypto-Zahlungen`,"widget.donateButton":`Spenden`,"widget.donationFallbackName":`Spende`,"widget.errorGeneric":`Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.`,"widget.footerText":`Keine Gebühren für Spender`},es:{"amount.customPlaceholder":`Monto personalizado`,"errors.minimumDonation":`La donación mínima es {{symbol}}{{amount}}`,"errors.minimumToken":`Mínimo {{symbol}}{{amount}}`,"recurring.comingSoon":`Donaciones recurrentes próximamente`,"recurring.duration":`Duración`,"recurring.every2min":`2 min (prueba)`,"recurring.frequency":`Frecuencia`,"recurring.monthly":`Mensual`,"recurring.months12":`12 meses`,"recurring.months24":`24 meses`,"recurring.months3":`3 meses`,"recurring.months6":`6 meses`,"recurring.notSupported":`Las donaciones recurrentes aún no están disponibles. Por favor, use una donación única.`,"recurring.toggleLabel":`Hacer una donación recurrente`,"recurring.unlimited":`Ilimitado`,"recurring.weekly":`Semanal`,"recurring.yearly":`Anual`,"widget.cryptoPayments":`Pagos cripto`,"widget.donateButton":`Donar`,"widget.donationFallbackName":`Donación`,"widget.errorGeneric":`Algo salió mal. Por favor, inténtelo de nuevo.`,"widget.footerText":`Sin comisiones para donantes`},fr:{"amount.customPlaceholder":`Montant personnalisé`,"errors.minimumDonation":`Le don minimum est de {{symbol}}{{amount}}`,"errors.minimumToken":`Minimum {{symbol}}{{amount}}`,"recurring.comingSoon":`Dons récurrents bientôt disponibles`,"recurring.duration":`Durée`,"recurring.every2min":`2 min (test)`,"recurring.frequency":`Fréquence`,"recurring.monthly":`Mensuel`,"recurring.months12":`12 mois`,"recurring.months24":`24 mois`,"recurring.months3":`3 mois`,"recurring.months6":`6 mois`,"recurring.notSupported":`Les dons récurrents ne sont pas encore disponibles. Veuillez faire un don unique.`,"recurring.toggleLabel":`Faire un don récurrent`,"recurring.unlimited":`Illimité`,"recurring.weekly":`Hebdomadaire`,"recurring.yearly":`Annuel`,"widget.cryptoPayments":`Paiements crypto`,"widget.donateButton":`Faire un don`,"widget.donationFallbackName":`Don`,"widget.errorGeneric":`Une erreur est survenue. Veuillez réessayer.`,"widget.footerText":`Zéro frais pour les donateurs`},it:{"amount.customPlaceholder":`Importo personalizzato`,"errors.minimumDonation":`La donazione minima è di {{symbol}}{{amount}}`,"errors.minimumToken":`Minimo {{symbol}}{{amount}}`,"recurring.comingSoon":`Donazioni ricorrenti disponibili a breve`,"recurring.duration":`Durata`,"recurring.every2min":`2 min (prova)`,"recurring.frequency":`Frequenza`,"recurring.monthly":`Mensile`,"recurring.months12":`12 mesi`,"recurring.months24":`24 mesi`,"recurring.months3":`3 mesi`,"recurring.months6":`6 mesi`,"recurring.notSupported":`Le donazioni ricorrenti non sono ancora disponibili. Ti invitiamo a effettuare una donazione una tantum.`,"recurring.toggleLabel":`Effettuare una donazione ricorrente`,"recurring.unlimited":`Illimitato`,"recurring.weekly":`Settimanale`,"recurring.yearly":`Annuale`,"widget.cryptoPayments":`Pagamenti in criptovaluta`,"widget.donateButton":`Dona`,"widget.donationFallbackName":`Don`,"widget.errorGeneric":`Si è verificato un errore. Riprovare.`,"widget.footerText":`Nessuna commissione per i donatori`},ja:{"amount.customPlaceholder":`任意の金額`,"errors.minimumDonation":`寄付の最低額は {{symbol}}{{amount}} です。`,"errors.minimumToken":`最小 {{symbol}}{{amount}}`,"recurring.comingSoon":`定期寄付の受付はまもなく開始されます`,"recurring.duration":`所要時間`,"recurring.every2min":`2分ごと(テスト)`,"recurring.frequency":`周波数`,"recurring.monthly":`月次`,"recurring.months12":`12ヶ月`,"recurring.months24":`24ヶ月`,"recurring.months3":`3ヶ月`,"recurring.months6":`6ヶ月`,"recurring.notSupported":`定期的な寄付はまだ対応しておりません。一度限りの寄付をご利用ください。`,"recurring.toggleLabel":`これを定期的な寄付にする`,"recurring.unlimited":`無制限`,"recurring.weekly":`週刊`,"recurring.yearly":`年間`,"widget.cryptoPayments":`仮想通貨による支払い`,"widget.donateButton":`寄付する`,"widget.donationFallbackName":`寄付`,"widget.errorGeneric":`問題が発生しました。もう一度お試しください。`,"widget.footerText":`寄付者への手数料は一切かかりません`},ko:{"amount.customPlaceholder":`사용자 지정 금액`,"errors.minimumDonation":`최소 기부 금액은 {{symbol}}{{amount}}입니다.`,"errors.minimumToken":`최소 {{symbol}}{{amount}}`,"recurring.comingSoon":`정기 기부 서비스가 곧 시작됩니다`,"recurring.duration":`기간`,"recurring.every2min":`2분마다 (테스트)`,"recurring.frequency":`주파수`,"recurring.monthly":`월간`,"recurring.months12":`12개월`,"recurring.months24":`24개월`,"recurring.months3":`3개월`,"recurring.months6":`6개월`,"recurring.notSupported":`정기 기부 기능은 아직 지원되지 않습니다. 일회성 기부를 이용해 주시기 바랍니다.`,"recurring.toggleLabel":`이 기부를 정기 기부로 설정하기`,"recurring.unlimited":`무제한`,"recurring.weekly":`주간`,"recurring.yearly":`연간`,"widget.cryptoPayments":`암호화폐 결제`,"widget.donateButton":`기부하기`,"widget.donationFallbackName":`기부`,"widget.errorGeneric":`문제가 발생했습니다. 다시 시도해 주세요.`,"widget.footerText":`기부자에게는 수수료가 전혀 없습니다`},nl:{"amount.customPlaceholder":`Aangepast bedrag`,"errors.minimumDonation":`De minimale donatie bedraagt {{symbol}}{{amount}}`,"errors.minimumToken":`Minimum {{symbol}}{{amount}}`,"recurring.comingSoon":`Terugkerende donaties volgen binnenkort`,"recurring.duration":`Duur`,"recurring.every2min":`Om de 2 minuten (test)`,"recurring.frequency":`Frequentie`,"recurring.monthly":`Maandelijks`,"recurring.months12":`12 maanden`,"recurring.months24":`24 maanden`,"recurring.months3":`3 maanden`,"recurring.months6":`6 maanden`,"recurring.notSupported":`Terugkerende donaties worden nog niet ondersteund. Maak alstublieft gebruik van de eenmalige donatie.`,"recurring.toggleLabel":`Maak hier een periodieke donatie van`,"recurring.unlimited":`Onbeperkt`,"recurring.weekly":`Wekelijks`,"recurring.yearly":`Jaarlijks`,"widget.cryptoPayments":`Cryptovaluta-betalingen`,"widget.donateButton":`Doneren`,"widget.donationFallbackName":`Donatie`,"widget.errorGeneric":`Er is een fout opgetreden. Probeer het nog eens.`,"widget.footerText":`Geen kosten voor donateurs`},pl:{"amount.customPlaceholder":`Indywidualna kwota`,"errors.minimumDonation":`Minimalna kwota darowizny wynosi {{symbol}}{{amount}}`,"errors.minimumToken":`Minimum {{symbol}}{{amount}}`,"recurring.comingSoon":`Wkrótce dostępne będą darowizny cykliczne`,"recurring.duration":`Czas trwania`,"recurring.every2min":`2 min (test)`,"recurring.frequency":`Częstotliwość`,"recurring.monthly":`Miesięcznik`,"recurring.months12":`12 miesięcy`,"recurring.months24":`24 miesiące`,"recurring.months3":`3 miesiące`,"recurring.months6":`6 miesięcy`,"recurring.notSupported":`Powtarzające się darowizny nie są jeszcze dostępne. Prosimy o przekazanie jednorazowej darowizny.`,"recurring.toggleLabel":`Wpłacać regularne darowizny`,"recurring.unlimited":`Nieograniczony`,"recurring.weekly":`Tygodnik`,"recurring.yearly":`Roczny`,"widget.cryptoPayments":`Płatności kryptowalutowe`,"widget.donateButton":`Przekaż darowiznę`,"widget.donationFallbackName":`Dar`,"widget.errorGeneric":`Wystąpił błąd. Spróbuj ponownie.`,"widget.footerText":`Zero opłat dla darczyńców`},pt:{"amount.customPlaceholder":`Montante personalizado`,"errors.minimumDonation":`A doação mínima é de {{symbol}}{{amount}}`,"errors.minimumToken":`Mínimo {{symbol}}{{amount}}`,"recurring.comingSoon":`Doações recorrentes disponíveis em breve`,"recurring.duration":`Duração`,"recurring.every2min":`2 min (teste)`,"recurring.frequency":`Frequência`,"recurring.monthly":`Mensal`,"recurring.months12":`12 meses`,"recurring.months24":`24 meses`,"recurring.months3":`3 meses`,"recurring.months6":`6 meses`,"recurring.notSupported":`As doações recorrentes ainda não estão disponíveis. Por favor, faça uma doação única.`,"recurring.toggleLabel":`Fazer um donativo recorrente`,"recurring.unlimited":`Ilimitado`,"recurring.weekly":`Semanal`,"recurring.yearly":`Anual`,"widget.cryptoPayments":`Pagamentos com criptomoedas`,"widget.donateButton":`Doar`,"widget.donationFallbackName":`Don`,"widget.errorGeneric":`Ocorreu um erro. Por favor, tente novamente.`,"widget.footerText":`Sem custos para os doadores`},ro:{"amount.customPlaceholder":`Suma personalizată`,"errors.minimumDonation":`Donația minimă este de {{symbol}}{{amount}}`,"errors.minimumToken":`Minim {{symbol}}{{amount}}`,"recurring.comingSoon":`Donațiile recurente vor fi disponibile în curând`,"recurring.duration":`Durată`,"recurring.every2min":`2 min (test)`,"recurring.frequency":`Frecvență`,"recurring.monthly":`Lunar`,"recurring.months12":`12 luni`,"recurring.months24":`24 de luni`,"recurring.months3":`3 luni`,"recurring.months6":`6 luni`,"recurring.notSupported":`Donațiile recurente nu sunt încă disponibile. Vă rugăm să efectuați o donație unică.`,"recurring.toggleLabel":`A face o donație periodică`,"recurring.unlimited":`Nelimitat`,"recurring.weekly":`Săptămânal`,"recurring.yearly":`Anual`,"widget.cryptoPayments":`Plăți cu criptomonede`,"widget.donateButton":`Donează`,"widget.donationFallbackName":`Don`,"widget.errorGeneric":`A apărut o eroare. Vă rugăm să încercați din nou.`,"widget.footerText":`Fără comisioane pentru donatori`},"zh-CN":{"amount.customPlaceholder":`自定义金额`,"errors.minimumDonation":`最低捐赠金额为 {{symbol}}{{amount}}`,"errors.minimumToken":`最小值 {{symbol}}{{amount}}`,"recurring.comingSoon":`定期捐款功能即将上线`,"recurring.duration":`时长`,"recurring.every2min":`每2分钟(测试)`,"recurring.frequency":`频率`,"recurring.monthly":`每月`,"recurring.months12":`12个月`,"recurring.months24":`24个月`,"recurring.months3":`3个月`,"recurring.months6":`6个月`,"recurring.notSupported":`目前尚不支持定期捐赠。请选择一次性捐赠。`,"recurring.toggleLabel":`将此设为定期捐款`,"recurring.unlimited":`无限`,"recurring.weekly":`每周`,"recurring.yearly":`每年`,"widget.cryptoPayments":`加密货币支付`,"widget.donateButton":`捐赠`,"widget.donationFallbackName":`捐赠`,"widget.errorGeneric":`出现了一些问题。请重试。`,"widget.footerText":`捐赠者无需支付任何费用`}},Gl={};Object.keys(Wl);function Kl(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.split(`.`),i=t;for(let t=0;t<e.length-1;t++){let n=e[t];(i[n]==null||typeof i[n]!=`object`)&&(i[n]={}),i=i[n]}i[e[e.length-1]]=r}return t}function ql(e){if(Gl[e])return Gl[e];let t=Kl(Wl[e]??Wl.en);return Gl[e]=t,t}function Jl(e){let t=e.toLowerCase();return t.startsWith(`zh`)?t:t.split(`-`)[0]}function Yl(){return Jl(navigator?.languages?.[0]||navigator?.language||`en`)}function Xl(e){let t=Jl(e||Yl());return ql(Wl[t]?t:`en`)}function Zl(e,t={}){return e.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]??e)}var Ql=[5,10,25,50],$l=[`light`,`dark`,`auto`],eu={USD:`$`,EUR:`€`,GBP:`£`,CAD:`CA$`,AUD:`A$`,CHF:`CHF`,JPY:`¥`,CNY:`¥`,BRL:`R$`,MXN:`MX$`,INR:`₹`,KRW:`₩`,SEK:`kr`,NOK:`kr`,DKK:`kr`,PLN:`zł`,CZK:`Kč`,HUF:`Ft`,TRY:`₺`,ZAR:`R`,NZD:`NZ$`,SGD:`S$`,HKD:`HK$`,TWD:`NT$`,THB:`฿`,PHP:`₱`,ILS:`₪`,AED:`AED`,SAR:`SAR`,NGN:`₦`,KES:`KSh`,COP:`COL$`,ARS:`ARS$`,CLP:`CLP$`,PEN:`S/`};function tu(e){return eu[e.toUpperCase()]||e}var nu=[`ckUSDC`,`ckUSDT`,`ckBTC`,`ckETH`,`ICP`],ru=[`weekly`,`monthly`,`yearly`,`every2min`],iu=[3,6,12,24],au={every2min:120,weekly:604800,monthly:2592e3,yearly:31536e3},ou=2592e3,su=.5;function cu(e){if(!e.target)throw Error(`[pybara-donate] "target" is required`);if(!e.recipientPrincipal)throw Error(`[pybara-donate] "recipientPrincipal" is required`);if(!e.siteUrl)throw Error(`[pybara-donate] "siteUrl" is required`);if(!e.siteName)throw Error(`[pybara-donate] "siteName" is required`);let t=e.presetAmounts??Ql;if(t.length>6)throw Error(`[pybara-donate] Maximum 6 preset amounts allowed`);if(t.some(e=>e<.5))throw Error(`[pybara-donate] Preset amounts must be >= $${su}`);let n=e.defaultFrequency??`monthly`;if(!ru.includes(n))throw Error(`[pybara-donate] Invalid frequency: ${n}`);let r=e.theme??`light`;if(!$l.includes(r))throw Error(`[pybara-donate] Invalid theme: ${r}. Valid values: ${$l.join(`, `)}`);let i=e.defaultDurationInMonths,a=i===null?null:i===void 0?12:Number(i);if(a!==null&&!iu.includes(a))throw Error(`[pybara-donate] Invalid duration: ${a}. Valid values: ${iu.join(`, `)}`);return{target:e.target,recipientPrincipal:e.recipientPrincipal,siteUrl:e.siteUrl,siteName:e.siteName,presetAmounts:t,allowCustom:e.allowCustom??!0,allowRecurring:e.allowRecurring??!0,defaultFrequency:n,defaultDurationInMonths:a,tokens:e.tokens??nu,buttonLabel:e.buttonLabel??Xl(e.locale).widget.donateButton,primaryColor:e.primaryColor??`#7c3aed`,theme:r,currency:(e.currency??`USD`).toUpperCase(),debug:e.debug??!1,staging:e.staging??!1,title:e.title,description:e.description,thankYouMessage:e.thankYouMessage,thankYouRedirectUrl:e.thankYouRedirectUrl,locale:e.locale,onSuccess:e.onSuccess,onError:e.onError,onClose:e.onClose,fontUrl:e.fontUrl}}var lu=class{constructor(e){this.selectedPreset=null,this.customValue=``,this.container=null,this.config=e}render(){let e=document.createElement(`div`);e.className=`pybara-donate__amounts-section`;let t=document.createElement(`div`);t.className=`pybara-donate__amounts`;for(let e of this.config.presetAmounts){let n=document.createElement(`button`);n.type=`button`,n.className=`pybara-donate__amount-btn`,n.textContent=`${this.config.currencySymbol}${e}`,n.dataset.amount=String(e),n.addEventListener(`click`,()=>{this.selectPreset(e)}),t.appendChild(n)}if(e.appendChild(t),this.config.allowCustom){let t=document.createElement(`div`);t.className=`pybara-donate__custom`;let n=document.createElement(`div`);n.className=`pybara-donate__custom-input-wrap`;let r=document.createElement(`span`);r.className=`pybara-donate__custom-prefix`,r.textContent=this.config.currencySymbol;let i=document.createElement(`input`);i.type=`number`,i.className=`pybara-donate__custom-input`,i.placeholder=this.config.customPlaceholder,i.min=String(su),i.step=`0.01`,i.addEventListener(`input`,()=>{if(this.customValue=i.value,this.customValue){this.clearPresetSelection();let e=parseFloat(this.customValue);this.config.onAmountChange(Number.isNaN(e)||e<.5?null:e)}else this.config.onAmountChange(null)}),i.addEventListener(`focus`,()=>{this.clearPresetSelection()}),n.appendChild(r),n.appendChild(i),t.appendChild(n),e.appendChild(t)}return this.container=e,e}selectPreset(e){if(this.selectedPreset=e,this.customValue=``,this.container){this.container.querySelectorAll(`.pybara-donate__amount-btn`).forEach(t=>{let n=t;n.dataset.amount===String(e)?n.classList.add(`pybara-donate__amount-btn--selected`):n.classList.remove(`pybara-donate__amount-btn--selected`)});let t=this.container.querySelector(`.pybara-donate__custom-input`);t&&(t.value=``)}this.config.onAmountChange(e)}clearPresetSelection(){this.selectedPreset=null,this.container&&this.container.querySelectorAll(`.pybara-donate__amount-btn`).forEach(e=>{e.classList.remove(`pybara-donate__amount-btn--selected`)})}getAmount(){if(this.selectedPreset!==null)return this.selectedPreset;if(this.customValue){let e=parseFloat(this.customValue);return Number.isNaN(e)||e<.5?null:e}return null}},uu=class{constructor(e){this.enabled=!1,this.container=null,this.optionsEl=null,this.config=e,this.frequency=e.defaultFrequency,this.duration_in_months=e.defaultIsUnlimited?void 0:e.defaultDurationInMonths,this.is_unlimited=e.defaultIsUnlimited}render(){let e=document.createElement(`div`);e.className=`pybara-donate__recurring`;let t=document.createElement(`label`);t.className=`pybara-donate__recurring-toggle`;let n=document.createElement(`input`);n.type=`checkbox`,n.checked=this.enabled,n.addEventListener(`change`,()=>{this.enabled=n.checked,this.updateOptionsVisibility(),this.emitChange()});let r=document.createElement(`span`);r.className=`pybara-donate__recurring-label`,r.textContent=this.config.strings.toggleLabel,t.appendChild(n),t.appendChild(r),e.appendChild(t);let i=document.createElement(`div`);i.className=`pybara-donate__recurring-options`,i.style.display=`none`;let a=this.config.strings,o={weekly:a.weekly,monthly:a.monthly,yearly:a.yearly,every2min:a.every2min},s={3:a.months3,6:a.months6,12:a.months12,24:a.months24,unlimited:a.unlimited},c=[...iu.map(e=>({value:String(e),label:s[String(e)]})),{value:`unlimited`,label:s.unlimited}],l=this.is_unlimited?`unlimited`:String(this.duration_in_months);return i.appendChild(this.createPillRow(a.frequency,ru.map(e=>({value:e,label:o[e]})),this.frequency,e=>{this.frequency=e,this.emitChange()})),i.appendChild(this.createPillRow(a.duration,c,l,e=>{e===`unlimited`?(this.is_unlimited=!0,this.duration_in_months=void 0):(this.is_unlimited=!1,this.duration_in_months=Number(e)),this.emitChange()})),e.appendChild(i),this.optionsEl=i,this.container=e,e}createPillRow(e,t,n,r){let i=document.createElement(`div`);i.className=`pybara-donate__recurring-row`;let a=document.createElement(`div`);a.className=`pybara-donate__recurring-row-label`,a.textContent=e,i.appendChild(a);let o=document.createElement(`div`);o.className=`pybara-donate__pill-group`;for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`pybara-donate__pill`,t.textContent=e.label,t.dataset.value=e.value,e.value===n&&t.classList.add(`pybara-donate__pill--selected`),t.addEventListener(`click`,()=>{o.querySelectorAll(`.pybara-donate__pill`).forEach(e=>{e.classList.remove(`pybara-donate__pill--selected`)}),t.classList.add(`pybara-donate__pill--selected`),r(e.value)}),o.appendChild(t)}return i.appendChild(o),i}updateOptionsVisibility(){this.optionsEl&&(this.optionsEl.style.display=this.enabled?`flex`:`none`)}emitChange(){this.config.onChange({enabled:this.enabled,frequency:this.frequency,duration_in_months:this.duration_in_months,is_unlimited:this.is_unlimited})}hide(){this.container&&(this.container.style.display=`none`),this.enabled=!1,this.emitChange()}show(){this.container&&(this.container.style.display=`block`)}getConfig(){return{enabled:this.enabled,frequency:this.frequency,duration_in_months:this.duration_in_months,is_unlimited:this.is_unlimited}}},du=`
|
|
58
|
+
:host {
|
|
59
|
+
display: block;
|
|
60
|
+
font-family: 'Pybara Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; /* Outfit, SIL OFL 1.1 — see assets/fonts/OFL.txt */
|
|
61
|
+
font-weight: 400;
|
|
62
|
+
color: var(--pybara-donate-text);
|
|
63
|
+
outline: transparent;
|
|
64
|
+
line-height: 1.5;
|
|
65
|
+
-webkit-font-smoothing: antialiased;
|
|
66
|
+
|
|
67
|
+
/* Neutral palette (light — overridden in dark theme block) */
|
|
68
|
+
--pybara-donate-surface: #ffffff;
|
|
69
|
+
--pybara-donate-panel: #f9fafb;
|
|
70
|
+
--pybara-donate-border: #e5e7eb;
|
|
71
|
+
--pybara-donate-border-strong: #d1d5db;
|
|
72
|
+
--pybara-donate-text: #1a1a2e;
|
|
73
|
+
--pybara-donate-text-mid: #374151;
|
|
74
|
+
--pybara-donate-text-soft: #6b7280;
|
|
75
|
+
--pybara-donate-text-faint: #9ca3af;
|
|
76
|
+
--pybara-donate-error-bg: #fef2f2;
|
|
77
|
+
--pybara-donate-error-border: #fecaca;
|
|
78
|
+
--pybara-donate-error-text: #dc2626;
|
|
79
|
+
--pybara-donate-token-bg: #f3f4f6;
|
|
80
|
+
--pybara-donate-token-ring: #ffffff;
|
|
81
|
+
|
|
82
|
+
/* Primary-derived (mix base updated to surface) */
|
|
83
|
+
--pybara-donate-primary: #7c3aed;
|
|
84
|
+
--pybara-donate-primary-dark: color-mix(in srgb, var(--pybara-donate-primary) 85%, #000);
|
|
85
|
+
--pybara-donate-primary-light: color-mix(in srgb, var(--pybara-donate-primary-strong) 50%, var(--pybara-donate-surface));
|
|
86
|
+
--pybara-donate-primary-bg: color-mix(in srgb, var(--pybara-donate-primary-strong) 8%, var(--pybara-donate-surface));
|
|
87
|
+
--pybara-donate-primary-bg-hover: color-mix(in srgb, var(--pybara-donate-primary-strong) 5%, var(--pybara-donate-surface));
|
|
88
|
+
|
|
89
|
+
/* Phase 2 fallbacks (overwritten by JS when primaryColor is hex) */
|
|
90
|
+
--pybara-donate-contrast: #ffffff;
|
|
91
|
+
--pybara-donate-primary-strong: var(--pybara-donate-primary);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
* {
|
|
95
|
+
box-sizing: border-box;
|
|
96
|
+
margin: 0;
|
|
97
|
+
padding: 0;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
.pybara-donate {
|
|
101
|
+
max-width: 420px;
|
|
102
|
+
padding: 24px;
|
|
103
|
+
border-radius: 16px;
|
|
104
|
+
background: var(--pybara-donate-surface);
|
|
105
|
+
border: 1px solid var(--pybara-donate-border);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/* Title & Description */
|
|
109
|
+
.pybara-donate__intro {
|
|
110
|
+
margin-bottom: 20px;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
.pybara-donate__title {
|
|
114
|
+
font-size: 20px;
|
|
115
|
+
font-weight: 700;
|
|
116
|
+
color: var(--pybara-donate-text);
|
|
117
|
+
margin-bottom: 4px;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
.pybara-donate__description {
|
|
121
|
+
font-size: 14px;
|
|
122
|
+
color: var(--pybara-donate-text-soft);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/* Amount Grid */
|
|
126
|
+
.pybara-donate__amounts {
|
|
127
|
+
display: flex;
|
|
128
|
+
gap: 8px;
|
|
129
|
+
margin-bottom: 16px;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
.pybara-donate__amounts > * {
|
|
133
|
+
flex: 1 1 0;
|
|
134
|
+
min-width: 0;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
.pybara-donate__amount-btn {
|
|
138
|
+
display: flex;
|
|
139
|
+
align-items: center;
|
|
140
|
+
justify-content: center;
|
|
141
|
+
padding: 12px 4px;
|
|
142
|
+
border: 2px solid var(--pybara-donate-border);
|
|
143
|
+
border-radius: 10px;
|
|
144
|
+
background: var(--pybara-donate-surface);
|
|
145
|
+
font-family: inherit;
|
|
146
|
+
font-size: clamp(13px, 3.5vw, 16px);
|
|
147
|
+
white-space: nowrap;
|
|
148
|
+
overflow: hidden;
|
|
149
|
+
text-overflow: ellipsis;
|
|
150
|
+
font-weight: 600;
|
|
151
|
+
color: var(--pybara-donate-text);
|
|
152
|
+
cursor: pointer;
|
|
153
|
+
transition: all 0.15s ease;
|
|
154
|
+
user-select: none;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
.pybara-donate__amount-btn:hover {
|
|
158
|
+
border-color: var(--pybara-donate-primary-light);
|
|
159
|
+
background: var(--pybara-donate-primary-bg-hover);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
.pybara-donate__amount-btn--selected {
|
|
163
|
+
border-color: var(--pybara-donate-primary-strong);
|
|
164
|
+
background: var(--pybara-donate-primary-bg);
|
|
165
|
+
color: var(--pybara-donate-primary-strong);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/* Custom Amount Input */
|
|
169
|
+
.pybara-donate__custom {
|
|
170
|
+
margin-bottom: 16px;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
.pybara-donate__custom-input-wrap {
|
|
174
|
+
position: relative;
|
|
175
|
+
display: flex;
|
|
176
|
+
align-items: center;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
.pybara-donate__custom-prefix {
|
|
180
|
+
position: absolute;
|
|
181
|
+
left: 14px;
|
|
182
|
+
font-size: 16px;
|
|
183
|
+
font-weight: 500;
|
|
184
|
+
color: var(--pybara-donate-text-soft);
|
|
185
|
+
pointer-events: none;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
.pybara-donate__custom-input {
|
|
189
|
+
width: 100%;
|
|
190
|
+
padding: 12px 14px 12px 28px;
|
|
191
|
+
border: 2px solid var(--pybara-donate-border);
|
|
192
|
+
border-radius: 10px;
|
|
193
|
+
font-family: inherit;
|
|
194
|
+
font-size: 16px;
|
|
195
|
+
color: var(--pybara-donate-text);
|
|
196
|
+
background: var(--pybara-donate-surface);
|
|
197
|
+
outline: none;
|
|
198
|
+
transition: border-color 0.15s ease;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
.pybara-donate__custom-input:focus {
|
|
202
|
+
border-color: var(--pybara-donate-primary-strong);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
.pybara-donate__custom-input::placeholder {
|
|
206
|
+
color: var(--pybara-donate-text-faint);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/* Recurring Section */
|
|
210
|
+
.pybara-donate__recurring {
|
|
211
|
+
margin-bottom: 20px;
|
|
212
|
+
padding: 16px;
|
|
213
|
+
border-radius: 10px;
|
|
214
|
+
background: var(--pybara-donate-panel);
|
|
215
|
+
border: 1px solid var(--pybara-donate-border);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
.pybara-donate__recurring-toggle {
|
|
219
|
+
display: flex;
|
|
220
|
+
align-items: center;
|
|
221
|
+
gap: 10px;
|
|
222
|
+
cursor: pointer;
|
|
223
|
+
user-select: none;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
.pybara-donate__recurring-toggle input[type="checkbox"] {
|
|
227
|
+
appearance: none;
|
|
228
|
+
-webkit-appearance: none;
|
|
229
|
+
width: 20px;
|
|
230
|
+
height: 20px;
|
|
231
|
+
border: 2px solid var(--pybara-donate-border-strong);
|
|
232
|
+
border-radius: 5px;
|
|
233
|
+
background: var(--pybara-donate-surface);
|
|
234
|
+
cursor: pointer;
|
|
235
|
+
position: relative;
|
|
236
|
+
flex-shrink: 0;
|
|
237
|
+
transition: all 0.15s ease;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
.pybara-donate__recurring-toggle input[type="checkbox"]:checked {
|
|
241
|
+
background: var(--pybara-donate-primary);
|
|
242
|
+
border-color: var(--pybara-donate-primary);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
.pybara-donate__recurring-toggle input[type="checkbox"]:checked::after {
|
|
246
|
+
content: '';
|
|
247
|
+
position: absolute;
|
|
248
|
+
left: 5px;
|
|
249
|
+
top: 1px;
|
|
250
|
+
width: 6px;
|
|
251
|
+
height: 11px;
|
|
252
|
+
border: solid var(--pybara-donate-contrast);
|
|
253
|
+
border-width: 0 2px 2px 0;
|
|
254
|
+
transform: rotate(45deg);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
.pybara-donate__recurring-label {
|
|
258
|
+
font-size: 14px;
|
|
259
|
+
font-weight: 500;
|
|
260
|
+
color: var(--pybara-donate-text-mid);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
.pybara-donate__recurring-options {
|
|
264
|
+
margin-top: 14px;
|
|
265
|
+
display: flex;
|
|
266
|
+
flex-direction: column;
|
|
267
|
+
gap: 12px;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
.pybara-donate__recurring-row {
|
|
271
|
+
display: flex;
|
|
272
|
+
flex-direction: column;
|
|
273
|
+
gap: 4px;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
.pybara-donate__recurring-row-label {
|
|
277
|
+
font-size: 12px;
|
|
278
|
+
font-weight: 500;
|
|
279
|
+
color: var(--pybara-donate-text-soft);
|
|
280
|
+
text-transform: uppercase;
|
|
281
|
+
letter-spacing: 0.05em;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
.pybara-donate__pill-group {
|
|
285
|
+
display: flex;
|
|
286
|
+
flex-wrap: wrap;
|
|
287
|
+
gap: 6px;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
.pybara-donate__pill {
|
|
291
|
+
padding: 6px 14px;
|
|
292
|
+
border: 1.5px solid var(--pybara-donate-border);
|
|
293
|
+
border-radius: 20px;
|
|
294
|
+
background: var(--pybara-donate-surface);
|
|
295
|
+
font-family: inherit;
|
|
296
|
+
font-size: 13px;
|
|
297
|
+
font-weight: 500;
|
|
298
|
+
color: var(--pybara-donate-text-mid);
|
|
299
|
+
cursor: pointer;
|
|
300
|
+
transition: all 0.15s ease;
|
|
301
|
+
user-select: none;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
.pybara-donate__pill:hover {
|
|
305
|
+
border-color: var(--pybara-donate-primary-light);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
.pybara-donate__pill--selected {
|
|
309
|
+
border-color: var(--pybara-donate-primary-strong);
|
|
310
|
+
background: var(--pybara-donate-primary-bg);
|
|
311
|
+
color: var(--pybara-donate-primary-strong);
|
|
312
|
+
font-weight: 600;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/* Donate Button */
|
|
316
|
+
.pybara-donate__submit {
|
|
317
|
+
width: 100%;
|
|
318
|
+
padding: 14px 24px;
|
|
319
|
+
border: none;
|
|
320
|
+
border-radius: 10px;
|
|
321
|
+
background: var(--pybara-donate-primary);
|
|
322
|
+
font-family: inherit;
|
|
323
|
+
font-size: 16px;
|
|
324
|
+
font-weight: 600;
|
|
325
|
+
color: var(--pybara-donate-contrast);
|
|
326
|
+
cursor: pointer;
|
|
327
|
+
transition: all 0.15s ease;
|
|
328
|
+
letter-spacing: 0.01em;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
.pybara-donate__submit:hover:not(:disabled) {
|
|
332
|
+
background: var(--pybara-donate-primary-dark);
|
|
333
|
+
transform: translateY(1px);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
.pybara-donate__submit:active:not(:disabled) {
|
|
337
|
+
transform: translateY(0);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
.pybara-donate__submit:disabled {
|
|
341
|
+
opacity: 0.5;
|
|
342
|
+
cursor: not-allowed;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/* Error Message */
|
|
346
|
+
.pybara-donate__error {
|
|
347
|
+
margin-top: 8px;
|
|
348
|
+
padding: 8px 12px;
|
|
349
|
+
border-radius: 8px;
|
|
350
|
+
background: var(--pybara-donate-error-bg);
|
|
351
|
+
border: 1px solid var(--pybara-donate-error-border);
|
|
352
|
+
font-size: 13px;
|
|
353
|
+
color: var(--pybara-donate-error-text);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/* Footer */
|
|
357
|
+
.pybara-donate__footer {
|
|
358
|
+
display: flex;
|
|
359
|
+
align-items: center;
|
|
360
|
+
justify-content: space-between;
|
|
361
|
+
margin-top: 16px;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
.pybara-donate__footer-brand {
|
|
365
|
+
display: flex;
|
|
366
|
+
align-items: center;
|
|
367
|
+
gap: 6px;
|
|
368
|
+
text-decoration: none;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
.pybara-donate__footer-logo {
|
|
372
|
+
flex-shrink: 0;
|
|
373
|
+
height: 22px;
|
|
374
|
+
width: auto;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
.pybara-donate__footer-logo svg {
|
|
378
|
+
height: 100%;
|
|
379
|
+
width: auto;
|
|
380
|
+
display: block;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
.pybara-donate__footer-brand-text {
|
|
384
|
+
display: flex;
|
|
385
|
+
flex-direction: column;
|
|
386
|
+
gap: 1px;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
.pybara-donate__footer-brand-text strong {
|
|
390
|
+
display: block;
|
|
391
|
+
font-size: 11px;
|
|
392
|
+
font-weight: 700;
|
|
393
|
+
color: var(--pybara-donate-text);
|
|
394
|
+
line-height: 1;
|
|
395
|
+
user-select: none;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
.pybara-donate__footer-brand-text span {
|
|
399
|
+
font-size: 9px;
|
|
400
|
+
color: var(--pybara-donate-text-faint);
|
|
401
|
+
line-height: 1;
|
|
402
|
+
user-select: none;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/* Token stack */
|
|
406
|
+
.pybara-donate__footer-tokens {
|
|
407
|
+
display: flex;
|
|
408
|
+
align-items: center;
|
|
409
|
+
filter: grayscale(1);
|
|
410
|
+
transition: filter .15s ease;
|
|
411
|
+
}
|
|
412
|
+
.pybara-donate__footer-tokens:hover {
|
|
413
|
+
filter: grayscale(0);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
.pybara-donate__footer-token {
|
|
417
|
+
border-radius: 50%;
|
|
418
|
+
border: 1.5px solid var(--pybara-donate-token-ring);
|
|
419
|
+
overflow: hidden;
|
|
420
|
+
flex-shrink: 0;
|
|
421
|
+
margin-left: -6.5px;
|
|
422
|
+
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12);
|
|
423
|
+
background: var(--pybara-donate-token-bg);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
.pybara-donate__footer-token:first-child {
|
|
427
|
+
margin-left: 0;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
.pybara-donate__footer-token img {
|
|
431
|
+
object-fit: cover;
|
|
432
|
+
display: block;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/* ── Dark theme ── */
|
|
436
|
+
/* Surface #1c222a = rgb(28,34,42) — must stay in sync with widget.ts surface literal */
|
|
437
|
+
:host([data-theme="dark"]) {
|
|
438
|
+
--pybara-donate-surface: #1c222a;
|
|
439
|
+
--pybara-donate-panel: #232b34;
|
|
440
|
+
--pybara-donate-border: #2b333d;
|
|
441
|
+
--pybara-donate-border-strong: #3a4450;
|
|
442
|
+
--pybara-donate-text: #eef1f4;
|
|
443
|
+
--pybara-donate-text-mid: #c6cdd4;
|
|
444
|
+
--pybara-donate-text-soft: #8d97a1;
|
|
445
|
+
--pybara-donate-text-faint: #6d7883;
|
|
446
|
+
--pybara-donate-error-bg: #2a1a1c;
|
|
447
|
+
--pybara-donate-error-border: #5c2b30;
|
|
448
|
+
--pybara-donate-error-text: #f0868f;
|
|
449
|
+
--pybara-donate-token-bg: #2b333d;
|
|
450
|
+
--pybara-donate-token-ring: #1c222a; /* ring matches surface so stack overlap reads */
|
|
451
|
+
--pybara-donate-primary-bg: color-mix(in srgb, var(--pybara-donate-primary-strong) 14%, var(--pybara-donate-surface));
|
|
452
|
+
--pybara-donate-primary-bg-hover: color-mix(in srgb, var(--pybara-donate-primary-strong) 9%, var(--pybara-donate-surface));
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
`;function fu(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 pu(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status} from ${e}`);return await t.json()}async function mu(e,t,n,r){let i=Pe[e],a=`https://${i.admin_core}.raw.icp0.io/widget-config`,o=`https://${i.admin_regs}.raw.icp0.io/widget-terms?site_url=${encodeURIComponent(t)}&principal=${encodeURIComponent(n)}`,s,c;try{[s,c]=await Promise.all([pu(a),pu(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[r.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)`}:fu(c.version,`1-0`)?{show:!0,recurring:l[r.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`}}function hu(e){if(typeof e!=`string`)return null;let t=e.trim();if(t.length===4&&t[0]===`#`){let e=parseInt(t[1]+t[1],16),n=parseInt(t[2]+t[2],16),r=parseInt(t[3]+t[3],16);return Number.isNaN(e)||Number.isNaN(n)||Number.isNaN(r)?null:[e,n,r]}if(t.length===7&&t[0]===`#`){let e=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),r=parseInt(t.slice(5,7),16);return Number.isNaN(e)||Number.isNaN(n)||Number.isNaN(r)?null:[e,n,r]}return null}function gu([e,t,n]){let r=e=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4};return .2126*r(e)+.7152*r(t)+.0722*r(n)}function _u(e,t){let n=gu(e),r=gu(t),i=Math.max(n,r),a=Math.min(n,r);return(i+.05)/(a+.05)}function vu(e,t,n){return[Math.round(e[0]+(t[0]-e[0])*n),Math.round(e[1]+(t[1]-e[1])*n),Math.round(e[2]+(t[2]-e[2])*n)]}function yu(e,t,n){let r=e;for(let i=1;i<=20;i++){if(_u(r,t)>=3)return r;r=vu(e,n,i*.05)}return r}function bu(e){return gu(e)<=.45?`#ffffff`:`#1a1a2e`}function xu(e){if(!e||e===`transparent`)return null;let t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);return!t||t[4]!==void 0&&parseFloat(t[4])===0?null:[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)]}function Su(e,t,n){let r=hu(t);if(!r)return;let i=n===`dark`?[28,34,42]:[255,255,255],a=n===`dark`?[255,255,255]:[26,26,46];e.style.setProperty(`--pybara-donate-contrast`,bu(r));let o=yu(r,i,a);e.style.setProperty(`--pybara-donate-primary-strong`,`rgb(${o[0]}, ${o[1]}, ${o[2]})`)}function Cu(e){let t=e;for(;t;){let e=getComputedStyle(t).backgroundColor,n=xu(e);if(n)return gu(n)<.4?`dark`:`light`;t=t.parentElement}return null}var wu={widget:`widget-donate`,recurring:`widget-donate-recurring`};function Tu(e,t,n){if(t||e===void 0)return 0;let r=au[n]??2592e3;return Math.ceil(e*ou/r)}function Eu(){let e=crypto.getRandomValues(new Uint8Array(16));return btoa(String.fromCharCode(...e))}var Du=`Pybara Sans`;async function Ou(e){if(e&&typeof FontFace<`u`){for(let e of document.fonts)if(e.family===Du)return;try{let t=new FontFace(Du,`url(${e}) format('woff2')`,{weight:`100 900`,style:`normal`,display:`swap`});await t.load(),document.fonts.add(t)}catch{}}}var ku=`<svg xmlns="http://www.w3.org/2000/svg" width="949.4" height="1000" viewBox="0 0 949.4 1000"><path fill="#fff" d="M849.6,223c-28.4-2.2-56.7-4-85.5.2-25.8,3.8-47.2,16.3-62.1,37s-6.2,16-9,23.9c-5.5,15.9-3.6,33,2.7,48.8,4.3,10.9,12.9,13.9,19.5,20.6,31.9,32.5,62.1,2.8,99.8-1.7.7,5.8-.9,11.2-2.1,16.4-9.8,40.6-26.6,79.1-53.6,111.9-16.3,19.8-34.7,36.4-57.7,47.4-22.4,10.8-38.5-9.3-53.9-22.2-.8,9.1-5.1,14.2-12.8,16.5-71.4,21.1-138,38-198.1,83.9-17.7,13.5-33.1,27.3-47.7,44.1-56.9,65.4-86.1,148.8-84,236.3-25.6-10.5-47.5-24.5-68.8-39.6-123.4-87.6-182.8-240.3-154.2-388.7,14.8-76.9,49.6-148.7,102.4-206.1,1.2,19.1,1.4,38.1.2,58.3,9.4-11.2,66.2-61.2,68.4-65.3l2.6-4.9c31.9-32.4,35.8-85.6,10.2-123.7-10.7-15.9-26.2-25.5-45.8-27.3,17.7-17,47.6-6.2,66,5.2,15.2,9.4,26.9,21.7,39.4,35.2,80.2-25.6,154.6-26.9,237.7-15,86,12.3,167.8,39.3,243.7,81.3,15.6,8.6,29.4,17.3,42.7,27.6h0ZM498.8,263.4l33.7-15.2c-7.5-7.9-15.7-13.2-19-22.2-4.5-12.6-8.6-24.2-17.8-34.1-14.4-15.6-36.8-22.2-56.8-13.9-22.4,9.3-35.7,30.3-36.5,54.3l-19.4,2c11.6,20.1,31.8,33.7,55.3,38.4,20.5,4.1,40.7-.4,60.5-9.3h0Z"/><path fill="#696969" d="M255.7,239.7l-2.6,4.9c-2.2,4.1-58.9,54.1-68.4,65.3,1.2-20.2,1-39.1-.2-58.3s-.3-26-2.7-40.1-2.4-34.2,4.4-49.3c5.7-12.7,19-17,31.2-11.5,16.2,7.4,23,25.5,18,42.4-4.1,13.7-.9,27.4,9.4,36.7l10.8,9.8h.1Z"/><path fill="#fff" d="M872.7,349.3c-.9,38-2.8,115.8-21.7,150.3-17.9-41.7-25.4-85.9-25.2-129.8,0-4.2.7-8.8,1.5-13.4s4.7-6.7,9.2-5.8l15,2.9c8,1.5,14.8-.2,21.1-4.1h.1Z"/><path fill="#010101" d="M498.8,263.4c-19.8,8.9-39.9,13.4-60.5,9.3-23.5-4.7-43.7-18.2-55.3-38.4l19.4-2c.8-24.1,14.1-45,36.5-54.3,20-8.3,42.4-1.7,56.8,13.9s13.3,21.5,17.8,34.1c3.2,9.1,11.5,14.4,19,22.2l-33.7,15.2h0Z"/><g><path fill="#010101" d="M856.4,577.4c-11.1,43.3-64.7,59.2-103.9,62.8-23,2.1-40.4-12.2-43-36.4-10.4,15-14,31.2-16.7,48.5-8.4,66,23.9,135.7,69.1,182.9-158.3,165.9-410,170.9-581.9,24.1-93-79.9-148.5-198.4-149.6-321.7-.9-108,37.8-220.1,109.7-301.7-15.9-66.6,10.6-186.5,89-199.4,40.5-6.7,80.4,15.6,109.2,41.9,88-23.8,185.5-19.6,274,0,85.6,19,180,54.1,252.8,103.1,36.6,24.6,49.7,62.4,48.6,105.6l-2.4,92.9c-.9,33.7-5.2,66-13.3,98.5-4.3,17.3-11,32.8-20.6,47.6-3.1,4.8-9.3,8.3-11.4,13.5l-9.7,37.8h.1ZM255.7,239.7l-10.8-9.8c-10.3-9.3-13.4-23.1-9.4-36.7,5-16.9-1.8-35-18-42.4-12.2-5.5-25.5-1.2-31.2,11.5-6.8,15.1-7.2,32.6-4.4,49.3s1.8,27,2.7,40.1c-52.8,57.4-87.6,129.3-102.4,206.1-28.7,148.4,30.8,301.1,154.2,388.7,21.3,15.1,43.2,29,68.8,39.6-2.1-87.5,27.1-170.9,84-236.3,14.6-16.8,30-30.6,47.7-44.1,60.1-45.9,126.7-62.9,198.1-83.9,7.6-2.3,12-7.4,12.8-16.5,15.5,13,31.5,33,53.9,22.2,22.9-11,41.3-27.6,57.7-47.4,27-32.8,43.8-71.2,53.6-111.9,2.8,4.5,8.6,3.6,12.9,1.5-.3,43.9,7.2,88,25.2,129.8,18.9-34.4,20.7-112.2,21.7-150.3s1-4.4.2-7.3c-14.4,2.5-30,.1-35.9-14.7-9.9-24.9,24.9-41.8,31-61.5,4.9-16-6.9-33.8-18.4-42.8-13.3-10.3-27.1-19-42.7-27.6-75.9-42-157.7-68.9-243.7-81.3-83.1-11.9-157.5-10.7-237.7,15-12.5-13.5-24.2-25.8-39.4-35.2-18.4-11.4-48.3-22.1-66-5.2,19.5,1.9,35.1,11.4,45.8,27.3,25.6,38.1,21.7,91.3-10.2,123.7h0ZM818.5,581.1c7.2-24.2,8.4-48.1,11.4-72.3l-19.2-53.8-16.7,137.6c7.3-.2,21.9-2.5,24.6-11.5h0ZM752.4,595.3c9.1.5,15.3.2,23.1-.5,7.7-39.3,15.1-78,18.4-119.6-12.2,15.1-22.1,29.9-34.8,43.2-3.9,4.1-5.2,8.3-5.1,14,.2,21.3-.4,41.8-1.5,62.8h-.1Z"/><path fill="#fff" d="M752.4,595.3c1.1-21,1.7-41.5,1.5-62.8,0-5.7,1.2-9.9,5.1-14,12.7-13.4,22.6-28.1,34.8-43.2-3.3,41.6-10.6,80.3-18.4,119.6-7.8.7-13.9,1-23.1.5h.1Z"/><path fill="#fff" d="M818.5,581.1c-2.7,9-17.3,11.3-24.6,11.5l16.7-137.6,19.2,53.8c-2.9,24.2-4.1,48.1-11.4,72.3h0Z"/><g><path fill="#696969" d="M849.6,223c11.5,8.9,23.3,26.7,18.4,42.8-6,19.7-40.8,36.6-31,61.5,5.9,14.8,21.5,17.2,35.9,14.7.8,2.9-.2,5.2-.2,7.3-6.3,3.9-13.1,5.6-21.1,4.1l-15-2.9c-4.5-.9-8.4,1.2-9.2,5.8-.8,4.6-1.4,9.2-1.5,13.4-4.4,2-10.1,2.9-12.9-1.5,1.2-5.2,2.9-10.6,2.1-16.4-37.7,4.5-67.9,34.2-99.8,1.7,0-1.1,1.6-1.2,2.9-.7,19.9,7.3,34.3,5,44.6-13.8,10.6-19.6,25.4-1.4,37.4-13.6,9.7-9.9-4.5-33.9-13-40.6-6.2-4.9-13.1-8.4-19.5-12.8-11.3-7.8-24.6-3.9-31.3,8.2s-5.7,9.8-11.6,7.7c-6.8-2.5-13.7-1.8-21.1-2.8-3.8-.5-7.1-3.9-10.6-1.1,2.7-7.9,3.2-15.9,9-23.9,15-20.7,36.3-33.2,62.1-37,28.8-4.2,57.1-2.5,85.5-.2h-.1Z"/><path fill="#010101" d="M715.2,353.5c-6.6-6.7-15.2-9.7-19.5-20.6-6.3-15.8-8.2-32.9-2.7-48.8,3.5-2.8,6.8.6,10.6,1.1,7.4.9,14.2.3,21.1,2.8,5.9,2.1,9.3-3.6,11.6-7.7,6.7-12.1,20-16,31.3-8.2,6.4,4.4,13.3,7.9,19.5,12.8,8.5,6.7,22.7,30.7,13,40.6-11.9,12.2-26.7-6-37.4,13.6-10.2,18.9-24.7,21.1-44.6,13.8s-3-.3-2.9.7h0Z"/></g></g></svg>`,Au=class{constructor(e){this.shadowRoot=null,this.adminClient=null,this.modal=null,this.donated=!1,this.amountSelector=null,this.recurringOptions=null,this.submitBtn=null,this.errorEl=null,this.fiatRate=1,this.themeObserver=null,this.themeMqCleanup=null,this.userConfig=e,this.config=cu(e),this.strings=Xl(this.config.locale),this.state={selectedAmount:null,customAmount:``,recurring:{enabled:!1,frequency:this.config.defaultFrequency,duration_in_months:this.config.defaultDurationInMonths??void 0,is_unlimited:this.config.defaultDurationInMonths===null},isModalOpen:!1}}async mount(){let e=typeof this.config.target==`string`?document.querySelector(this.config.target):this.config.target;if(!e)throw Error(`[pybara-donate] Target element not found: ${this.config.target}`);if(!this.userConfig.pluginVersion){let e=await mu(this.config.staging?`staging`:`prod`,window.location.origin,this.config.recipientPrincipal,wu);if(!e.show){console.info(`[pybara-donate] Not shown: ${e.reason}.`);return}e.recurring||(this.config.allowRecurring=!1)}Ou(this.config.fontUrl);let t=document.createElement(`div`);t.className=`pybara-donate-host`,this.shadowRoot=t.attachShadow({mode:`open`});let n=document.createElement(`style`);n.textContent=du,this.shadowRoot.appendChild(n);let r=this.config.theme===`auto`?Cu(e)??(window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`):this.config.theme;if(t.dataset.theme=r,t.style.setProperty(`--pybara-donate-primary`,this.config.primaryColor),hu(this.config.primaryColor)||this.log(`primaryColor "${this.config.primaryColor}" is not hex — contrast clamp skipped, CSS fallbacks apply`),Su(t,this.config.primaryColor,r),this.config.theme===`auto`){let n=!1,r=()=>{n||(n=!0,requestAnimationFrame(()=>{n=!1;let r=Cu(e)??(window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`);r!==t.dataset.theme&&(t.dataset.theme=r,Su(t,this.config.primaryColor,r))}))},i={attributes:!0,attributeFilter:[`class`,`data-theme`,`data-color-scheme`,`data-bs-theme`,`data-mode`,`data-color-mode`,`style`]};this.themeObserver=new MutationObserver(r),this.themeObserver.observe(document.documentElement,i),this.themeObserver.observe(document.body,i);let a=window.matchMedia?.(`(prefers-color-scheme: dark)`);a&&(a.addEventListener(`change`,r),this.themeMqCleanup=()=>a.removeEventListener(`change`,r))}let i=this.buildWidgetDOM();this.shadowRoot.appendChild(i),e.appendChild(t),await this.initAdminClient(),this.preconnectWallet(),this.initCheckoutModal(),this.log(`Widget mounted successfully`)}preconnectWallet(){let e=Ne[this.config.staging?`staging`:`prod`];if(document.head.querySelector(`link[rel="preconnect"][href="${e}"]`))return;let t=document.createElement(`link`);t.rel=`preconnect`,t.href=e,document.head.appendChild(t)}initCheckoutModal(){let e=this.config.staging?`staging`:`prod`;this.modal=new Ul({walletUrl:Ne[e],context:`donation`,...this.config.thankYouMessage?{thankYouMessage:this.config.thankYouMessage}:{},onSuccess:e=>{this.log(`Donation successful — Block: ${e.blockIndex}, Token: ${e.token}`),this.donated=!0;let t=this.state.selectedAmount??0,n={blockHeight:BigInt(e.blockIndex),token:e.token,amount:t.toFixed(2),recurring:this.state.recurring.enabled,frequency:this.state.recurring.enabled?this.state.recurring.frequency:void 0,duration_in_months:this.state.recurring.enabled?this.state.recurring.duration_in_months:void 0,is_unlimited:this.state.recurring.enabled?this.state.recurring.is_unlimited:!1,donorPrincipal:e.payerPrincipal,recipientPrincipal:this.config.recipientPrincipal};this.userConfig.onSuccess&&this.userConfig.onSuccess(n)},onError:e=>{this.state.isModalOpen=!1,console.error(`[pybara-donate] Payment error:`,e),this.userConfig.onError&&this.userConfig.onError(e),this.initCheckoutModal()},onClose:()=>{if(this.state.isModalOpen=!1,this.donated){if(this.donated=!1,this.config.thankYouRedirectUrl){window.location.href=this.config.thankYouRedirectUrl;return}}else this.userConfig.onClose&&this.userConfig.onClose();this.initCheckoutModal()}})}buildWidgetDOM(){let e=document.createElement(`div`);if(e.className=`pybara-donate`,this.config.title||this.config.description){let t=document.createElement(`div`);if(t.className=`pybara-donate__intro`,this.config.title){let e=document.createElement(`h3`);e.className=`pybara-donate__title`,e.textContent=this.config.title,t.appendChild(e)}if(this.config.description){let e=document.createElement(`p`);e.className=`pybara-donate__description`,e.textContent=this.config.description,t.appendChild(e)}e.appendChild(t)}this.amountSelector=new lu({presetAmounts:this.config.presetAmounts,allowCustom:this.config.allowCustom,currencySymbol:tu(this.config.currency),customPlaceholder:this.strings.amount.customPlaceholder,onAmountChange:e=>{this.state.selectedAmount=e,this.updateSubmitState()}}),e.appendChild(this.amountSelector.render()),this.config.allowRecurring&&(this.recurringOptions=new uu({defaultFrequency:this.config.defaultFrequency,defaultDurationInMonths:this.config.defaultDurationInMonths??12,defaultIsUnlimited:this.config.defaultDurationInMonths===null,strings:this.strings.recurring,onChange:e=>{this.state.recurring=e,this.updateSubmitState()}}),e.appendChild(this.recurringOptions.render())),this.errorEl=document.createElement(`div`),this.errorEl.className=`pybara-donate__error`,this.errorEl.style.display=`none`,e.appendChild(this.errorEl),this.submitBtn=document.createElement(`button`),this.submitBtn.type=`button`,this.submitBtn.className=`pybara-donate__submit`,this.submitBtn.textContent=this.config.buttonLabel,this.submitBtn.disabled=!0,this.submitBtn.addEventListener(`click`,()=>this.handleDonate()),e.appendChild(this.submitBtn);let t=this.config.tokens.map(e=>`<div class="pybara-donate__footer-token"><img src="https://assets.pybara.com/images/tokens/${e.toLowerCase()}.svg" alt="${e}" loading="lazy" width="20" height="20"></div>`).join(``),n=document.createElement(`div`);return n.className=`pybara-donate__footer`,n.innerHTML=`
|
|
456
|
+
<a href="https://pybara.com" target="_blank" rel="noopener noreferrer" class="pybara-donate__footer-brand">
|
|
457
|
+
<div class="pybara-donate__footer-logo">${ku}</div>
|
|
458
|
+
<div class="pybara-donate__footer-brand-text">
|
|
459
|
+
<strong>Pybara</strong>
|
|
460
|
+
<span>${this.strings.widget.cryptoPayments}</span>
|
|
461
|
+
</div>
|
|
462
|
+
</a>
|
|
463
|
+
<div class="pybara-donate__footer-tokens">${t}</div>
|
|
464
|
+
`,e.appendChild(n),e}async initAdminClient(){try{let e=this.config.staging?`staging`:`prod`;if(this.adminClient=new El({adminCoreCanisterId:Pe[e].admin_core,debug:this.config.debug}),await this.adminClient.init(),await this.adminClient.getPybaraAdminConfig(),this.adminClient.getRecipientDataWithCache(this.config.siteUrl).catch(()=>{}),this.config.currency!==`USD`){let e=await this.adminClient.getFiatRate(this.config.currency);e===null?console.warn(`[pybara-donate] Could not fetch ${this.config.currency}/USD rate — amounts will be treated as USD`):(this.fiatRate=e,this.log(`Fiat rate: 1 ${this.config.currency} = $${e.toFixed(4)} USD`))}this.log(`Admin client initialized`)}catch(e){console.error(`[pybara-donate] Failed to init admin client:`,e)}}updateSubmitState(){if(!this.submitBtn)return;let e=this.state.selectedAmount,t=e!==null&&e>=.5;if(this.submitBtn.disabled=!t,t&&e!==null){let t=this.state.recurring.enabled?` / ${this.state.recurring.frequency}`:``,n=tu(this.config.currency);this.submitBtn.textContent=`${this.config.buttonLabel} ${n}${e.toFixed(2)}${t}`}else this.submitBtn.textContent=this.config.buttonLabel;this.hideError()}buildSdkFields(e){let t=[[`site_url`,this.config.siteUrl],[`site_name`,this.config.siteName],[`donation_amount_usd`,Math.round(e*1e4).toString()],[`donation_type`,this.state.recurring.enabled?`recurring`:`oneTime`],[`platform`,`pybara-donate`]],n=(e,n)=>{n!==void 0&&n!==``&&t.push([e,n])};return n(`donation_amount_local`,this.state.selectedAmount===null?void 0:Math.round(this.state.selectedAmount*1e4).toString()),n(`donation_local_currency`,this.config.currency),n(`site_country`,this.userConfig.siteCountry),n(`donor_is_anonymous`,this.userConfig.donorIsAnonymous?.toString()),n(`donor_message`,this.userConfig.donorMessage),n(`donor_first_name`,this.userConfig.donorFirstName),n(`donor_last_name`,this.userConfig.donorLastName),n(`donor_email`,this.userConfig.donorEmail),n(`donor_company`,this.userConfig.donorCompany),n(`donor_country`,this.userConfig.donorCountry),n(`donor_address_line_1`,this.userConfig.donorAddressLine1),n(`donor_address_line_2`,this.userConfig.donorAddressLine2),n(`donor_address_city`,this.userConfig.donorAddressCity),n(`donor_address_state`,this.userConfig.donorAddressState),n(`donor_address_postal_code`,this.userConfig.donorAddressPostalCode),n(`donor_address_country`,this.userConfig.donorAddressCountry),n(`donor_tos_version`,this.userConfig.donorTosVersion),n(`donor_tos_accepted_at`,this.userConfig.donorTosAcceptedAt),n(`recipient_tos_version`,this.userConfig.recipientTosVersion),n(`recipient_tos_accepted_at`,this.userConfig.recipientTosAcceptedAt),n(`plugin_version`,this.userConfig.pluginVersion),t}async handleDonate(){let e=this.state.selectedAmount;if(e===null||e<.5){this.showError(Zl(this.strings.errors.minimumDonation,{symbol:tu(this.config.currency),amount:su.toFixed(2)}));return}if(!this.state.isModalOpen){this.state.isModalOpen=!0,this.log(`Opening checkout — $${e} ${this.state.recurring.enabled?`(recurring)`:`(one-time)`}`);try{let t=e*this.fiatRate,n=!1;try{this.adminClient&&await this.adminClient.getRecipientDataWithCache(this.config.siteUrl)}catch(e){console.warn(`[pybara-donate] Recipient access validation failed:`,e),n=!0}this.modal||this.initCheckoutModal();let r=this.modal;if(!r)throw Error(`CheckoutModal failed to initialize`);n?(r.renderTerminalState(`This recipient is currently unable to accept donations.`),this.initCheckoutModal()):await r.show({modalData:{amountUSD:t,beneficiary:this.config.recipientPrincipal,salt:Eu(),reference:this.config.siteName},recurring:this.state.recurring.enabled?{frequency:this.state.recurring.frequency,totalPulls:Tu(this.state.recurring.duration_in_months,this.state.recurring.is_unlimited,this.state.recurring.frequency),...this.state.recurring.is_unlimited?{}:{durationMonths:this.state.recurring.duration_in_months}}:void 0,sdkFields:this.buildSdkFields(t)})}catch(e){this.state.isModalOpen=!1,console.error(`[pybara-donate] Failed to open checkout:`,e),this.showError(this.strings.widget.errorGeneric)}}}showError(e){this.errorEl&&(this.errorEl.textContent=e,this.errorEl.style.display=`block`)}hideError(){this.errorEl&&(this.errorEl.style.display=`none`)}log(e){this.config.debug&&console.log(`[pybara-donate] ${e}`)}destroy(){this.themeObserver?.disconnect(),this.themeObserver=null,this.themeMqCleanup?.(),this.themeMqCleanup=null,this.shadowRoot?.host&&this.shadowRoot.host.remove(),this.adminClient=null,this.shadowRoot=null,this.log(`Widget destroyed`)}},ju=new Map;function Mu(e){let t=typeof e.target==`string`?e.target:e.target.id||`pybara-${Date.now()}`;ju.has(t)&&ju.get(t)?.destroy();let n=new Au(e);return ju.set(t,n),n.mount().catch(e=>{console.error(`[pybara-donate] Mount failed:`,e)}),n}function Nu(){for(let e of ju.values())e.destroy();ju.clear()}return e.DonationWidget=Au,e.destroyAll=Nu,e.init=Mu,e})({});
|