/*! For license information please see app.faa45d87ae3703251239.js.LICENSE.txt */ (()=>{var __webpack_modules__={"./node_modules/@babel/runtime/helpers/OverloadYield.js":module=>{module.exports=function _OverloadYield(e,d){this.v=e,this.k=d},module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js":(__unused_webpack___webpack_module__,__webpack_exports__,__webpack_require__)=>{"use strict";function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e_arrayLikeToArray})},"./node_modules/@babel/runtime/helpers/esm/slicedToArray.js":(__unused_webpack___webpack_module__,__webpack_exports__,__webpack_require__)=>{"use strict";__webpack_require__.d(__webpack_exports__,{A:()=>_slicedToArray});var unsupportedIterableToArray=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js");function _slicedToArray(r,e){return function _arrayWithHoles(r){if(Array.isArray(r))return r}(r)||function _iterableToArrayLimit(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||(0,unsupportedIterableToArray.A)(r,e)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}},"./node_modules/@babel/runtime/helpers/esm/typeof.js":(__unused_webpack___webpack_module__,__webpack_exports__,__webpack_require__)=>{"use strict";function _typeof(o){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}__webpack_require__.d(__webpack_exports__,{A:()=>_typeof})},"./node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js":(__unused_webpack___webpack_module__,__webpack_exports__,__webpack_require__)=>{"use strict";__webpack_require__.d(__webpack_exports__,{A:()=>_unsupportedIterableToArray});var _arrayLikeToArray_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js");function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return(0,_arrayLikeToArray_js__WEBPACK_IMPORTED_MODULE_0__.A)(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?(0,_arrayLikeToArray_js__WEBPACK_IMPORTED_MODULE_0__.A)(r,a):void 0}}},"./node_modules/@babel/runtime/helpers/regenerator.js":(module,__unused_webpack_exports,__webpack_require__)=>{var regeneratorDefine=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorDefine.js");function _regenerator(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return regeneratorDefine(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function d(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(regeneratorDefine(t={},n,function(){return this}),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,regeneratorDefine(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,regeneratorDefine(u,"constructor",GeneratorFunctionPrototype),regeneratorDefine(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",regeneratorDefine(GeneratorFunctionPrototype,o,"GeneratorFunction"),regeneratorDefine(u),regeneratorDefine(u,o,"Generator"),regeneratorDefine(u,n,function(){return this}),regeneratorDefine(u,"toString",function(){return"[object Generator]"}),(module.exports=_regenerator=function _regenerator(){return{w:i,m:f}},module.exports.__esModule=!0,module.exports.default=module.exports)()}module.exports=_regenerator,module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/helpers/regeneratorAsync.js":(module,__unused_webpack_exports,__webpack_require__)=>{var regeneratorAsyncGen=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js");module.exports=function _regeneratorAsync(n,e,r,t,o){var a=regeneratorAsyncGen(n,e,r,t,o);return a.next().then(function(n){return n.done?n.value:a.next()})},module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js":(module,__unused_webpack_exports,__webpack_require__)=>{var regenerator=__webpack_require__("./node_modules/@babel/runtime/helpers/regenerator.js"),regeneratorAsyncIterator=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js");module.exports=function _regeneratorAsyncGen(r,e,t,o,n){return new regeneratorAsyncIterator(regenerator().w(r,e,t,o),n||Promise)},module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js":(module,__unused_webpack_exports,__webpack_require__)=>{var OverloadYield=__webpack_require__("./node_modules/@babel/runtime/helpers/OverloadYield.js"),regeneratorDefine=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorDefine.js");module.exports=function AsyncIterator(t,e){function n(r,o,i,f){try{var c=t[r](o),u=c.value;return u instanceof OverloadYield?e.resolve(u.v).then(function(t){n("next",t,i,f)},function(t){n("throw",t,i,f)}):e.resolve(u).then(function(t){c.value=t,i(c)},function(t){return n("throw",t,i,f)})}catch(t){f(t)}}var r;this.next||(regeneratorDefine(AsyncIterator.prototype),regeneratorDefine(AsyncIterator.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),regeneratorDefine(this,"_invoke",function(t,o,i){function f(){return new e(function(e,r){n(t,i,e,r)})}return r=r?r.then(f,f):f()},!0)},module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/helpers/regeneratorDefine.js":module=>{function _regeneratorDefine(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}module.exports=_regeneratorDefine=function regeneratorDefine(e,r,n,t){if(r)i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n;else{var o=function o(r,n){_regeneratorDefine(e,r,function(e){return this._invoke(r,n,e)})};o("next",0),o("throw",1),o("return",2)}},module.exports.__esModule=!0,module.exports.default=module.exports,_regeneratorDefine(e,r,n,t)}module.exports=_regeneratorDefine,module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/helpers/regeneratorKeys.js":module=>{module.exports=function _regeneratorKeys(e){var n=Object(e),r=[];for(var t in n)r.unshift(t);return function e(){for(;r.length;)if((t=r.pop())in n)return e.value=t,e.done=!1,e;return e.done=!0,e}},module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/helpers/regeneratorRuntime.js":(module,__unused_webpack_exports,__webpack_require__)=>{var OverloadYield=__webpack_require__("./node_modules/@babel/runtime/helpers/OverloadYield.js"),regenerator=__webpack_require__("./node_modules/@babel/runtime/helpers/regenerator.js"),regeneratorAsync=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorAsync.js"),regeneratorAsyncGen=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js"),regeneratorAsyncIterator=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js"),regeneratorKeys=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorKeys.js"),regeneratorValues=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorValues.js");function _regeneratorRuntime(){"use strict";var r=regenerator(),e=r.m(_regeneratorRuntime),t=(Object.getPrototypeOf?Object.getPrototypeOf(e):e.__proto__).constructor;function n(r){var e="function"==typeof r&&r.constructor;return!!e&&(e===t||"GeneratorFunction"===(e.displayName||e.name))}var o={throw:1,return:2,break:3,continue:3};function a(r){var e,t;return function(n){e||(e={stop:function stop(){return t(n.a,2)},catch:function _catch(){return n.v},abrupt:function abrupt(r,e){return t(n.a,o[r],e)},delegateYield:function delegateYield(r,o,a){return e.resultName=o,t(n.d,regeneratorValues(r),a)},finish:function finish(r){return t(n.f,r)}},t=function t(r,_t,o){n.p=e.prev,n.n=e.next;try{return r(_t,o)}finally{e.next=n.n}}),e.resultName&&(e[e.resultName]=n.v,e.resultName=void 0),e.sent=n.v,e.next=n.n;try{return r.call(this,e)}finally{n.p=e.prev,n.n=e.next}}}return(module.exports=_regeneratorRuntime=function _regeneratorRuntime(){return{wrap:function wrap(e,t,n,o){return r.w(a(e),t,n,o&&o.reverse())},isGeneratorFunction:n,mark:r.m,awrap:function awrap(r,e){return new OverloadYield(r,e)},AsyncIterator:regeneratorAsyncIterator,async:function async(r,e,t,o,u){return(n(e)?regeneratorAsyncGen:regeneratorAsync)(a(r),e,t,o,u)},keys:regeneratorKeys,values:regeneratorValues}},module.exports.__esModule=!0,module.exports.default=module.exports)()}module.exports=_regeneratorRuntime,module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/helpers/regeneratorValues.js":(module,__unused_webpack_exports,__webpack_require__)=>{var _typeof=__webpack_require__("./node_modules/@babel/runtime/helpers/typeof.js").default;module.exports=function _regeneratorValues(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function next(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(_typeof(e)+" is not iterable")},module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/helpers/typeof.js":module=>{function _typeof(o){return module.exports=_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},module.exports.__esModule=!0,module.exports.default=module.exports,_typeof(o)}module.exports=_typeof,module.exports.__esModule=!0,module.exports.default=module.exports},"./node_modules/@babel/runtime/regenerator/index.js":(module,__unused_webpack_exports,__webpack_require__)=>{var runtime=__webpack_require__("./node_modules/@babel/runtime/helpers/regeneratorRuntime.js")();module.exports=runtime;try{regeneratorRuntime=runtime}catch(accidentalStrictMode){"object"==typeof globalThis?globalThis.regeneratorRuntime=runtime:Function("r","regeneratorRuntime = r")(runtime)}},"./node_modules/@noble/curves/abstract/curve.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.negateCt=negateCt,exports.normalizeZ=function normalizeZ(c,property,points){const getz="pz"===property?p=>p.pz:p=>p.ez,toInv=(0,modular_ts_1.FpInvertBatch)(c.Fp,points.map(getz));return points.map((p,i)=>p.toAffine(toInv[i])).map(c.fromAffine)},exports.wNAF=function wNAF(c,bits){return{constTimeNegate:negateCt,hasPrecomputes:elm=>1!==getW(elm),unsafeLadder(elm,n,p=c.ZERO){let d=elm;for(;n>_0n;)n&_1n&&(p=p.add(d)),d=d.double(),n>>=_1n;return p},precomputeWindow(elm,W){const{windows,windowSize}=calcWOpts(W,bits),points=[];let p=elm,base=p;for(let window=0;window_0n||k2>_0n;)k1&_1n&&(p1=p1.add(acc)),k2&_1n&&(p2=p2.add(acc)),acc=acc.double(),k1>>=_1n,k2>>=_1n;return{p1,p2}},exports.pippenger=function pippenger(c,fieldN,points,scalars){validateMSMPoints(points,c),validateMSMScalars(scalars,fieldN);const plength=points.length,slength=scalars.length;if(plength!==slength)throw new Error("arrays of points and scalars must have equal length");const zero=c.ZERO,wbits=(0,utils_ts_1.bitLen)(BigInt(plength));let windowSize=1;wbits>12?windowSize=wbits-3:wbits>4?windowSize=wbits-2:wbits>0&&(windowSize=2);const MASK=(0,utils_ts_1.bitMask)(windowSize),buckets=new Array(Number(MASK)+1).fill(zero),lastBits=Math.floor((fieldN.BITS-1)/windowSize)*windowSize;let sum=zero;for(let i=lastBits;i>=0;i-=windowSize){buckets.fill(zero);for(let j=0;j>BigInt(i)&MASK);buckets[wbits]=buckets[wbits].add(points[j])}let resI=zero;for(let j=buckets.length-1,sumI=zero;j>0;j--)sumI=sumI.add(buckets[j]),resI=resI.add(sumI);if(sum=sum.add(resI),0!==i)for(let j=0;j{const res=[];for(let i=0,acc=p;i{if(validateMSMScalars(scalars,fieldN),scalars.length>points.length)throw new Error("array of scalars must be smaller than array of points");let res=zero;for(let i=0;i>shiftBy&MASK);curr&&(res=res.add(tables[j][curr-1]))}}return res}},exports.validateBasic=function validateBasic(curve){return(0,modular_ts_1.validateField)(curve.Fp),(0,utils_ts_1.validateObject)(curve,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...(0,modular_ts_1.nLength)(curve.n,curve.nBitLength),...curve,p:curve.Fp.ORDER})},exports._createCurveFields=function _createCurveFields(type,CURVE,curveOpts={}){if(!CURVE||"object"!=typeof CURVE)throw new Error(`expected valid ${type} CURVE object`);for(const p of["p","n","h"]){const val=CURVE[p];if(!("bigint"==typeof val&&val>_0n))throw new Error(`CURVE.${p} must be positive bigint`)}const Fp=createField(CURVE.p,curveOpts.Fp),Fn=createField(CURVE.n,curveOpts.Fn),params=["Gx","Gy","a","weierstrass"===type?"b":"d"];for(const p of params)if(!Fp.isValid(CURVE[p]))throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);return{Fp,Fn}};const utils_ts_1=__webpack_require__("./node_modules/@noble/curves/utils.js"),modular_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/modular.js"),_0n=BigInt(0),_1n=BigInt(1);function negateCt(condition,item){const neg=item.negate();return condition?neg:item}function validateW(W,bits){if(!Number.isSafeInteger(W)||W<=0||W>bits)throw new Error("invalid window size, expected [1.."+bits+"], got W="+W)}function calcWOpts(W,scalarBits){validateW(W,scalarBits);const maxNumber=2**W;return{windows:Math.ceil(scalarBits/W)+1,windowSize:2**(W-1),mask:(0,utils_ts_1.bitMask)(W),maxNumber,shiftBy:BigInt(W)}}function calcOffsets(n,window,wOpts){const{windowSize,mask,maxNumber,shiftBy}=wOpts;let wbits=Number(n&mask),nextN=n>>shiftBy;wbits>windowSize&&(wbits-=maxNumber,nextN+=_1n);const offsetStart=window*windowSize;return{nextN,offset:offsetStart+Math.abs(wbits)-1,isZero:0===wbits,isNeg:wbits<0,isNegF:window%2!=0,offsetF:offsetStart}}function validateMSMPoints(points,c){if(!Array.isArray(points))throw new Error("array expected");points.forEach((p,i)=>{if(!(p instanceof c))throw new Error("invalid point at index "+i)})}function validateMSMScalars(scalars,field){if(!Array.isArray(scalars))throw new Error("array of scalars expected");scalars.forEach((s,i)=>{if(!field.isValid(s))throw new Error("invalid scalar at index "+i)})}const pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(P){return pointWindowSizes.get(P)||1}function assert0(n){if(n!==_0n)throw new Error("invalid wNAF")}function createField(order,field){if(field){if(field.ORDER!==order)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return(0,modular_ts_1.validateField)(field),field}return(0,modular_ts_1.Field)(order)}},"./node_modules/@noble/curves/abstract/edwards.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.edwards=edwards,exports.eddsa=eddsa,exports.twistedEdwards=function twistedEdwards(c){const{CURVE,curveOpts,eddsaOpts}=function _eddsa_legacy_opts_to_new(c){const CURVE={a:c.a,d:c.d,p:c.Fp.ORDER,n:c.n,h:c.h,Gx:c.Gx,Gy:c.Gy},Fp=c.Fp,Fn=(0,modular_ts_1.Field)(CURVE.n,c.nBitLength,!0),curveOpts={Fp,Fn,uvRatio:c.uvRatio},eddsaOpts={hash:c.hash,randomBytes:c.randomBytes,adjustScalarBytes:c.adjustScalarBytes,domain:c.domain,prehash:c.prehash,mapToCurve:c.mapToCurve};return{CURVE,curveOpts,eddsaOpts}}(c),EDDSA=eddsa(edwards(CURVE,curveOpts),eddsaOpts);return function _eddsa_new_output_to_legacy(c,eddsa){const legacy=Object.assign({},eddsa,{ExtendedPoint:eddsa.Point,CURVE:c});return legacy}(c,EDDSA)};const utils_ts_1=__webpack_require__("./node_modules/@noble/curves/utils.js"),curve_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/curve.js"),modular_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/modular.js"),_0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_8n=BigInt(8),VERIFY_DEFAULT={zip215:!0};function edwards(CURVE,curveOpts={}){const{Fp,Fn}=(0,curve_ts_1._createCurveFields)("edwards",CURVE,curveOpts),{h:cofactor,n:CURVE_ORDER}=CURVE;(0,utils_ts_1._validateObject)(curveOpts,{},{uvRatio:"function"});const MASK=_2n<Fp.create(n),uvRatio=curveOpts.uvRatio||((u,v)=>{try{return{isValid:!0,value:Fp.sqrt(Fp.div(u,v))}}catch(e){return{isValid:!1,value:_0n}}});if(!function isEdValidXY(Fp,CURVE,x,y){const x2=Fp.sqr(x),y2=Fp.sqr(y),left=Fp.add(Fp.mul(CURVE.a,x2),y2),right=Fp.add(Fp.ONE,Fp.mul(CURVE.d,Fp.mul(x2,y2)));return Fp.eql(left,right)}(Fp,CURVE,CURVE.Gx,CURVE.Gy))throw new Error("bad curve params: generator point");function acoord(title,n,banZero=!1){const min=banZero?_1n:_0n;return(0,utils_ts_1.aInRange)("coordinate "+title,n,min,MASK),n}function aextpoint(other){if(!(other instanceof Point))throw new Error("ExtendedPoint expected")}const toAffineMemo=(0,utils_ts_1.memoized)((p,iz)=>{const{ex:x,ey:y,ez:z}=p,is0=p.is0();null==iz&&(iz=is0?_8n:Fp.inv(z));const ax=modP(x*iz),ay=modP(y*iz),zz=modP(z*iz);if(is0)return{x:_0n,y:_1n};if(zz!==_1n)throw new Error("invZ was invalid");return{x:ax,y:ay}}),assertValidMemo=(0,utils_ts_1.memoized)(p=>{const{a,d}=CURVE;if(p.is0())throw new Error("bad point: ZERO");const{ex:X,ey:Y,ez:Z,et:T}=p,X2=modP(X*X),Y2=modP(Y*Y),Z2=modP(Z*Z),Z4=modP(Z2*Z2),aX2=modP(X2*a);if(modP(Z2*modP(aX2+Y2))!==modP(Z4+modP(d*modP(X2*Y2))))throw new Error("bad point: equation left != right (1)");if(modP(X*Y)!==modP(Z*T))throw new Error("bad point: equation left != right (2)");return!0});class Point{constructor(ex,ey,ez,et){this.ex=acoord("x",ex),this.ey=acoord("y",ey),this.ez=acoord("z",ez,!0),this.et=acoord("t",et),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(p){if(p instanceof Point)throw new Error("extended point not allowed");const{x,y}=p||{};return acoord("x",x),acoord("y",y),new Point(x,y,_1n,modP(x*y))}static normalizeZ(points){return(0,curve_ts_1.normalizeZ)(Point,"ez",points)}static msm(points,scalars){return(0,curve_ts_1.pippenger)(Point,Fn,points,scalars)}_setWindowSize(windowSize){this.precompute(windowSize)}precompute(windowSize=8,isLazy=!0){return wnaf.setWindowSize(this,windowSize),isLazy||this.multiply(_2n),this}assertValidity(){assertValidMemo(this)}equals(other){aextpoint(other);const{ex:X1,ey:Y1,ez:Z1}=this,{ex:X2,ey:Y2,ez:Z2}=other,X1Z2=modP(X1*Z2),X2Z1=modP(X2*Z1),Y1Z2=modP(Y1*Z2),Y2Z1=modP(Y2*Z1);return X1Z2===X2Z1&&Y1Z2===Y2Z1}is0(){return this.equals(Point.ZERO)}negate(){return new Point(modP(-this.ex),this.ey,this.ez,modP(-this.et))}double(){const{a}=CURVE,{ex:X1,ey:Y1,ez:Z1}=this,A=modP(X1*X1),B=modP(Y1*Y1),C=modP(_2n*modP(Z1*Z1)),D=modP(a*A),x1y1=X1+Y1,E=modP(modP(x1y1*x1y1)-A-B),G=D+B,F=G-C,H=D-B,X3=modP(E*F),Y3=modP(G*H),T3=modP(E*H),Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}add(other){aextpoint(other);const{a,d}=CURVE,{ex:X1,ey:Y1,ez:Z1,et:T1}=this,{ex:X2,ey:Y2,ez:Z2,et:T2}=other,A=modP(X1*X2),B=modP(Y1*Y2),C=modP(T1*d*T2),D=modP(Z1*Z2),E=modP((X1+Y1)*(X2+Y2)-A-B),F=D-C,G=D+C,H=modP(B-a*A),X3=modP(E*F),Y3=modP(G*H),T3=modP(E*H),Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}subtract(other){return this.add(other.negate())}multiply(scalar){const n=scalar;(0,utils_ts_1.aInRange)("scalar",n,_1n,CURVE_ORDER);const{p,f}=wnaf.wNAFCached(this,n,Point.normalizeZ);return Point.normalizeZ([p,f])[0]}multiplyUnsafe(scalar,acc=Point.ZERO){const n=scalar;return(0,utils_ts_1.aInRange)("scalar",n,_0n,CURVE_ORDER),n===_0n?Point.ZERO:this.is0()||n===_1n?this:wnaf.wNAFCachedUnsafe(this,n,Point.normalizeZ,acc)}isSmallOrder(){return this.multiplyUnsafe(cofactor).is0()}isTorsionFree(){return wnaf.wNAFCachedUnsafe(this,CURVE_ORDER).is0()}toAffine(invertedZ){return toAffineMemo(this,invertedZ)}clearCofactor(){return cofactor===_1n?this:this.multiplyUnsafe(cofactor)}static fromBytes(bytes,zip215=!1){return(0,utils_ts_1.abytes)(bytes),this.fromHex(bytes,zip215)}static fromHex(hex,zip215=!1){const{d,a}=CURVE,len=Fp.BYTES;hex=(0,utils_ts_1.ensureBytes)("pointHex",hex,len),(0,utils_ts_1.abool)("zip215",zip215);const normed=hex.slice(),lastByte=hex[len-1];normed[len-1]=-129&lastByte;const y=(0,utils_ts_1.bytesToNumberLE)(normed),max=zip215?MASK:Fp.ORDER;(0,utils_ts_1.aInRange)("pointHex.y",y,_0n,max);const y2=modP(y*y),u=modP(y2-_1n),v=modP(d*y2-a);let{isValid,value:x}=uvRatio(u,v);if(!isValid)throw new Error("Point.fromHex: invalid y coordinate");const isXOdd=(x&_1n)===_1n,isLastByteOdd=!!(128&lastByte);if(!zip215&&x===_0n&&isLastByteOdd)throw new Error("Point.fromHex: x=0 and x_0=1");return isLastByteOdd!==isXOdd&&(x=modP(-x)),Point.fromAffine({x,y})}static fromPrivateScalar(scalar){return Point.BASE.multiply(scalar)}toBytes(){const{x,y}=this.toAffine(),bytes=(0,utils_ts_1.numberToBytesLE)(y,Fp.BYTES);return bytes[bytes.length-1]|=x&_1n?128:0,bytes}toRawBytes(){return this.toBytes()}toHex(){return(0,utils_ts_1.bytesToHex)(this.toBytes())}toString(){return``}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy,_1n,modP(CURVE.Gx*CURVE.Gy)),Point.ZERO=new Point(_0n,_1n,_1n,_0n),Point.Fp=Fp,Point.Fn=Fn;const wnaf=(0,curve_ts_1.wNAF)(Point,8*Fn.BYTES);return Point}function eddsa(Point,eddsaOpts){(0,utils_ts_1._validateObject)(eddsaOpts,{hash:"function"},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash,hash:cHash}=eddsaOpts,{BASE:G,Fp,Fn}=Point,CURVE_ORDER=Fn.ORDER,randomBytes_=eddsaOpts.randomBytes||utils_ts_1.randomBytes,adjustScalarBytes=eddsaOpts.adjustScalarBytes||(bytes=>bytes),domain=eddsaOpts.domain||((data,ctx,phflag)=>{if((0,utils_ts_1.abool)("phflag",phflag),ctx.length||phflag)throw new Error("Contexts/pre-hash are not supported");return data});function modN(a){return Fn.create(a)}function modN_LE(hash){return modN((0,utils_ts_1.bytesToNumberLE)(hash))}function getExtendedPublicKey(key){const{head,prefix,scalar}=function getPrivateScalar(key){const len=Fp.BYTES;key=(0,utils_ts_1.ensureBytes)("private key",key,len);const hashed=(0,utils_ts_1.ensureBytes)("hashed private key",cHash(key),2*len),head=adjustScalarBytes(hashed.slice(0,len));return{head,prefix:hashed.slice(len,2*len),scalar:modN_LE(head)}}(key),point=G.multiply(scalar),pointBytes=point.toBytes();return{head,prefix,scalar,point,pointBytes}}function hashDomainToScalar(context=Uint8Array.of(),...msgs){const msg=(0,utils_ts_1.concatBytes)(...msgs);return modN_LE(cHash(domain(msg,(0,utils_ts_1.ensureBytes)("context",context),!!prehash)))}const verifyOpts=VERIFY_DEFAULT;G.precompute(8);return{getPublicKey:function getPublicKey(privKey){return getExtendedPublicKey(privKey).pointBytes},sign:function sign(msg,privKey,options={}){msg=(0,utils_ts_1.ensureBytes)("message",msg),prehash&&(msg=prehash(msg));const{prefix,scalar,pointBytes}=getExtendedPublicKey(privKey),r=hashDomainToScalar(options.context,prefix,msg),R=G.multiply(r).toBytes(),s=modN(r+hashDomainToScalar(options.context,R,pointBytes,msg)*scalar);(0,utils_ts_1.aInRange)("signature.s",s,_0n,CURVE_ORDER);const L=Fp.BYTES,res=(0,utils_ts_1.concatBytes)(R,(0,utils_ts_1.numberToBytesLE)(s,L));return(0,utils_ts_1.ensureBytes)("result",res,2*L)},verify:function verify(sig,msg,publicKey,options=verifyOpts){const{context,zip215}=options,len=Fp.BYTES;sig=(0,utils_ts_1.ensureBytes)("signature",sig,2*len),msg=(0,utils_ts_1.ensureBytes)("message",msg),publicKey=(0,utils_ts_1.ensureBytes)("publicKey",publicKey,len),void 0!==zip215&&(0,utils_ts_1.abool)("zip215",zip215),prehash&&(msg=prehash(msg));const s=(0,utils_ts_1.bytesToNumberLE)(sig.slice(len,2*len));let A,R,SB;try{A=Point.fromHex(publicKey,zip215),R=Point.fromHex(sig.slice(0,len),zip215),SB=G.multiplyUnsafe(s)}catch(error){return!1}if(!zip215&&A.isSmallOrder())return!1;const k=hashDomainToScalar(context,R.toBytes(),A.toBytes(),msg);return R.add(A.multiplyUnsafe(k)).subtract(SB).clearCofactor().is0()},utils:{getExtendedPublicKey,randomPrivateKey:()=>randomBytes_(Fp.BYTES),precompute:(windowSize=8,point=Point.BASE)=>point.precompute(windowSize,!1)},Point}}},"./node_modules/@noble/curves/abstract/hash-to-curve.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.expand_message_xmd=expand_message_xmd,exports.expand_message_xof=expand_message_xof,exports.hash_to_field=hash_to_field,exports.isogenyMap=function isogenyMap(field,map){const coeff=map.map(i=>Array.from(i).reverse());return(x,y)=>{const[xn,xd,yn,yd]=coeff.map(val=>val.reduce((acc,i)=>field.add(field.mul(acc,x),i))),[xd_inv,yd_inv]=(0,modular_ts_1.FpInvertBatch)(field,[xd,yd],!0);return x=field.mul(xn,xd_inv),y=field.mul(y,field.mul(yn,yd_inv)),{x,y}}},exports.createHasher=function createHasher(Point,mapToCurve,defaults){if("function"!=typeof mapToCurve)throw new Error("mapToCurve() must be defined");function map(num){return Point.fromAffine(mapToCurve(num))}function clear(initial){const P=initial.clearCofactor();return P.equals(Point.ZERO)?Point.ZERO:(P.assertValidity(),P)}return{defaults,hashToCurve(msg,options){const dst=defaults.DST?defaults.DST:{},u=hash_to_field(msg,2,Object.assign({},defaults,dst,options)),u0=map(u[0]),u1=map(u[1]);return clear(u0.add(u1))},encodeToCurve(msg,options){const dst=defaults.encodeDST?defaults.encodeDST:{};return clear(map(hash_to_field(msg,1,Object.assign({},defaults,dst,options))[0]))},mapToCurve(scalars){if(!Array.isArray(scalars))throw new Error("expected array of bigints");for(const i of scalars)if("bigint"!=typeof i)throw new Error("expected array of bigints");return clear(map(scalars))}}};const utils_ts_1=__webpack_require__("./node_modules/@noble/curves/utils.js"),modular_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/modular.js"),os2ip=utils_ts_1.bytesToNumberBE;function i2osp(value,length){if(anum(value),anum(length),value<0||value>=1<<8*length)throw new Error("invalid I2OSP input: "+value);const res=Array.from({length}).fill(0);for(let i=length-1;i>=0;i--)res[i]=255&value,value>>>=8;return new Uint8Array(res)}function strxor(a,b){const arr=new Uint8Array(a.length);for(let i=0;i255&&(DST=H((0,utils_ts_1.concatBytes)((0,utils_ts_1.utf8ToBytes)("H2C-OVERSIZE-DST-"),DST)));const{outputLen:b_in_bytes,blockLen:r_in_bytes}=H,ell=Math.ceil(lenInBytes/b_in_bytes);if(lenInBytes>65535||ell>255)throw new Error("expand_message_xmd: invalid lenInBytes");const DST_prime=(0,utils_ts_1.concatBytes)(DST,i2osp(DST.length,1)),Z_pad=i2osp(0,r_in_bytes),l_i_b_str=i2osp(lenInBytes,2),b=new Array(ell),b_0=H((0,utils_ts_1.concatBytes)(Z_pad,msg,l_i_b_str,i2osp(0,1),DST_prime));b[0]=H((0,utils_ts_1.concatBytes)(b_0,i2osp(1,1),DST_prime));for(let i=1;i<=ell;i++){const args=[strxor(b_0,b[i-1]),i2osp(i+1,1),DST_prime];b[i]=H((0,utils_ts_1.concatBytes)(...args))}return(0,utils_ts_1.concatBytes)(...b).slice(0,lenInBytes)}function expand_message_xof(msg,DST,lenInBytes,k,H){if((0,utils_ts_1.abytes)(msg),(0,utils_ts_1.abytes)(DST),anum(lenInBytes),DST.length>255){const dkLen=Math.ceil(2*k/8);DST=H.create({dkLen}).update((0,utils_ts_1.utf8ToBytes)("H2C-OVERSIZE-DST-")).update(DST).digest()}if(lenInBytes>65535||DST.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return H.create({dkLen:lenInBytes}).update(msg).update(i2osp(lenInBytes,2)).update(DST).update(i2osp(DST.length,1)).digest()}function hash_to_field(msg,count,options){(0,utils_ts_1._validateObject)(options,{p:"bigint",m:"number",k:"number",hash:"function"});const{p,k,m,hash,expand,DST:_DST}=options;if(!(0,utils_ts_1.isBytes)(_DST)&&"string"!=typeof _DST)throw new Error("DST must be string or uint8array");if(!(0,utils_ts_1.isHash)(options.hash))throw new Error("expected valid hash");(0,utils_ts_1.abytes)(msg),anum(count);const DST="string"==typeof _DST?(0,utils_ts_1.utf8ToBytes)(_DST):_DST,log2p=p.toString(2).length,L=Math.ceil((log2p+k)/8),len_in_bytes=count*m*L;let prb;if("xmd"===expand)prb=expand_message_xmd(msg,DST,len_in_bytes,hash);else if("xof"===expand)prb=expand_message_xof(msg,DST,len_in_bytes,k,hash);else{if("_internal_pass"!==expand)throw new Error('expand must be "xmd" or "xof"');prb=msg}const u=new Array(count);for(let i=0;i{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isNegativeLE=void 0,exports.mod=mod,exports.pow=function pow(num,power,modulo){return FpPow(Field(modulo),num,power)},exports.pow2=function pow2(x,power,modulo){let res=x;for(;power-- >_0n;)res*=res,res%=modulo;return res},exports.invert=invert,exports.tonelliShanks=tonelliShanks,exports.FpSqrt=FpSqrt,exports.validateField=function validateField(field){const opts=FIELD_FIELDS.reduce((map,val)=>(map[val]="function",map),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});return(0,utils_ts_1._validateObject)(field,opts),field},exports.FpPow=FpPow,exports.FpInvertBatch=FpInvertBatch,exports.FpDiv=function FpDiv(Fp,lhs,rhs){return Fp.mul(lhs,"bigint"==typeof rhs?invert(rhs,Fp.ORDER):Fp.inv(rhs))},exports.FpLegendre=FpLegendre,exports.FpIsSquare=function FpIsSquare(Fp,n){return 1===FpLegendre(Fp,n)},exports.nLength=nLength,exports.Field=Field,exports.FpSqrtOdd=function FpSqrtOdd(Fp,elm){if(!Fp.isOdd)throw new Error("Field doesn't have isOdd");const root=Fp.sqrt(elm);return Fp.isOdd(root)?root:Fp.neg(root)},exports.FpSqrtEven=function FpSqrtEven(Fp,elm){if(!Fp.isOdd)throw new Error("Field doesn't have isOdd");const root=Fp.sqrt(elm);return Fp.isOdd(root)?Fp.neg(root):root},exports.hashToPrivateScalar=function hashToPrivateScalar(hash,groupOrder,isLE=!1){const hashLen=(hash=(0,utils_ts_1.ensureBytes)("privateHash",hash)).length,minLen=nLength(groupOrder).nByteLength+8;if(minLen<24||hashLen1024)throw new Error("hashToPrivateScalar: expected "+minLen+"-1024 bytes of input, got "+hashLen);return mod(isLE?(0,utils_ts_1.bytesToNumberLE)(hash):(0,utils_ts_1.bytesToNumberBE)(hash),groupOrder-_1n)+_1n},exports.getFieldBytesLength=getFieldBytesLength,exports.getMinHashLength=getMinHashLength,exports.mapHashToField=function mapHashToField(key,fieldOrder,isLE=!1){const len=key.length,fieldLen=getFieldBytesLength(fieldOrder),minLen=getMinHashLength(fieldOrder);if(len<16||len1024)throw new Error("expected "+minLen+"-1024 bytes of input, got "+len);const reduced=mod(isLE?(0,utils_ts_1.bytesToNumberLE)(key):(0,utils_ts_1.bytesToNumberBE)(key),fieldOrder-_1n)+_1n;return isLE?(0,utils_ts_1.numberToBytesLE)(reduced,fieldLen):(0,utils_ts_1.numberToBytesBE)(reduced,fieldLen)};const utils_ts_1=__webpack_require__("./node_modules/@noble/curves/utils.js"),_0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_3n=BigInt(3),_4n=BigInt(4),_5n=BigInt(5),_8n=BigInt(8);function mod(a,b){const result=a%b;return result>=_0n?result:b+result}function invert(number,modulo){if(number===_0n)throw new Error("invert: expected non-zero number");if(modulo<=_0n)throw new Error("invert: expected positive modulus, got "+modulo);let a=mod(number,modulo),b=modulo,x=_0n,y=_1n,u=_1n,v=_0n;for(;a!==_0n;){const q=b/a,r=b%a,m=x-u*q,n=y-v*q;b=a,a=r,x=u,y=v,u=m,v=n}if(b!==_1n)throw new Error("invert: does not exist");return mod(x,modulo)}function sqrt3mod4(Fp,n){const p1div4=(Fp.ORDER+_1n)/_4n,root=Fp.pow(n,p1div4);if(!Fp.eql(Fp.sqr(root),n))throw new Error("Cannot find square root");return root}function sqrt5mod8(Fp,n){const p5div8=(Fp.ORDER-_5n)/_8n,n2=Fp.mul(n,_2n),v=Fp.pow(n2,p5div8),nv=Fp.mul(n,v),i=Fp.mul(Fp.mul(nv,_2n),v),root=Fp.mul(nv,Fp.sub(i,Fp.ONE));if(!Fp.eql(Fp.sqr(root),n))throw new Error("Cannot find square root");return root}function tonelliShanks(P){if(P1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===S)return sqrt3mod4;let cc=_Fp.pow(Z,Q);const Q1div2=(Q+_1n)/_2n;return function tonelliSlow(Fp,n){if(Fp.is0(n))return n;if(1!==FpLegendre(Fp,n))throw new Error("Cannot find square root");let M=S,c=Fp.mul(Fp.ONE,cc),t=Fp.pow(n,Q),R=Fp.pow(n,Q1div2);for(;!Fp.eql(t,Fp.ONE);){if(Fp.is0(t))return Fp.ZERO;let i=1,t_tmp=Fp.sqr(t);for(;!Fp.eql(t_tmp,Fp.ONE);)if(i++,t_tmp=Fp.sqr(t_tmp),i===M)throw new Error("Cannot find square root");const exponent=_1n<(mod(num,modulo)&_1n)===_1n;const FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function FpPow(Fp,num,power){if(power<_0n)throw new Error("invalid exponent, negatives unsupported");if(power===_0n)return Fp.ONE;if(power===_1n)return num;let p=Fp.ONE,d=num;for(;power>_0n;)power&_1n&&(p=Fp.mul(p,d)),d=Fp.sqr(d),power>>=_1n;return p}function FpInvertBatch(Fp,nums,passZero=!1){const inverted=new Array(nums.length).fill(passZero?Fp.ZERO:void 0),multipliedAcc=nums.reduce((acc,num,i)=>Fp.is0(num)?acc:(inverted[i]=acc,Fp.mul(acc,num)),Fp.ONE),invertedAcc=Fp.inv(multipliedAcc);return nums.reduceRight((acc,num,i)=>Fp.is0(num)?acc:(inverted[i]=Fp.mul(acc,inverted[i]),Fp.mul(acc,num)),invertedAcc),inverted}function FpLegendre(Fp,n){const p1mod2=(Fp.ORDER-_1n)/_2n,powered=Fp.pow(n,p1mod2),yes=Fp.eql(powered,Fp.ONE),zero=Fp.eql(powered,Fp.ZERO),no=Fp.eql(powered,Fp.neg(Fp.ONE));if(!yes&&!zero&&!no)throw new Error("invalid Legendre symbol result");return yes?1:zero?0:-1}function nLength(n,nBitLength){void 0!==nBitLength&&(0,utils_ts_1.anumber)(nBitLength);const _nBitLength=void 0!==nBitLength?nBitLength:n.toString(2).length;return{nBitLength:_nBitLength,nByteLength:Math.ceil(_nBitLength/8)}}function Field(ORDER,bitLenOrOpts,isLE=!1,opts={}){if(ORDER<=_0n)throw new Error("invalid field: expected ORDER > 0, got "+ORDER);let _nbitLength,_sqrt;if("object"==typeof bitLenOrOpts&&null!=bitLenOrOpts){if(opts.sqrt||isLE)throw new Error("cannot specify opts in two arguments");const _opts=bitLenOrOpts;_opts.BITS&&(_nbitLength=_opts.BITS),_opts.sqrt&&(_sqrt=_opts.sqrt),"boolean"==typeof _opts.isLE&&(isLE=_opts.isLE)}else"number"==typeof bitLenOrOpts&&(_nbitLength=bitLenOrOpts),opts.sqrt&&(_sqrt=opts.sqrt);const{nBitLength:BITS,nByteLength:BYTES}=nLength(ORDER,_nbitLength);if(BYTES>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let sqrtP;const f=Object.freeze({ORDER,isLE,BITS,BYTES,MASK:(0,utils_ts_1.bitMask)(BITS),ZERO:_0n,ONE:_1n,create:num=>mod(num,ORDER),isValid:num=>{if("bigint"!=typeof num)throw new Error("invalid field element: expected bigint, got "+typeof num);return _0n<=num&&numnum===_0n,isValidNot0:num=>!f.is0(num)&&f.isValid(num),isOdd:num=>(num&_1n)===_1n,neg:num=>mod(-num,ORDER),eql:(lhs,rhs)=>lhs===rhs,sqr:num=>mod(num*num,ORDER),add:(lhs,rhs)=>mod(lhs+rhs,ORDER),sub:(lhs,rhs)=>mod(lhs-rhs,ORDER),mul:(lhs,rhs)=>mod(lhs*rhs,ORDER),pow:(num,power)=>FpPow(f,num,power),div:(lhs,rhs)=>mod(lhs*invert(rhs,ORDER),ORDER),sqrN:num=>num*num,addN:(lhs,rhs)=>lhs+rhs,subN:(lhs,rhs)=>lhs-rhs,mulN:(lhs,rhs)=>lhs*rhs,inv:num=>invert(num,ORDER),sqrt:_sqrt||(n=>(sqrtP||(sqrtP=FpSqrt(ORDER)),sqrtP(f,n))),toBytes:num=>isLE?(0,utils_ts_1.numberToBytesLE)(num,BYTES):(0,utils_ts_1.numberToBytesBE)(num,BYTES),fromBytes:bytes=>{if(bytes.length!==BYTES)throw new Error("Field.fromBytes: expected "+BYTES+" bytes, got "+bytes.length);return isLE?(0,utils_ts_1.bytesToNumberLE)(bytes):(0,utils_ts_1.bytesToNumberBE)(bytes)},invertBatch:lst=>FpInvertBatch(f,lst),cmov:(a,b,c)=>c?b:a});return Object.freeze(f)}function getFieldBytesLength(fieldOrder){if("bigint"!=typeof fieldOrder)throw new Error("field order must be bigint");const bitLength=fieldOrder.toString(2).length;return Math.ceil(bitLength/8)}function getMinHashLength(fieldOrder){const length=getFieldBytesLength(fieldOrder);return length+Math.ceil(length/2)}},"./node_modules/@noble/curves/abstract/montgomery.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.montgomery=function montgomery(curveDef){const CURVE=function validateOpts(curve){return(0,utils_ts_1._validateObject)(curve,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...curve})}(curveDef),{P,type,adjustScalarBytes,powPminus2,randomBytes:rand}=CURVE,is25519="x25519"===type;if(!is25519&&"x448"!==type)throw new Error("invalid type");const randomBytes_=rand||utils_ts_1.randomBytes,montgomeryBits=is25519?255:448,fieldLen=is25519?32:56,Gu=is25519?BigInt(9):BigInt(5),a24=is25519?BigInt(121665):BigInt(39081),minScalar=is25519?_2n**BigInt(254):_2n**BigInt(447),maxAdded=is25519?BigInt(8)*_2n**BigInt(251)-_1n:BigInt(4)*_2n**BigInt(445)-_1n,maxScalar=minScalar+maxAdded+_1n,modP=n=>(0,modular_ts_1.mod)(n,P),GuBytes=encodeU(Gu);function encodeU(u){return(0,utils_ts_1.numberToBytesLE)(modP(u),fieldLen)}function scalarMult(scalar,u){const pu=function montgomeryLadder(u,scalar){(0,utils_ts_1.aInRange)("u",u,_0n,P),(0,utils_ts_1.aInRange)("scalar",scalar,minScalar,maxScalar);const k=scalar,x_1=u;let x_2=_1n,z_2=_0n,x_3=u,z_3=_1n,swap=_0n;for(let t=BigInt(montgomeryBits-1);t>=_0n;t--){const k_t=k>>t&_1n;swap^=k_t,({x_2,x_3}=cswap(swap,x_2,x_3)),({x_2:z_2,x_3:z_3}=cswap(swap,z_2,z_3)),swap=k_t;const A=x_2+z_2,AA=modP(A*A),B=x_2-z_2,BB=modP(B*B),E=AA-BB,C=x_3+z_3,DA=modP((x_3-z_3)*A),CB=modP(C*B),dacb=DA+CB,da_cb=DA-CB;x_3=modP(dacb*dacb),z_3=modP(x_1*modP(da_cb*da_cb)),x_2=modP(AA*BB),z_2=modP(E*(AA+modP(a24*E)))}({x_2,x_3}=cswap(swap,x_2,x_3)),({x_2:z_2,x_3:z_3}=cswap(swap,z_2,z_3));const z2=powPminus2(z_2);return modP(x_2*z2)}(function decodeU(u){const _u=(0,utils_ts_1.ensureBytes)("u coordinate",u,fieldLen);return is25519&&(_u[31]&=127),modP((0,utils_ts_1.bytesToNumberLE)(_u))}(u),function decodeScalar(scalar){return(0,utils_ts_1.bytesToNumberLE)(adjustScalarBytes((0,utils_ts_1.ensureBytes)("scalar",scalar,fieldLen)))}(scalar));if(pu===_0n)throw new Error("invalid private or public key received");return encodeU(pu)}function scalarMultBase(scalar){return scalarMult(scalar,GuBytes)}function cswap(swap,x_2,x_3){const dummy=modP(swap*(x_2-x_3));return{x_2:x_2=modP(x_2-dummy),x_3:x_3=modP(x_3+dummy)}}return{scalarMult,scalarMultBase,getSharedSecret:(privateKey,publicKey)=>scalarMult(privateKey,publicKey),getPublicKey:privateKey=>scalarMultBase(privateKey),utils:{randomPrivateKey:()=>randomBytes_(fieldLen)},GuBytes:GuBytes.slice()}};const utils_ts_1=__webpack_require__("./node_modules/@noble/curves/utils.js"),modular_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/modular.js"),_0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2)},"./node_modules/@noble/curves/ed25519.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.hash_to_ristretto255=exports.hashToRistretto255=exports.RistrettoPoint=exports.encodeToCurve=exports.hashToCurve=exports.ed25519_hasher=exports.edwardsToMontgomery=exports.x25519=exports.ed25519ph=exports.ed25519ctx=exports.ed25519=exports.ED25519_TORSION_SUBGROUP=void 0,exports.edwardsToMontgomeryPub=edwardsToMontgomeryPub,exports.edwardsToMontgomeryPriv=function edwardsToMontgomeryPriv(edwardsPriv){const hashed=ed25519Defaults.hash(edwardsPriv.subarray(0,32));return ed25519Defaults.adjustScalarBytes(hashed).subarray(0,32)};const sha2_js_1=__webpack_require__("./node_modules/@noble/hashes/sha2.js"),utils_js_1=__webpack_require__("./node_modules/@noble/hashes/utils.js"),curve_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/curve.js"),edwards_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/edwards.js"),hash_to_curve_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/hash-to-curve.js"),modular_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/modular.js"),montgomery_ts_1=__webpack_require__("./node_modules/@noble/curves/abstract/montgomery.js"),utils_ts_1=__webpack_require__("./node_modules/@noble/curves/utils.js"),_0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_3n=BigInt(3),_5n=BigInt(5),_8n=BigInt(8),ed25519_CURVE={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:_8n,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ed25519_pow_2_252_3(x){const _10n=BigInt(10),_20n=BigInt(20),_40n=BigInt(40),_80n=BigInt(80),P=ed25519_CURVE.p,b2=x*x%P*x%P,b4=(0,modular_ts_1.pow2)(b2,_2n,P)*b2%P,b5=(0,modular_ts_1.pow2)(b4,_1n,P)*x%P,b10=(0,modular_ts_1.pow2)(b5,_5n,P)*b5%P,b20=(0,modular_ts_1.pow2)(b10,_10n,P)*b10%P,b40=(0,modular_ts_1.pow2)(b20,_20n,P)*b20%P,b80=(0,modular_ts_1.pow2)(b40,_40n,P)*b40%P,b160=(0,modular_ts_1.pow2)(b80,_80n,P)*b80%P,b240=(0,modular_ts_1.pow2)(b160,_80n,P)*b80%P,b250=(0,modular_ts_1.pow2)(b240,_10n,P)*b10%P;return{pow_p_5_8:(0,modular_ts_1.pow2)(b250,_2n,P)*x%P,b2}}function adjustScalarBytes(bytes){return bytes[0]&=248,bytes[31]&=127,bytes[31]|=64,bytes}const ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function uvRatio(u,v){const P=ed25519_CURVE.p,v3=(0,modular_ts_1.mod)(v*v*v,P),pow=ed25519_pow_2_252_3(u*(0,modular_ts_1.mod)(v3*v3*v,P)).pow_p_5_8;let x=(0,modular_ts_1.mod)(u*v3*pow,P);const vx2=(0,modular_ts_1.mod)(v*x*x,P),root1=x,root2=(0,modular_ts_1.mod)(x*ED25519_SQRT_M1,P),useRoot1=vx2===u,useRoot2=vx2===(0,modular_ts_1.mod)(-u,P),noRoot=vx2===(0,modular_ts_1.mod)(-u*ED25519_SQRT_M1,P);return useRoot1&&(x=root1),(useRoot2||noRoot)&&(x=root2),(0,modular_ts_1.isNegativeLE)(x,P)&&(x=(0,modular_ts_1.mod)(-x,P)),{isValid:useRoot1||useRoot2,value:x}}exports.ED25519_TORSION_SUBGROUP=["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"];const Fp=(()=>(0,modular_ts_1.Field)(ed25519_CURVE.p,void 0,!0))(),ed25519Defaults=(()=>({...ed25519_CURVE,Fp,hash:sha2_js_1.sha512,adjustScalarBytes,uvRatio}))();function ed25519_domain(data,ctx,phflag){if(ctx.length>255)throw new Error("Context is too big");return(0,utils_js_1.concatBytes)((0,utils_js_1.utf8ToBytes)("SigEd25519 no Ed25519 collisions"),new Uint8Array([phflag?1:0,ctx.length]),ctx,data)}function edwardsToMontgomeryPub(edwardsPub){const bpub=(0,utils_ts_1.ensureBytes)("pub",edwardsPub),{y}=exports.ed25519.Point.fromHex(bpub),_1n=BigInt(1);return Fp.toBytes(Fp.create((_1n+y)*Fp.inv(_1n-y)))}exports.ed25519=(0,edwards_ts_1.twistedEdwards)(ed25519Defaults),exports.ed25519ctx=(0,edwards_ts_1.twistedEdwards)({...ed25519Defaults,domain:ed25519_domain}),exports.ed25519ph=(0,edwards_ts_1.twistedEdwards)(Object.assign({},ed25519Defaults,{domain:ed25519_domain,prehash:sha2_js_1.sha512})),exports.x25519=(()=>{const P=ed25519_CURVE.p;return(0,montgomery_ts_1.montgomery)({P,type:"x25519",powPminus2:x=>{const{pow_p_5_8,b2}=ed25519_pow_2_252_3(x);return(0,modular_ts_1.mod)((0,modular_ts_1.pow2)(pow_p_5_8,_3n,P)*b2,P)},adjustScalarBytes})})(),exports.edwardsToMontgomery=edwardsToMontgomeryPub;const ELL2_C1=(()=>(Fp.ORDER+_3n)/_8n)(),ELL2_C2=(()=>Fp.pow(_2n,ELL2_C1))(),ELL2_C3=(()=>Fp.sqrt(Fp.neg(Fp.ONE)))();const ELL2_C1_EDWARDS=(()=>(0,modular_ts_1.FpSqrtEven)(Fp,Fp.neg(BigInt(486664))))();function map_to_curve_elligator2_edwards25519(u){const{xMn,xMd,yMn,yMd}=function map_to_curve_elligator2_curve25519(u){const ELL2_C4=(Fp.ORDER-_5n)/_8n,ELL2_J=BigInt(486662);let tv1=Fp.sqr(u);tv1=Fp.mul(tv1,_2n);let xd=Fp.add(tv1,Fp.ONE),x1n=Fp.neg(ELL2_J),tv2=Fp.sqr(xd),gxd=Fp.mul(tv2,xd),gx1=Fp.mul(tv1,ELL2_J);gx1=Fp.mul(gx1,x1n),gx1=Fp.add(gx1,tv2),gx1=Fp.mul(gx1,x1n);let tv3=Fp.sqr(gxd);tv2=Fp.sqr(tv3),tv3=Fp.mul(tv3,gxd),tv3=Fp.mul(tv3,gx1),tv2=Fp.mul(tv2,tv3);let y11=Fp.pow(tv2,ELL2_C4);y11=Fp.mul(y11,tv3);let y12=Fp.mul(y11,ELL2_C3);tv2=Fp.sqr(y11),tv2=Fp.mul(tv2,gxd);let e1=Fp.eql(tv2,gx1),y1=Fp.cmov(y12,y11,e1),x2n=Fp.mul(x1n,tv1),y21=Fp.mul(y11,u);y21=Fp.mul(y21,ELL2_C2);let y22=Fp.mul(y21,ELL2_C3),gx2=Fp.mul(gx1,tv1);tv2=Fp.sqr(y21),tv2=Fp.mul(tv2,gxd);let e2=Fp.eql(tv2,gx2),y2=Fp.cmov(y22,y21,e2);tv2=Fp.sqr(y1),tv2=Fp.mul(tv2,gxd);let e3=Fp.eql(tv2,gx1),xn=Fp.cmov(x2n,x1n,e3),y=Fp.cmov(y2,y1,e3),e4=Fp.isOdd(y);return y=Fp.cmov(y,Fp.neg(y),e3!==e4),{xMn:xn,xMd:xd,yMn:y,yMd:_1n}}(u);let xn=Fp.mul(xMn,yMd);xn=Fp.mul(xn,ELL2_C1_EDWARDS);let xd=Fp.mul(xMd,yMn),yn=Fp.sub(xMn,xMd),yd=Fp.add(xMn,xMd),tv1=Fp.mul(xd,yd),e=Fp.eql(tv1,Fp.ZERO);xn=Fp.cmov(xn,Fp.ZERO,e),xd=Fp.cmov(xd,Fp.ONE,e),yn=Fp.cmov(yn,Fp.ONE,e),yd=Fp.cmov(yd,Fp.ONE,e);const[xd_inv,yd_inv]=(0,modular_ts_1.FpInvertBatch)(Fp,[xd,yd],!0);return{x:Fp.mul(xn,xd_inv),y:Fp.mul(yn,yd_inv)}}function aristp(other){if(!(other instanceof RistPoint))throw new Error("RistrettoPoint expected")}exports.ed25519_hasher=(0,hash_to_curve_ts_1.createHasher)(exports.ed25519.Point,scalars=>map_to_curve_elligator2_edwards25519(scalars[0]),{DST:"edwards25519_XMD:SHA-512_ELL2_RO_",encodeDST:"edwards25519_XMD:SHA-512_ELL2_NU_",p:Fp.ORDER,m:1,k:128,expand:"xmd",hash:sha2_js_1.sha512}),exports.hashToCurve=exports.ed25519_hasher.hashToCurve,exports.encodeToCurve=exports.ed25519_hasher.encodeToCurve;const SQRT_M1=ED25519_SQRT_M1,SQRT_AD_MINUS_ONE=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),INVSQRT_A_MINUS_D=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ONE_MINUS_D_SQ=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),D_MINUS_ONE_SQ=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),invertSqrt=number=>uvRatio(_1n,number),MAX_255B=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),bytes255ToNumberLE=bytes=>exports.ed25519.CURVE.Fp.create((0,utils_ts_1.bytesToNumberLE)(bytes)&MAX_255B);function calcElligatorRistrettoMap(r0){const{d}=exports.ed25519.CURVE,P=exports.ed25519.CURVE.Fp.ORDER,mod=exports.ed25519.CURVE.Fp.create,r=mod(SQRT_M1*r0*r0),Ns=mod((r+_1n)*ONE_MINUS_D_SQ);let c=BigInt(-1);const D=mod((c-d*r)*mod(r+d));let{isValid:Ns_D_is_sq,value:s}=uvRatio(Ns,D),s_=mod(s*r0);(0,modular_ts_1.isNegativeLE)(s_,P)||(s_=mod(-s_)),Ns_D_is_sq||(s=s_),Ns_D_is_sq||(c=r);const Nt=mod(c*(r-_1n)*D_MINUS_ONE_SQ-D),s2=s*s,W0=mod((s+s)*D),W1=mod(Nt*SQRT_AD_MINUS_ONE),W2=mod(_1n-s2),W3=mod(_1n+s2);return new exports.ed25519.Point(mod(W0*W3),mod(W2*W1),mod(W1*W3),mod(W0*W2))}class RistPoint{constructor(ep){this.ep=ep}static fromAffine(ap){return new RistPoint(exports.ed25519.Point.fromAffine(ap))}static hashToCurve(hex){hex=(0,utils_ts_1.ensureBytes)("ristrettoHash",hex,64);const R1=calcElligatorRistrettoMap(bytes255ToNumberLE(hex.slice(0,32))),R2=calcElligatorRistrettoMap(bytes255ToNumberLE(hex.slice(32,64)));return new RistPoint(R1.add(R2))}static fromBytes(bytes){return(0,utils_js_1.abytes)(bytes),this.fromHex(bytes)}static fromHex(hex){hex=(0,utils_ts_1.ensureBytes)("ristrettoHex",hex,32);const{a,d}=exports.ed25519.CURVE,P=Fp.ORDER,mod=Fp.create,emsg="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=bytes255ToNumberLE(hex);if(!(0,utils_ts_1.equalBytes)((0,utils_ts_1.numberToBytesLE)(s,32),hex)||(0,modular_ts_1.isNegativeLE)(s,P))throw new Error(emsg);const s2=mod(s*s),u1=mod(_1n+a*s2),u2=mod(_1n-a*s2),u1_2=mod(u1*u1),u2_2=mod(u2*u2),v=mod(a*d*u1_2-u2_2),{isValid,value:I}=invertSqrt(mod(v*u2_2)),Dx=mod(I*u2),Dy=mod(I*Dx*v);let x=mod((s+s)*Dx);(0,modular_ts_1.isNegativeLE)(x,P)&&(x=mod(-x));const y=mod(u1*Dy),t=mod(x*y);if(!isValid||(0,modular_ts_1.isNegativeLE)(t,P)||y===_0n)throw new Error(emsg);return new RistPoint(new exports.ed25519.Point(x,y,_1n,t))}static msm(points,scalars){const Fn=(0,modular_ts_1.Field)(exports.ed25519.CURVE.n,exports.ed25519.CURVE.nBitLength);return(0,curve_ts_1.pippenger)(RistPoint,Fn,points,scalars)}toBytes(){let{ex:x,ey:y,ez:z,et:t}=this.ep;const P=Fp.ORDER,mod=Fp.create,u1=mod(mod(z+y)*mod(z-y)),u2=mod(x*y),u2sq=mod(u2*u2),{value:invsqrt}=invertSqrt(mod(u1*u2sq)),D1=mod(invsqrt*u1),D2=mod(invsqrt*u2),zInv=mod(D1*D2*t);let D;if((0,modular_ts_1.isNegativeLE)(t*zInv,P)){let _x=mod(y*SQRT_M1),_y=mod(x*SQRT_M1);x=_x,y=_y,D=mod(D1*INVSQRT_A_MINUS_D)}else D=D2;(0,modular_ts_1.isNegativeLE)(x*zInv,P)&&(y=mod(-y));let s=mod((z-y)*D);return(0,modular_ts_1.isNegativeLE)(s,P)&&(s=mod(-s)),(0,utils_ts_1.numberToBytesLE)(s,32)}toRawBytes(){return this.toBytes()}toHex(){return(0,utils_ts_1.bytesToHex)(this.toBytes())}toString(){return this.toHex()}equals(other){aristp(other);const{ex:X1,ey:Y1}=this.ep,{ex:X2,ey:Y2}=other.ep,mod=Fp.create,one=mod(X1*Y2)===mod(Y1*X2),two=mod(Y1*Y2)===mod(X1*X2);return one||two}add(other){return aristp(other),new RistPoint(this.ep.add(other.ep))}subtract(other){return aristp(other),new RistPoint(this.ep.subtract(other.ep))}multiply(scalar){return new RistPoint(this.ep.multiply(scalar))}multiplyUnsafe(scalar){return new RistPoint(this.ep.multiplyUnsafe(scalar))}double(){return new RistPoint(this.ep.double())}negate(){return new RistPoint(this.ep.negate())}}exports.RistrettoPoint=(RistPoint.BASE||(RistPoint.BASE=new RistPoint(exports.ed25519.Point.BASE)),RistPoint.ZERO||(RistPoint.ZERO=new RistPoint(exports.ed25519.Point.ZERO)),RistPoint);exports.hashToRistretto255=(msg,options)=>{const d=options.DST,DST="string"==typeof d?(0,utils_js_1.utf8ToBytes)(d):d,uniform_bytes=(0,hash_to_curve_ts_1.expand_message_xmd)(msg,DST,64,sha2_js_1.sha512);return RistPoint.hashToCurve(uniform_bytes)},exports.hash_to_ristretto255=exports.hashToRistretto255},"./node_modules/@noble/curves/utils.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.notImplemented=exports.bitMask=exports.utf8ToBytes=exports.randomBytes=exports.isBytes=exports.hexToBytes=exports.concatBytes=exports.bytesToUtf8=exports.bytesToHex=exports.anumber=exports.abytes=void 0,exports.abool=function abool(title,value){if("boolean"!=typeof value)throw new Error(title+" boolean expected, got "+value)},exports.numberToHexUnpadded=numberToHexUnpadded,exports.hexToNumber=hexToNumber,exports.bytesToNumberBE=function bytesToNumberBE(bytes){return hexToNumber((0,utils_js_1.bytesToHex)(bytes))},exports.bytesToNumberLE=function bytesToNumberLE(bytes){return(0,utils_js_1.abytes)(bytes),hexToNumber((0,utils_js_1.bytesToHex)(Uint8Array.from(bytes).reverse()))},exports.numberToBytesBE=numberToBytesBE,exports.numberToBytesLE=function numberToBytesLE(n,len){return numberToBytesBE(n,len).reverse()},exports.numberToVarBytesBE=function numberToVarBytesBE(n){return(0,utils_js_1.hexToBytes)(numberToHexUnpadded(n))},exports.ensureBytes=function ensureBytes(title,hex,expectedLength){let res;if("string"==typeof hex)try{res=(0,utils_js_1.hexToBytes)(hex)}catch(e){throw new Error(title+" must be hex string or Uint8Array, cause: "+e)}else{if(!(0,utils_js_1.isBytes)(hex))throw new Error(title+" must be hex string or Uint8Array");res=Uint8Array.from(hex)}const len=res.length;if("number"==typeof expectedLength&&len!==expectedLength)throw new Error(title+" of length "+expectedLength+" expected, got "+len);return res},exports.equalBytes=function equalBytes(a,b){if(a.length!==b.length)return!1;let diff=0;for(let i=0;i_0n;n>>=_1n,len+=1);return len},exports.bitGet=function bitGet(n,pos){return n>>BigInt(pos)&_1n},exports.bitSet=function bitSet(n,pos,value){return n|(value?_1n:_0n)<new Uint8Array(len),u8of=byte=>Uint8Array.of(byte);let v=u8n(hashLen),k=u8n(hashLen),i=0;const reset=()=>{v.fill(1),k.fill(0),i=0},h=(...b)=>hmacFn(k,v,...b),reseed=(seed=u8n(0))=>{k=h(u8of(0),seed),v=h(),0!==seed.length&&(k=h(u8of(1),seed),v=h())},gen=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let len=0;const out=[];for(;len{let res;for(reset(),reseed(seed);!(res=pred(gen()));)reseed();return reset(),res}},exports.validateObject=function validateObject(object,validators,optValidators={}){const checkField=(fieldName,type,isOptional)=>{const checkVal=validatorFns[type];if("function"!=typeof checkVal)throw new Error("invalid validator function");const val=object[fieldName];if(!(isOptional&&void 0===val||checkVal(val,object)))throw new Error("param "+String(fieldName)+" is invalid. Expected "+type+", got "+val)};for(const[fieldName,type]of Object.entries(validators))checkField(fieldName,type,!1);for(const[fieldName,type]of Object.entries(optValidators))checkField(fieldName,type,!0);return object},exports.isHash=function isHash(val){return"function"==typeof val&&Number.isSafeInteger(val.outputLen)},exports._validateObject=function _validateObject(object,fields,optFields={}){if(!object||"object"!=typeof object)throw new Error("expected valid options object");function checkField(fieldName,expectedType,isOpt){const val=object[fieldName];if(isOpt&&void 0===val)return;const current=typeof val;if(current!==expectedType||null===val)throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`)}Object.entries(fields).forEach(([k,v])=>checkField(k,v,!1)),Object.entries(optFields).forEach(([k,v])=>checkField(k,v,!0))},exports.memoized=function memoized(fn){const map=new WeakMap;return(arg,...args)=>{const val=map.get(arg);if(void 0!==val)return val;const computed=fn(arg,...args);return map.set(arg,computed),computed}};const utils_js_1=__webpack_require__("./node_modules/@noble/hashes/utils.js");var utils_js_2=__webpack_require__("./node_modules/@noble/hashes/utils.js");Object.defineProperty(exports,"abytes",{enumerable:!0,get:function(){return utils_js_2.abytes}}),Object.defineProperty(exports,"anumber",{enumerable:!0,get:function(){return utils_js_2.anumber}}),Object.defineProperty(exports,"bytesToHex",{enumerable:!0,get:function(){return utils_js_2.bytesToHex}}),Object.defineProperty(exports,"bytesToUtf8",{enumerable:!0,get:function(){return utils_js_2.bytesToUtf8}}),Object.defineProperty(exports,"concatBytes",{enumerable:!0,get:function(){return utils_js_2.concatBytes}}),Object.defineProperty(exports,"hexToBytes",{enumerable:!0,get:function(){return utils_js_2.hexToBytes}}),Object.defineProperty(exports,"isBytes",{enumerable:!0,get:function(){return utils_js_2.isBytes}}),Object.defineProperty(exports,"randomBytes",{enumerable:!0,get:function(){return utils_js_2.randomBytes}}),Object.defineProperty(exports,"utf8ToBytes",{enumerable:!0,get:function(){return utils_js_2.utf8ToBytes}});const _0n=BigInt(0),_1n=BigInt(1);function numberToHexUnpadded(num){const hex=num.toString(16);return 1&hex.length?"0"+hex:hex}function hexToNumber(hex){if("string"!=typeof hex)throw new Error("hex string expected, got "+typeof hex);return""===hex?_0n:BigInt("0x"+hex)}function numberToBytesBE(n,len){return(0,utils_js_1.hexToBytes)(n.toString(16).padStart(2*len,"0"))}const isPosBig=n=>"bigint"==typeof n&&_0n<=n;function inRange(n,min,max){return isPosBig(n)&&isPosBig(min)&&isPosBig(max)&&min<=n&&n(_1n<"bigint"==typeof val,function:val=>"function"==typeof val,boolean:val=>"boolean"==typeof val,string:val=>"string"==typeof val,stringOrUint8Array:val=>"string"==typeof val||(0,utils_js_1.isBytes)(val),isSafeInteger:val=>Number.isSafeInteger(val),array:val=>Array.isArray(val),field:(val,object)=>object.Fp.isValid(val),hash:val=>"function"==typeof val&&Number.isSafeInteger(val.outputLen)};exports.notImplemented=()=>{throw new Error("not implemented")}},"./node_modules/@noble/hashes/_md.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SHA512_IV=exports.SHA384_IV=exports.SHA224_IV=exports.SHA256_IV=exports.HashMD=void 0,exports.setBigUint64=setBigUint64,exports.Chi=function Chi(a,b,c){return a&b^~a&c},exports.Maj=function Maj(a,b,c){return a&b^a&c^b&c};const utils_ts_1=__webpack_require__("./node_modules/@noble/hashes/utils.js");function setBigUint64(view,byteOffset,value,isLE){if("function"==typeof view.setBigUint64)return view.setBigUint64(byteOffset,value,isLE);const _32n=BigInt(32),_u32_max=BigInt(4294967295),wh=Number(value>>_32n&_u32_max),wl=Number(value&_u32_max),h=isLE?4:0,l=isLE?0:4;view.setUint32(byteOffset+h,wh,isLE),view.setUint32(byteOffset+l,wl,isLE)}class HashMD extends utils_ts_1.Hash{constructor(blockLen,outputLen,padOffset,isLE){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=blockLen,this.outputLen=outputLen,this.padOffset=padOffset,this.isLE=isLE,this.buffer=new Uint8Array(blockLen),this.view=(0,utils_ts_1.createView)(this.buffer)}update(data){(0,utils_ts_1.aexists)(this),data=(0,utils_ts_1.toBytes)(data),(0,utils_ts_1.abytes)(data);const{view,buffer,blockLen}=this,len=data.length;for(let pos=0;posblockLen-pos&&(this.process(view,0),pos=0);for(let i=pos;istate.length)throw new Error("_sha2: outputLen bigger than state");for(let i=0;i{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.toBig=exports.shrSL=exports.shrSH=exports.rotrSL=exports.rotrSH=exports.rotrBL=exports.rotrBH=exports.rotr32L=exports.rotr32H=exports.rotlSL=exports.rotlSH=exports.rotlBL=exports.rotlBH=exports.add5L=exports.add5H=exports.add4L=exports.add4H=exports.add3L=exports.add3H=void 0,exports.add=add,exports.fromBig=fromBig,exports.split=split;const U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(n,le=!1){return le?{h:Number(n&U32_MASK64),l:Number(n>>_32n&U32_MASK64)}:{h:0|Number(n>>_32n&U32_MASK64),l:0|Number(n&U32_MASK64)}}function split(lst,le=!1){const len=lst.length;let Ah=new Uint32Array(len),Al=new Uint32Array(len);for(let i=0;iBigInt(h>>>0)<<_32n|BigInt(l>>>0);exports.toBig=toBig;const shrSH=(h,_l,s)=>h>>>s;exports.shrSH=shrSH;const shrSL=(h,l,s)=>h<<32-s|l>>>s;exports.shrSL=shrSL;const rotrSH=(h,l,s)=>h>>>s|l<<32-s;exports.rotrSH=rotrSH;const rotrSL=(h,l,s)=>h<<32-s|l>>>s;exports.rotrSL=rotrSL;const rotrBH=(h,l,s)=>h<<64-s|l>>>s-32;exports.rotrBH=rotrBH;const rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;exports.rotrBL=rotrBL;const rotr32H=(_h,l)=>l;exports.rotr32H=rotr32H;const rotr32L=(h,_l)=>h;exports.rotr32L=rotr32L;const rotlSH=(h,l,s)=>h<>>32-s;exports.rotlSH=rotlSH;const rotlSL=(h,l,s)=>l<>>32-s;exports.rotlSL=rotlSL;const rotlBH=(h,l,s)=>l<>>64-s;exports.rotlBH=rotlBH;const rotlBL=(h,l,s)=>h<>>64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:0|l}}exports.rotlBL=rotlBL;const add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0);exports.add3L=add3L;const add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0;exports.add3H=add3H;const add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0);exports.add4L=add4L;const add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0;exports.add4H=add4H;const add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0);exports.add5L=add5L;const add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0;exports.add5H=add5H;const u64={fromBig,split,toBig,shrSH,shrSL,rotrSH,rotrSL,rotrBH,rotrBL,rotr32H,rotr32L,rotlSH,rotlSL,rotlBH,rotlBL,add,add3L,add3H,add4L,add4H,add5H,add5L};exports.default=u64},"./node_modules/@noble/hashes/crypto.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.crypto=void 0,exports.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0},"./node_modules/@noble/hashes/sha2.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.sha512_224=exports.sha512_256=exports.sha384=exports.sha512=exports.sha224=exports.sha256=exports.SHA512_256=exports.SHA512_224=exports.SHA384=exports.SHA512=exports.SHA224=exports.SHA256=void 0;const _md_ts_1=__webpack_require__("./node_modules/@noble/hashes/_md.js"),u64=__webpack_require__("./node_modules/@noble/hashes/_u64.js"),utils_ts_1=__webpack_require__("./node_modules/@noble/hashes/utils.js"),SHA256_K=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]),SHA256_W=new Uint32Array(64);class SHA256 extends _md_ts_1.HashMD{constructor(outputLen=32){super(64,outputLen,8,!1),this.A=0|_md_ts_1.SHA256_IV[0],this.B=0|_md_ts_1.SHA256_IV[1],this.C=0|_md_ts_1.SHA256_IV[2],this.D=0|_md_ts_1.SHA256_IV[3],this.E=0|_md_ts_1.SHA256_IV[4],this.F=0|_md_ts_1.SHA256_IV[5],this.G=0|_md_ts_1.SHA256_IV[6],this.H=0|_md_ts_1.SHA256_IV[7]}get(){const{A,B,C,D,E,F,G,H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=0|A,this.B=0|B,this.C=0|C,this.D=0|D,this.E=0|E,this.F=0|F,this.G=0|G,this.H=0|H}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,!1);for(let i=16;i<64;i++){const W15=SHA256_W[i-15],W2=SHA256_W[i-2],s0=(0,utils_ts_1.rotr)(W15,7)^(0,utils_ts_1.rotr)(W15,18)^W15>>>3,s1=(0,utils_ts_1.rotr)(W2,17)^(0,utils_ts_1.rotr)(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A,B,C,D,E,F,G,H}=this;for(let i=0;i<64;i++){const T1=H+((0,utils_ts_1.rotr)(E,6)^(0,utils_ts_1.rotr)(E,11)^(0,utils_ts_1.rotr)(E,25))+(0,_md_ts_1.Chi)(E,F,G)+SHA256_K[i]+SHA256_W[i]|0,T2=((0,utils_ts_1.rotr)(A,2)^(0,utils_ts_1.rotr)(A,13)^(0,utils_ts_1.rotr)(A,22))+(0,_md_ts_1.Maj)(A,B,C)|0;H=G,G=F,F=E,E=D+T1|0,D=C,C=B,B=A,A=T1+T2|0}A=A+this.A|0,B=B+this.B|0,C=C+this.C|0,D=D+this.D|0,E=E+this.E|0,F=F+this.F|0,G=G+this.G|0,H=H+this.H|0,this.set(A,B,C,D,E,F,G,H)}roundClean(){(0,utils_ts_1.clean)(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,utils_ts_1.clean)(this.buffer)}}exports.SHA256=SHA256;class SHA224 extends SHA256{constructor(){super(28),this.A=0|_md_ts_1.SHA224_IV[0],this.B=0|_md_ts_1.SHA224_IV[1],this.C=0|_md_ts_1.SHA224_IV[2],this.D=0|_md_ts_1.SHA224_IV[3],this.E=0|_md_ts_1.SHA224_IV[4],this.F=0|_md_ts_1.SHA224_IV[5],this.G=0|_md_ts_1.SHA224_IV[6],this.H=0|_md_ts_1.SHA224_IV[7]}}exports.SHA224=SHA224;const K512=(()=>u64.split(["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"].map(n=>BigInt(n))))(),SHA512_Kh=(()=>K512[0])(),SHA512_Kl=(()=>K512[1])(),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends _md_ts_1.HashMD{constructor(outputLen=64){super(128,outputLen,16,!1),this.Ah=0|_md_ts_1.SHA512_IV[0],this.Al=0|_md_ts_1.SHA512_IV[1],this.Bh=0|_md_ts_1.SHA512_IV[2],this.Bl=0|_md_ts_1.SHA512_IV[3],this.Ch=0|_md_ts_1.SHA512_IV[4],this.Cl=0|_md_ts_1.SHA512_IV[5],this.Dh=0|_md_ts_1.SHA512_IV[6],this.Dl=0|_md_ts_1.SHA512_IV[7],this.Eh=0|_md_ts_1.SHA512_IV[8],this.El=0|_md_ts_1.SHA512_IV[9],this.Fh=0|_md_ts_1.SHA512_IV[10],this.Fl=0|_md_ts_1.SHA512_IV[11],this.Gh=0|_md_ts_1.SHA512_IV[12],this.Gl=0|_md_ts_1.SHA512_IV[13],this.Hh=0|_md_ts_1.SHA512_IV[14],this.Hl=0|_md_ts_1.SHA512_IV[15]}get(){const{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=0|Ah,this.Al=0|Al,this.Bh=0|Bh,this.Bl=0|Bl,this.Ch=0|Ch,this.Cl=0|Cl,this.Dh=0|Dh,this.Dl=0|Dl,this.Eh=0|Eh,this.El=0|El,this.Fh=0|Fh,this.Fl=0|Fl,this.Gh=0|Gh,this.Gl=0|Gl,this.Hh=0|Hh,this.Hl=0|Hl}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA512_W_H[i]=view.getUint32(offset),SHA512_W_L[i]=view.getUint32(offset+=4);for(let i=16;i<80;i++){const W15h=0|SHA512_W_H[i-15],W15l=0|SHA512_W_L[i-15],s0h=u64.rotrSH(W15h,W15l,1)^u64.rotrSH(W15h,W15l,8)^u64.shrSH(W15h,W15l,7),s0l=u64.rotrSL(W15h,W15l,1)^u64.rotrSL(W15h,W15l,8)^u64.shrSL(W15h,W15l,7),W2h=0|SHA512_W_H[i-2],W2l=0|SHA512_W_L[i-2],s1h=u64.rotrSH(W2h,W2l,19)^u64.rotrBH(W2h,W2l,61)^u64.shrSH(W2h,W2l,6),s1l=u64.rotrSL(W2h,W2l,19)^u64.rotrBL(W2h,W2l,61)^u64.shrSL(W2h,W2l,6),SUMl=u64.add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]),SUMh=u64.add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=0|SUMh,SHA512_W_L[i]=0|SUMl}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){const sigma1h=u64.rotrSH(Eh,El,14)^u64.rotrSH(Eh,El,18)^u64.rotrBH(Eh,El,41),sigma1l=u64.rotrSL(Eh,El,14)^u64.rotrSL(Eh,El,18)^u64.rotrBL(Eh,El,41),CHIh=Eh&Fh^~Eh&Gh,CHIl=El&Fl^~El&Gl,T1ll=u64.add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]),T1h=u64.add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]),T1l=0|T1ll,sigma0h=u64.rotrSH(Ah,Al,28)^u64.rotrBH(Ah,Al,34)^u64.rotrBH(Ah,Al,39),sigma0l=u64.rotrSL(Ah,Al,28)^u64.rotrBL(Ah,Al,34)^u64.rotrBL(Ah,Al,39),MAJh=Ah&Bh^Ah&Ch^Bh&Ch,MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=0|Gh,Hl=0|Gl,Gh=0|Fh,Gl=0|Fl,Fh=0|Eh,Fl=0|El,({h:Eh,l:El}=u64.add(0|Dh,0|Dl,0|T1h,0|T1l)),Dh=0|Ch,Dl=0|Cl,Ch=0|Bh,Cl=0|Bl,Bh=0|Ah,Bl=0|Al;const All=u64.add3L(T1l,sigma0l,MAJl);Ah=u64.add3H(All,T1h,sigma0h,MAJh),Al=0|All}({h:Ah,l:Al}=u64.add(0|this.Ah,0|this.Al,0|Ah,0|Al)),({h:Bh,l:Bl}=u64.add(0|this.Bh,0|this.Bl,0|Bh,0|Bl)),({h:Ch,l:Cl}=u64.add(0|this.Ch,0|this.Cl,0|Ch,0|Cl)),({h:Dh,l:Dl}=u64.add(0|this.Dh,0|this.Dl,0|Dh,0|Dl)),({h:Eh,l:El}=u64.add(0|this.Eh,0|this.El,0|Eh,0|El)),({h:Fh,l:Fl}=u64.add(0|this.Fh,0|this.Fl,0|Fh,0|Fl)),({h:Gh,l:Gl}=u64.add(0|this.Gh,0|this.Gl,0|Gh,0|Gl)),({h:Hh,l:Hl}=u64.add(0|this.Hh,0|this.Hl,0|Hh,0|Hl)),this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){(0,utils_ts_1.clean)(SHA512_W_H,SHA512_W_L)}destroy(){(0,utils_ts_1.clean)(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}exports.SHA512=SHA512;class SHA384 extends SHA512{constructor(){super(48),this.Ah=0|_md_ts_1.SHA384_IV[0],this.Al=0|_md_ts_1.SHA384_IV[1],this.Bh=0|_md_ts_1.SHA384_IV[2],this.Bl=0|_md_ts_1.SHA384_IV[3],this.Ch=0|_md_ts_1.SHA384_IV[4],this.Cl=0|_md_ts_1.SHA384_IV[5],this.Dh=0|_md_ts_1.SHA384_IV[6],this.Dl=0|_md_ts_1.SHA384_IV[7],this.Eh=0|_md_ts_1.SHA384_IV[8],this.El=0|_md_ts_1.SHA384_IV[9],this.Fh=0|_md_ts_1.SHA384_IV[10],this.Fl=0|_md_ts_1.SHA384_IV[11],this.Gh=0|_md_ts_1.SHA384_IV[12],this.Gl=0|_md_ts_1.SHA384_IV[13],this.Hh=0|_md_ts_1.SHA384_IV[14],this.Hl=0|_md_ts_1.SHA384_IV[15]}}exports.SHA384=SHA384;const T224_IV=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),T256_IV=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class SHA512_224 extends SHA512{constructor(){super(28),this.Ah=0|T224_IV[0],this.Al=0|T224_IV[1],this.Bh=0|T224_IV[2],this.Bl=0|T224_IV[3],this.Ch=0|T224_IV[4],this.Cl=0|T224_IV[5],this.Dh=0|T224_IV[6],this.Dl=0|T224_IV[7],this.Eh=0|T224_IV[8],this.El=0|T224_IV[9],this.Fh=0|T224_IV[10],this.Fl=0|T224_IV[11],this.Gh=0|T224_IV[12],this.Gl=0|T224_IV[13],this.Hh=0|T224_IV[14],this.Hl=0|T224_IV[15]}}exports.SHA512_224=SHA512_224;class SHA512_256 extends SHA512{constructor(){super(32),this.Ah=0|T256_IV[0],this.Al=0|T256_IV[1],this.Bh=0|T256_IV[2],this.Bl=0|T256_IV[3],this.Ch=0|T256_IV[4],this.Cl=0|T256_IV[5],this.Dh=0|T256_IV[6],this.Dl=0|T256_IV[7],this.Eh=0|T256_IV[8],this.El=0|T256_IV[9],this.Fh=0|T256_IV[10],this.Fl=0|T256_IV[11],this.Gh=0|T256_IV[12],this.Gl=0|T256_IV[13],this.Hh=0|T256_IV[14],this.Hl=0|T256_IV[15]}}exports.SHA512_256=SHA512_256,exports.sha256=(0,utils_ts_1.createHasher)(()=>new SHA256),exports.sha224=(0,utils_ts_1.createHasher)(()=>new SHA224),exports.sha512=(0,utils_ts_1.createHasher)(()=>new SHA512),exports.sha384=(0,utils_ts_1.createHasher)(()=>new SHA384),exports.sha512_256=(0,utils_ts_1.createHasher)(()=>new SHA512_256),exports.sha512_224=(0,utils_ts_1.createHasher)(()=>new SHA512_224)},"./node_modules/@noble/hashes/utils.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.wrapXOFConstructorWithOpts=exports.wrapConstructorWithOpts=exports.wrapConstructor=exports.Hash=exports.nextTick=exports.swap32IfBE=exports.byteSwapIfBE=exports.swap8IfBE=exports.isLE=void 0,exports.isBytes=isBytes,exports.anumber=anumber,exports.abytes=abytes,exports.ahash=function ahash(h){if("function"!=typeof h||"function"!=typeof h.create)throw new Error("Hash should be wrapped by utils.createHasher");anumber(h.outputLen),anumber(h.blockLen)},exports.aexists=function aexists(instance,checkFinished=!0){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")},exports.aoutput=function aoutput(out,instance){abytes(out);const min=instance.outputLen;if(out.length>>shift},exports.rotl=function rotl(word,shift){return word<>>32-shift>>>0},exports.byteSwap=byteSwap,exports.byteSwap32=byteSwap32,exports.bytesToHex=function bytesToHex(bytes){if(abytes(bytes),hasHexBuiltin)return bytes.toHex();let hex="";for(let i=0;i=0&&diff0&&!lengths.includes(b.length))throw new Error("Uint8Array expected of length "+lengths+", got length="+b.length)}function byteSwap(word){return word<<24&4278190080|word<<8&16711680|word>>>8&65280|word>>>24&255}function byteSwap32(arr){for(let i=0;in:n=>byteSwap(n),exports.byteSwapIfBE=exports.swap8IfBE,exports.swap32IfBE=exports.isLE?u=>u:byteSwap32;const hasHexBuiltin=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),hexes=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(ch){return ch>=asciis._0&&ch<=asciis._9?ch-asciis._0:ch>=asciis.A&&ch<=asciis.F?ch-(asciis.A-10):ch>=asciis.a&&ch<=asciis.f?ch-(asciis.a-10):void 0}function utf8ToBytes(str){if("string"!=typeof str)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(str))}function toBytes(data){return"string"==typeof data&&(data=utf8ToBytes(data)),abytes(data),data}exports.nextTick=async()=>{};function createHasher(hashCons){const hashC=msg=>hashCons().update(toBytes(msg)).digest(),tmp=hashCons();return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.create=()=>hashCons(),hashC}function createOptHasher(hashCons){const hashC=(msg,opts)=>hashCons(opts).update(toBytes(msg)).digest(),tmp=hashCons({});return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.create=opts=>hashCons(opts),hashC}function createXOFer(hashCons){const hashC=(msg,opts)=>hashCons(opts).update(toBytes(msg)).digest(),tmp=hashCons({});return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.create=opts=>hashCons(opts),hashC}exports.Hash=class Hash{},exports.wrapConstructor=createHasher,exports.wrapConstructorWithOpts=createOptHasher,exports.wrapXOFConstructorWithOpts=createXOFer},"./node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/lib/esm/index.browser.js":(__unused_webpack___webpack_module__,__webpack_exports__,__webpack_require__)=>{"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{startRemoteScenario:()=>startRemoteScenario,transact:()=>transact});var _solana_web3_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/@solana/web3.js/lib/index.browser.esm.js"),_solana_mobile_mobile_wallet_adapter_protocol__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/node_modules/@solana-mobile/mobile-wallet-adapter-protocol/lib/cjs/index.browser.js"),bs58__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/node_modules/bs58/index.js");function __rest(s,e){var t={};for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(null!=s&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(p=Object.getOwnPropertySymbols(s);ic.charCodeAt(0)))}function getPayloadFromTransaction(transaction){return fromUint8Array("version"in transaction?transaction.serialize():transaction.serialize({requireAllSignatures:!1,verifySignatures:!1}))}function getTransactionFromWireMessage(byteArray){const messageOffset=byteArray[0]*_solana_web3_js__WEBPACK_IMPORTED_MODULE_0__.SIGNATURE_LENGTH_IN_BYTES+1;return"legacy"===_solana_web3_js__WEBPACK_IMPORTED_MODULE_0__.VersionedMessage.deserializeMessageVersion(byteArray.slice(messageOffset,byteArray.length))?_solana_web3_js__WEBPACK_IMPORTED_MODULE_0__.Transaction.from(byteArray):_solana_web3_js__WEBPACK_IMPORTED_MODULE_0__.VersionedTransaction.deserialize(byteArray)}function transact(callback,config){return __awaiter(this,void 0,void 0,function*(){return yield(0,_solana_mobile_mobile_wallet_adapter_protocol__WEBPACK_IMPORTED_MODULE_1__.hL)(wallet=>callback(augmentWalletAPI(wallet)),config)})}function startRemoteScenario(config){return __awaiter(this,void 0,void 0,function*(){const{wallet,close,associationUrl}=yield(0,_solana_mobile_mobile_wallet_adapter_protocol__WEBPACK_IMPORTED_MODULE_1__.X2)(config);return{wallet:wallet.then(wallet=>augmentWalletAPI(wallet)),close,associationUrl}})}function augmentWalletAPI(wallet){return new Proxy({},{get(target,p){if(null==target[p])switch(p){case"signAndSendTransactions":target[p]=function(_a){var{minContextSlot,commitment,skipPreflight,maxRetries,waitForCommitmentToSendNextTransaction,transactions}=_a,rest=__rest(_a,["minContextSlot","commitment","skipPreflight","maxRetries","waitForCommitmentToSendNextTransaction","transactions"]);return __awaiter(this,void 0,void 0,function*(){const payloads=transactions.map(getPayloadFromTransaction),options={min_context_slot:minContextSlot,commitment,skip_preflight:skipPreflight,max_retries:maxRetries,wait_for_commitment_to_send_next_transaction:waitForCommitmentToSendNextTransaction},{signatures:base64EncodedSignatures}=yield wallet.signAndSendTransactions(Object.assign(Object.assign(Object.assign({},rest),Object.values(options).some(element=>null!=element)?{options}:null),{payloads}));return base64EncodedSignatures.map(toUint8Array).map(bs58__WEBPACK_IMPORTED_MODULE_2__.encode)})};break;case"signMessages":target[p]=function(_a){var{payloads}=_a,rest=__rest(_a,["payloads"]);return __awaiter(this,void 0,void 0,function*(){const base64EncodedPayloads=payloads.map(fromUint8Array),{signed_payloads:base64EncodedSignedMessages}=yield wallet.signMessages(Object.assign(Object.assign({},rest),{payloads:base64EncodedPayloads}));return base64EncodedSignedMessages.map(toUint8Array)})};break;case"signTransactions":target[p]=function(_a){var{transactions}=_a,rest=__rest(_a,["transactions"]);return __awaiter(this,void 0,void 0,function*(){const payloads=transactions.map(getPayloadFromTransaction),{signed_payloads:base64EncodedCompiledTransactions}=yield wallet.signTransactions(Object.assign(Object.assign({},rest),{payloads}));return base64EncodedCompiledTransactions.map(toUint8Array).map(getTransactionFromWireMessage)})};break;default:target[p]=wallet[p]}return target[p]},defineProperty:()=>!1,deleteProperty:()=>!1})}},"./node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/node_modules/@solana-mobile/mobile-wallet-adapter-protocol/lib/cjs/index.browser.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var walletStandardUtil=__webpack_require__("./node_modules/@solana/wallet-standard-util/lib/cjs/index.js");const SolanaMobileWalletAdapterErrorCode={ERROR_ASSOCIATION_PORT_OUT_OF_RANGE:"ERROR_ASSOCIATION_PORT_OUT_OF_RANGE",ERROR_REFLECTOR_ID_OUT_OF_RANGE:"ERROR_REFLECTOR_ID_OUT_OF_RANGE",ERROR_FORBIDDEN_WALLET_BASE_URL:"ERROR_FORBIDDEN_WALLET_BASE_URL",ERROR_SECURE_CONTEXT_REQUIRED:"ERROR_SECURE_CONTEXT_REQUIRED",ERROR_SESSION_CLOSED:"ERROR_SESSION_CLOSED",ERROR_SESSION_TIMEOUT:"ERROR_SESSION_TIMEOUT",ERROR_WALLET_NOT_FOUND:"ERROR_WALLET_NOT_FOUND",ERROR_INVALID_PROTOCOL_VERSION:"ERROR_INVALID_PROTOCOL_VERSION",ERROR_BROWSER_NOT_SUPPORTED:"ERROR_BROWSER_NOT_SUPPORTED"};class SolanaMobileWalletAdapterError extends Error{constructor(...args){const[code,message,data]=args;super(message),this.code=code,this.data=data,this.name="SolanaMobileWalletAdapterError"}}class SolanaMobileWalletAdapterProtocolError extends Error{constructor(...args){const[jsonRpcMessageId,code,message,data]=args;super(message),this.code=code,this.data=data,this.jsonRpcMessageId=jsonRpcMessageId,this.name="SolanaMobileWalletAdapterProtocolError"}}function __awaiter(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function fromUint8Array(byteArray,urlsafe){const base64=window.btoa(String.fromCharCode.call(null,...byteArray));return urlsafe?base64.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):base64}function createHelloReq(ecdhPublicKey,associationKeypairPrivateKey){return __awaiter(this,void 0,void 0,function*(){const publicKeyBuffer=yield crypto.subtle.exportKey("raw",ecdhPublicKey),signatureBuffer=yield crypto.subtle.sign({hash:"SHA-256",name:"ECDSA"},associationKeypairPrivateKey,publicKeyBuffer),response=new Uint8Array(publicKeyBuffer.byteLength+signatureBuffer.byteLength);return response.set(new Uint8Array(publicKeyBuffer),0),response.set(new Uint8Array(signatureBuffer),publicKeyBuffer.byteLength),response})}function createSIWSMessageBase64(payload){return function encode(input){return window.btoa(input)}(function createSIWSMessage(payload){return walletStandardUtil.createSignInMessageText(payload)}(payload))}function createMobileWalletProxy(protocolVersion,protocolRequestHandler){return new Proxy({},{get:(target,p)=>"then"===p?null:(null==target[p]&&(target[p]=function(inputParams){return __awaiter(this,void 0,void 0,function*(){const{method,params}=function handleMobileWalletRequest(methodName,methodParams,protocolVersion){let params=methodParams,method=methodName.toString().replace(/[A-Z]/g,letter=>`_${letter.toLowerCase()}`).toLowerCase();switch(methodName){case"authorize":{let{chain}=params;if("legacy"===protocolVersion){switch(chain){case"solana:testnet":chain="testnet";break;case"solana:devnet":chain="devnet";break;case"solana:mainnet":chain="mainnet-beta";break;default:chain=params.cluster}params.cluster=chain}else{switch(chain){case"testnet":case"devnet":chain=`solana:${chain}`;break;case"mainnet-beta":chain="solana:mainnet"}params.chain=chain}}case"reauthorize":{const{auth_token,identity}=params;if(auth_token)if("legacy"===protocolVersion)method="reauthorize",params={auth_token,identity};else method="authorize";break}}return{method,params}}(p,inputParams,protocolVersion),result=yield protocolRequestHandler(method,params);return"authorize"===method&¶ms.sign_in_payload&&!result.sign_in_result&&(result.sign_in_result=yield function signInFallback(signInPayload,authorizationResult,protocolRequestHandler){var _a;return __awaiter(this,void 0,void 0,function*(){const domain=null!==(_a=signInPayload.domain)&&void 0!==_a?_a:window.location.host,address=authorizationResult.accounts[0].address,siwsMessage=createSIWSMessageBase64(Object.assign(Object.assign({},signInPayload),{domain,address}));return{address,signed_message:siwsMessage,signature:(yield protocolRequestHandler("sign_messages",{addresses:[address],payloads:[siwsMessage]})).signed_payloads[0].slice(siwsMessage.length)}})}(params.sign_in_payload,result,protocolRequestHandler)),function handleMobileWalletResponse(method,response,protocolVersion){if("getCapabilities"===method){const capabilities=response;switch(protocolVersion){case"legacy":{const features=["solana:signTransactions"];return!0===capabilities.supports_clone_authorization&&features.push("solana:cloneAuthorization"),Object.assign(Object.assign({},capabilities),{features})}case"v1":return Object.assign(Object.assign({},capabilities),{supports_sign_and_send_transactions:!0,supports_clone_authorization:capabilities.features.includes("solana:cloneAuthorization")})}}return response}(p,result,protocolVersion)})}),target[p]),defineProperty:()=>!1,deleteProperty:()=>!1})}function encryptMessage(plaintext,sequenceNumber,sharedSecret){return __awaiter(this,void 0,void 0,function*(){const sequenceNumberVector=function createSequenceNumberVector(sequenceNumber){if(sequenceNumber>=4294967296)throw new Error("Outbound sequence number overflow. The maximum sequence number is 32-bytes.");const byteArray=new ArrayBuffer(4);return new DataView(byteArray).setUint32(0,sequenceNumber,!1),new Uint8Array(byteArray)}(sequenceNumber),initializationVector=new Uint8Array(12);crypto.getRandomValues(initializationVector);const ciphertext=yield crypto.subtle.encrypt(getAlgorithmParams(sequenceNumberVector,initializationVector),sharedSecret,(new TextEncoder).encode(plaintext)),response=new Uint8Array(sequenceNumberVector.byteLength+initializationVector.byteLength+ciphertext.byteLength);return response.set(new Uint8Array(sequenceNumberVector),0),response.set(new Uint8Array(initializationVector),sequenceNumberVector.byteLength),response.set(new Uint8Array(ciphertext),sequenceNumberVector.byteLength+initializationVector.byteLength),response})}function decryptMessage(message,sharedSecret){return __awaiter(this,void 0,void 0,function*(){const sequenceNumberVector=message.slice(0,4),initializationVector=message.slice(4,16),ciphertext=message.slice(16),plaintextBuffer=yield crypto.subtle.decrypt(getAlgorithmParams(sequenceNumberVector,initializationVector),sharedSecret,ciphertext);return function getUtf8Decoder(){void 0===_utf8Decoder&&(_utf8Decoder=new TextDecoder("utf-8"));return _utf8Decoder}().decode(plaintextBuffer)})}function getAlgorithmParams(sequenceNumber,initializationVector){return{additionalData:sequenceNumber,iv:initializationVector,name:"AES-GCM",tagLength:128}}let _utf8Decoder;function generateAssociationKeypair(){return __awaiter(this,void 0,void 0,function*(){return yield crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"])})}function generateECDHKeypair(){return __awaiter(this,void 0,void 0,function*(){return yield crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey","deriveBits"])})}function arrayBufferToBase64String(buffer){let binary="";const bytes=new Uint8Array(buffer),len=bytes.byteLength;for(let ii=0;ii65535)throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE,`Association port number must be between 49152 and 65535. ${port} given.`,{port});return port}function getStringWithURLUnsafeCharactersReplaced(unsafeBase64EncodedString){return unsafeBase64EncodedString.replace(/[/+=]/g,m=>({"/":"_","+":"-","=":"."}[m]))}function getPathParts(pathString){return pathString.replace(/(^\/+|\/+$)/g,"").split("/")}function getIntentURL(methodPathname,intentUrlBase){let baseUrl=null;if(intentUrlBase){try{baseUrl=new URL(intentUrlBase)}catch(_a){}if("https:"!==(null==baseUrl?void 0:baseUrl.protocol))throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,"Base URLs supplied by wallets must be valid `https` URLs")}baseUrl||(baseUrl=new URL("solana-wallet:/"));const pathname=methodPathname.startsWith("/")?methodPathname:[...getPathParts(baseUrl.pathname),...getPathParts(methodPathname)].join("/");return new URL(pathname,baseUrl)}function encryptJsonRpcMessage(jsonRpcMessage,sharedSecret){return __awaiter(this,void 0,void 0,function*(){return encryptMessage(JSON.stringify(jsonRpcMessage),jsonRpcMessage.id,sharedSecret)})}function decryptJsonRpcMessage(message,sharedSecret){return __awaiter(this,void 0,void 0,function*(){const plaintext=yield decryptMessage(message,sharedSecret),jsonRpcMessage=JSON.parse(plaintext);if(Object.hasOwnProperty.call(jsonRpcMessage,"error"))throw new SolanaMobileWalletAdapterProtocolError(jsonRpcMessage.id,jsonRpcMessage.error.code,jsonRpcMessage.error.message);return jsonRpcMessage})}function parseHelloRsp(payloadBuffer,associationPublicKey,ecdhPrivateKey){return __awaiter(this,void 0,void 0,function*(){const[associationPublicKeyBuffer,walletPublicKey]=yield Promise.all([crypto.subtle.exportKey("raw",associationPublicKey),crypto.subtle.importKey("raw",payloadBuffer.slice(0,65),{name:"ECDH",namedCurve:"P-256"},!1,[])]),sharedSecret=yield crypto.subtle.deriveBits({name:"ECDH",public:walletPublicKey},ecdhPrivateKey,256),ecdhSecretKey=yield crypto.subtle.importKey("raw",sharedSecret,"HKDF",!1,["deriveKey"]);return yield crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(associationPublicKeyBuffer),info:new Uint8Array},ecdhSecretKey,{name:"AES-GCM",length:128},!1,["encrypt","decrypt"])})}function parseSessionProps(message,sharedSecret){return __awaiter(this,void 0,void 0,function*(){const plaintext=yield decryptMessage(message,sharedSecret),jsonProperties=JSON.parse(plaintext);let protocolVersion="legacy";if(Object.hasOwnProperty.call(jsonProperties,"v"))switch(jsonProperties.v){case 1:case"1":case"v1":protocolVersion="v1";break;case"legacy":protocolVersion="legacy";break;default:throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION,`Unknown/unsupported protocol version: ${jsonProperties.v}`)}return{protocol_version:protocolVersion}})}const Browser_Firefox=0,Browser_Other=1;let _frame=null;function launchAssociation(associationUrl){return __awaiter(this,void 0,void 0,function*(){if("https:"===associationUrl.protocol)window.location.assign(associationUrl);else try{const browser=function getBrowser(){return-1!==navigator.userAgent.indexOf("Firefox/")?Browser_Firefox:Browser_Other}();switch(browser){case Browser_Firefox:!function launchUrlThroughHiddenFrame(url){null==_frame&&(_frame=document.createElement("iframe"),_frame.style.display="none",document.body.appendChild(_frame)),_frame.contentWindow.location.href=url.toString()}(associationUrl);break;case Browser_Other:{const detectionPromise=function getDetectionPromise(){return new Promise((resolve,reject)=>{function cleanup(){clearTimeout(timeoutId),window.removeEventListener("blur",handleBlur)}function handleBlur(){cleanup(),resolve()}window.addEventListener("blur",handleBlur);const timeoutId=setTimeout(()=>{cleanup(),reject()},3e3)})}();window.location.assign(associationUrl),yield detectionPromise;break}}}catch(e){throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND,"Found no installed wallet that supports the mobile wallet protocol.")}})}function startSession(associationPublicKey,associationURLBase){return __awaiter(this,void 0,void 0,function*(){const randomAssociationPort=function getRandomAssociationPort(){return assertAssociationPort(49152+Math.floor(16384*Math.random()))}(),associationUrl=yield function getAssociateAndroidIntentURL(associationPublicKey,putativePort,associationURLBase,protocolVersions=["v1"]){return __awaiter(this,void 0,void 0,function*(){const associationPort=assertAssociationPort(putativePort),encodedKey=arrayBufferToBase64String(yield crypto.subtle.exportKey("raw",associationPublicKey)),url=getIntentURL("v1/associate/local",associationURLBase);return url.searchParams.set("association",getStringWithURLUnsafeCharactersReplaced(encodedKey)),url.searchParams.set("port",`${associationPort}`),protocolVersions.forEach(version=>{url.searchParams.set("v",version)}),url})}(associationPublicKey,randomAssociationPort,associationURLBase);return yield launchAssociation(associationUrl),randomAssociationPort})}const WEBSOCKET_CONNECTION_CONFIG={retryDelayScheduleMs:[150,150,200,500,500,750,750,1e3],timeoutMs:3e4};function assertSecureContext(){if("undefined"==typeof window||!0!==window.isSecureContext)throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED,"The mobile wallet adapter protocol must be used in a secure context (`https`).")}function assertSecureEndpointSpecificURI(walletUriBase){let url;try{url=new URL(walletUriBase)}catch(_a){throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,"Invalid base URL supplied by wallet")}if("https:"!==url.protocol)throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,"Base URLs supplied by wallets must be valid `https` URLs")}function getSequenceNumberFromByteArray(byteArray){return new DataView(byteArray).getUint32(0,!1)}function getReflectorIdFromByteArray(byteArray){let{value:length,offset}=function decodeVarLong(byteArray){var b,bytes=new Uint8Array(byteArray),l=byteArray.byteLength,value=0,offset=0;do{if(offset>=l||offset>10)throw new RangeError("Failed to decode varint");value|=(127&(b=bytes[offset++]))<<7*offset}while(b>=128);return{value,offset}}(byteArray);return new Uint8Array(byteArray.slice(offset,offset+length))}exports.X2=function startRemoteScenario(config){return __awaiter(this,void 0,void 0,function*(){assertSecureContext();const associationKeypair=yield generateAssociationKeypair(),websocketURL=`wss://${null==config?void 0:config.remoteHostAuthority}/reflect`;let connectionStartTime;const getNextRetryDelayMs=(()=>{const schedule=[...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];return()=>schedule.length>1?schedule.shift():schedule[0]})();let encoding,socket,disposeSocket,nextJsonRpcMessageId=1,lastKnownInboundSequenceNumber=0,state={__type:"disconnected"},decodeBytes=evt=>__awaiter(this,void 0,void 0,function*(){if("base64"==encoding){return function toUint8Array(base64EncodedByteArray){return new Uint8Array(window.atob(base64EncodedByteArray).split("").map(c=>c.charCodeAt(0)))}(yield evt.data).buffer}return yield evt.data.arrayBuffer()});const associationUrl=yield new Promise((resolve,reject)=>{const handleOpen=()=>__awaiter(this,void 0,void 0,function*(){"connecting"===state.__type?(encoding=socket.protocol.includes("com.solana.mobilewalletadapter.v1.base64")?"base64":"binary",socket.removeEventListener("open",handleOpen)):console.warn(`Expected adapter state to be \`connecting\` at the moment the websocket opens. Got \`${state.__type}\`.`)}),handleClose=evt=>{evt.wasClean?state={__type:"disconnected"}:reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED,`The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`,{closeEvent:evt})),disposeSocket()},handleError=_evt=>__awaiter(this,void 0,void 0,function*(){disposeSocket(),Date.now()-connectionStartTime>=WEBSOCKET_CONNECTION_CONFIG.timeoutMs?reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT,`Failed to connect to the wallet websocket at ${websocketURL}.`)):(yield new Promise(resolve=>{const retryDelayMs=getNextRetryDelayMs();retryWaitTimeoutId=window.setTimeout(resolve,retryDelayMs)}),attemptSocketConnection())}),handleReflectorIdMessage=evt=>__awaiter(this,void 0,void 0,function*(){const responseBuffer=yield decodeBytes(evt);if("connecting"===state.__type){if(0==responseBuffer.byteLength)throw new Error("Encountered unexpected message while connecting");const reflectorId=getReflectorIdFromByteArray(responseBuffer);state={__type:"reflector_id_received",reflectorId};const associationUrl=yield function getRemoteAssociateAndroidIntentURL(associationPublicKey,hostAuthority,reflectorId,associationURLBase,protocolVersions=["v1"]){return __awaiter(this,void 0,void 0,function*(){const encodedKey=arrayBufferToBase64String(yield crypto.subtle.exportKey("raw",associationPublicKey)),url=getIntentURL("v1/associate/remote",associationURLBase);return url.searchParams.set("association",getStringWithURLUnsafeCharactersReplaced(encodedKey)),url.searchParams.set("reflector",`${hostAuthority}`),url.searchParams.set("id",`${fromUint8Array(reflectorId,!0)}`),protocolVersions.forEach(version=>{url.searchParams.set("v",version)}),url})}(associationKeypair.publicKey,config.remoteHostAuthority,reflectorId,null==config?void 0:config.baseUri);socket.removeEventListener("message",handleReflectorIdMessage),resolve(associationUrl)}});let retryWaitTimeoutId;const attemptSocketConnection=()=>{disposeSocket&&disposeSocket(),state={__type:"connecting",associationKeypair},void 0===connectionStartTime&&(connectionStartTime=Date.now()),socket=new WebSocket(websocketURL,["com.solana.mobilewalletadapter.v1","com.solana.mobilewalletadapter.v1.base64"]),socket.addEventListener("open",handleOpen),socket.addEventListener("close",handleClose),socket.addEventListener("error",handleError),socket.addEventListener("message",handleReflectorIdMessage),disposeSocket=()=>{window.clearTimeout(retryWaitTimeoutId),socket.removeEventListener("open",handleOpen),socket.removeEventListener("close",handleClose),socket.removeEventListener("error",handleError),socket.removeEventListener("message",handleReflectorIdMessage)}};attemptSocketConnection()});let handleClose,sessionEstablished=!1;return{associationUrl,close:()=>{socket.close(),handleClose()},wallet:new Promise((resolve,reject)=>{const jsonRpcResponsePromises={},handleMessage=evt=>__awaiter(this,void 0,void 0,function*(){const responseBuffer=yield decodeBytes(evt);switch(state.__type){case"reflector_id_received":if(0!==responseBuffer.byteLength)throw new Error("Encountered unexpected message while awaiting reflection");const ecdhKeypair=yield generateECDHKeypair(),binaryMsg=yield createHelloReq(ecdhKeypair.publicKey,associationKeypair.privateKey);"base64"==encoding?socket.send(fromUint8Array(binaryMsg)):socket.send(binaryMsg),state={__type:"hello_req_sent",associationPublicKey:associationKeypair.publicKey,ecdhPrivateKey:ecdhKeypair.privateKey};break;case"connected":try{const sequenceNumber=getSequenceNumberFromByteArray(responseBuffer.slice(0,4));if(sequenceNumber!==lastKnownInboundSequenceNumber+1)throw new Error("Encrypted message has invalid sequence number");lastKnownInboundSequenceNumber=sequenceNumber;const jsonRpcMessage=yield decryptJsonRpcMessage(responseBuffer,state.sharedSecret),responsePromise=jsonRpcResponsePromises[jsonRpcMessage.id];delete jsonRpcResponsePromises[jsonRpcMessage.id],responsePromise.resolve(jsonRpcMessage.result)}catch(e){if(!(e instanceof SolanaMobileWalletAdapterProtocolError))throw e;{const responsePromise=jsonRpcResponsePromises[e.jsonRpcMessageId];delete jsonRpcResponsePromises[e.jsonRpcMessageId],responsePromise.reject(e)}}break;case"hello_req_sent":{const sharedSecret=yield parseHelloRsp(responseBuffer,state.associationPublicKey,state.ecdhPrivateKey),sessionPropertiesBuffer=responseBuffer.slice(65),sessionProperties=0!==sessionPropertiesBuffer.byteLength?yield(()=>__awaiter(this,void 0,void 0,function*(){const sequenceNumber=getSequenceNumberFromByteArray(sessionPropertiesBuffer.slice(0,4));if(sequenceNumber!==lastKnownInboundSequenceNumber+1)throw new Error("Encrypted message has invalid sequence number");return lastKnownInboundSequenceNumber=sequenceNumber,parseSessionProps(sessionPropertiesBuffer,sharedSecret)}))():{protocol_version:"legacy"};state={__type:"connected",sharedSecret,sessionProperties};const wallet=createMobileWalletProxy(sessionProperties.protocol_version,(method,params)=>__awaiter(this,void 0,void 0,function*(){const id=nextJsonRpcMessageId++,binaryMsg=yield encryptJsonRpcMessage({id,jsonrpc:"2.0",method,params:null!=params?params:{}},sharedSecret);return"base64"==encoding?socket.send(fromUint8Array(binaryMsg)):socket.send(binaryMsg),new Promise((resolve,reject)=>{jsonRpcResponsePromises[id]={resolve(result){switch(method){case"authorize":case"reauthorize":{const{wallet_uri_base}=result;if(null!=wallet_uri_base)try{assertSecureEndpointSpecificURI(wallet_uri_base)}catch(e){return void reject(e)}break}}resolve(result)},reject}})}));sessionEstablished=!0;try{resolve(wallet)}catch(e){reject(e)}break}}});socket.addEventListener("message",handleMessage),handleClose=()=>{socket.removeEventListener("message",handleMessage),disposeSocket(),sessionEstablished||reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED,"The wallet session was closed before connection.",{closeEvent:new CloseEvent("socket was closed before connection")}))}})}})},exports.hL=function transact(callback,config){return __awaiter(this,void 0,void 0,function*(){assertSecureContext();const associationKeypair=yield generateAssociationKeypair(),websocketURL=`ws://localhost:${yield startSession(associationKeypair.publicKey,null==config?void 0:config.baseUri)}/solana-wallet`;let connectionStartTime;const getNextRetryDelayMs=(()=>{const schedule=[...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];return()=>schedule.length>1?schedule.shift():schedule[0]})();let nextJsonRpcMessageId=1,lastKnownInboundSequenceNumber=0,state={__type:"disconnected"};return new Promise((resolve,reject)=>{let socket;const jsonRpcResponsePromises={},handleOpen=()=>__awaiter(this,void 0,void 0,function*(){if("connecting"!==state.__type)return void console.warn(`Expected adapter state to be \`connecting\` at the moment the websocket opens. Got \`${state.__type}\`.`);socket.removeEventListener("open",handleOpen);const{associationKeypair}=state,ecdhKeypair=yield generateECDHKeypair();socket.send(yield createHelloReq(ecdhKeypair.publicKey,associationKeypair.privateKey)),state={__type:"hello_req_sent",associationPublicKey:associationKeypair.publicKey,ecdhPrivateKey:ecdhKeypair.privateKey}}),handleClose=evt=>{evt.wasClean?state={__type:"disconnected"}:reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED,`The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`,{closeEvent:evt})),disposeSocket()},handleError=_evt=>__awaiter(this,void 0,void 0,function*(){disposeSocket(),Date.now()-connectionStartTime>=WEBSOCKET_CONNECTION_CONFIG.timeoutMs?reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT,`Failed to connect to the wallet websocket at ${websocketURL}.`)):(yield new Promise(resolve=>{const retryDelayMs=getNextRetryDelayMs();retryWaitTimeoutId=window.setTimeout(resolve,retryDelayMs)}),attemptSocketConnection())}),handleMessage=evt=>__awaiter(this,void 0,void 0,function*(){const responseBuffer=yield evt.data.arrayBuffer();switch(state.__type){case"connecting":if(0!==responseBuffer.byteLength)throw new Error("Encountered unexpected message while connecting");const ecdhKeypair=yield generateECDHKeypair();socket.send(yield createHelloReq(ecdhKeypair.publicKey,associationKeypair.privateKey)),state={__type:"hello_req_sent",associationPublicKey:associationKeypair.publicKey,ecdhPrivateKey:ecdhKeypair.privateKey};break;case"connected":try{const sequenceNumber=getSequenceNumberFromByteArray(responseBuffer.slice(0,4));if(sequenceNumber!==lastKnownInboundSequenceNumber+1)throw new Error("Encrypted message has invalid sequence number");lastKnownInboundSequenceNumber=sequenceNumber;const jsonRpcMessage=yield decryptJsonRpcMessage(responseBuffer,state.sharedSecret),responsePromise=jsonRpcResponsePromises[jsonRpcMessage.id];delete jsonRpcResponsePromises[jsonRpcMessage.id],responsePromise.resolve(jsonRpcMessage.result)}catch(e){if(!(e instanceof SolanaMobileWalletAdapterProtocolError))throw e;{const responsePromise=jsonRpcResponsePromises[e.jsonRpcMessageId];delete jsonRpcResponsePromises[e.jsonRpcMessageId],responsePromise.reject(e)}}break;case"hello_req_sent":{if(0===responseBuffer.byteLength){const ecdhKeypair=yield generateECDHKeypair();socket.send(yield createHelloReq(ecdhKeypair.publicKey,associationKeypair.privateKey)),state={__type:"hello_req_sent",associationPublicKey:associationKeypair.publicKey,ecdhPrivateKey:ecdhKeypair.privateKey};break}const sharedSecret=yield parseHelloRsp(responseBuffer,state.associationPublicKey,state.ecdhPrivateKey),sessionPropertiesBuffer=responseBuffer.slice(65),sessionProperties=0!==sessionPropertiesBuffer.byteLength?yield(()=>__awaiter(this,void 0,void 0,function*(){const sequenceNumber=getSequenceNumberFromByteArray(sessionPropertiesBuffer.slice(0,4));if(sequenceNumber!==lastKnownInboundSequenceNumber+1)throw new Error("Encrypted message has invalid sequence number");return lastKnownInboundSequenceNumber=sequenceNumber,parseSessionProps(sessionPropertiesBuffer,sharedSecret)}))():{protocol_version:"legacy"};state={__type:"connected",sharedSecret,sessionProperties};const wallet=createMobileWalletProxy(sessionProperties.protocol_version,(method,params)=>__awaiter(this,void 0,void 0,function*(){const id=nextJsonRpcMessageId++;return socket.send(yield encryptJsonRpcMessage({id,jsonrpc:"2.0",method,params:null!=params?params:{}},sharedSecret)),new Promise((resolve,reject)=>{jsonRpcResponsePromises[id]={resolve(result){switch(method){case"authorize":case"reauthorize":{const{wallet_uri_base}=result;if(null!=wallet_uri_base)try{assertSecureEndpointSpecificURI(wallet_uri_base)}catch(e){return void reject(e)}break}}resolve(result)},reject}})}));try{resolve(yield callback(wallet))}catch(e){reject(e)}finally{disposeSocket(),socket.close()}break}}});let disposeSocket,retryWaitTimeoutId;const attemptSocketConnection=()=>{disposeSocket&&disposeSocket(),state={__type:"connecting",associationKeypair},void 0===connectionStartTime&&(connectionStartTime=Date.now()),socket=new WebSocket(websocketURL,["com.solana.mobilewalletadapter.v1"]),socket.addEventListener("open",handleOpen),socket.addEventListener("close",handleClose),socket.addEventListener("error",handleError),socket.addEventListener("message",handleMessage),disposeSocket=()=>{window.clearTimeout(retryWaitTimeoutId),socket.removeEventListener("open",handleOpen),socket.removeEventListener("close",handleClose),socket.removeEventListener("error",handleError),socket.removeEventListener("message",handleMessage)}};attemptSocketConnection()})})}},"./node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/node_modules/base-x/src/index.js":module=>{"use strict";module.exports=function base(ALPHABET){if(ALPHABET.length>=255)throw new TypeError("Alphabet too long");for(var BASE_MAP=new Uint8Array(256),j=0;j>>0,b256=new Uint8Array(size);source[psz];){var charCode=source.charCodeAt(psz);if(charCode>255)return;var carry=BASE_MAP[charCode];if(255===carry)return;for(var i=0,it3=size-1;(0!==carry||i>>0,b256[it3]=carry%256>>>0,carry=carry/256>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,psz++}for(var it4=size-length;it4!==size&&0===b256[it4];)it4++;for(var vch=new Uint8Array(zeroes+(size-it4)),j=zeroes;it4!==size;)vch[j++]=b256[it4++];return vch}return{encode:function encode(source){if(source instanceof Uint8Array||(ArrayBuffer.isView(source)?source=new Uint8Array(source.buffer,source.byteOffset,source.byteLength):Array.isArray(source)&&(source=Uint8Array.from(source))),!(source instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===source.length)return"";for(var zeroes=0,length=0,pbegin=0,pend=source.length;pbegin!==pend&&0===source[pbegin];)pbegin++,zeroes++;for(var size=(pend-pbegin)*iFACTOR+1>>>0,b58=new Uint8Array(size);pbegin!==pend;){for(var carry=source[pbegin],i=0,it1=size-1;(0!==carry||i>>0,b58[it1]=carry%BASE>>>0,carry=carry/BASE>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,pbegin++}for(var it2=size-length;it2!==size&&0===b58[it2];)it2++;for(var str=LEADER.repeat(zeroes);it2{const basex=__webpack_require__("./node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/node_modules/base-x/src/index.js");module.exports=basex("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},"./node_modules/@solana-mobile/wallet-adapter-mobile/lib/cjs/index.browser.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var walletAdapterBase=__webpack_require__("./node_modules/@solana/wallet-adapter-base/lib/cjs/index.js"),web3_js=__webpack_require__("./node_modules/@solana/web3.js/lib/index.browser.esm.js"),walletStandardFeatures=__webpack_require__("./node_modules/@solana/wallet-standard-features/lib/cjs/index.js"),walletStandardMobile=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/lib/cjs/index.js");function __awaiter(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __classPrivateFieldGet(receiver,state,kind,f){if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===kind?f:"a"===kind?f.call(receiver):f?f.value:state.get(receiver)}function __classPrivateFieldSet(receiver,state,value,kind,f){if("m"===kind)throw new TypeError("Private method is not writable");if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===kind?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value}function fromUint8Array(byteArray){return window.btoa(String.fromCharCode.call(null,...byteArray))}var _BaseSolanaMobileWalletAdapter_instances,_BaseSolanaMobileWalletAdapter_wallet,_BaseSolanaMobileWalletAdapter_connecting,_BaseSolanaMobileWalletAdapter_readyState,_BaseSolanaMobileWalletAdapter_accountSelector,_BaseSolanaMobileWalletAdapter_selectedAccount,_BaseSolanaMobileWalletAdapter_publicKey,_BaseSolanaMobileWalletAdapter_handleChangeEvent,_BaseSolanaMobileWalletAdapter_connect,_BaseSolanaMobileWalletAdapter_declareWalletAsInstalled,_BaseSolanaMobileWalletAdapter_assertIsAuthorized,_BaseSolanaMobileWalletAdapter_performSignTransactions,_BaseSolanaMobileWalletAdapter_runWithGuard;function chainOrClusterToChainId(chain){switch(chain){case"mainnet-beta":return"solana:mainnet";case"testnet":return"solana:testnet";case"devnet":return"solana:devnet";default:return chain}}class BaseSolanaMobileWalletAdapter extends walletAdapterBase.BaseSignInMessageSignerWalletAdapter{constructor(wallet,config){super(),_BaseSolanaMobileWalletAdapter_instances.add(this),this.supportedTransactionVersions=new Set(["legacy",0]),_BaseSolanaMobileWalletAdapter_wallet.set(this,void 0),_BaseSolanaMobileWalletAdapter_connecting.set(this,!1),_BaseSolanaMobileWalletAdapter_readyState.set(this,function getIsSupported(){return"undefined"!=typeof window&&window.isSecureContext&&"undefined"!=typeof document&&/android/i.test(navigator.userAgent)}()?walletAdapterBase.WalletReadyState.Loadable:walletAdapterBase.WalletReadyState.Unsupported),_BaseSolanaMobileWalletAdapter_accountSelector.set(this,void 0),_BaseSolanaMobileWalletAdapter_selectedAccount.set(this,void 0),_BaseSolanaMobileWalletAdapter_publicKey.set(this,void 0),_BaseSolanaMobileWalletAdapter_handleChangeEvent.set(this,properties=>__awaiter(this,void 0,void 0,function*(){if(properties.accounts&&properties.accounts.length>0){__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_declareWalletAsInstalled).call(this);const nextSelectedAccount=yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_accountSelector,"f").call(this,properties.accounts);nextSelectedAccount!==__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_selectedAccount,"f")&&(__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_selectedAccount,nextSelectedAccount,"f"),__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_publicKey,void 0,"f"),this.emit("connect",this.publicKey))}})),__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_accountSelector,accounts=>__awaiter(this,void 0,void 0,function*(){var _a;const selectedBase64EncodedAddress=yield config.addressSelector.select(accounts.map(({publicKey})=>fromUint8Array(publicKey)));return null!==(_a=accounts.find(({publicKey})=>fromUint8Array(publicKey)===selectedBase64EncodedAddress))&&void 0!==_a?_a:accounts[0]}),"f"),__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_wallet,wallet,"f"),__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features["standard:events"].on("change",__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_handleChangeEvent,"f")),this.name=__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").name,this.icon=__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").icon,this.url=__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").url}get publicKey(){var _a;if(!__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_publicKey,"f")&&__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_selectedAccount,"f"))try{__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_publicKey,new web3_js.PublicKey(__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_selectedAccount,"f").publicKey),"f")}catch(e){throw new walletAdapterBase.WalletPublicKeyError(e instanceof Error&&(null==e?void 0:e.message)||"Unknown error",e)}return null!==(_a=__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_publicKey,"f"))&&void 0!==_a?_a:null}get connected(){return __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").connected}get connecting(){return __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_connecting,"f")}get readyState(){return __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_readyState,"f")}autoConnect_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(){return __awaiter(this,void 0,void 0,function*(){return yield this.autoConnect()})}autoConnect(){return __awaiter(this,void 0,void 0,function*(){__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_connect).call(this,!0)})}connect(){return __awaiter(this,void 0,void 0,function*(){__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_connect).call(this)})}performAuthorization(signInPayload){return __awaiter(this,void 0,void 0,function*(){try{const cachedAuthorizationResult=yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").cachedAuthorizationResult;if(cachedAuthorizationResult)return yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features["standard:connect"].connect({silent:!0}),cachedAuthorizationResult;signInPayload?yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features[walletStandardFeatures.SolanaSignIn].signIn(signInPayload):yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features["standard:connect"].connect();return yield yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").cachedAuthorizationResult}catch(e){throw new walletAdapterBase.WalletConnectionError(e instanceof Error&&e.message||"Unknown error",e)}})}disconnect(){return __awaiter(this,void 0,void 0,function*(){return yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_runWithGuard).call(this,()=>__awaiter(this,void 0,void 0,function*(){__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_connecting,!1,"f"),__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_publicKey,void 0,"f"),__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_selectedAccount,void 0,"f"),yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features["standard:disconnect"].disconnect(),this.emit("disconnect")}))})}signIn(input){return __awaiter(this,void 0,void 0,function*(){return __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_runWithGuard).call(this,()=>__awaiter(this,void 0,void 0,function*(){var _a;if(__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_readyState,"f")!==walletAdapterBase.WalletReadyState.Installed&&__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_readyState,"f")!==walletAdapterBase.WalletReadyState.Loadable)throw new walletAdapterBase.WalletNotReadyError;__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_connecting,!0,"f");try{const outputs=yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features[walletStandardFeatures.SolanaSignIn].signIn(Object.assign(Object.assign({},input),{domain:null!==(_a=null==input?void 0:input.domain)&&void 0!==_a?_a:window.location.host}));if(outputs.length>0)return outputs[0];throw new Error("Sign in failed, no sign in result returned by wallet")}catch(e){throw new walletAdapterBase.WalletConnectionError(e instanceof Error&&e.message||"Unknown error",e)}finally{__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_connecting,!1,"f")}}))})}signMessage(message){return __awaiter(this,void 0,void 0,function*(){return yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_runWithGuard).call(this,()=>__awaiter(this,void 0,void 0,function*(){const account=__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_assertIsAuthorized).call(this);try{return(yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features[walletStandardFeatures.SolanaSignMessage].signMessage({account,message}))[0].signature}catch(error){throw new walletAdapterBase.WalletSignMessageError(null==error?void 0:error.message,error)}}))})}sendTransaction(transaction,connection,options){return __awaiter(this,void 0,void 0,function*(){return yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_runWithGuard).call(this,()=>__awaiter(this,void 0,void 0,function*(){const account=__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_assertIsAuthorized).call(this);try{function getTargetCommitment(){let targetCommitment,targetPreflightCommitment;switch(connection.commitment){case"confirmed":case"finalized":case"processed":targetCommitment=connection.commitment;break;default:targetCommitment="finalized"}switch(null==options?void 0:options.preflightCommitment){case"confirmed":case"finalized":case"processed":targetPreflightCommitment=options.preflightCommitment;break;case void 0:targetPreflightCommitment=targetCommitment;break;default:targetPreflightCommitment="finalized"}return("finalized"===targetPreflightCommitment?2:"confirmed"===targetPreflightCommitment?1:0)<("finalized"===targetCommitment?2:"confirmed"===targetCommitment?1:0)?targetPreflightCommitment:targetCommitment}if(walletStandardFeatures.SolanaSignAndSendTransaction in __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features){const chain=chainOrClusterToChainId(__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").currentAuthorization.chain),[signature]=(yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features[walletStandardFeatures.SolanaSignAndSendTransaction].signAndSendTransaction({account,transaction:transaction.serialize(),chain,options:options?{skipPreflight:options.skipPreflight,maxRetries:options.maxRetries}:void 0})).map(output=>fromUint8Array(output.signature));return signature}{const[signedTransaction]=yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_performSignTransactions).call(this,[transaction]);if(function isVersionedTransaction(transaction){return"version"in transaction}(signedTransaction))return yield connection.sendTransaction(signedTransaction);{const serializedTransaction=signedTransaction.serialize();return yield connection.sendRawTransaction(serializedTransaction,Object.assign(Object.assign({},options),{preflightCommitment:getTargetCommitment()}))}}}catch(error){throw new walletAdapterBase.WalletSendTransactionError(null==error?void 0:error.message,error)}}))})}signTransaction(transaction){return __awaiter(this,void 0,void 0,function*(){return yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_runWithGuard).call(this,()=>__awaiter(this,void 0,void 0,function*(){const[signedTransaction]=yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_performSignTransactions).call(this,[transaction]);return signedTransaction}))})}signAllTransactions(transactions){return __awaiter(this,void 0,void 0,function*(){return yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_runWithGuard).call(this,()=>__awaiter(this,void 0,void 0,function*(){return yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_performSignTransactions).call(this,transactions)}))})}}_BaseSolanaMobileWalletAdapter_wallet=new WeakMap,_BaseSolanaMobileWalletAdapter_connecting=new WeakMap,_BaseSolanaMobileWalletAdapter_readyState=new WeakMap,_BaseSolanaMobileWalletAdapter_accountSelector=new WeakMap,_BaseSolanaMobileWalletAdapter_selectedAccount=new WeakMap,_BaseSolanaMobileWalletAdapter_publicKey=new WeakMap,_BaseSolanaMobileWalletAdapter_handleChangeEvent=new WeakMap,_BaseSolanaMobileWalletAdapter_instances=new WeakSet,_BaseSolanaMobileWalletAdapter_connect=function _BaseSolanaMobileWalletAdapter_connect(autoConnect=!1){return __awaiter(this,void 0,void 0,function*(){if(!this.connecting&&!this.connected)return yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_runWithGuard).call(this,()=>__awaiter(this,void 0,void 0,function*(){if(__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_readyState,"f")!==walletAdapterBase.WalletReadyState.Installed&&__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_readyState,"f")!==walletAdapterBase.WalletReadyState.Loadable)throw new walletAdapterBase.WalletNotReadyError;__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_connecting,!0,"f");try{yield __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features["standard:connect"].connect({silent:autoConnect})}catch(e){throw new walletAdapterBase.WalletConnectionError(e instanceof Error&&e.message||"Unknown error",e)}finally{__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_connecting,!1,"f")}}))})},_BaseSolanaMobileWalletAdapter_declareWalletAsInstalled=function _BaseSolanaMobileWalletAdapter_declareWalletAsInstalled(){__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_readyState,"f")!==walletAdapterBase.WalletReadyState.Installed&&this.emit("readyStateChange",__classPrivateFieldSet(this,_BaseSolanaMobileWalletAdapter_readyState,walletAdapterBase.WalletReadyState.Installed,"f"))},_BaseSolanaMobileWalletAdapter_assertIsAuthorized=function _BaseSolanaMobileWalletAdapter_assertIsAuthorized(){if(!__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").isAuthorized||!__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_selectedAccount,"f"))throw new walletAdapterBase.WalletNotConnectedError;return __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_selectedAccount,"f")},_BaseSolanaMobileWalletAdapter_performSignTransactions=function _BaseSolanaMobileWalletAdapter_performSignTransactions(transactions){return __awaiter(this,void 0,void 0,function*(){const account=__classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_instances,"m",_BaseSolanaMobileWalletAdapter_assertIsAuthorized).call(this);try{if(walletStandardFeatures.SolanaSignTransaction in __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features)return __classPrivateFieldGet(this,_BaseSolanaMobileWalletAdapter_wallet,"f").features[walletStandardFeatures.SolanaSignTransaction].signTransaction(...transactions.map(value=>({account,transaction:value.serialize()}))).then(outputs=>outputs.map(output=>{const byteArray=output.signedTransaction,messageOffset=64*byteArray[0]+1;return"legacy"===web3_js.VersionedMessage.deserializeMessageVersion(byteArray.slice(messageOffset,byteArray.length))?web3_js.Transaction.from(byteArray):web3_js.VersionedTransaction.deserialize(byteArray)}));throw new Error("Connected wallet does not support signing transactions")}catch(error){throw new walletAdapterBase.WalletSignTransactionError(null==error?void 0:error.message,error)}})},_BaseSolanaMobileWalletAdapter_runWithGuard=function _BaseSolanaMobileWalletAdapter_runWithGuard(callback){return __awaiter(this,void 0,void 0,function*(){try{return yield callback()}catch(e){throw this.emit("error",e),e}})};class LocalSolanaMobileWalletAdapter extends BaseSolanaMobileWalletAdapter{constructor(config){var _a;const chain=chainOrClusterToChainId(null!==(_a=config.chain)&&void 0!==_a?_a:config.cluster);super(new walletStandardMobile.LocalSolanaMobileWalletAdapterWallet({appIdentity:config.appIdentity,authorizationCache:{set:config.authorizationResultCache.set,get:()=>__awaiter(this,void 0,void 0,function*(){const authorizationResult=yield config.authorizationResultCache.get();return authorizationResult&&"chain"in authorizationResult?authorizationResult:authorizationResult?Object.assign(Object.assign({},authorizationResult),{chain}):void 0}),clear:config.authorizationResultCache.clear},chains:[chain],chainSelector:walletStandardMobile.createDefaultChainSelector(),onWalletNotFound:()=>__awaiter(this,void 0,void 0,function*(){config.onWalletNotFound(this)})}),{addressSelector:config.addressSelector,chain})}}function defaultWalletNotFoundHandler(mobileWalletAdapter){return __awaiter(this,void 0,void 0,function*(){return walletStandardMobile.defaultErrorModalWalletNotFoundHandler()})}exports.Ne=class SolanaMobileWalletAdapter extends LocalSolanaMobileWalletAdapter{},exports.fG="Mobile Wallet Adapter",exports.RP=function createDefaultAddressSelector(){return{select(addresses){return __awaiter(this,void 0,void 0,function*(){return addresses[0]})}}},exports.u=function createDefaultAuthorizationResultCache(){return walletStandardMobile.createDefaultAuthorizationCache()},exports.O0=function createDefaultWalletNotFoundHandler(){return defaultWalletNotFoundHandler}},"./node_modules/@solana-mobile/wallet-standard-mobile/lib/cjs/index.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var walletStandardFeatures=__webpack_require__("./node_modules/@solana/wallet-standard-features/lib/cjs/index.js"),web3_js=__webpack_require__("./node_modules/@solana/web3.js/lib/index.browser.esm.js"),QRCode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/browser.js"),features=__webpack_require__("./node_modules/@wallet-standard/features/lib/cjs/index.js"),walletStandardChains=__webpack_require__("./node_modules/@solana/wallet-standard-chains/lib/cjs/index.js"),mobileWalletAdapterProtocolWeb3js=__webpack_require__("./node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/lib/esm/index.browser.js"),base58=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/bs58/index.js");function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var _EmbeddedModal_instances,_EmbeddedModal_root,_EmbeddedModal_eventListeners,_EmbeddedModal_listenersAttached,_EmbeddedModal_injectHTML,_EmbeddedModal_attachEventListeners,_EmbeddedModal_removeEventListeners,_EmbeddedModal_handleKeyDown,QRCode__default=_interopDefaultLegacy(QRCode),base58__default=_interopDefaultLegacy(base58);function __awaiter(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __classPrivateFieldGet$1(receiver,state,kind,f){if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===kind?f:"a"===kind?f.call(receiver):f?f.value:state.get(receiver)}function __classPrivateFieldSet$1(receiver,state,value,kind,f){if("m"===kind)throw new TypeError("Private method is not writable");if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===kind?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value}class EmbeddedModal{constructor(){_EmbeddedModal_instances.add(this),_EmbeddedModal_root.set(this,null),_EmbeddedModal_eventListeners.set(this,{}),_EmbeddedModal_listenersAttached.set(this,!1),this.dom=null,this.open=()=>{console.debug("Modal open"),__classPrivateFieldGet$1(this,_EmbeddedModal_instances,"m",_EmbeddedModal_attachEventListeners).call(this),__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f")&&(__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f").style.display="flex")},this.close=(event=void 0)=>{var _a;console.debug("Modal close"),__classPrivateFieldGet$1(this,_EmbeddedModal_instances,"m",_EmbeddedModal_removeEventListeners).call(this),__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f")&&(__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f").style.display="none"),null===(_a=__classPrivateFieldGet$1(this,_EmbeddedModal_eventListeners,"f").close)||void 0===_a||_a.forEach(listener=>listener(event))},_EmbeddedModal_handleKeyDown.set(this,event=>{"Escape"===event.key&&this.close(event)}),this.init=this.init.bind(this),__classPrivateFieldSet$1(this,_EmbeddedModal_root,document.getElementById("mobile-wallet-adapter-embedded-root-ui"),"f")}init(){return __awaiter(this,void 0,void 0,function*(){console.log("Injecting modal"),__classPrivateFieldGet$1(this,_EmbeddedModal_instances,"m",_EmbeddedModal_injectHTML).call(this)})}addEventListener(event,listener){var _a;return(null===(_a=__classPrivateFieldGet$1(this,_EmbeddedModal_eventListeners,"f")[event])||void 0===_a?void 0:_a.push(listener))||(__classPrivateFieldGet$1(this,_EmbeddedModal_eventListeners,"f")[event]=[listener]),()=>this.removeEventListener(event,listener)}removeEventListener(event,listener){var _a;__classPrivateFieldGet$1(this,_EmbeddedModal_eventListeners,"f")[event]=null===(_a=__classPrivateFieldGet$1(this,_EmbeddedModal_eventListeners,"f")[event])||void 0===_a?void 0:_a.filter(existingListener=>listener!==existingListener)}}_EmbeddedModal_root=new WeakMap,_EmbeddedModal_eventListeners=new WeakMap,_EmbeddedModal_listenersAttached=new WeakMap,_EmbeddedModal_handleKeyDown=new WeakMap,_EmbeddedModal_instances=new WeakSet,_EmbeddedModal_injectHTML=function _EmbeddedModal_injectHTML(){if(document.getElementById("mobile-wallet-adapter-embedded-root-ui"))return void(__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f")||__classPrivateFieldSet$1(this,_EmbeddedModal_root,document.getElementById("mobile-wallet-adapter-embedded-root-ui"),"f"));__classPrivateFieldSet$1(this,_EmbeddedModal_root,document.createElement("div"),"f"),__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f").id="mobile-wallet-adapter-embedded-root-ui",__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f").innerHTML='\n\n',__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f").style.display="none";const content=__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f").querySelector(".mobile-wallet-adapter-embedded-modal-content");content&&(content.innerHTML=this.contentHtml);const styles=document.createElement("style");styles.id="mobile-wallet-adapter-embedded-modal-styles",styles.textContent='\n.mobile-wallet-adapter-embedded-modal-container {\n display: flex; /* Use flexbox to center content */\n justify-content: center; /* Center horizontally */\n align-items: center; /* Center vertically */\n position: fixed; /* Stay in place */\n z-index: 1; /* Sit on top */\n left: 0;\n top: 0;\n width: 100%; /* Full width */\n height: 100%; /* Full height */\n background-color: rgba(0,0,0,0.4); /* Black w/ opacity */\n overflow-y: auto; /* enable scrolling */\n}\n\n.mobile-wallet-adapter-embedded-modal-card {\n display: flex;\n flex-direction: column;\n margin: auto 20px;\n max-width: 780px;\n padding: 20px;\n border-radius: 24px;\n background: #ffffff;\n font-family: "Inter Tight", "PT Sans", Calibri, sans-serif;\n transform: translateY(-200%);\n animation: slide-in 0.5s forwards;\n}\n\n@keyframes slide-in {\n 100% { transform: translateY(0%); }\n}\n\n.mobile-wallet-adapter-embedded-modal-close {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 32px;\n height: 32px;\n cursor: pointer;\n background: #e4e9e9;\n border: none;\n border-radius: 50%;\n}\n\n.mobile-wallet-adapter-embedded-modal-close:focus-visible {\n outline-color: red;\n}\n\n.mobile-wallet-adapter-embedded-modal-close svg {\n fill: #546266;\n transition: fill 200ms ease 0s;\n}\n\n.mobile-wallet-adapter-embedded-modal-close:hover svg {\n fill: #fff;\n}\n'+this.contentStyles;const host=document.createElement("div");host.innerHTML='\n\n\n\n',this.dom=host.attachShadow({mode:"closed"}),this.dom.appendChild(styles),this.dom.appendChild(__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f")),document.body.appendChild(host)},_EmbeddedModal_attachEventListeners=function _EmbeddedModal_attachEventListeners(){if(!__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f")||__classPrivateFieldGet$1(this,_EmbeddedModal_listenersAttached,"f"))return;[...__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f").querySelectorAll("[data-modal-close]")].forEach(closer=>null==closer?void 0:closer.addEventListener("click",this.close)),window.addEventListener("load",this.close),document.addEventListener("keydown",__classPrivateFieldGet$1(this,_EmbeddedModal_handleKeyDown,"f")),__classPrivateFieldSet$1(this,_EmbeddedModal_listenersAttached,!0,"f")},_EmbeddedModal_removeEventListeners=function _EmbeddedModal_removeEventListeners(){if(!__classPrivateFieldGet$1(this,_EmbeddedModal_listenersAttached,"f"))return;if(window.removeEventListener("load",this.close),document.removeEventListener("keydown",__classPrivateFieldGet$1(this,_EmbeddedModal_handleKeyDown,"f")),!__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f"))return;[...__classPrivateFieldGet$1(this,_EmbeddedModal_root,"f").querySelectorAll("[data-modal-close]")].forEach(closer=>null==closer?void 0:closer.removeEventListener("click",this.close)),__classPrivateFieldSet$1(this,_EmbeddedModal_listenersAttached,!1,"f")};class RemoteConnectionModal extends EmbeddedModal{constructor(){super(...arguments),this.contentStyles=css$1,this.contentHtml=QRCodeHtml}initWithQR(qrCode){const _super=Object.create(null,{init:{get:()=>super.init}});return __awaiter(this,void 0,void 0,function*(){_super.init.call(this),this.populateQRCode(qrCode)})}populateQRCode(qrUrl){var _a;return __awaiter(this,void 0,void 0,function*(){const qrcodeContainer=null===(_a=this.dom)||void 0===_a?void 0:_a.getElementById("mobile-wallet-adapter-embedded-modal-qr-code-container");if(qrcodeContainer){const qrCodeElement=yield QRCode__default.default.toCanvas(qrUrl,{width:200,margin:0});null!==qrcodeContainer.firstElementChild?qrcodeContainer.replaceChild(qrCodeElement,qrcodeContainer.firstElementChild):qrcodeContainer.appendChild(qrCodeElement)}else console.error("QRCode Container not found")})}}const QRCodeHtml='\n
\n
\n \n \n \n \n
Remote Mobile Wallet Adapter
\n
\n
\n
\n

\n Open your wallet and scan this code\n

\n
\n
\n
\n
\n

\n\n',css$1='\n.mobile-wallet-adapter-embedded-modal-qr-content {\n display: flex; \n margin-top: 10px;\n padding: 10px;\n}\n\n.mobile-wallet-adapter-embedded-modal-qr-content > div:first-child {\n display: flex;\n flex-direction: column;\n flex: 2;\n margin-top: auto;\n margin-right: 30px;\n}\n\n.mobile-wallet-adapter-embedded-modal-qr-content > div:nth-child(2) {\n display: flex;\n flex-direction: column;\n flex: 1;\n margin-left: auto;\n}\n\n.mobile-wallet-adapter-embedded-modal-footer {\n display: flex;\n padding: 10px;\n}\n\n.mobile-wallet-adapter-embedded-modal-icon {}\n\n.mobile-wallet-adapter-embedded-modal-title {\n color: #000000;\n font-size: 2.5em;\n font-weight: 600;\n}\n\n.mobile-wallet-adapter-embedded-modal-qr-label {\n text-align: right;\n color: #000000;\n}\n\n.mobile-wallet-adapter-embedded-modal-qr-code-container {\n margin-left: auto;\n}\n\n.mobile-wallet-adapter-embedded-modal-divider {\n margin-top: 20px;\n padding-left: 10px;\n padding-right: 10px;\n}\n\n.mobile-wallet-adapter-embedded-modal-divider hr {\n border-top: 1px solid #D9DEDE;\n}\n\n.mobile-wallet-adapter-embedded-modal-subtitle {\n margin: auto;\n margin-right: 60px;\n padding: 20px;\n color: #6E8286;\n}\n\n.mobile-wallet-adapter-embedded-modal-progress-badge {\n display: flex;\n background: #F7F8F8;\n height: 56px;\n min-width: 200px;\n margin: auto;\n padding-left: 20px;\n padding-right: 20px;\n border-radius: 18px;\n color: #A8B6B8;\n align-items: center;\n}\n\n.mobile-wallet-adapter-embedded-modal-progress-badge > div:first-child {\n margin-left: auto;\n margin-right: 20px;\n}\n\n.mobile-wallet-adapter-embedded-modal-progress-badge > div:nth-child(2) {\n margin-right: auto;\n}\n\n/* Smaller screens */\n@media all and (max-width: 600px) {\n .mobile-wallet-adapter-embedded-modal-card {\n text-align: center;\n }\n .mobile-wallet-adapter-embedded-modal-qr-content {\n flex-direction: column;\n }\n .mobile-wallet-adapter-embedded-modal-qr-content > div:first-child {\n margin: auto;\n }\n .mobile-wallet-adapter-embedded-modal-qr-content > div:nth-child(2) {\n margin: auto;\n flex: 2 auto;\n }\n .mobile-wallet-adapter-embedded-modal-footer {\n flex-direction: column;\n }\n .mobile-wallet-adapter-embedded-modal-icon {\n display: none;\n }\n .mobile-wallet-adapter-embedded-modal-title {\n font-size: 1.5em;\n }\n .mobile-wallet-adapter-embedded-modal-subtitle {\n margin-right: unset;\n }\n .mobile-wallet-adapter-embedded-modal-qr-label {\n text-align: center;\n }\n .mobile-wallet-adapter-embedded-modal-qr-code-container {\n margin: auto;\n }\n}\n\n/* Spinner */\n@keyframes spinLeft {\n 0% {\n transform: rotate(20deg);\n }\n 50% {\n transform: rotate(160deg);\n }\n 100% {\n transform: rotate(20deg);\n }\n}\n@keyframes spinRight {\n 0% {\n transform: rotate(160deg);\n }\n 50% {\n transform: rotate(20deg);\n }\n 100% {\n transform: rotate(160deg);\n }\n}\n@keyframes spin {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(2520deg);\n }\n}\n\n.spinner {\n position: relative;\n width: 1.5em;\n height: 1.5em;\n margin: auto;\n animation: spin 10s linear infinite;\n}\n.spinner::before {\n content: "";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n}\n.right, .rightWrapper, .left, .leftWrapper {\n position: absolute;\n top: 0;\n overflow: hidden;\n width: .75em;\n height: 1.5em;\n}\n.left, .leftWrapper {\n left: 0;\n}\n.right {\n left: -12px;\n}\n.rightWrapper {\n right: 0;\n}\n.circle {\n border: .125em solid #A8B6B8;\n width: 1.25em; /* 1.5em - 2*0.125em border */\n height: 1.25em; /* 1.5em - 2*0.125em border */\n border-radius: 0.75em; /* 0.5*1.5em spinner size 8 */\n}\n.left {\n transform-origin: 100% 50%;\n animation: spinLeft 2.5s cubic-bezier(.2,0,.8,1) infinite;\n}\n.right {\n transform-origin: 100% 50%;\n animation: spinRight 2.5s cubic-bezier(.2,0,.8,1) infinite;\n}\n',icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03IDIuNUgxN0MxNy44Mjg0IDIuNSAxOC41IDMuMTcxNTcgMTguNSA0VjIwQzE4LjUgMjAuODI4NCAxNy44Mjg0IDIxLjUgMTcgMjEuNUg3QzYuMTcxNTcgMjEuNSA1LjUgMjAuODI4NCA1LjUgMjBWNEM1LjUgMy4xNzE1NyA2LjE3MTU3IDIuNSA3IDIuNVpNMyA0QzMgMS43OTA4NiA0Ljc5MDg2IDAgNyAwSDE3QzE5LjIwOTEgMCAyMSAxLjc5MDg2IDIxIDRWMjBDMjEgMjIuMjA5MSAxOS4yMDkxIDI0IDE3IDI0SDdDNC43OTA4NiAyNCAzIDIyLjIwOTEgMyAyMFY0Wk0xMSA0LjYxNTM4QzEwLjQ0NzcgNC42MTUzOCAxMCA1LjA2MzEgMTAgNS42MTUzOFY2LjM4NDYyQzEwIDYuOTM2OSAxMC40NDc3IDcuMzg0NjIgMTEgNy4zODQ2MkgxM0MxMy41NTIzIDcuMzg0NjIgMTQgNi45MzY5IDE0IDYuMzg0NjJWNS42MTUzOEMxNCA1LjA2MzEgMTMuNTUyMyA0LjYxNTM4IDEzIDQuNjE1MzhIMTFaIiBmaWxsPSIjRENCOEZGIi8+Cjwvc3ZnPgo=";function isVersionedTransaction(transaction){return"version"in transaction}function fromUint8Array(byteArray){return window.btoa(String.fromCharCode.call(null,...byteArray))}function toUint8Array(base64EncodedByteArray){return new Uint8Array(window.atob(base64EncodedByteArray).split("").map(c=>c.charCodeAt(0)))}var _LocalSolanaMobileWalletAdapterWallet_instances,_LocalSolanaMobileWalletAdapterWallet_listeners,_LocalSolanaMobileWalletAdapterWallet_version,_LocalSolanaMobileWalletAdapterWallet_name,_LocalSolanaMobileWalletAdapterWallet_url,_LocalSolanaMobileWalletAdapterWallet_icon,_LocalSolanaMobileWalletAdapterWallet_appIdentity,_LocalSolanaMobileWalletAdapterWallet_authorization,_LocalSolanaMobileWalletAdapterWallet_authorizationCache,_LocalSolanaMobileWalletAdapterWallet_connecting,_LocalSolanaMobileWalletAdapterWallet_connectionGeneration,_LocalSolanaMobileWalletAdapterWallet_chains,_LocalSolanaMobileWalletAdapterWallet_chainSelector,_LocalSolanaMobileWalletAdapterWallet_optionalFeatures,_LocalSolanaMobileWalletAdapterWallet_onWalletNotFound,_LocalSolanaMobileWalletAdapterWallet_on,_LocalSolanaMobileWalletAdapterWallet_emit,_LocalSolanaMobileWalletAdapterWallet_off,_LocalSolanaMobileWalletAdapterWallet_connect,_LocalSolanaMobileWalletAdapterWallet_performAuthorization,_LocalSolanaMobileWalletAdapterWallet_handleAuthorizationResult,_LocalSolanaMobileWalletAdapterWallet_handleWalletCapabilitiesResult,_LocalSolanaMobileWalletAdapterWallet_performReauthorization,_LocalSolanaMobileWalletAdapterWallet_disconnect,_LocalSolanaMobileWalletAdapterWallet_transact,_LocalSolanaMobileWalletAdapterWallet_assertIsAuthorized,_LocalSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts,_LocalSolanaMobileWalletAdapterWallet_performSignTransactions,_LocalSolanaMobileWalletAdapterWallet_performSignAndSendTransaction,_LocalSolanaMobileWalletAdapterWallet_signAndSendTransaction,_LocalSolanaMobileWalletAdapterWallet_signTransaction,_LocalSolanaMobileWalletAdapterWallet_signMessage,_LocalSolanaMobileWalletAdapterWallet_signIn,_LocalSolanaMobileWalletAdapterWallet_performSignIn,_RemoteSolanaMobileWalletAdapterWallet_instances,_RemoteSolanaMobileWalletAdapterWallet_listeners,_RemoteSolanaMobileWalletAdapterWallet_version,_RemoteSolanaMobileWalletAdapterWallet_name,_RemoteSolanaMobileWalletAdapterWallet_url,_RemoteSolanaMobileWalletAdapterWallet_icon,_RemoteSolanaMobileWalletAdapterWallet_appIdentity,_RemoteSolanaMobileWalletAdapterWallet_authorization,_RemoteSolanaMobileWalletAdapterWallet_authorizationCache,_RemoteSolanaMobileWalletAdapterWallet_connecting,_RemoteSolanaMobileWalletAdapterWallet_connectionGeneration,_RemoteSolanaMobileWalletAdapterWallet_chains,_RemoteSolanaMobileWalletAdapterWallet_chainSelector,_RemoteSolanaMobileWalletAdapterWallet_optionalFeatures,_RemoteSolanaMobileWalletAdapterWallet_onWalletNotFound,_RemoteSolanaMobileWalletAdapterWallet_hostAuthority,_RemoteSolanaMobileWalletAdapterWallet_session,_RemoteSolanaMobileWalletAdapterWallet_on,_RemoteSolanaMobileWalletAdapterWallet_emit,_RemoteSolanaMobileWalletAdapterWallet_off,_RemoteSolanaMobileWalletAdapterWallet_connect,_RemoteSolanaMobileWalletAdapterWallet_performAuthorization,_RemoteSolanaMobileWalletAdapterWallet_handleAuthorizationResult,_RemoteSolanaMobileWalletAdapterWallet_handleWalletCapabilitiesResult,_RemoteSolanaMobileWalletAdapterWallet_performReauthorization,_RemoteSolanaMobileWalletAdapterWallet_disconnect,_RemoteSolanaMobileWalletAdapterWallet_transact,_RemoteSolanaMobileWalletAdapterWallet_assertIsAuthorized,_RemoteSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts,_RemoteSolanaMobileWalletAdapterWallet_performSignTransactions,_RemoteSolanaMobileWalletAdapterWallet_performSignAndSendTransaction,_RemoteSolanaMobileWalletAdapterWallet_signAndSendTransaction,_RemoteSolanaMobileWalletAdapterWallet_signTransaction,_RemoteSolanaMobileWalletAdapterWallet_signMessage,_RemoteSolanaMobileWalletAdapterWallet_signIn,_RemoteSolanaMobileWalletAdapterWallet_performSignIn;const DEFAULT_FEATURES=[walletStandardFeatures.SolanaSignAndSendTransaction,walletStandardFeatures.SolanaSignTransaction,walletStandardFeatures.SolanaSignMessage,walletStandardFeatures.SolanaSignIn];class LocalSolanaMobileWalletAdapterWallet{constructor(config){_LocalSolanaMobileWalletAdapterWallet_instances.add(this),_LocalSolanaMobileWalletAdapterWallet_listeners.set(this,{}),_LocalSolanaMobileWalletAdapterWallet_version.set(this,"1.0.0"),_LocalSolanaMobileWalletAdapterWallet_name.set(this,"Mobile Wallet Adapter"),_LocalSolanaMobileWalletAdapterWallet_url.set(this,"https://solanamobile.com/wallets"),_LocalSolanaMobileWalletAdapterWallet_icon.set(this,icon),_LocalSolanaMobileWalletAdapterWallet_appIdentity.set(this,void 0),_LocalSolanaMobileWalletAdapterWallet_authorization.set(this,void 0),_LocalSolanaMobileWalletAdapterWallet_authorizationCache.set(this,void 0),_LocalSolanaMobileWalletAdapterWallet_connecting.set(this,!1),_LocalSolanaMobileWalletAdapterWallet_connectionGeneration.set(this,0),_LocalSolanaMobileWalletAdapterWallet_chains.set(this,[]),_LocalSolanaMobileWalletAdapterWallet_chainSelector.set(this,void 0),_LocalSolanaMobileWalletAdapterWallet_optionalFeatures.set(this,void 0),_LocalSolanaMobileWalletAdapterWallet_onWalletNotFound.set(this,void 0),_LocalSolanaMobileWalletAdapterWallet_on.set(this,(event,listener)=>{var _a;return(null===(_a=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_listeners,"f")[event])||void 0===_a?void 0:_a.push(listener))||(__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_listeners,"f")[event]=[listener]),()=>__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_instances,"m",_LocalSolanaMobileWalletAdapterWallet_off).call(this,event,listener)}),_LocalSolanaMobileWalletAdapterWallet_connect.set(this,({silent}={})=>__awaiter(this,void 0,void 0,function*(){if(__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_connecting,"f")||this.connected)return{accounts:this.accounts};__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_connecting,!0,"f");try{if(silent){const cachedAuthorization=yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorizationCache,"f").get();if(!cachedAuthorization)return{accounts:this.accounts};yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_handleAuthorizationResult,"f").call(this,cachedAuthorization)}else yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_performAuthorization,"f").call(this)}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}finally{__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_connecting,!1,"f")}return{accounts:this.accounts}})),_LocalSolanaMobileWalletAdapterWallet_performAuthorization.set(this,signInPayload=>__awaiter(this,void 0,void 0,function*(){try{const cachedAuthorizationResult=yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorizationCache,"f").get();if(cachedAuthorizationResult)return __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_handleAuthorizationResult,"f").call(this,cachedAuthorizationResult),cachedAuthorizationResult;const selectedChain=yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_chainSelector,"f").select(__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_chains,"f"));return yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_transact,"f").call(this,wallet=>__awaiter(this,void 0,void 0,function*(){const[capabilities,mwaAuthorizationResult]=yield Promise.all([wallet.getCapabilities(),wallet.authorize({chain:selectedChain,identity:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_appIdentity,"f"),sign_in_payload:signInPayload})]),accounts=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts,"f").call(this,mwaAuthorizationResult.accounts),authorization=Object.assign(Object.assign({},mwaAuthorizationResult),{accounts,chain:selectedChain});return Promise.all([__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_handleWalletCapabilitiesResult,"f").call(this,capabilities),__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorizationCache,"f").set(authorization),__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_handleAuthorizationResult,"f").call(this,authorization)]),authorization}))}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}})),_LocalSolanaMobileWalletAdapterWallet_handleAuthorizationResult.set(this,authorization=>__awaiter(this,void 0,void 0,function*(){var _a;const didPublicKeysChange=null==__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f")||(null===(_a=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f"))||void 0===_a?void 0:_a.accounts.length)!==authorization.accounts.length||__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f").accounts.some((account,ii)=>account.address!==authorization.accounts[ii].address);__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,authorization,"f"),didPublicKeysChange&&__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_instances,"m",_LocalSolanaMobileWalletAdapterWallet_emit).call(this,"change",{accounts:this.accounts})})),_LocalSolanaMobileWalletAdapterWallet_handleWalletCapabilitiesResult.set(this,capabilities=>__awaiter(this,void 0,void 0,function*(){const supportsSignTransaction=capabilities.features.includes("solana:signTransactions"),supportsSignAndSendTransaction=capabilities.supports_sign_and_send_transactions,didCapabilitiesChange=walletStandardFeatures.SolanaSignAndSendTransaction in this.features!==supportsSignAndSendTransaction||walletStandardFeatures.SolanaSignTransaction in this.features!==supportsSignTransaction;__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_optionalFeatures,Object.assign(Object.assign({},(supportsSignAndSendTransaction||!supportsSignAndSendTransaction&&!supportsSignTransaction)&&{[walletStandardFeatures.SolanaSignAndSendTransaction]:{version:"1.0.0",supportedTransactionVersions:["legacy",0],signAndSendTransaction:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_signAndSendTransaction,"f")}}),supportsSignTransaction&&{[walletStandardFeatures.SolanaSignTransaction]:{version:"1.0.0",supportedTransactionVersions:["legacy",0],signTransaction:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_signTransaction,"f")}}),"f"),didCapabilitiesChange&&__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_instances,"m",_LocalSolanaMobileWalletAdapterWallet_emit).call(this,"change",{features:this.features})})),_LocalSolanaMobileWalletAdapterWallet_performReauthorization.set(this,(wallet,authToken,chain)=>__awaiter(this,void 0,void 0,function*(){try{const mwaAuthorizationResult=yield wallet.authorize({auth_token:authToken,identity:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_appIdentity,"f"),chain}),accounts=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts,"f").call(this,mwaAuthorizationResult.accounts),authorization=Object.assign(Object.assign({},mwaAuthorizationResult),{accounts,chain});Promise.all([__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorizationCache,"f").set(authorization),__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_handleAuthorizationResult,"f").call(this,authorization)])}catch(e){throw __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_disconnect,"f").call(this),new Error(e instanceof Error&&e.message||"Unknown error")}})),_LocalSolanaMobileWalletAdapterWallet_disconnect.set(this,()=>__awaiter(this,void 0,void 0,function*(){var _b;__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorizationCache,"f").clear(),__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_connecting,!1,"f"),__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_connectionGeneration,(_b=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_connectionGeneration,"f"),++_b),"f"),__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,void 0,"f"),__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_instances,"m",_LocalSolanaMobileWalletAdapterWallet_emit).call(this,"change",{accounts:this.accounts})})),_LocalSolanaMobileWalletAdapterWallet_transact.set(this,callback=>__awaiter(this,void 0,void 0,function*(){var _c;const walletUriBase=null===(_c=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f"))||void 0===_c?void 0:_c.wallet_uri_base,config=walletUriBase?{baseUri:walletUriBase}:void 0,currentConnectionGeneration=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_connectionGeneration,"f");try{return yield mobileWalletAdapterProtocolWeb3js.transact(callback,config)}catch(e){throw __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_connectionGeneration,"f")!==currentConnectionGeneration&&(yield new Promise(()=>{})),e instanceof Error&&"SolanaMobileWalletAdapterError"===e.name&&"ERROR_WALLET_NOT_FOUND"===e.code&&(yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_onWalletNotFound,"f").call(this,this)),e}})),_LocalSolanaMobileWalletAdapterWallet_assertIsAuthorized.set(this,()=>{if(!__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f"))throw new Error("Wallet not connected");return{authToken:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f").auth_token,chain:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f").chain}}),_LocalSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts.set(this,accounts=>accounts.map(account=>{var _a,_b;const publicKey=toUint8Array(account.address);return{address:base58__default.default.encode(publicKey),publicKey,label:account.label,icon:account.icon,chains:null!==(_a=account.chains)&&void 0!==_a?_a:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_chains,"f"),features:null!==(_b=account.features)&&void 0!==_b?_b:DEFAULT_FEATURES}})),_LocalSolanaMobileWalletAdapterWallet_performSignTransactions.set(this,transactions=>__awaiter(this,void 0,void 0,function*(){const{authToken,chain}=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_assertIsAuthorized,"f").call(this);try{return yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_transact,"f").call(this,wallet=>__awaiter(this,void 0,void 0,function*(){yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_performReauthorization,"f").call(this,wallet,authToken,chain);return yield wallet.signTransactions({transactions})}))}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}})),_LocalSolanaMobileWalletAdapterWallet_performSignAndSendTransaction.set(this,(transaction,options)=>__awaiter(this,void 0,void 0,function*(){const{authToken,chain}=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_assertIsAuthorized,"f").call(this);try{return yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_transact,"f").call(this,wallet=>__awaiter(this,void 0,void 0,function*(){const[capabilities,_1]=yield Promise.all([wallet.getCapabilities(),__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_performReauthorization,"f").call(this,wallet,authToken,chain)]);if(capabilities.supports_sign_and_send_transactions){return(yield wallet.signAndSendTransactions(Object.assign(Object.assign({},options),{transactions:[transaction]})))[0]}throw new Error("connected wallet does not support signAndSendTransaction")}))}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}})),_LocalSolanaMobileWalletAdapterWallet_signAndSendTransaction.set(this,(...inputs)=>__awaiter(this,void 0,void 0,function*(){const outputs=[];for(const input of inputs){const transaction=web3_js.VersionedTransaction.deserialize(input.transaction),signature=yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_performSignAndSendTransaction,"f").call(this,transaction,input.options);outputs.push({signature:base58__default.default.decode(signature)})}return outputs})),_LocalSolanaMobileWalletAdapterWallet_signTransaction.set(this,(...inputs)=>__awaiter(this,void 0,void 0,function*(){const transactions=inputs.map(({transaction})=>web3_js.VersionedTransaction.deserialize(transaction));return(yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_performSignTransactions,"f").call(this,transactions)).map(signedTransaction=>({signedTransaction:isVersionedTransaction(signedTransaction)?signedTransaction.serialize():new Uint8Array(signedTransaction.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))})),_LocalSolanaMobileWalletAdapterWallet_signMessage.set(this,(...inputs)=>__awaiter(this,void 0,void 0,function*(){const{authToken,chain}=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_assertIsAuthorized,"f").call(this),addresses=inputs.map(({account})=>fromUint8Array(account.publicKey)),messages=inputs.map(({message})=>message);try{return yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_transact,"f").call(this,wallet=>__awaiter(this,void 0,void 0,function*(){yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_performReauthorization,"f").call(this,wallet,authToken,chain);return(yield wallet.signMessages({addresses,payloads:messages})).map(signedMessage=>({signedMessage,signature:signedMessage.slice(-64)}))}))}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}})),_LocalSolanaMobileWalletAdapterWallet_signIn.set(this,(...inputs)=>__awaiter(this,void 0,void 0,function*(){const outputs=[];if(!(inputs.length>1))return[yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_performSignIn,"f").call(this,inputs[0])];for(const input of inputs)outputs.push(yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_performSignIn,"f").call(this,input));return outputs})),_LocalSolanaMobileWalletAdapterWallet_performSignIn.set(this,input=>__awaiter(this,void 0,void 0,function*(){var _d,_e;__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_connecting,!0,"f");try{const authorizationResult=yield __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_performAuthorization,"f").call(this,Object.assign(Object.assign({},input),{domain:null!==(_d=null==input?void 0:input.domain)&&void 0!==_d?_d:window.location.host}));if(!authorizationResult.sign_in_result)throw new Error("Sign in failed, no sign in result returned by wallet");const signedInAddress=authorizationResult.sign_in_result.address;return{account:Object.assign(Object.assign({},null!==(_e=authorizationResult.accounts.find(acc=>acc.address==signedInAddress))&&void 0!==_e?_e:{address:signedInAddress}),{publicKey:toUint8Array(signedInAddress)}),signedMessage:toUint8Array(authorizationResult.sign_in_result.signed_message),signature:toUint8Array(authorizationResult.sign_in_result.signature)}}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}finally{__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_connecting,!1,"f")}})),__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorizationCache,config.authorizationCache,"f"),__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_appIdentity,config.appIdentity,"f"),__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_chains,config.chains,"f"),__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_chainSelector,config.chainSelector,"f"),__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_onWalletNotFound,config.onWalletNotFound,"f"),__classPrivateFieldSet$1(this,_LocalSolanaMobileWalletAdapterWallet_optionalFeatures,{[walletStandardFeatures.SolanaSignAndSendTransaction]:{version:"1.0.0",supportedTransactionVersions:["legacy",0],signAndSendTransaction:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_signAndSendTransaction,"f")}},"f")}get version(){return __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_version,"f")}get name(){return __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_name,"f")}get url(){return __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_url,"f")}get icon(){return __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_icon,"f")}get chains(){return __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_chains,"f")}get features(){return Object.assign({[features.StandardConnect]:{version:"1.0.0",connect:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_connect,"f")},[features.StandardDisconnect]:{version:"1.0.0",disconnect:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_disconnect,"f")},[features.StandardEvents]:{version:"1.0.0",on:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_on,"f")},[walletStandardFeatures.SolanaSignMessage]:{version:"1.0.0",signMessage:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_signMessage,"f")},[walletStandardFeatures.SolanaSignIn]:{version:"1.0.0",signIn:__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_signIn,"f")}},__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_optionalFeatures,"f"))}get accounts(){var _a,_b;return null!==(_b=null===(_a=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f"))||void 0===_a?void 0:_a.accounts)&&void 0!==_b?_b:[]}get connected(){return!!__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f")}get isAuthorized(){return!!__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f")}get currentAuthorization(){return __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorization,"f")}get cachedAuthorizationResult(){return __classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_authorizationCache,"f").get()}}_LocalSolanaMobileWalletAdapterWallet_listeners=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_version=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_name=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_url=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_icon=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_appIdentity=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_authorization=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_authorizationCache=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_connecting=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_connectionGeneration=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_chains=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_chainSelector=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_optionalFeatures=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_onWalletNotFound=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_on=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_connect=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_performAuthorization=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_handleAuthorizationResult=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_handleWalletCapabilitiesResult=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_performReauthorization=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_disconnect=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_transact=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_assertIsAuthorized=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_performSignTransactions=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_performSignAndSendTransaction=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_signAndSendTransaction=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_signTransaction=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_signMessage=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_signIn=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_performSignIn=new WeakMap,_LocalSolanaMobileWalletAdapterWallet_instances=new WeakSet,_LocalSolanaMobileWalletAdapterWallet_emit=function _LocalSolanaMobileWalletAdapterWallet_emit(event,...args){var _a;null===(_a=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_listeners,"f")[event])||void 0===_a||_a.forEach(listener=>listener.apply(null,args))},_LocalSolanaMobileWalletAdapterWallet_off=function _LocalSolanaMobileWalletAdapterWallet_off(event,listener){var _a;__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_listeners,"f")[event]=null===(_a=__classPrivateFieldGet$1(this,_LocalSolanaMobileWalletAdapterWallet_listeners,"f")[event])||void 0===_a?void 0:_a.filter(existingListener=>listener!==existingListener)};class RemoteSolanaMobileWalletAdapterWallet{constructor(config){_RemoteSolanaMobileWalletAdapterWallet_instances.add(this),_RemoteSolanaMobileWalletAdapterWallet_listeners.set(this,{}),_RemoteSolanaMobileWalletAdapterWallet_version.set(this,"1.0.0"),_RemoteSolanaMobileWalletAdapterWallet_name.set(this,"Mobile Wallet Adapter"),_RemoteSolanaMobileWalletAdapterWallet_url.set(this,"https://solanamobile.com/wallets"),_RemoteSolanaMobileWalletAdapterWallet_icon.set(this,icon),_RemoteSolanaMobileWalletAdapterWallet_appIdentity.set(this,void 0),_RemoteSolanaMobileWalletAdapterWallet_authorization.set(this,void 0),_RemoteSolanaMobileWalletAdapterWallet_authorizationCache.set(this,void 0),_RemoteSolanaMobileWalletAdapterWallet_connecting.set(this,!1),_RemoteSolanaMobileWalletAdapterWallet_connectionGeneration.set(this,0),_RemoteSolanaMobileWalletAdapterWallet_chains.set(this,[]),_RemoteSolanaMobileWalletAdapterWallet_chainSelector.set(this,void 0),_RemoteSolanaMobileWalletAdapterWallet_optionalFeatures.set(this,void 0),_RemoteSolanaMobileWalletAdapterWallet_onWalletNotFound.set(this,void 0),_RemoteSolanaMobileWalletAdapterWallet_hostAuthority.set(this,void 0),_RemoteSolanaMobileWalletAdapterWallet_session.set(this,void 0),_RemoteSolanaMobileWalletAdapterWallet_on.set(this,(event,listener)=>{var _a;return(null===(_a=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_listeners,"f")[event])||void 0===_a?void 0:_a.push(listener))||(__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_listeners,"f")[event]=[listener]),()=>__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_instances,"m",_RemoteSolanaMobileWalletAdapterWallet_off).call(this,event,listener)}),_RemoteSolanaMobileWalletAdapterWallet_connect.set(this,({silent}={})=>__awaiter(this,void 0,void 0,function*(){if(__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connecting,"f")||this.connected)return{accounts:this.accounts};__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connecting,!0,"f");try{yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_performAuthorization,"f").call(this)}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}finally{__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connecting,!1,"f")}return{accounts:this.accounts}})),_RemoteSolanaMobileWalletAdapterWallet_performAuthorization.set(this,signInPayload=>__awaiter(this,void 0,void 0,function*(){try{const cachedAuthorizationResult=yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorizationCache,"f").get();if(cachedAuthorizationResult)return __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_handleAuthorizationResult,"f").call(this,cachedAuthorizationResult),cachedAuthorizationResult;__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_session,"f")&&__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_session,void 0,"f");const selectedChain=yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_chainSelector,"f").select(__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_chains,"f"));return yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_transact,"f").call(this,wallet=>__awaiter(this,void 0,void 0,function*(){const[capabilities,mwaAuthorizationResult]=yield Promise.all([wallet.getCapabilities(),wallet.authorize({chain:selectedChain,identity:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_appIdentity,"f"),sign_in_payload:signInPayload})]),accounts=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts,"f").call(this,mwaAuthorizationResult.accounts),authorizationResult=Object.assign(Object.assign({},mwaAuthorizationResult),{accounts,chain:selectedChain});return Promise.all([__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_handleWalletCapabilitiesResult,"f").call(this,capabilities),__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorizationCache,"f").set(authorizationResult),__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_handleAuthorizationResult,"f").call(this,authorizationResult)]),authorizationResult}))}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}})),_RemoteSolanaMobileWalletAdapterWallet_handleAuthorizationResult.set(this,authorization=>__awaiter(this,void 0,void 0,function*(){var _a;const didPublicKeysChange=null==__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f")||(null===(_a=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f"))||void 0===_a?void 0:_a.accounts.length)!==authorization.accounts.length||__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f").accounts.some((account,ii)=>account.address!==authorization.accounts[ii].address);__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,authorization,"f"),didPublicKeysChange&&__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_instances,"m",_RemoteSolanaMobileWalletAdapterWallet_emit).call(this,"change",{accounts:this.accounts})})),_RemoteSolanaMobileWalletAdapterWallet_handleWalletCapabilitiesResult.set(this,capabilities=>__awaiter(this,void 0,void 0,function*(){const supportsSignTransaction=capabilities.features.includes("solana:signTransactions"),supportsSignAndSendTransaction=capabilities.supports_sign_and_send_transactions||capabilities.features.includes("solana:signAndSendTransaction"),didCapabilitiesChange=walletStandardFeatures.SolanaSignAndSendTransaction in this.features!==supportsSignAndSendTransaction||walletStandardFeatures.SolanaSignTransaction in this.features!==supportsSignTransaction;__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_optionalFeatures,Object.assign(Object.assign({},supportsSignAndSendTransaction&&{[walletStandardFeatures.SolanaSignAndSendTransaction]:{version:"1.0.0",supportedTransactionVersions:capabilities.supported_transaction_versions,signAndSendTransaction:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_signAndSendTransaction,"f")}}),supportsSignTransaction&&{[walletStandardFeatures.SolanaSignTransaction]:{version:"1.0.0",supportedTransactionVersions:capabilities.supported_transaction_versions,signTransaction:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_signTransaction,"f")}}),"f"),didCapabilitiesChange&&__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_instances,"m",_RemoteSolanaMobileWalletAdapterWallet_emit).call(this,"change",{features:this.features})})),_RemoteSolanaMobileWalletAdapterWallet_performReauthorization.set(this,(wallet,authToken,chain)=>__awaiter(this,void 0,void 0,function*(){try{const mwaAuthorizationResult=yield wallet.authorize({auth_token:authToken,identity:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_appIdentity,"f")}),accounts=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts,"f").call(this,mwaAuthorizationResult.accounts),authorization=Object.assign(Object.assign({},mwaAuthorizationResult),{accounts,chain});Promise.all([__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorizationCache,"f").set(authorization),__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_handleAuthorizationResult,"f").call(this,authorization)])}catch(e){throw __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_disconnect,"f").call(this),new Error(e instanceof Error&&e.message||"Unknown error")}})),_RemoteSolanaMobileWalletAdapterWallet_disconnect.set(this,()=>__awaiter(this,void 0,void 0,function*(){var _b,_c;null===(_b=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_session,"f"))||void 0===_b||_b.close(),__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorizationCache,"f").clear(),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connecting,!1,"f"),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connectionGeneration,(_c=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connectionGeneration,"f"),++_c),"f"),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,void 0,"f"),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_session,void 0,"f"),__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_instances,"m",_RemoteSolanaMobileWalletAdapterWallet_emit).call(this,"change",{accounts:this.accounts})})),_RemoteSolanaMobileWalletAdapterWallet_transact.set(this,callback=>__awaiter(this,void 0,void 0,function*(){var _d;const walletUriBase=null===(_d=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f"))||void 0===_d?void 0:_d.wallet_uri_base,baseConfig=walletUriBase?{baseUri:walletUriBase}:void 0,remoteConfig=Object.assign(Object.assign({},baseConfig),{remoteHostAuthority:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_hostAuthority,"f")}),currentConnectionGeneration=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connectionGeneration,"f"),modal=new RemoteConnectionModal;if(__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_session,"f"))return callback(__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_session,"f").wallet);try{const{associationUrl,close,wallet}=yield mobileWalletAdapterProtocolWeb3js.startRemoteScenario(remoteConfig),removeCloseListener=modal.addEventListener("close",event=>{event&&close()});return modal.initWithQR(associationUrl.toString()),modal.open(),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_session,{close,wallet:yield wallet},"f"),removeCloseListener(),modal.close(),yield callback(__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_session,"f").wallet)}catch(e){throw modal.close(),__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connectionGeneration,"f")!==currentConnectionGeneration&&(yield new Promise(()=>{})),e instanceof Error&&"SolanaMobileWalletAdapterError"===e.name&&"ERROR_WALLET_NOT_FOUND"===e.code&&(yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_onWalletNotFound,"f").call(this,this)),e}})),_RemoteSolanaMobileWalletAdapterWallet_assertIsAuthorized.set(this,()=>{if(!__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f"))throw new Error("Wallet not connected");return{authToken:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f").auth_token,chain:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f").chain}}),_RemoteSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts.set(this,accounts=>accounts.map(account=>{var _a,_b;const publicKey=toUint8Array(account.address);return{address:base58__default.default.encode(publicKey),publicKey,label:account.label,icon:account.icon,chains:null!==(_a=account.chains)&&void 0!==_a?_a:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_chains,"f"),features:null!==(_b=account.features)&&void 0!==_b?_b:DEFAULT_FEATURES}})),_RemoteSolanaMobileWalletAdapterWallet_performSignTransactions.set(this,transactions=>__awaiter(this,void 0,void 0,function*(){const{authToken,chain}=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_assertIsAuthorized,"f").call(this);try{return yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_transact,"f").call(this,wallet=>__awaiter(this,void 0,void 0,function*(){yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_performReauthorization,"f").call(this,wallet,authToken,chain);return yield wallet.signTransactions({transactions})}))}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}})),_RemoteSolanaMobileWalletAdapterWallet_performSignAndSendTransaction.set(this,(transaction,options)=>__awaiter(this,void 0,void 0,function*(){const{authToken,chain}=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_assertIsAuthorized,"f").call(this);try{return yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_transact,"f").call(this,wallet=>__awaiter(this,void 0,void 0,function*(){const[capabilities,_1]=yield Promise.all([wallet.getCapabilities(),__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_performReauthorization,"f").call(this,wallet,authToken,chain)]);if(capabilities.supports_sign_and_send_transactions){return(yield wallet.signAndSendTransactions(Object.assign(Object.assign({},options),{transactions:[transaction]})))[0]}throw new Error("connected wallet does not support signAndSendTransaction")}))}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}})),_RemoteSolanaMobileWalletAdapterWallet_signAndSendTransaction.set(this,(...inputs)=>__awaiter(this,void 0,void 0,function*(){const outputs=[];for(const input of inputs){const transaction=web3_js.VersionedTransaction.deserialize(input.transaction),signature=yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_performSignAndSendTransaction,"f").call(this,transaction,input.options);outputs.push({signature:base58__default.default.decode(signature)})}return outputs})),_RemoteSolanaMobileWalletAdapterWallet_signTransaction.set(this,(...inputs)=>__awaiter(this,void 0,void 0,function*(){const transactions=inputs.map(({transaction})=>web3_js.VersionedTransaction.deserialize(transaction));return(yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_performSignTransactions,"f").call(this,transactions)).map(signedTransaction=>({signedTransaction:isVersionedTransaction(signedTransaction)?signedTransaction.serialize():new Uint8Array(signedTransaction.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))})),_RemoteSolanaMobileWalletAdapterWallet_signMessage.set(this,(...inputs)=>__awaiter(this,void 0,void 0,function*(){const{authToken,chain}=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_assertIsAuthorized,"f").call(this),addresses=inputs.map(({account})=>fromUint8Array(account.publicKey)),messages=inputs.map(({message})=>message);try{return yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_transact,"f").call(this,wallet=>__awaiter(this,void 0,void 0,function*(){yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_performReauthorization,"f").call(this,wallet,authToken,chain);return(yield wallet.signMessages({addresses,payloads:messages})).map(signedMessage=>({signedMessage,signature:signedMessage.slice(-64)}))}))}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}})),_RemoteSolanaMobileWalletAdapterWallet_signIn.set(this,(...inputs)=>__awaiter(this,void 0,void 0,function*(){const outputs=[];if(!(inputs.length>1))return[yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_performSignIn,"f").call(this,inputs[0])];for(const input of inputs)outputs.push(yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_performSignIn,"f").call(this,input));return outputs})),_RemoteSolanaMobileWalletAdapterWallet_performSignIn.set(this,input=>__awaiter(this,void 0,void 0,function*(){var _e,_f;__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connecting,!0,"f");try{const authorizationResult=yield __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_performAuthorization,"f").call(this,Object.assign(Object.assign({},input),{domain:null!==(_e=null==input?void 0:input.domain)&&void 0!==_e?_e:window.location.host}));if(!authorizationResult.sign_in_result)throw new Error("Sign in failed, no sign in result returned by wallet");const signedInAddress=authorizationResult.sign_in_result.address;return{account:Object.assign(Object.assign({},null!==(_f=authorizationResult.accounts.find(acc=>acc.address==signedInAddress))&&void 0!==_f?_f:{address:signedInAddress}),{publicKey:toUint8Array(signedInAddress)}),signedMessage:toUint8Array(authorizationResult.sign_in_result.signed_message),signature:toUint8Array(authorizationResult.sign_in_result.signature)}}catch(e){throw new Error(e instanceof Error&&e.message||"Unknown error")}finally{__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connecting,!1,"f")}})),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorizationCache,config.authorizationCache,"f"),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_appIdentity,config.appIdentity,"f"),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_chains,config.chains,"f"),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_chainSelector,config.chainSelector,"f"),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_hostAuthority,config.remoteHostAuthority,"f"),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_onWalletNotFound,config.onWalletNotFound,"f"),__classPrivateFieldSet$1(this,_RemoteSolanaMobileWalletAdapterWallet_optionalFeatures,{[walletStandardFeatures.SolanaSignAndSendTransaction]:{version:"1.0.0",supportedTransactionVersions:["legacy",0],signAndSendTransaction:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_signAndSendTransaction,"f")}},"f")}get version(){return __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_version,"f")}get name(){return __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_name,"f")}get url(){return __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_url,"f")}get icon(){return __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_icon,"f")}get chains(){return __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_chains,"f")}get features(){return Object.assign({[features.StandardConnect]:{version:"1.0.0",connect:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_connect,"f")},[features.StandardDisconnect]:{version:"1.0.0",disconnect:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_disconnect,"f")},[features.StandardEvents]:{version:"1.0.0",on:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_on,"f")},[walletStandardFeatures.SolanaSignMessage]:{version:"1.0.0",signMessage:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_signMessage,"f")},[walletStandardFeatures.SolanaSignIn]:{version:"1.0.0",signIn:__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_signIn,"f")}},__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_optionalFeatures,"f"))}get accounts(){var _a,_b;return null!==(_b=null===(_a=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f"))||void 0===_a?void 0:_a.accounts)&&void 0!==_b?_b:[]}get connected(){return!!__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_session,"f")&&!!__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f")}get isAuthorized(){return!!__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f")}get currentAuthorization(){return __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorization,"f")}get cachedAuthorizationResult(){return __classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_authorizationCache,"f").get()}}_RemoteSolanaMobileWalletAdapterWallet_listeners=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_version=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_name=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_url=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_icon=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_appIdentity=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_authorization=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_authorizationCache=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_connecting=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_connectionGeneration=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_chains=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_chainSelector=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_optionalFeatures=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_onWalletNotFound=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_hostAuthority=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_session=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_on=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_connect=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_performAuthorization=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_handleAuthorizationResult=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_handleWalletCapabilitiesResult=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_performReauthorization=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_disconnect=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_transact=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_assertIsAuthorized=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_accountsToWalletStandardAccounts=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_performSignTransactions=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_performSignAndSendTransaction=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_signAndSendTransaction=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_signTransaction=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_signMessage=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_signIn=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_performSignIn=new WeakMap,_RemoteSolanaMobileWalletAdapterWallet_instances=new WeakSet,_RemoteSolanaMobileWalletAdapterWallet_emit=function _RemoteSolanaMobileWalletAdapterWallet_emit(event,...args){var _a;null===(_a=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_listeners,"f")[event])||void 0===_a||_a.forEach(listener=>listener.apply(null,args))},_RemoteSolanaMobileWalletAdapterWallet_off=function _RemoteSolanaMobileWalletAdapterWallet_off(event,listener){var _a;__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_listeners,"f")[event]=null===(_a=__classPrivateFieldGet$1(this,_RemoteSolanaMobileWalletAdapterWallet_listeners,"f")[event])||void 0===_a?void 0:_a.filter(existingListener=>listener!==existingListener)};var _RegisterWalletEvent_detail,__classPrivateFieldSet=function(receiver,state,value,kind,f){if("m"===kind)throw new TypeError("Private method is not writable");if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===kind?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet=function(receiver,state,kind,f){if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===kind?f:"a"===kind?f.call(receiver):f?f.value:state.get(receiver)};function registerWallet(wallet){const callback=({register})=>register(wallet);try{window.dispatchEvent(new RegisterWalletEvent(callback))}catch(error){console.error("wallet-standard:register-wallet event could not be dispatched\n",error)}try{window.addEventListener("wallet-standard:app-ready",({detail:api})=>callback(api))}catch(error){console.error("wallet-standard:app-ready event listener could not be added\n",error)}}class RegisterWalletEvent extends Event{constructor(callback){super("wallet-standard:register-wallet",{bubbles:!1,cancelable:!1,composed:!1}),_RegisterWalletEvent_detail.set(this,void 0),__classPrivateFieldSet(this,_RegisterWalletEvent_detail,callback,"f")}get detail(){return __classPrivateFieldGet(this,_RegisterWalletEvent_detail,"f")}get type(){return"wallet-standard:register-wallet"}preventDefault(){throw new Error("preventDefault cannot be called")}stopImmediatePropagation(){throw new Error("stopImmediatePropagation cannot be called")}stopPropagation(){throw new Error("stopPropagation cannot be called")}}_RegisterWalletEvent_detail=new WeakMap;class ErrorModal extends EmbeddedModal{constructor(){super(...arguments),this.contentStyles=css,this.contentHtml=ErrorDialogHtml}initWithError(error){super.init(),this.populateError(error)}populateError(error){var _a,_b;const errorMessageElement=null===(_a=this.dom)||void 0===_a?void 0:_a.getElementById("mobile-wallet-adapter-error-message"),actionBtn=null===(_b=this.dom)||void 0===_b?void 0:_b.getElementById("mobile-wallet-adapter-error-action");if(errorMessageElement){if("SolanaMobileWalletAdapterError"===error.name)switch(error.code){case"ERROR_WALLET_NOT_FOUND":return errorMessageElement.innerHTML="To use mobile wallet adapter, you must have a compatible mobile wallet application installed on your device.",void(actionBtn&&actionBtn.addEventListener("click",()=>{window.location.href="https://solanamobile.com/wallets"}));case"ERROR_BROWSER_NOT_SUPPORTED":return errorMessageElement.innerHTML="This browser appears to be incompatible with mobile wallet adapter. Open this page in a compatible mobile browser app and try again.",void(actionBtn&&(actionBtn.style.display="none"))}errorMessageElement.innerHTML=`An unexpected error occurred: ${error.message}`}else console.log("Failed to locate error dialog element")}}const ErrorDialogHtml='\n\n
We can\'t find a wallet.
\n
\n
\n \n
\n',css="\n.mobile-wallet-adapter-embedded-modal-content {\n text-align: center;\n}\n\n.mobile-wallet-adapter-embedded-modal-error-icon {\n margin-top: 24px;\n}\n\n.mobile-wallet-adapter-embedded-modal-title {\n margin: 18px 100px auto 100px;\n color: #000000;\n font-size: 2.75em;\n font-weight: 600;\n}\n\n.mobile-wallet-adapter-embedded-modal-subtitle {\n margin: 30px 60px 40px 60px;\n color: #000000;\n font-size: 1.25em;\n font-weight: 400;\n}\n\n.mobile-wallet-adapter-embedded-modal-error-action {\n display: block;\n width: 100%;\n height: 56px;\n /*margin-top: 40px;*/\n font-size: 1.25em;\n /*line-height: 24px;*/\n /*letter-spacing: -1%;*/\n background: #000000;\n color: #FFFFFF;\n border-radius: 18px;\n}\n\n/* Smaller screens */\n@media all and (max-width: 600px) {\n .mobile-wallet-adapter-embedded-modal-title {\n font-size: 1.5em;\n margin-right: 12px;\n margin-left: 12px;\n }\n .mobile-wallet-adapter-embedded-modal-subtitle {\n margin-right: 12px;\n margin-left: 12px;\n }\n}\n";function defaultErrorModalWalletNotFoundHandler(){return __awaiter(this,void 0,void 0,function*(){if("undefined"!=typeof window){const userAgent=window.navigator.userAgent.toLowerCase(),errorDialog=new ErrorModal;userAgent.includes("wv")?errorDialog.initWithError({name:"SolanaMobileWalletAdapterError",code:"ERROR_BROWSER_NOT_SUPPORTED",message:""}):errorDialog.initWithError({name:"SolanaMobileWalletAdapterError",code:"ERROR_WALLET_NOT_FOUND",message:""}),errorDialog.open()}})}const CACHE_KEY="SolanaMobileWalletAdapterDefaultAuthorizationCache";exports.LocalSolanaMobileWalletAdapterWallet=LocalSolanaMobileWalletAdapterWallet,exports.RemoteSolanaMobileWalletAdapterWallet=RemoteSolanaMobileWalletAdapterWallet,exports.SolanaMobileWalletAdapterWalletName="Mobile Wallet Adapter",exports.createDefaultAuthorizationCache=function createDefaultAuthorizationCache(){let storage;try{storage=window.localStorage}catch(_a){}return{clear(){return __awaiter(this,void 0,void 0,function*(){if(storage)try{storage.removeItem(CACHE_KEY)}catch(_a){}})},get(){return __awaiter(this,void 0,void 0,function*(){if(storage)try{const parsed=JSON.parse(storage.getItem(CACHE_KEY));if(parsed&&parsed.accounts){const parsedAccounts=parsed.accounts.map(account=>Object.assign(Object.assign({},account),{publicKey:"publicKey"in account?new Uint8Array(Object.values(account.publicKey)):new web3_js.PublicKey(account.address).toBytes()}));return Object.assign(Object.assign({},parsed),{accounts:parsedAccounts})}return parsed||void 0}catch(_a){}})},set(authorizationResult){return __awaiter(this,void 0,void 0,function*(){if(storage)try{storage.setItem(CACHE_KEY,JSON.stringify(authorizationResult))}catch(_a){}})}}},exports.createDefaultChainSelector=function createDefaultChainSelector(){return{select(chains){return __awaiter(this,void 0,void 0,function*(){return 1===chains.length?chains[0]:chains.includes(walletStandardChains.SOLANA_MAINNET_CHAIN)?walletStandardChains.SOLANA_MAINNET_CHAIN:chains[0]})}}},exports.createDefaultWalletNotFoundHandler=function createDefaultWalletNotFoundHandler(){return()=>__awaiter(this,void 0,void 0,function*(){defaultErrorModalWalletNotFoundHandler()})},exports.defaultErrorModalWalletNotFoundHandler=defaultErrorModalWalletNotFoundHandler,exports.registerMwa=function registerMwa(config){!function getIsLocalAssociationSupported(){return"undefined"!=typeof window&&window.isSecureContext&&"undefined"!=typeof document&&/android/i.test(navigator.userAgent)}()?function getIsRemoteAssociationSupported(){return"undefined"!=typeof window&&window.isSecureContext&&"undefined"!=typeof document&&!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}()&&void 0!==config.remoteHostAuthority&®isterWallet(new RemoteSolanaMobileWalletAdapterWallet(Object.assign(Object.assign({},config),{remoteHostAuthority:config.remoteHostAuthority}))):registerWallet(new LocalSolanaMobileWalletAdapterWallet(config))}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/base-x/src/index.js":module=>{"use strict";module.exports=function base(ALPHABET){if(ALPHABET.length>=255)throw new TypeError("Alphabet too long");for(var BASE_MAP=new Uint8Array(256),j=0;j>>0,b256=new Uint8Array(size);source[psz];){var charCode=source.charCodeAt(psz);if(charCode>255)return;var carry=BASE_MAP[charCode];if(255===carry)return;for(var i=0,it3=size-1;(0!==carry||i>>0,b256[it3]=carry%256>>>0,carry=carry/256>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,psz++}for(var it4=size-length;it4!==size&&0===b256[it4];)it4++;for(var vch=new Uint8Array(zeroes+(size-it4)),j=zeroes;it4!==size;)vch[j++]=b256[it4++];return vch}return{encode:function encode(source){if(source instanceof Uint8Array||(ArrayBuffer.isView(source)?source=new Uint8Array(source.buffer,source.byteOffset,source.byteLength):Array.isArray(source)&&(source=Uint8Array.from(source))),!(source instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===source.length)return"";for(var zeroes=0,length=0,pbegin=0,pend=source.length;pbegin!==pend&&0===source[pbegin];)pbegin++,zeroes++;for(var size=(pend-pbegin)*iFACTOR+1>>>0,b58=new Uint8Array(size);pbegin!==pend;){for(var carry=source[pbegin],i=0,it1=size-1;(0!==carry||i>>0,b58[it1]=carry%BASE>>>0,carry=carry/BASE>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,pbegin++}for(var it2=size-length;it2!==size&&0===b58[it2];)it2++;for(var str=LEADER.repeat(zeroes);it2{const basex=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/base-x/src/index.js");module.exports=basex("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/browser.js":(__unused_webpack_module,exports,__webpack_require__)=>{const canPromise=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/can-promise.js"),QRCode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/qrcode.js"),CanvasRenderer=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/renderer/canvas.js"),SvgRenderer=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/renderer/svg-tag.js");function renderCanvas(renderFunc,canvas,text,opts,cb){const args=[].slice.call(arguments,1),argsNum=args.length,isLastArgCb="function"==typeof args[argsNum-1];if(!isLastArgCb&&!canPromise())throw new Error("Callback required as last argument");if(!isLastArgCb){if(argsNum<1)throw new Error("Too few arguments provided");return 1===argsNum?(text=canvas,canvas=opts=void 0):2!==argsNum||canvas.getContext||(opts=text,text=canvas,canvas=void 0),new Promise(function(resolve,reject){try{const data=QRCode.create(text,opts);resolve(renderFunc(data,canvas,opts))}catch(e){reject(e)}})}if(argsNum<2)throw new Error("Too few arguments provided");2===argsNum?(cb=text,text=canvas,canvas=opts=void 0):3===argsNum&&(canvas.getContext&&void 0===cb?(cb=opts,opts=void 0):(cb=opts,opts=text,text=canvas,canvas=void 0));try{const data=QRCode.create(text,opts);cb(null,renderFunc(data,canvas,opts))}catch(e){cb(e)}}exports.create=QRCode.create,exports.toCanvas=renderCanvas.bind(null,CanvasRenderer.render),exports.toDataURL=renderCanvas.bind(null,CanvasRenderer.renderToDataURL),exports.toString=renderCanvas.bind(null,function(data,_,opts){return SvgRenderer.render(data,opts)})},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/can-promise.js":module=>{module.exports=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/alignment-pattern.js":(__unused_webpack_module,exports,__webpack_require__)=>{const getSymbolSize=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/utils.js").getSymbolSize;exports.getRowColCoords=function getRowColCoords(version){if(1===version)return[];const posCount=Math.floor(version/7)+2,size=getSymbolSize(version),intervals=145===size?26:2*Math.ceil((size-13)/(2*posCount-2)),positions=[size-7];for(let i=1;i{const Mode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/mode.js"),ALPHA_NUM_CHARS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function AlphanumericData(data){this.mode=Mode.ALPHANUMERIC,this.data=data}AlphanumericData.getBitsLength=function getBitsLength(length){return 11*Math.floor(length/2)+length%2*6},AlphanumericData.prototype.getLength=function getLength(){return this.data.length},AlphanumericData.prototype.getBitsLength=function getBitsLength(){return AlphanumericData.getBitsLength(this.data.length)},AlphanumericData.prototype.write=function write(bitBuffer){let i;for(i=0;i+2<=this.data.length;i+=2){let value=45*ALPHA_NUM_CHARS.indexOf(this.data[i]);value+=ALPHA_NUM_CHARS.indexOf(this.data[i+1]),bitBuffer.put(value,11)}this.data.length%2&&bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]),6)},module.exports=AlphanumericData},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/bit-buffer.js":module=>{function BitBuffer(){this.buffer=[],this.length=0}BitBuffer.prototype={get:function(index){const bufIndex=Math.floor(index/8);return 1==(this.buffer[bufIndex]>>>7-index%8&1)},put:function(num,length){for(let i=0;i>>length-i-1&1))},getLengthInBits:function(){return this.length},putBit:function(bit){const bufIndex=Math.floor(this.length/8);this.buffer.length<=bufIndex&&this.buffer.push(0),bit&&(this.buffer[bufIndex]|=128>>>this.length%8),this.length++}},module.exports=BitBuffer},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/bit-matrix.js":module=>{function BitMatrix(size){if(!size||size<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=size,this.data=new Uint8Array(size*size),this.reservedBit=new Uint8Array(size*size)}BitMatrix.prototype.set=function(row,col,value,reserved){const index=row*this.size+col;this.data[index]=value,reserved&&(this.reservedBit[index]=!0)},BitMatrix.prototype.get=function(row,col){return this.data[row*this.size+col]},BitMatrix.prototype.xor=function(row,col,value){this.data[row*this.size+col]^=value},BitMatrix.prototype.isReserved=function(row,col){return this.reservedBit[row*this.size+col]},module.exports=BitMatrix},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/byte-data.js":(module,__unused_webpack_exports,__webpack_require__)=>{const Mode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/mode.js");function ByteData(data){this.mode=Mode.BYTE,this.data="string"==typeof data?(new TextEncoder).encode(data):new Uint8Array(data)}ByteData.getBitsLength=function getBitsLength(length){return 8*length},ByteData.prototype.getLength=function getLength(){return this.data.length},ByteData.prototype.getBitsLength=function getBitsLength(){return ByteData.getBitsLength(this.data.length)},ByteData.prototype.write=function(bitBuffer){for(let i=0,l=this.data.length;i{const ECLevel=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/error-correction-level.js"),EC_BLOCKS_TABLE=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],EC_CODEWORDS_TABLE=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];exports.getBlocksCount=function getBlocksCount(version,errorCorrectionLevel){switch(errorCorrectionLevel){case ECLevel.L:return EC_BLOCKS_TABLE[4*(version-1)+0];case ECLevel.M:return EC_BLOCKS_TABLE[4*(version-1)+1];case ECLevel.Q:return EC_BLOCKS_TABLE[4*(version-1)+2];case ECLevel.H:return EC_BLOCKS_TABLE[4*(version-1)+3];default:return}},exports.getTotalCodewordsCount=function getTotalCodewordsCount(version,errorCorrectionLevel){switch(errorCorrectionLevel){case ECLevel.L:return EC_CODEWORDS_TABLE[4*(version-1)+0];case ECLevel.M:return EC_CODEWORDS_TABLE[4*(version-1)+1];case ECLevel.Q:return EC_CODEWORDS_TABLE[4*(version-1)+2];case ECLevel.H:return EC_CODEWORDS_TABLE[4*(version-1)+3];default:return}}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/error-correction-level.js":(__unused_webpack_module,exports)=>{exports.L={bit:1},exports.M={bit:0},exports.Q={bit:3},exports.H={bit:2},exports.isValid=function isValid(level){return level&&void 0!==level.bit&&level.bit>=0&&level.bit<4},exports.from=function from(value,defaultValue){if(exports.isValid(value))return value;try{return function fromString(string){if("string"!=typeof string)throw new Error("Param is not a string");switch(string.toLowerCase()){case"l":case"low":return exports.L;case"m":case"medium":return exports.M;case"q":case"quartile":return exports.Q;case"h":case"high":return exports.H;default:throw new Error("Unknown EC Level: "+string)}}(value)}catch(e){return defaultValue}}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/finder-pattern.js":(__unused_webpack_module,exports,__webpack_require__)=>{const getSymbolSize=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/utils.js").getSymbolSize;exports.getPositions=function getPositions(version){const size=getSymbolSize(version);return[[0,0],[size-7,0],[0,size-7]]}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/format-info.js":(__unused_webpack_module,exports,__webpack_require__)=>{const Utils=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/utils.js"),G15_BCH=Utils.getBCHDigit(1335);exports.getEncodedBits=function getEncodedBits(errorCorrectionLevel,mask){const data=errorCorrectionLevel.bit<<3|mask;let d=data<<10;for(;Utils.getBCHDigit(d)-G15_BCH>=0;)d^=1335<{const EXP_TABLE=new Uint8Array(512),LOG_TABLE=new Uint8Array(256);!function initTables(){let x=1;for(let i=0;i<255;i++)EXP_TABLE[i]=x,LOG_TABLE[x]=i,x<<=1,256&x&&(x^=285);for(let i=255;i<512;i++)EXP_TABLE[i]=EXP_TABLE[i-255]}(),exports.log=function log(n){if(n<1)throw new Error("log("+n+")");return LOG_TABLE[n]},exports.exp=function exp(n){return EXP_TABLE[n]},exports.mul=function mul(x,y){return 0===x||0===y?0:EXP_TABLE[LOG_TABLE[x]+LOG_TABLE[y]]}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/kanji-data.js":(module,__unused_webpack_exports,__webpack_require__)=>{const Mode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/mode.js"),Utils=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/utils.js");function KanjiData(data){this.mode=Mode.KANJI,this.data=data}KanjiData.getBitsLength=function getBitsLength(length){return 13*length},KanjiData.prototype.getLength=function getLength(){return this.data.length},KanjiData.prototype.getBitsLength=function getBitsLength(){return KanjiData.getBitsLength(this.data.length)},KanjiData.prototype.write=function(bitBuffer){let i;for(i=0;i=33088&&value<=40956)value-=33088;else{if(!(value>=57408&&value<=60351))throw new Error("Invalid SJIS character: "+this.data[i]+"\nMake sure your charset is UTF-8");value-=49472}value=192*(value>>>8&255)+(255&value),bitBuffer.put(value,13)}},module.exports=KanjiData},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/mask-pattern.js":(__unused_webpack_module,exports)=>{exports.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const PenaltyScores_N1=3,PenaltyScores_N2=3,PenaltyScores_N3=40,PenaltyScores_N4=10;function getMaskAt(maskPattern,i,j){switch(maskPattern){case exports.Patterns.PATTERN000:return(i+j)%2==0;case exports.Patterns.PATTERN001:return i%2==0;case exports.Patterns.PATTERN010:return j%3==0;case exports.Patterns.PATTERN011:return(i+j)%3==0;case exports.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(j/3))%2==0;case exports.Patterns.PATTERN101:return i*j%2+i*j%3==0;case exports.Patterns.PATTERN110:return(i*j%2+i*j%3)%2==0;case exports.Patterns.PATTERN111:return(i*j%3+(i+j)%2)%2==0;default:throw new Error("bad maskPattern:"+maskPattern)}}exports.isValid=function isValid(mask){return null!=mask&&""!==mask&&!isNaN(mask)&&mask>=0&&mask<=7},exports.from=function from(value){return exports.isValid(value)?parseInt(value,10):void 0},exports.getPenaltyN1=function getPenaltyN1(data){const size=data.size;let points=0,sameCountCol=0,sameCountRow=0,lastCol=null,lastRow=null;for(let row=0;row=5&&(points+=PenaltyScores_N1+(sameCountCol-5)),lastCol=module,sameCountCol=1),module=data.get(col,row),module===lastRow?sameCountRow++:(sameCountRow>=5&&(points+=PenaltyScores_N1+(sameCountRow-5)),lastRow=module,sameCountRow=1)}sameCountCol>=5&&(points+=PenaltyScores_N1+(sameCountCol-5)),sameCountRow>=5&&(points+=PenaltyScores_N1+(sameCountRow-5))}return points},exports.getPenaltyN2=function getPenaltyN2(data){const size=data.size;let points=0;for(let row=0;row=10&&(1488===bitsCol||93===bitsCol)&&points++,bitsRow=bitsRow<<1&2047|data.get(col,row),col>=10&&(1488===bitsRow||93===bitsRow)&&points++}return points*PenaltyScores_N3},exports.getPenaltyN4=function getPenaltyN4(data){let darkCount=0;const modulesCount=data.data.length;for(let i=0;i{const VersionCheck=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/version-check.js"),Regex=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/regex.js");exports.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},exports.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},exports.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},exports.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},exports.MIXED={bit:-1},exports.getCharCountIndicator=function getCharCountIndicator(mode,version){if(!mode.ccBits)throw new Error("Invalid mode: "+mode);if(!VersionCheck.isValid(version))throw new Error("Invalid version: "+version);return version>=1&&version<10?mode.ccBits[0]:version<27?mode.ccBits[1]:mode.ccBits[2]},exports.getBestModeForData=function getBestModeForData(dataStr){return Regex.testNumeric(dataStr)?exports.NUMERIC:Regex.testAlphanumeric(dataStr)?exports.ALPHANUMERIC:Regex.testKanji(dataStr)?exports.KANJI:exports.BYTE},exports.toString=function toString(mode){if(mode&&mode.id)return mode.id;throw new Error("Invalid mode")},exports.isValid=function isValid(mode){return mode&&mode.bit&&mode.ccBits},exports.from=function from(value,defaultValue){if(exports.isValid(value))return value;try{return function fromString(string){if("string"!=typeof string)throw new Error("Param is not a string");switch(string.toLowerCase()){case"numeric":return exports.NUMERIC;case"alphanumeric":return exports.ALPHANUMERIC;case"kanji":return exports.KANJI;case"byte":return exports.BYTE;default:throw new Error("Unknown mode: "+string)}}(value)}catch(e){return defaultValue}}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/numeric-data.js":(module,__unused_webpack_exports,__webpack_require__)=>{const Mode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/mode.js");function NumericData(data){this.mode=Mode.NUMERIC,this.data=data.toString()}NumericData.getBitsLength=function getBitsLength(length){return 10*Math.floor(length/3)+(length%3?length%3*3+1:0)},NumericData.prototype.getLength=function getLength(){return this.data.length},NumericData.prototype.getBitsLength=function getBitsLength(){return NumericData.getBitsLength(this.data.length)},NumericData.prototype.write=function write(bitBuffer){let i,group,value;for(i=0;i+3<=this.data.length;i+=3)group=this.data.substr(i,3),value=parseInt(group,10),bitBuffer.put(value,10);const remainingNum=this.data.length-i;remainingNum>0&&(group=this.data.substr(i),value=parseInt(group,10),bitBuffer.put(value,3*remainingNum+1))},module.exports=NumericData},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/polynomial.js":(__unused_webpack_module,exports,__webpack_require__)=>{const GF=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/galois-field.js");exports.mul=function mul(p1,p2){const coeff=new Uint8Array(p1.length+p2.length-1);for(let i=0;i=0;){const coeff=result[0];for(let i=0;i{const Utils=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/utils.js"),ECLevel=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/error-correction-level.js"),BitBuffer=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/bit-buffer.js"),BitMatrix=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/bit-matrix.js"),AlignmentPattern=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/alignment-pattern.js"),FinderPattern=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/finder-pattern.js"),MaskPattern=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/mask-pattern.js"),ECCode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/error-correction-code.js"),ReedSolomonEncoder=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/reed-solomon-encoder.js"),Version=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/version.js"),FormatInfo=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/format-info.js"),Mode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/mode.js"),Segments=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/segments.js");function setupFormatInfo(matrix,errorCorrectionLevel,maskPattern){const size=matrix.size,bits=FormatInfo.getEncodedBits(errorCorrectionLevel,maskPattern);let i,mod;for(i=0;i<15;i++)mod=1==(bits>>i&1),i<6?matrix.set(i,8,mod,!0):i<8?matrix.set(i+1,8,mod,!0):matrix.set(size-15+i,8,mod,!0),i<8?matrix.set(8,size-i-1,mod,!0):i<9?matrix.set(8,15-i-1+1,mod,!0):matrix.set(8,15-i-1,mod,!0);matrix.set(size-8,8,1,!0)}function createData(version,errorCorrectionLevel,segments){const buffer=new BitBuffer;segments.forEach(function(data){buffer.put(data.mode.bit,4),buffer.put(data.getLength(),Mode.getCharCountIndicator(data.mode,version)),data.write(buffer)});const dataTotalCodewordsBits=8*(Utils.getSymbolTotalCodewords(version)-ECCode.getTotalCodewordsCount(version,errorCorrectionLevel));for(buffer.getLengthInBits()+4<=dataTotalCodewordsBits&&buffer.put(0,4);buffer.getLengthInBits()%8!=0;)buffer.putBit(0);const remainingByte=(dataTotalCodewordsBits-buffer.getLengthInBits())/8;for(let i=0;i=0&&r<=6&&(0===c||6===c)||c>=0&&c<=6&&(0===r||6===r)||r>=2&&r<=4&&c>=2&&c<=4?matrix.set(row+r,col+c,!0,!0):matrix.set(row+r,col+c,!1,!0))}}(modules,version),function setupTimingPattern(matrix){const size=matrix.size;for(let r=8;r=7&&function setupVersionInfo(matrix,version){const size=matrix.size,bits=Version.getEncodedBits(version);let row,col,mod;for(let i=0;i<18;i++)row=Math.floor(i/3),col=i%3+size-8-3,mod=1==(bits>>i&1),matrix.set(row,col,mod,!0),matrix.set(col,row,mod,!0)}(modules,version),function setupData(matrix,data){const size=matrix.size;let inc=-1,row=size-1,bitIndex=7,byteIndex=0;for(let col=size-1;col>0;col-=2)for(6===col&&col--;;){for(let c=0;c<2;c++)if(!matrix.isReserved(row,col-c)){let dark=!1;byteIndex>>bitIndex&1)),matrix.set(row,col-c,dark),bitIndex--,-1===bitIndex&&(byteIndex++,bitIndex=7)}if(row+=inc,row<0||size<=row){row-=inc,inc=-inc;break}}}(modules,dataBits),isNaN(maskPattern)&&(maskPattern=MaskPattern.getBestMask(modules,setupFormatInfo.bind(null,modules,errorCorrectionLevel))),MaskPattern.applyMask(maskPattern,modules),setupFormatInfo(modules,errorCorrectionLevel,maskPattern),{modules,version,errorCorrectionLevel,maskPattern,segments}}exports.create=function create(data,options){if(void 0===data||""===data)throw new Error("No input text");let version,mask,errorCorrectionLevel=ECLevel.M;return void 0!==options&&(errorCorrectionLevel=ECLevel.from(options.errorCorrectionLevel,ECLevel.M),version=Version.from(options.version),mask=MaskPattern.from(options.maskPattern),options.toSJISFunc&&Utils.setToSJISFunction(options.toSJISFunc)),createSymbol(data,version,errorCorrectionLevel,mask)}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/reed-solomon-encoder.js":(module,__unused_webpack_exports,__webpack_require__)=>{const Polynomial=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/polynomial.js");function ReedSolomonEncoder(degree){this.genPoly=void 0,this.degree=degree,this.degree&&this.initialize(this.degree)}ReedSolomonEncoder.prototype.initialize=function initialize(degree){this.degree=degree,this.genPoly=Polynomial.generateECPolynomial(this.degree)},ReedSolomonEncoder.prototype.encode=function encode(data){if(!this.genPoly)throw new Error("Encoder not initialized");const paddedData=new Uint8Array(data.length+this.degree);paddedData.set(data);const remainder=Polynomial.mod(paddedData,this.genPoly),start=this.degree-remainder.length;if(start>0){const buff=new Uint8Array(this.degree);return buff.set(remainder,start),buff}return remainder},module.exports=ReedSolomonEncoder},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/regex.js":(__unused_webpack_module,exports)=>{let kanji="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";kanji=kanji.replace(/u/g,"\\u");const byte="(?:(?![A-Z0-9 $%*+\\-./:]|"+kanji+")(?:.|[\r\n]))+";exports.KANJI=new RegExp(kanji,"g"),exports.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),exports.BYTE=new RegExp(byte,"g"),exports.NUMERIC=new RegExp("[0-9]+","g"),exports.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");const TEST_KANJI=new RegExp("^"+kanji+"$"),TEST_NUMERIC=new RegExp("^[0-9]+$"),TEST_ALPHANUMERIC=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");exports.testKanji=function testKanji(str){return TEST_KANJI.test(str)},exports.testNumeric=function testNumeric(str){return TEST_NUMERIC.test(str)},exports.testAlphanumeric=function testAlphanumeric(str){return TEST_ALPHANUMERIC.test(str)}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/segments.js":(__unused_webpack_module,exports,__webpack_require__)=>{const Mode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/mode.js"),NumericData=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/numeric-data.js"),AlphanumericData=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/alphanumeric-data.js"),ByteData=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/byte-data.js"),KanjiData=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/kanji-data.js"),Regex=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/regex.js"),Utils=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/utils.js"),dijkstra=__webpack_require__("./node_modules/dijkstrajs/dijkstra.js");function getStringByteLength(str){return unescape(encodeURIComponent(str)).length}function getSegments(regex,mode,str){const segments=[];let result;for(;null!==(result=regex.exec(str));)segments.push({data:result[0],index:result.index,mode,length:result[0].length});return segments}function getSegmentsFromString(dataStr){const numSegs=getSegments(Regex.NUMERIC,Mode.NUMERIC,dataStr),alphaNumSegs=getSegments(Regex.ALPHANUMERIC,Mode.ALPHANUMERIC,dataStr);let byteSegs,kanjiSegs;Utils.isKanjiModeEnabled()?(byteSegs=getSegments(Regex.BYTE,Mode.BYTE,dataStr),kanjiSegs=getSegments(Regex.KANJI,Mode.KANJI,dataStr)):(byteSegs=getSegments(Regex.BYTE_KANJI,Mode.BYTE,dataStr),kanjiSegs=[]);return numSegs.concat(alphaNumSegs,byteSegs,kanjiSegs).sort(function(s1,s2){return s1.index-s2.index}).map(function(obj){return{data:obj.data,mode:obj.mode,length:obj.length}})}function getSegmentBitsLength(length,mode){switch(mode){case Mode.NUMERIC:return NumericData.getBitsLength(length);case Mode.ALPHANUMERIC:return AlphanumericData.getBitsLength(length);case Mode.KANJI:return KanjiData.getBitsLength(length);case Mode.BYTE:return ByteData.getBitsLength(length)}}function buildSingleSegment(data,modesHint){let mode;const bestMode=Mode.getBestModeForData(data);if(mode=Mode.from(modesHint,bestMode),mode!==Mode.BYTE&&mode.bit=0?acc[acc.length-1]:null;return prevSeg&&prevSeg.mode===curr.mode?(acc[acc.length-1].data+=curr.data,acc):(acc.push(curr),acc)},[])}(optimizedSegs))},exports.rawSplit=function rawSplit(data){return exports.fromArray(getSegmentsFromString(data,Utils.isKanjiModeEnabled()))}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/utils.js":(__unused_webpack_module,exports)=>{let toSJISFunction;const CODEWORDS_COUNT=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];exports.getSymbolSize=function getSymbolSize(version){if(!version)throw new Error('"version" cannot be null or undefined');if(version<1||version>40)throw new Error('"version" should be in range from 1 to 40');return 4*version+17},exports.getSymbolTotalCodewords=function getSymbolTotalCodewords(version){return CODEWORDS_COUNT[version]},exports.getBCHDigit=function(data){let digit=0;for(;0!==data;)digit++,data>>>=1;return digit},exports.setToSJISFunction=function setToSJISFunction(f){if("function"!=typeof f)throw new Error('"toSJISFunc" is not a valid function.');toSJISFunction=f},exports.isKanjiModeEnabled=function(){return void 0!==toSJISFunction},exports.toSJIS=function toSJIS(kanji){return toSJISFunction(kanji)}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/version-check.js":(__unused_webpack_module,exports)=>{exports.isValid=function isValid(version){return!isNaN(version)&&version>=1&&version<=40}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/version.js":(__unused_webpack_module,exports,__webpack_require__)=>{const Utils=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/utils.js"),ECCode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/error-correction-code.js"),ECLevel=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/error-correction-level.js"),Mode=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/mode.js"),VersionCheck=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/core/version-check.js"),G18_BCH=Utils.getBCHDigit(7973);function getReservedBitsCount(mode,version){return Mode.getCharCountIndicator(mode,version)+4}function getTotalBitsFromDataArray(segments,version){let totalBits=0;return segments.forEach(function(data){const reservedBits=getReservedBitsCount(data.mode,version);totalBits+=reservedBits+data.getBitsLength()}),totalBits}exports.from=function from(value,defaultValue){return VersionCheck.isValid(value)?parseInt(value,10):defaultValue},exports.getCapacity=function getCapacity(version,errorCorrectionLevel,mode){if(!VersionCheck.isValid(version))throw new Error("Invalid QR Code version");void 0===mode&&(mode=Mode.BYTE);const dataTotalCodewordsBits=8*(Utils.getSymbolTotalCodewords(version)-ECCode.getTotalCodewordsCount(version,errorCorrectionLevel));if(mode===Mode.MIXED)return dataTotalCodewordsBits;const usableBits=dataTotalCodewordsBits-getReservedBitsCount(mode,version);switch(mode){case Mode.NUMERIC:return Math.floor(usableBits/10*3);case Mode.ALPHANUMERIC:return Math.floor(usableBits/11*2);case Mode.KANJI:return Math.floor(usableBits/13);case Mode.BYTE:default:return Math.floor(usableBits/8)}},exports.getBestVersionForData=function getBestVersionForData(data,errorCorrectionLevel){let seg;const ecl=ECLevel.from(errorCorrectionLevel,ECLevel.M);if(Array.isArray(data)){if(data.length>1)return function getBestVersionForMixedData(segments,errorCorrectionLevel){for(let currentVersion=1;currentVersion<=40;currentVersion++)if(getTotalBitsFromDataArray(segments,currentVersion)<=exports.getCapacity(currentVersion,errorCorrectionLevel,Mode.MIXED))return currentVersion}(data,ecl);if(0===data.length)return 1;seg=data[0]}else seg=data;return function getBestVersionForDataLength(mode,length,errorCorrectionLevel){for(let currentVersion=1;currentVersion<=40;currentVersion++)if(length<=exports.getCapacity(currentVersion,errorCorrectionLevel,mode))return currentVersion}(seg.mode,seg.getLength(),ecl)},exports.getEncodedBits=function getEncodedBits(version){if(!VersionCheck.isValid(version)||version<7)throw new Error("Invalid QR Code version");let d=version<<12;for(;Utils.getBCHDigit(d)-G18_BCH>=0;)d^=7973<{const Utils=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/renderer/utils.js");exports.render=function render(qrData,canvas,options){let opts=options,canvasEl=canvas;void 0!==opts||canvas&&canvas.getContext||(opts=canvas,canvas=void 0),canvas||(canvasEl=function getCanvasElement(){try{return document.createElement("canvas")}catch(e){throw new Error("You need to specify a canvas element")}}()),opts=Utils.getOptions(opts);const size=Utils.getImageWidth(qrData.modules.size,opts),ctx=canvasEl.getContext("2d"),image=ctx.createImageData(size,size);return Utils.qrToImageData(image.data,qrData,opts),function clearCanvas(ctx,canvas,size){ctx.clearRect(0,0,canvas.width,canvas.height),canvas.style||(canvas.style={}),canvas.height=size,canvas.width=size,canvas.style.height=size+"px",canvas.style.width=size+"px"}(ctx,canvasEl,size),ctx.putImageData(image,0,0),canvasEl},exports.renderToDataURL=function renderToDataURL(qrData,canvas,options){let opts=options;void 0!==opts||canvas&&canvas.getContext||(opts=canvas,canvas=void 0),opts||(opts={});const canvasEl=exports.render(qrData,canvas,opts),type=opts.type||"image/png",rendererOpts=opts.rendererOpts||{};return canvasEl.toDataURL(type,rendererOpts.quality)}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/renderer/svg-tag.js":(__unused_webpack_module,exports,__webpack_require__)=>{const Utils=__webpack_require__("./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/renderer/utils.js");function getColorAttrib(color,attrib){const alpha=color.a/255,str=attrib+'="'+color.hex+'"';return alpha<1?str+" "+attrib+'-opacity="'+alpha.toFixed(2).slice(1)+'"':str}function svgCmd(cmd,x,y){let str=cmd+x;return void 0!==y&&(str+=" "+y),str}exports.render=function render(qrData,options,cb){const opts=Utils.getOptions(options),size=qrData.modules.size,data=qrData.modules.data,qrcodesize=size+2*opts.margin,bg=opts.color.light.a?"':"",path="0&&col>0&&data[i-1]||(path+=newRow?svgCmd("M",col+margin,.5+row+margin):svgCmd("m",moveBy,0),moveBy=0,newRow=!1),col+1',viewBox='viewBox="0 0 '+qrcodesize+" "+qrcodesize+'"',svgTag=''+bg+path+"\n";return"function"==typeof cb&&cb(null,svgTag),svgTag}},"./node_modules/@solana-mobile/wallet-standard-mobile/node_modules/qrcode/lib/renderer/utils.js":(__unused_webpack_module,exports)=>{function hex2rgba(hex){if("number"==typeof hex&&(hex=hex.toString()),"string"!=typeof hex)throw new Error("Color should be defined as hex string");let hexCode=hex.slice().replace("#","").split("");if(hexCode.length<3||5===hexCode.length||hexCode.length>8)throw new Error("Invalid hex color: "+hex);3!==hexCode.length&&4!==hexCode.length||(hexCode=Array.prototype.concat.apply([],hexCode.map(function(c){return[c,c]}))),6===hexCode.length&&hexCode.push("F","F");const hexValue=parseInt(hexCode.join(""),16);return{r:hexValue>>24&255,g:hexValue>>16&255,b:hexValue>>8&255,a:255&hexValue,hex:"#"+hexCode.slice(0,6).join("")}}exports.getOptions=function getOptions(options){options||(options={}),options.color||(options.color={});const margin=void 0===options.margin||null===options.margin||options.margin<0?4:options.margin,width=options.width&&options.width>=21?options.width:void 0,scale=options.scale||4;return{width,scale:width?4:scale,margin,color:{dark:hex2rgba(options.color.dark||"#000000ff"),light:hex2rgba(options.color.light||"#ffffffff")},type:options.type,rendererOpts:options.rendererOpts||{}}},exports.getScale=function getScale(qrSize,opts){return opts.width&&opts.width>=qrSize+2*opts.margin?opts.width/(qrSize+2*opts.margin):opts.scale},exports.getImageWidth=function getImageWidth(qrSize,opts){const scale=exports.getScale(qrSize,opts);return Math.floor((qrSize+2*opts.margin)*scale)},exports.qrToImageData=function qrToImageData(imgData,qr,opts){const size=qr.modules.size,data=qr.modules.data,scale=exports.getScale(size,opts),symbolSize=Math.floor((size+2*opts.margin)*scale),scaledMargin=opts.margin*scale,palette=[opts.color.light,opts.color.dark];for(let i=0;i=scaledMargin&&j>=scaledMargin&&i{"use strict";exports.I0=exports.DH=exports.NX=exports.u8=exports.cY=void 0,exports.av=exports.O6=exports.w3=exports.Wg=void 0;const buffer_1=__webpack_require__("./node_modules/buffer/index.js");function checkUint8Array(b){if(!(b instanceof Uint8Array))throw new TypeError("b must be a Uint8Array")}function uint8ArrayToBuffer(b){return checkUint8Array(b),buffer_1.Buffer.from(b.buffer,b.byteOffset,b.length)}class Layout{constructor(span,property){if(!Number.isInteger(span))throw new TypeError("span must be an integer");this.span=span,this.property=property}makeDestinationObject(){return{}}getSpan(b,offset){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(property){const rv=Object.create(this.constructor.prototype);return Object.assign(rv,this),rv.property=property,rv}fromArray(values){}}function nameWithProperty(name,lo){return lo.property?name+"["+lo.property+"]":name}class ExternalLayout extends Layout{isCount(){throw new Error("ExternalLayout is abstract")}}class GreedyCount extends ExternalLayout{constructor(elementSpan=1,property){if(!Number.isInteger(elementSpan)||0>=elementSpan)throw new TypeError("elementSpan must be a (positive) integer");super(-1,property),this.elementSpan=elementSpan}isCount(){return!0}decode(b,offset=0){checkUint8Array(b);const rem=b.length-offset;return Math.floor(rem/this.elementSpan)}encode(src,b,offset){return 0}}class OffsetLayout extends ExternalLayout{constructor(layout,offset=0,property){if(!(layout instanceof Layout))throw new TypeError("layout must be a Layout");if(!Number.isInteger(offset))throw new TypeError("offset must be integer or undefined");super(layout.span,property||layout.property),this.layout=layout,this.offset=offset}isCount(){return this.layout instanceof UInt||this.layout instanceof UIntBE}decode(b,offset=0){return this.layout.decode(b,offset+this.offset)}encode(src,b,offset=0){return this.layout.encode(src,b,offset+this.offset)}}class UInt extends Layout{constructor(span,property){if(super(span,property),6span+elo.encode(v,b,offset+span),0);return this.count instanceof ExternalLayout&&this.count.encode(src.length,b,offset),span}}class Structure extends Layout{constructor(fields,property,decodePrefixes){if(!Array.isArray(fields)||!fields.reduce((acc,v)=>acc&&v instanceof Layout,!0))throw new TypeError("fields must be array of Layout instances");"boolean"==typeof property&&void 0===decodePrefixes&&(decodePrefixes=property,property=void 0);for(const fd of fields)if(0>fd.span&&void 0===fd.property)throw new Error("fields cannot contain unnamed variable-length layout");let span=-1;try{span=fields.reduce((span,fd)=>span+fd.getSpan(),0)}catch(e){}super(span,property),this.fields=fields,this.decodePrefixes=!!decodePrefixes}getSpan(b,offset=0){if(0<=this.span)return this.span;let span=0;try{span=this.fields.reduce((span,fd)=>{const fsp=fd.getSpan(b,offset);return offset+=fsp,span+fsp},0)}catch(e){throw new RangeError("indeterminate span")}return span}decode(b,offset=0){checkUint8Array(b);const dest=this.makeDestinationObject();for(const fd of this.fields)if(void 0!==fd.property&&(dest[fd.property]=fd.decode(b,offset)),offset+=fd.getSpan(b,offset),this.decodePrefixes&&b.length===offset)break;return dest}encode(src,b,offset=0){const firstOffset=offset;let lastOffset=0,lastWrote=0;for(const fd of this.fields){let span=fd.span;if(lastWrote=0span&&(span=fd.getSpan(b,offset)))}lastOffset=offset,offset+=span}return lastOffset+lastWrote-firstOffset}fromArray(values){const dest=this.makeDestinationObject();for(const fd of this.fields)void 0!==fd.property&&0fd.span?offset=-1:0<=offset&&(offset+=fd.span)}}}class UnionDiscriminator{constructor(property){this.property=property}decode(b,offset){throw new Error("UnionDiscriminator is abstract")}encode(src,b,offset){throw new Error("UnionDiscriminator is abstract")}}class UnionLayoutDiscriminator extends UnionDiscriminator{constructor(layout,property){if(!(layout instanceof ExternalLayout&&layout.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(property||layout.property||"variant"),this.layout=layout}decode(b,offset){return this.layout.decode(b,offset)}encode(src,b,offset){return this.layout.encode(src,b,offset)}}class Union extends Layout{constructor(discr,defaultLayout,property){let discriminator;if(discr instanceof UInt||discr instanceof UIntBE)discriminator=new UnionLayoutDiscriminator(new OffsetLayout(discr));else if(discr instanceof ExternalLayout&&discr.isCount())discriminator=new UnionLayoutDiscriminator(discr);else{if(!(discr instanceof UnionDiscriminator))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");discriminator=discr}if(void 0===defaultLayout&&(defaultLayout=null),!(null===defaultLayout||defaultLayout instanceof Layout))throw new TypeError("defaultLayout must be null or a Layout");if(null!==defaultLayout){if(0>defaultLayout.span)throw new Error("defaultLayout must have constant span");void 0===defaultLayout.property&&(defaultLayout=defaultLayout.replicate("content"))}let span=-1;defaultLayout&&(span=defaultLayout.span,0<=span&&(discr instanceof UInt||discr instanceof UIntBE)&&(span+=discriminator.layout.span)),super(span,property),this.discriminator=discriminator,this.usesPrefixDiscriminator=discr instanceof UInt||discr instanceof UIntBE,this.defaultLayout=defaultLayout,this.registry={};let boundGetSourceVariant=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(src){return boundGetSourceVariant(src)},this.configGetSourceVariant=function(gsv){boundGetSourceVariant=gsv.bind(this)}}getSpan(b,offset=0){if(0<=this.span)return this.span;const vlo=this.getVariant(b,offset);if(!vlo)throw new Error("unable to determine span for unrecognized variant");return vlo.getSpan(b,offset)}defaultGetSourceVariant(src){if(Object.prototype.hasOwnProperty.call(src,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(src,this.defaultLayout.property))return;const vlo=this.registry[src[this.discriminator.property]];if(vlo&&(!vlo.layout||vlo.property&&Object.prototype.hasOwnProperty.call(src,vlo.property)))return vlo}else for(const tag in this.registry){const vlo=this.registry[tag];if(vlo.property&&Object.prototype.hasOwnProperty.call(src,vlo.property))return vlo}throw new Error("unable to infer src variant")}decode(b,offset=0){let dest;const dlo=this.discriminator,discr=dlo.decode(b,offset),clo=this.registry[discr];if(void 0===clo){const defaultLayout=this.defaultLayout;let contentOffset=0;this.usesPrefixDiscriminator&&(contentOffset=dlo.layout.span),dest=this.makeDestinationObject(),dest[dlo.property]=discr,dest[defaultLayout.property]=defaultLayout.decode(b,offset+contentOffset)}else dest=clo.decode(b,offset);return dest}encode(src,b,offset=0){const vlo=this.getSourceVariant(src);if(void 0===vlo){const dlo=this.discriminator,clo=this.defaultLayout;let contentOffset=0;return this.usesPrefixDiscriminator&&(contentOffset=dlo.layout.span),dlo.encode(src[dlo.property],b,offset),contentOffset+clo.encode(src[clo.property],b,offset+contentOffset)}return vlo.encode(src,b,offset)}addVariant(variant,layout,property){const rv=new VariantLayout(this,variant,layout,property);return this.registry[variant]=rv,rv}getVariant(vb,offset=0){let variant;return variant=vb instanceof Uint8Array?this.discriminator.decode(vb,offset):vb,this.registry[variant]}}class VariantLayout extends Layout{constructor(union,variant,layout,property){if(!(union instanceof Union))throw new TypeError("union must be a Union");if(!Number.isInteger(variant)||0>variant)throw new TypeError("variant must be a (non-negative) integer");if("string"==typeof layout&&void 0===property&&(property=layout,layout=null),layout){if(!(layout instanceof Layout))throw new TypeError("layout must be a Layout");if(null!==union.defaultLayout&&0<=layout.span&&layout.span>union.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if("string"!=typeof property)throw new TypeError("variant must have a String property")}let span=union.span;0>union.span&&(span=layout?layout.span:0,0<=span&&union.usesPrefixDiscriminator&&(span+=union.discriminator.layout.span)),super(span,property),this.union=union,this.variant=variant,this.layout=layout||null}getSpan(b,offset=0){if(0<=this.span)return this.span;let contentOffset=0;this.union.usesPrefixDiscriminator&&(contentOffset=this.union.discriminator.layout.span);let span=0;return this.layout&&(span=this.layout.getSpan(b,offset+contentOffset)),contentOffset+span}decode(b,offset=0){const dest=this.makeDestinationObject();if(this!==this.union.getVariant(b,offset))throw new Error("variant mismatch");let contentOffset=0;return this.union.usesPrefixDiscriminator&&(contentOffset=this.union.discriminator.layout.span),this.layout?dest[this.property]=this.layout.decode(b,offset+contentOffset):this.property?dest[this.property]=!0:this.union.usesPrefixDiscriminator&&(dest[this.union.discriminator.property]=this.variant),dest}encode(src,b,offset=0){let contentOffset=0;if(this.union.usesPrefixDiscriminator&&(contentOffset=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(src,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,b,offset);let span=contentOffset;if(this.layout&&(this.layout.encode(src[this.property],b,offset+contentOffset),span+=this.layout.getSpan(b,offset+contentOffset),0<=this.union.span&&span>this.union.span))throw new Error("encoded variant overruns containing union");return span}fromArray(values){if(this.layout)return this.layout.fromArray(values)}}function fixBitwiseResult(v){return 0>v&&(v+=4294967296),v}class BitStructure extends Layout{constructor(word,msb,property){if(!(word instanceof UInt||word instanceof UIntBE))throw new TypeError("word must be a UInt or UIntBE layout");if("string"==typeof msb&&void 0===property&&(property=msb,msb=!1),4=bits)throw new TypeError("bits must be positive integer");const totalBits=8*container.span,usedBits=container.fields.reduce((sum,fd)=>sum+fd.bits,0);if(bits+usedBits>totalBits)throw new Error("bits too long for span remainder ("+(totalBits-usedBits)+" of "+totalBits+" remain)");this.container=container,this.bits=bits,this.valueMask=(1<>>this.start}encode(value){if("number"!=typeof value||!Number.isInteger(value)||value!==fixBitwiseResult(value&this.valueMask))throw new TypeError(nameWithProperty("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const word=this.container._packedGetValue(),wordValue=fixBitwiseResult(value<span&&(span=this.length.decode(b,offset)),span}decode(b,offset=0){let span=this.span;return 0>span&&(span=this.length.decode(b,offset)),uint8ArrayToBuffer(b).slice(offset,offset+span)}encode(src,b,offset){let span=this.length;if(this.length instanceof ExternalLayout&&(span=src.length),!(src instanceof Uint8Array&&span===src.length))throw new TypeError(nameWithProperty("Blob.encode",this)+" requires (length "+span+") Uint8Array as src");if(offset+span>b.length)throw new RangeError("encoding overruns Uint8Array");const srcBuffer=uint8ArrayToBuffer(src);return uint8ArrayToBuffer(b).write(srcBuffer.toString("hex"),offset,span,"hex"),this.length instanceof ExternalLayout&&this.length.encode(span,b,offset),span}}class CString extends Layout{constructor(property){super(-1,property)}getSpan(b,offset=0){checkUint8Array(b);let idx=offset;for(;idxb.length)throw new RangeError("encoding overruns Buffer");const buffer=uint8ArrayToBuffer(b);return srcb.copy(buffer,offset),buffer[offset+span]=0,span+1}}class UTF8 extends Layout{constructor(maxSpan,property){if("string"==typeof maxSpan&&void 0===property&&(property=maxSpan,maxSpan=void 0),void 0===maxSpan)maxSpan=-1;else if(!Number.isInteger(maxSpan))throw new TypeError("maxSpan must be an integer");super(-1,property),this.maxSpan=maxSpan}getSpan(b,offset=0){return checkUint8Array(b),b.length-offset}decode(b,offset=0){const span=this.getSpan(b,offset);if(0<=this.maxSpan&&this.maxSpanb.length)throw new RangeError("encoding overruns Buffer");return srcb.copy(uint8ArrayToBuffer(b),offset),span}}class Constant extends Layout{constructor(value,property){super(0,property),this.value=value}decode(b,offset){return this.value}encode(src,b,offset){return 0}}exports.cY=(layout,offset,property)=>new OffsetLayout(layout,offset,property),exports.u8=property=>new UInt(1,property),exports.NX=property=>new UInt(2,property),exports.DH=property=>new UInt(4,property),exports.I0=property=>new NearUInt64(property),exports.Wg=property=>new NearInt64(property),exports.w3=(fields,property,decodePrefixes)=>new Structure(fields,property,decodePrefixes),exports.O6=(elementLayout,count,property)=>new Sequence(elementLayout,count,property),exports.av=(length,property)=>new Blob(length,property)},"./node_modules/@solana/wallet-adapter-base/lib/cjs/adapter.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseWalletAdapter=exports.WalletReadyState=exports.EventEmitter=void 0,exports.scopePollingDetectionStrategy=function scopePollingDetectionStrategy(detect){if("undefined"==typeof window||"undefined"==typeof document)return;const disposers=[];function detectAndDispose(){if(detect())for(const dispose of disposers)dispose()}const interval=setInterval(detectAndDispose,1e3);disposers.push(()=>clearInterval(interval)),"loading"===document.readyState&&(document.addEventListener("DOMContentLoaded",detectAndDispose,{once:!0}),disposers.push(()=>document.removeEventListener("DOMContentLoaded",detectAndDispose)));"complete"!==document.readyState&&(window.addEventListener("load",detectAndDispose,{once:!0}),disposers.push(()=>window.removeEventListener("load",detectAndDispose)));detectAndDispose()},exports.isIosAndRedirectable=function isIosAndRedirectable(){if(!navigator)return!1;const userAgent=navigator.userAgent.toLowerCase(),isIos=userAgent.includes("iphone")||userAgent.includes("ipad"),isSafari=userAgent.includes("safari");return isIos&&isSafari};const eventemitter3_1=__importDefault(__webpack_require__("./node_modules/eventemitter3/index.js"));exports.EventEmitter=eventemitter3_1.default;const errors_js_1=__webpack_require__("./node_modules/@solana/wallet-adapter-base/lib/cjs/errors.js");var WalletReadyState;!function(WalletReadyState){WalletReadyState.Installed="Installed",WalletReadyState.NotDetected="NotDetected",WalletReadyState.Loadable="Loadable",WalletReadyState.Unsupported="Unsupported"}(WalletReadyState||(exports.WalletReadyState=WalletReadyState={}));class BaseWalletAdapter extends eventemitter3_1.default{get connected(){return!!this.publicKey}autoConnect(){return __awaiter(this,void 0,void 0,function*(){yield this.connect()})}prepareTransaction(transaction_1,connection_1){return __awaiter(this,arguments,void 0,function*(transaction,connection,options={}){const publicKey=this.publicKey;if(!publicKey)throw new errors_js_1.WalletNotConnectedError;return transaction.feePayer=transaction.feePayer||publicKey,transaction.recentBlockhash=transaction.recentBlockhash||(yield connection.getLatestBlockhash({commitment:options.preflightCommitment,minContextSlot:options.minContextSlot})).blockhash,transaction})}}exports.BaseWalletAdapter=BaseWalletAdapter},"./node_modules/@solana/wallet-adapter-base/lib/cjs/errors.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WalletWindowClosedError=exports.WalletWindowBlockedError=exports.WalletTimeoutError=exports.WalletSignInError=exports.WalletSignMessageError=exports.WalletSignTransactionError=exports.WalletSendTransactionError=exports.WalletNotConnectedError=exports.WalletKeypairError=exports.WalletPublicKeyError=exports.WalletAccountError=exports.WalletDisconnectionError=exports.WalletDisconnectedError=exports.WalletConnectionError=exports.WalletConfigError=exports.WalletLoadError=exports.WalletNotReadyError=exports.WalletError=void 0;class WalletError extends Error{constructor(message,error){super(message),this.error=error}}exports.WalletError=WalletError;exports.WalletNotReadyError=class WalletNotReadyError extends WalletError{constructor(){super(...arguments),this.name="WalletNotReadyError"}};exports.WalletLoadError=class WalletLoadError extends WalletError{constructor(){super(...arguments),this.name="WalletLoadError"}};exports.WalletConfigError=class WalletConfigError extends WalletError{constructor(){super(...arguments),this.name="WalletConfigError"}};exports.WalletConnectionError=class WalletConnectionError extends WalletError{constructor(){super(...arguments),this.name="WalletConnectionError"}};exports.WalletDisconnectedError=class WalletDisconnectedError extends WalletError{constructor(){super(...arguments),this.name="WalletDisconnectedError"}};exports.WalletDisconnectionError=class WalletDisconnectionError extends WalletError{constructor(){super(...arguments),this.name="WalletDisconnectionError"}};exports.WalletAccountError=class WalletAccountError extends WalletError{constructor(){super(...arguments),this.name="WalletAccountError"}};exports.WalletPublicKeyError=class WalletPublicKeyError extends WalletError{constructor(){super(...arguments),this.name="WalletPublicKeyError"}};exports.WalletKeypairError=class WalletKeypairError extends WalletError{constructor(){super(...arguments),this.name="WalletKeypairError"}};exports.WalletNotConnectedError=class WalletNotConnectedError extends WalletError{constructor(){super(...arguments),this.name="WalletNotConnectedError"}};exports.WalletSendTransactionError=class WalletSendTransactionError extends WalletError{constructor(){super(...arguments),this.name="WalletSendTransactionError"}};exports.WalletSignTransactionError=class WalletSignTransactionError extends WalletError{constructor(){super(...arguments),this.name="WalletSignTransactionError"}};exports.WalletSignMessageError=class WalletSignMessageError extends WalletError{constructor(){super(...arguments),this.name="WalletSignMessageError"}};exports.WalletSignInError=class WalletSignInError extends WalletError{constructor(){super(...arguments),this.name="WalletSignInError"}};exports.WalletTimeoutError=class WalletTimeoutError extends WalletError{constructor(){super(...arguments),this.name="WalletTimeoutError"}};exports.WalletWindowBlockedError=class WalletWindowBlockedError extends WalletError{constructor(){super(...arguments),this.name="WalletWindowBlockedError"}};exports.WalletWindowClosedError=class WalletWindowClosedError extends WalletError{constructor(){super(...arguments),this.name="WalletWindowClosedError"}}},"./node_modules/@solana/wallet-adapter-base/lib/cjs/index.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__("./node_modules/@solana/wallet-adapter-base/lib/cjs/adapter.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-adapter-base/lib/cjs/errors.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-adapter-base/lib/cjs/signer.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-adapter-base/lib/cjs/standard.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-adapter-base/lib/cjs/transaction.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-adapter-base/lib/cjs/types.js"),exports)},"./node_modules/@solana/wallet-adapter-base/lib/cjs/signer.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__rest=this&&this.__rest||function(s,e){var t={};for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(null!=s&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(p=Object.getOwnPropertySymbols(s);i{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isWalletAdapterCompatibleStandardWallet=function isWalletAdapterCompatibleStandardWallet(wallet){return features_1.StandardConnect in wallet.features&&features_1.StandardEvents in wallet.features&&(wallet_standard_features_1.SolanaSignAndSendTransaction in wallet.features||wallet_standard_features_1.SolanaSignTransaction in wallet.features)};const wallet_standard_features_1=__webpack_require__("./node_modules/@solana/wallet-standard-features/lib/cjs/index.js"),features_1=__webpack_require__("./node_modules/@solana/wallet-adapter-base/node_modules/@wallet-standard/features/lib/cjs/index.js")},"./node_modules/@solana/wallet-adapter-base/lib/cjs/transaction.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isVersionedTransaction=function isVersionedTransaction(transaction){return"version"in transaction}},"./node_modules/@solana/wallet-adapter-base/lib/cjs/types.js":(__unused_webpack_module,exports)=>{"use strict";var WalletAdapterNetwork;Object.defineProperty(exports,"__esModule",{value:!0}),exports.WalletAdapterNetwork=void 0,function(WalletAdapterNetwork){WalletAdapterNetwork.Mainnet="mainnet-beta",WalletAdapterNetwork.Testnet="testnet",WalletAdapterNetwork.Devnet="devnet"}(WalletAdapterNetwork||(exports.WalletAdapterNetwork=WalletAdapterNetwork={}))},"./node_modules/@solana/wallet-adapter-base/node_modules/@wallet-standard/features/lib/cjs/connect.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Connect=exports.StandardConnect=void 0,exports.StandardConnect="standard:connect",exports.Connect=exports.StandardConnect},"./node_modules/@solana/wallet-adapter-base/node_modules/@wallet-standard/features/lib/cjs/disconnect.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Disconnect=exports.StandardDisconnect=void 0,exports.StandardDisconnect="standard:disconnect",exports.Disconnect=exports.StandardDisconnect},"./node_modules/@solana/wallet-adapter-base/node_modules/@wallet-standard/features/lib/cjs/events.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Events=exports.StandardEvents=void 0,exports.StandardEvents="standard:events",exports.Events=exports.StandardEvents},"./node_modules/@solana/wallet-adapter-base/node_modules/@wallet-standard/features/lib/cjs/index.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__("./node_modules/@solana/wallet-adapter-base/node_modules/@wallet-standard/features/lib/cjs/connect.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-adapter-base/node_modules/@wallet-standard/features/lib/cjs/disconnect.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-adapter-base/node_modules/@wallet-standard/features/lib/cjs/events.js"),exports)},"./node_modules/@solana/wallet-standard-chains/lib/cjs/index.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SOLANA_CHAINS=exports.SOLANA_LOCALNET_CHAIN=exports.SOLANA_TESTNET_CHAIN=exports.SOLANA_DEVNET_CHAIN=exports.SOLANA_MAINNET_CHAIN=void 0,exports.isSolanaChain=function isSolanaChain(chain){return exports.SOLANA_CHAINS.includes(chain)},exports.SOLANA_MAINNET_CHAIN="solana:mainnet",exports.SOLANA_DEVNET_CHAIN="solana:devnet",exports.SOLANA_TESTNET_CHAIN="solana:testnet",exports.SOLANA_LOCALNET_CHAIN="solana:localnet",exports.SOLANA_CHAINS=[exports.SOLANA_MAINNET_CHAIN,exports.SOLANA_DEVNET_CHAIN,exports.SOLANA_TESTNET_CHAIN,exports.SOLANA_LOCALNET_CHAIN]},"./node_modules/@solana/wallet-standard-features/lib/cjs/index.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__("./node_modules/@solana/wallet-standard-features/lib/cjs/signAndSendTransaction.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-standard-features/lib/cjs/signIn.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-standard-features/lib/cjs/signMessage.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-standard-features/lib/cjs/signTransaction.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-standard-features/lib/cjs/signAndSendAllTransactions.js"),exports)},"./node_modules/@solana/wallet-standard-features/lib/cjs/signAndSendAllTransactions.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SignAndSendAllTransactions=void 0,exports.SignAndSendAllTransactions="solana:signAndSendAllTransactions"},"./node_modules/@solana/wallet-standard-features/lib/cjs/signAndSendTransaction.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SolanaSignAndSendTransaction=void 0,exports.SolanaSignAndSendTransaction="solana:signAndSendTransaction"},"./node_modules/@solana/wallet-standard-features/lib/cjs/signIn.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SolanaSignIn=void 0,exports.SolanaSignIn="solana:signIn"},"./node_modules/@solana/wallet-standard-features/lib/cjs/signMessage.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SolanaSignMessage=void 0,exports.SolanaSignMessage="solana:signMessage"},"./node_modules/@solana/wallet-standard-features/lib/cjs/signTransaction.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SolanaSignTransaction=void 0,exports.SolanaSignTransaction="solana:signTransaction"},"./node_modules/@solana/wallet-standard-util/lib/cjs/commitment.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getCommitment=function getCommitment(commitment){switch(commitment){case"processed":case"confirmed":case"finalized":case void 0:return commitment;case"recent":return"processed";case"single":case"singleGossip":return"confirmed";case"max":case"root":return"finalized";default:return}}},"./node_modules/@solana/wallet-standard-util/lib/cjs/endpoint.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LOCALNET_ENDPOINT=exports.TESTNET_ENDPOINT=exports.DEVNET_ENDPOINT=exports.MAINNET_ENDPOINT=void 0,exports.getChainForEndpoint=function getChainForEndpoint(endpoint){return endpoint.includes(exports.MAINNET_ENDPOINT)?wallet_standard_chains_1.SOLANA_MAINNET_CHAIN:/\bdevnet\b/i.test(endpoint)?wallet_standard_chains_1.SOLANA_DEVNET_CHAIN:/\btestnet\b/i.test(endpoint)?wallet_standard_chains_1.SOLANA_TESTNET_CHAIN:/\blocalhost\b/i.test(endpoint)||/\b127\.0\.0\.1\b/.test(endpoint)?wallet_standard_chains_1.SOLANA_LOCALNET_CHAIN:wallet_standard_chains_1.SOLANA_MAINNET_CHAIN},exports.getEndpointForChain=function getEndpointForChain(chain,endpoint){return endpoint||(chain===wallet_standard_chains_1.SOLANA_MAINNET_CHAIN?exports.MAINNET_ENDPOINT:chain===wallet_standard_chains_1.SOLANA_DEVNET_CHAIN?exports.DEVNET_ENDPOINT:chain===wallet_standard_chains_1.SOLANA_TESTNET_CHAIN?exports.TESTNET_ENDPOINT:chain===wallet_standard_chains_1.SOLANA_LOCALNET_CHAIN?exports.LOCALNET_ENDPOINT:exports.MAINNET_ENDPOINT)};const wallet_standard_chains_1=__webpack_require__("./node_modules/@solana/wallet-standard-chains/lib/cjs/index.js");exports.MAINNET_ENDPOINT="https://api.mainnet-beta.solana.com",exports.DEVNET_ENDPOINT="https://api.devnet.solana.com",exports.TESTNET_ENDPOINT="https://api.testnet.solana.com",exports.LOCALNET_ENDPOINT="http://localhost:8899"},"./node_modules/@solana/wallet-standard-util/lib/cjs/index.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__("./node_modules/@solana/wallet-standard-util/lib/cjs/commitment.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-standard-util/lib/cjs/endpoint.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-standard-util/lib/cjs/signIn.js"),exports),__exportStar(__webpack_require__("./node_modules/@solana/wallet-standard-util/lib/cjs/signMessage.js"),exports)},"./node_modules/@solana/wallet-standard-util/lib/cjs/signIn.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.verifySignIn=function verifySignIn(input,output){const{signedMessage,signature,account:{publicKey}}=output,message=deriveSignInMessage(input,output);return!!message&&(0,signMessage_js_1.verifyMessageSignature)({message,signedMessage,signature,publicKey})},exports.deriveSignInMessage=deriveSignInMessage,exports.deriveSignInMessageText=deriveSignInMessageText,exports.parseSignInMessage=parseSignInMessage,exports.parseSignInMessageText=parseSignInMessageText,exports.createSignInMessage=function createSignInMessage(input){const text=createSignInMessageText(input);return(new TextEncoder).encode(text)},exports.createSignInMessageText=createSignInMessageText;const signMessage_js_1=__webpack_require__("./node_modules/@solana/wallet-standard-util/lib/cjs/signMessage.js"),util_js_1=__webpack_require__("./node_modules/@solana/wallet-standard-util/lib/cjs/util.js");function deriveSignInMessage(input,output){const text=deriveSignInMessageText(input,output);return text?(new TextEncoder).encode(text):null}function deriveSignInMessageText(input,output){const parsed=parseSignInMessage(output.signedMessage);if(!parsed)return null;if(input.domain&&input.domain!==parsed.domain)return null;if(input.address&&input.address!==parsed.address)return null;if(input.statement!==parsed.statement)return null;if(input.uri!==parsed.uri)return null;if(input.version!==parsed.version)return null;if(input.chainId!==parsed.chainId)return null;if(input.nonce!==parsed.nonce)return null;if(input.issuedAt!==parsed.issuedAt)return null;if(input.expirationTime!==parsed.expirationTime)return null;if(input.notBefore!==parsed.notBefore)return null;if(input.requestId!==parsed.requestId)return null;if(input.resources){if(!parsed.resources)return null;if(!(0,util_js_1.arraysEqual)(input.resources,parsed.resources))return null}else if(parsed.resources)return null;return createSignInMessageText(parsed)}function parseSignInMessage(message){return parseSignInMessageText((new TextDecoder).decode(message))}const MESSAGE=new RegExp("^(?[^\\n]+?) wants you to sign in with your Solana account:\\n(?
[^\\n]+)(?:\\n|$)(?:\\n(?[\\S\\s]*?)(?:\\n|$))??(?:\\nURI: (?[^\\n]+))?(?:\\nVersion: (?[^\\n]+))?(?:\\nChain ID: (?[^\\n]+))?(?:\\nNonce: (?[^\\n]+))?(?:\\nIssued At: (?[^\\n]+))?(?:\\nExpiration Time: (?[^\\n]+))?(?:\\nNot Before: (?[^\\n]+))?(?:\\nRequest ID: (?[^\\n]+))?(?:\\nResources:(?(?:\\n- [^\\n]+)*))?\\n*$");function parseSignInMessageText(text){var _a;const match=MESSAGE.exec(text);if(!match)return null;const groups=match.groups;return groups?{domain:groups.domain,address:groups.address,statement:groups.statement,uri:groups.uri,version:groups.version,nonce:groups.nonce,chainId:groups.chainId,issuedAt:groups.issuedAt,expirationTime:groups.expirationTime,notBefore:groups.notBefore,requestId:groups.requestId,resources:null===(_a=groups.resources)||void 0===_a?void 0:_a.split("\n- ").slice(1)}:null}function createSignInMessageText(input){let message=`${input.domain} wants you to sign in with your Solana account:\n`;message+=`${input.address}`,input.statement&&(message+=`\n\n${input.statement}`);const fields=[];if(input.uri&&fields.push(`URI: ${input.uri}`),input.version&&fields.push(`Version: ${input.version}`),input.chainId&&fields.push(`Chain ID: ${input.chainId}`),input.nonce&&fields.push(`Nonce: ${input.nonce}`),input.issuedAt&&fields.push(`Issued At: ${input.issuedAt}`),input.expirationTime&&fields.push(`Expiration Time: ${input.expirationTime}`),input.notBefore&&fields.push(`Not Before: ${input.notBefore}`),input.requestId&&fields.push(`Request ID: ${input.requestId}`),input.resources){fields.push("Resources:");for(const resource of input.resources)fields.push(`- ${resource}`)}return fields.length&&(message+=`\n\n${fields.join("\n")}`),message}},"./node_modules/@solana/wallet-standard-util/lib/cjs/signMessage.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.verifyMessageSignature=verifyMessageSignature,exports.verifySignMessage=function verifySignMessage(input,output){const{message,account:{publicKey}}=input,{signedMessage,signature}=output;return verifyMessageSignature({message,signedMessage,signature,publicKey})};const ed25519_1=__webpack_require__("./node_modules/@noble/curves/ed25519.js"),util_js_1=__webpack_require__("./node_modules/@solana/wallet-standard-util/lib/cjs/util.js");function verifyMessageSignature({message,signedMessage,signature,publicKey}){return(0,util_js_1.bytesEqual)(message,signedMessage)&&ed25519_1.ed25519.verify(signature,signedMessage,publicKey)}},"./node_modules/@solana/wallet-standard-util/lib/cjs/util.js":(__unused_webpack_module,exports)=>{"use strict";function arraysEqual(a,b){if(a===b)return!0;const length=a.length;if(length!==b.length)return!1;for(let i=0;i{"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{Account:()=>Account,AddressLookupTableAccount:()=>AddressLookupTableAccount,AddressLookupTableInstruction:()=>AddressLookupTableInstruction,AddressLookupTableProgram:()=>AddressLookupTableProgram,Authorized:()=>Authorized,BLOCKHASH_CACHE_TIMEOUT_MS:()=>BLOCKHASH_CACHE_TIMEOUT_MS,BPF_LOADER_DEPRECATED_PROGRAM_ID:()=>BPF_LOADER_DEPRECATED_PROGRAM_ID,BPF_LOADER_PROGRAM_ID:()=>BPF_LOADER_PROGRAM_ID,BpfLoader:()=>BpfLoader,COMPUTE_BUDGET_INSTRUCTION_LAYOUTS:()=>COMPUTE_BUDGET_INSTRUCTION_LAYOUTS,ComputeBudgetInstruction:()=>ComputeBudgetInstruction,ComputeBudgetProgram:()=>ComputeBudgetProgram,Connection:()=>Connection,Ed25519Program:()=>Ed25519Program,Enum:()=>Enum,EpochSchedule:()=>EpochSchedule,FeeCalculatorLayout:()=>FeeCalculatorLayout,Keypair:()=>Keypair,LAMPORTS_PER_SOL:()=>LAMPORTS_PER_SOL,LOOKUP_TABLE_INSTRUCTION_LAYOUTS:()=>LOOKUP_TABLE_INSTRUCTION_LAYOUTS,Loader:()=>Loader,Lockup:()=>Lockup,MAX_SEED_LENGTH:()=>MAX_SEED_LENGTH,Message:()=>Message,MessageAccountKeys:()=>MessageAccountKeys,MessageV0:()=>MessageV0,NONCE_ACCOUNT_LENGTH:()=>NONCE_ACCOUNT_LENGTH,NonceAccount:()=>NonceAccount,PACKET_DATA_SIZE:()=>PACKET_DATA_SIZE,PUBLIC_KEY_LENGTH:()=>PUBLIC_KEY_LENGTH,PublicKey:()=>PublicKey,SIGNATURE_LENGTH_IN_BYTES:()=>SIGNATURE_LENGTH_IN_BYTES,SOLANA_SCHEMA:()=>SOLANA_SCHEMA,STAKE_CONFIG_ID:()=>STAKE_CONFIG_ID,STAKE_INSTRUCTION_LAYOUTS:()=>STAKE_INSTRUCTION_LAYOUTS,SYSTEM_INSTRUCTION_LAYOUTS:()=>SYSTEM_INSTRUCTION_LAYOUTS,SYSVAR_CLOCK_PUBKEY:()=>SYSVAR_CLOCK_PUBKEY,SYSVAR_EPOCH_SCHEDULE_PUBKEY:()=>SYSVAR_EPOCH_SCHEDULE_PUBKEY,SYSVAR_INSTRUCTIONS_PUBKEY:()=>SYSVAR_INSTRUCTIONS_PUBKEY,SYSVAR_RECENT_BLOCKHASHES_PUBKEY:()=>SYSVAR_RECENT_BLOCKHASHES_PUBKEY,SYSVAR_RENT_PUBKEY:()=>SYSVAR_RENT_PUBKEY,SYSVAR_REWARDS_PUBKEY:()=>SYSVAR_REWARDS_PUBKEY,SYSVAR_SLOT_HASHES_PUBKEY:()=>SYSVAR_SLOT_HASHES_PUBKEY,SYSVAR_SLOT_HISTORY_PUBKEY:()=>SYSVAR_SLOT_HISTORY_PUBKEY,SYSVAR_STAKE_HISTORY_PUBKEY:()=>SYSVAR_STAKE_HISTORY_PUBKEY,Secp256k1Program:()=>Secp256k1Program,SendTransactionError:()=>SendTransactionError,SolanaJSONRPCError:()=>SolanaJSONRPCError,SolanaJSONRPCErrorCode:()=>SolanaJSONRPCErrorCode,StakeAuthorizationLayout:()=>StakeAuthorizationLayout,StakeInstruction:()=>StakeInstruction,StakeProgram:()=>StakeProgram,Struct:()=>index_browser_esm_Struct,SystemInstruction:()=>SystemInstruction,SystemProgram:()=>SystemProgram,Transaction:()=>Transaction,TransactionExpiredBlockheightExceededError:()=>TransactionExpiredBlockheightExceededError,TransactionExpiredNonceInvalidError:()=>TransactionExpiredNonceInvalidError,TransactionExpiredTimeoutError:()=>TransactionExpiredTimeoutError,TransactionInstruction:()=>TransactionInstruction,TransactionMessage:()=>TransactionMessage,TransactionStatus:()=>TransactionStatus,VALIDATOR_INFO_KEY:()=>VALIDATOR_INFO_KEY,VERSION_PREFIX_MASK:()=>VERSION_PREFIX_MASK,VOTE_PROGRAM_ID:()=>VOTE_PROGRAM_ID,ValidatorInfo:()=>ValidatorInfo,VersionedMessage:()=>VersionedMessage,VersionedTransaction:()=>VersionedTransaction,VoteAccount:()=>VoteAccount,VoteAuthorizationLayout:()=>VoteAuthorizationLayout,VoteInit:()=>VoteInit,VoteInstruction:()=>VoteInstruction,VoteProgram:()=>VoteProgram,clusterApiUrl:()=>clusterApiUrl,sendAndConfirmRawTransaction:()=>sendAndConfirmRawTransaction,sendAndConfirmTransaction:()=>sendAndConfirmTransaction});var node_modules_buffer=__webpack_require__("./node_modules/buffer/index.js");const crypto_crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function isBytes(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&"Uint8Array"===a.constructor.name}function anumber(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function utils_abytes(b,...lengths){if(!isBytes(b))throw new Error("Uint8Array expected");if(lengths.length>0&&!lengths.includes(b.length))throw new Error("Uint8Array expected of length "+lengths+", got length="+b.length)}function aexists(instance,checkFinished=!0){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function aoutput(out,instance){utils_abytes(out);const min=instance.outputLen;if(out.length>>shift}const isLE=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function byteSwap(word){return word<<24&4278190080|word<<8&16711680|word>>>8&65280|word>>>24&255}const swap32IfBE=isLE?u=>u:function byteSwap32(arr){for(let i=0;i"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),hexes=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));function utils_bytesToHex(bytes){if(utils_abytes(bytes),hasHexBuiltin)return bytes.toHex();let hex="";for(let i=0;i=asciis__0&&ch<=asciis__9?ch-asciis__0:ch>=asciis_A&&ch<=asciis_F?ch-(asciis_A-10):ch>=asciis_a&&ch<=asciis_f?ch-(asciis_a-10):void 0}function hexToBytes(hex){if("string"!=typeof hex)throw new Error("hex string expected, got "+typeof hex);if(hasHexBuiltin)return Uint8Array.fromHex(hex);const hl=hex.length,al=hl/2;if(hl%2)throw new Error("hex string expected, got unpadded hex of length "+hl);const array=new Uint8Array(al);for(let ai=0,hi=0;aihashCons().update(toBytes(msg)).digest(),tmp=hashCons();return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.create=()=>hashCons(),hashC}function utils_randomBytes(bytesLength=32){if(crypto_crypto&&"function"==typeof crypto_crypto.getRandomValues)return crypto_crypto.getRandomValues(new Uint8Array(bytesLength));if(crypto_crypto&&"function"==typeof crypto_crypto.randomBytes)return Uint8Array.from(crypto_crypto.randomBytes(bytesLength));throw new Error("crypto.getRandomValues must be defined")}function Chi(a,b,c){return a&b^~a&c}function Maj(a,b,c){return a&b^a&c^b&c}class HashMD extends Hash{constructor(blockLen,outputLen,padOffset,isLE){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=blockLen,this.outputLen=outputLen,this.padOffset=padOffset,this.isLE=isLE,this.buffer=new Uint8Array(blockLen),this.view=createView(this.buffer)}update(data){aexists(this),utils_abytes(data=toBytes(data));const{view,buffer,blockLen}=this,len=data.length;for(let pos=0;posblockLen-pos&&(this.process(view,0),pos=0);for(let i=pos;i>_32n&_u32_max),wl=Number(value&_u32_max),h=isLE?4:0,l=isLE?0:4;view.setUint32(byteOffset+h,wh,isLE),view.setUint32(byteOffset+l,wl,isLE)}(view,blockLen-8,BigInt(8*this.length),isLE),this.process(view,0);const oview=createView(out),len=this.outputLen;if(len%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const outLen=len/4,state=this.get();if(outLen>state.length)throw new Error("_sha2: outputLen bigger than state");for(let i=0;i>_32n&U32_MASK64)}:{h:0|Number(n>>_32n&U32_MASK64),l:0|Number(n&U32_MASK64)}}function split(lst,le=!1){const len=lst.length;let Ah=new Uint32Array(len),Al=new Uint32Array(len);for(let i=0;ih>>>s,shrSL=(h,l,s)=>h<<32-s|l>>>s,rotrSH=(h,l,s)=>h>>>s|l<<32-s,rotrSL=(h,l,s)=>h<<32-s|l>>>s,rotrBH=(h,l,s)=>h<<64-s|l>>>s-32,rotrBL=(h,l,s)=>h>>>s-32|l<<64-s,rotlSH=(h,l,s)=>h<>>32-s,rotlSL=(h,l,s)=>l<>>32-s,rotlBH=(h,l,s)=>l<>>64-s,rotlBL=(h,l,s)=>h<>>64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:0|l}}const add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0),add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0,add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0),add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0,add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0),add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0,SHA256_K=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]),SHA256_W=new Uint32Array(64);class SHA256 extends HashMD{constructor(outputLen=32){super(64,outputLen,8,!1),this.A=0|SHA256_IV[0],this.B=0|SHA256_IV[1],this.C=0|SHA256_IV[2],this.D=0|SHA256_IV[3],this.E=0|SHA256_IV[4],this.F=0|SHA256_IV[5],this.G=0|SHA256_IV[6],this.H=0|SHA256_IV[7]}get(){const{A,B,C,D,E,F,G,H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=0|A,this.B=0|B,this.C=0|C,this.D=0|D,this.E=0|E,this.F=0|F,this.G=0|G,this.H=0|H}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,!1);for(let i=16;i<64;i++){const W15=SHA256_W[i-15],W2=SHA256_W[i-2],s0=rotr(W15,7)^rotr(W15,18)^W15>>>3,s1=rotr(W2,17)^rotr(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A,B,C,D,E,F,G,H}=this;for(let i=0;i<64;i++){const T1=H+(rotr(E,6)^rotr(E,11)^rotr(E,25))+Chi(E,F,G)+SHA256_K[i]+SHA256_W[i]|0,T2=(rotr(A,2)^rotr(A,13)^rotr(A,22))+Maj(A,B,C)|0;H=G,G=F,F=E,E=D+T1|0,D=C,C=B,B=A,A=T1+T2|0}A=A+this.A|0,B=B+this.B|0,C=C+this.C|0,D=D+this.D|0,E=E+this.E|0,F=F+this.F|0,G=G+this.G|0,H=H+this.H|0,this.set(A,B,C,D,E,F,G,H)}roundClean(){clean(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0),clean(this.buffer)}}const K512=(()=>split(["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"].map(n=>BigInt(n))))(),SHA512_Kh=(()=>K512[0])(),SHA512_Kl=(()=>K512[1])(),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends HashMD{constructor(outputLen=64){super(128,outputLen,16,!1),this.Ah=0|SHA512_IV[0],this.Al=0|SHA512_IV[1],this.Bh=0|SHA512_IV[2],this.Bl=0|SHA512_IV[3],this.Ch=0|SHA512_IV[4],this.Cl=0|SHA512_IV[5],this.Dh=0|SHA512_IV[6],this.Dl=0|SHA512_IV[7],this.Eh=0|SHA512_IV[8],this.El=0|SHA512_IV[9],this.Fh=0|SHA512_IV[10],this.Fl=0|SHA512_IV[11],this.Gh=0|SHA512_IV[12],this.Gl=0|SHA512_IV[13],this.Hh=0|SHA512_IV[14],this.Hl=0|SHA512_IV[15]}get(){const{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=0|Ah,this.Al=0|Al,this.Bh=0|Bh,this.Bl=0|Bl,this.Ch=0|Ch,this.Cl=0|Cl,this.Dh=0|Dh,this.Dl=0|Dl,this.Eh=0|Eh,this.El=0|El,this.Fh=0|Fh,this.Fl=0|Fl,this.Gh=0|Gh,this.Gl=0|Gl,this.Hh=0|Hh,this.Hl=0|Hl}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA512_W_H[i]=view.getUint32(offset),SHA512_W_L[i]=view.getUint32(offset+=4);for(let i=16;i<80;i++){const W15h=0|SHA512_W_H[i-15],W15l=0|SHA512_W_L[i-15],s0h=rotrSH(W15h,W15l,1)^rotrSH(W15h,W15l,8)^shrSH(W15h,0,7),s0l=rotrSL(W15h,W15l,1)^rotrSL(W15h,W15l,8)^shrSL(W15h,W15l,7),W2h=0|SHA512_W_H[i-2],W2l=0|SHA512_W_L[i-2],s1h=rotrSH(W2h,W2l,19)^rotrBH(W2h,W2l,61)^shrSH(W2h,0,6),s1l=rotrSL(W2h,W2l,19)^rotrBL(W2h,W2l,61)^shrSL(W2h,W2l,6),SUMl=add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]),SUMh=add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=0|SUMh,SHA512_W_L[i]=0|SUMl}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){const sigma1h=rotrSH(Eh,El,14)^rotrSH(Eh,El,18)^rotrBH(Eh,El,41),sigma1l=rotrSL(Eh,El,14)^rotrSL(Eh,El,18)^rotrBL(Eh,El,41),CHIh=Eh&Fh^~Eh&Gh,T1ll=add5L(Hl,sigma1l,El&Fl^~El&Gl,SHA512_Kl[i],SHA512_W_L[i]),T1h=add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]),T1l=0|T1ll,sigma0h=rotrSH(Ah,Al,28)^rotrBH(Ah,Al,34)^rotrBH(Ah,Al,39),sigma0l=rotrSL(Ah,Al,28)^rotrBL(Ah,Al,34)^rotrBL(Ah,Al,39),MAJh=Ah&Bh^Ah&Ch^Bh&Ch,MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=0|Gh,Hl=0|Gl,Gh=0|Fh,Gl=0|Fl,Fh=0|Eh,Fl=0|El,({h:Eh,l:El}=add(0|Dh,0|Dl,0|T1h,0|T1l)),Dh=0|Ch,Dl=0|Cl,Ch=0|Bh,Cl=0|Bl,Bh=0|Ah,Bl=0|Al;const All=add3L(T1l,sigma0l,MAJl);Ah=add3H(All,T1h,sigma0h,MAJh),Al=0|All}({h:Ah,l:Al}=add(0|this.Ah,0|this.Al,0|Ah,0|Al)),({h:Bh,l:Bl}=add(0|this.Bh,0|this.Bl,0|Bh,0|Bl)),({h:Ch,l:Cl}=add(0|this.Ch,0|this.Cl,0|Ch,0|Cl)),({h:Dh,l:Dl}=add(0|this.Dh,0|this.Dl,0|Dh,0|Dl)),({h:Eh,l:El}=add(0|this.Eh,0|this.El,0|Eh,0|El)),({h:Fh,l:Fl}=add(0|this.Fh,0|this.Fl,0|Fh,0|Fl)),({h:Gh,l:Gl}=add(0|this.Gh,0|this.Gl,0|Gh,0|Gl)),({h:Hh,l:Hl}=add(0|this.Hh,0|this.Hl,0|Hh,0|Hl)),this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){clean(SHA512_W_H,SHA512_W_L)}destroy(){clean(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha2_sha256=utils_createHasher(()=>new SHA256),sha2_sha512=utils_createHasher(()=>new SHA512),_0n=BigInt(0),_1n=BigInt(1);function abool(title,value){if("boolean"!=typeof value)throw new Error(title+" boolean expected, got "+value)}function numberToHexUnpadded(num){const hex=num.toString(16);return 1&hex.length?"0"+hex:hex}function hexToNumber(hex){if("string"!=typeof hex)throw new Error("hex string expected, got "+typeof hex);return""===hex?_0n:BigInt("0x"+hex)}function utils_bytesToNumberBE(bytes){return hexToNumber(utils_bytesToHex(bytes))}function utils_bytesToNumberLE(bytes){return utils_abytes(bytes),hexToNumber(utils_bytesToHex(Uint8Array.from(bytes).reverse()))}function utils_numberToBytesBE(n,len){return hexToBytes(n.toString(16).padStart(2*len,"0"))}function utils_numberToBytesLE(n,len){return utils_numberToBytesBE(n,len).reverse()}function utils_ensureBytes(title,hex,expectedLength){let res;if("string"==typeof hex)try{res=hexToBytes(hex)}catch(e){throw new Error(title+" must be hex string or Uint8Array, cause: "+e)}else{if(!isBytes(hex))throw new Error(title+" must be hex string or Uint8Array");res=Uint8Array.from(hex)}const len=res.length;if("number"==typeof expectedLength&&len!==expectedLength)throw new Error(title+" of length "+expectedLength+" expected, got "+len);return res}const isPosBig=n=>"bigint"==typeof n&&_0n<=n;function utils_aInRange(title,n,min,max){if(!function utils_inRange(n,min,max){return isPosBig(n)&&isPosBig(min)&&isPosBig(max)&&min<=n&&n(_1n<checkField(k,v,!1)),Object.entries(optFields).forEach(([k,v])=>checkField(k,v,!0))}function memoized(fn){const map=new WeakMap;return(arg,...args)=>{const val=map.get(arg);if(void 0!==val)return val;const computed=fn(arg,...args);return map.set(arg,computed),computed}}const modular_0n=BigInt(0),modular_1n=BigInt(1),_2n=BigInt(2),_3n=BigInt(3),_4n=BigInt(4),_5n=BigInt(5),_8n=BigInt(8);function modular_mod(a,b){const result=a%b;return result>=modular_0n?result:b+result}function modular_pow2(x,power,modulo){let res=x;for(;power-- >modular_0n;)res*=res,res%=modulo;return res}function invert(number,modulo){if(number===modular_0n)throw new Error("invert: expected non-zero number");if(modulo<=modular_0n)throw new Error("invert: expected positive modulus, got "+modulo);let a=modular_mod(number,modulo),b=modulo,x=modular_0n,y=modular_1n,u=modular_1n,v=modular_0n;for(;a!==modular_0n;){const q=b/a,r=b%a,m=x-u*q,n=y-v*q;b=a,a=r,x=u,y=v,u=m,v=n}if(b!==modular_1n)throw new Error("invert: does not exist");return modular_mod(x,modulo)}function sqrt3mod4(Fp,n){const p1div4=(Fp.ORDER+modular_1n)/_4n,root=Fp.pow(n,p1div4);if(!Fp.eql(Fp.sqr(root),n))throw new Error("Cannot find square root");return root}function sqrt5mod8(Fp,n){const p5div8=(Fp.ORDER-_5n)/_8n,n2=Fp.mul(n,_2n),v=Fp.pow(n2,p5div8),nv=Fp.mul(n,v),i=Fp.mul(Fp.mul(nv,_2n),v),root=Fp.mul(nv,Fp.sub(i,Fp.ONE));if(!Fp.eql(Fp.sqr(root),n))throw new Error("Cannot find square root");return root}function FpSqrt(P){return P%_4n===_3n?sqrt3mod4:P%_8n===_5n?sqrt5mod8:function tonelliShanks(P){if(P1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===S)return sqrt3mod4;let cc=_Fp.pow(Z,Q);const Q1div2=(Q+modular_1n)/_2n;return function tonelliSlow(Fp,n){if(Fp.is0(n))return n;if(1!==FpLegendre(Fp,n))throw new Error("Cannot find square root");let M=S,c=Fp.mul(Fp.ONE,cc),t=Fp.pow(n,Q),R=Fp.pow(n,Q1div2);for(;!Fp.eql(t,Fp.ONE);){if(Fp.is0(t))return Fp.ZERO;let i=1,t_tmp=Fp.sqr(t);for(;!Fp.eql(t_tmp,Fp.ONE);)if(i++,t_tmp=Fp.sqr(t_tmp),i===M)throw new Error("Cannot find square root");const exponent=modular_1n<modular_0n;)power&modular_1n&&(p=Fp.mul(p,d)),d=Fp.sqr(d),power>>=modular_1n;return p}function modular_FpInvertBatch(Fp,nums,passZero=!1){const inverted=new Array(nums.length).fill(passZero?Fp.ZERO:void 0),multipliedAcc=nums.reduce((acc,num,i)=>Fp.is0(num)?acc:(inverted[i]=acc,Fp.mul(acc,num)),Fp.ONE),invertedAcc=Fp.inv(multipliedAcc);return nums.reduceRight((acc,num,i)=>Fp.is0(num)?acc:(inverted[i]=Fp.mul(acc,inverted[i]),Fp.mul(acc,num)),invertedAcc),inverted}function FpLegendre(Fp,n){const p1mod2=(Fp.ORDER-modular_1n)/_2n,powered=Fp.pow(n,p1mod2),yes=Fp.eql(powered,Fp.ONE),zero=Fp.eql(powered,Fp.ZERO),no=Fp.eql(powered,Fp.neg(Fp.ONE));if(!yes&&!zero&&!no)throw new Error("invalid Legendre symbol result");return yes?1:zero?0:-1}function modular_nLength(n,nBitLength){void 0!==nBitLength&&anumber(nBitLength);const _nBitLength=void 0!==nBitLength?nBitLength:n.toString(2).length;return{nBitLength:_nBitLength,nByteLength:Math.ceil(_nBitLength/8)}}function modular_Field(ORDER,bitLenOrOpts,isLE=!1,opts={}){if(ORDER<=modular_0n)throw new Error("invalid field: expected ORDER > 0, got "+ORDER);let _nbitLength,_sqrt;if("object"==typeof bitLenOrOpts&&null!=bitLenOrOpts){if(opts.sqrt||isLE)throw new Error("cannot specify opts in two arguments");const _opts=bitLenOrOpts;_opts.BITS&&(_nbitLength=_opts.BITS),_opts.sqrt&&(_sqrt=_opts.sqrt),"boolean"==typeof _opts.isLE&&(isLE=_opts.isLE)}else"number"==typeof bitLenOrOpts&&(_nbitLength=bitLenOrOpts),opts.sqrt&&(_sqrt=opts.sqrt);const{nBitLength:BITS,nByteLength:BYTES}=modular_nLength(ORDER,_nbitLength);if(BYTES>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let sqrtP;const f=Object.freeze({ORDER,isLE,BITS,BYTES,MASK:utils_bitMask(BITS),ZERO:modular_0n,ONE:modular_1n,create:num=>modular_mod(num,ORDER),isValid:num=>{if("bigint"!=typeof num)throw new Error("invalid field element: expected bigint, got "+typeof num);return modular_0n<=num&&numnum===modular_0n,isValidNot0:num=>!f.is0(num)&&f.isValid(num),isOdd:num=>(num&modular_1n)===modular_1n,neg:num=>modular_mod(-num,ORDER),eql:(lhs,rhs)=>lhs===rhs,sqr:num=>modular_mod(num*num,ORDER),add:(lhs,rhs)=>modular_mod(lhs+rhs,ORDER),sub:(lhs,rhs)=>modular_mod(lhs-rhs,ORDER),mul:(lhs,rhs)=>modular_mod(lhs*rhs,ORDER),pow:(num,power)=>FpPow(f,num,power),div:(lhs,rhs)=>modular_mod(lhs*invert(rhs,ORDER),ORDER),sqrN:num=>num*num,addN:(lhs,rhs)=>lhs+rhs,subN:(lhs,rhs)=>lhs-rhs,mulN:(lhs,rhs)=>lhs*rhs,inv:num=>invert(num,ORDER),sqrt:_sqrt||(n=>(sqrtP||(sqrtP=FpSqrt(ORDER)),sqrtP(f,n))),toBytes:num=>isLE?utils_numberToBytesLE(num,BYTES):utils_numberToBytesBE(num,BYTES),fromBytes:bytes=>{if(bytes.length!==BYTES)throw new Error("Field.fromBytes: expected "+BYTES+" bytes, got "+bytes.length);return isLE?utils_bytesToNumberLE(bytes):utils_bytesToNumberBE(bytes)},invertBatch:lst=>modular_FpInvertBatch(f,lst),cmov:(a,b,c)=>c?b:a});return Object.freeze(f)}function getFieldBytesLength(fieldOrder){if("bigint"!=typeof fieldOrder)throw new Error("field order must be bigint");const bitLength=fieldOrder.toString(2).length;return Math.ceil(bitLength/8)}function getMinHashLength(fieldOrder){const length=getFieldBytesLength(fieldOrder);return length+Math.ceil(length/2)}const curve_0n=BigInt(0),curve_1n=BigInt(1);function negateCt(condition,item){const neg=item.negate();return condition?neg:item}function normalizeZ(c,property,points){const getz="pz"===property?p=>p.pz:p=>p.ez,toInv=modular_FpInvertBatch(c.Fp,points.map(getz));return points.map((p,i)=>p.toAffine(toInv[i])).map(c.fromAffine)}function validateW(W,bits){if(!Number.isSafeInteger(W)||W<=0||W>bits)throw new Error("invalid window size, expected [1.."+bits+"], got W="+W)}function calcWOpts(W,scalarBits){validateW(W,scalarBits);const maxNumber=2**W;return{windows:Math.ceil(scalarBits/W)+1,windowSize:2**(W-1),mask:utils_bitMask(W),maxNumber,shiftBy:BigInt(W)}}function calcOffsets(n,window,wOpts){const{windowSize,mask,maxNumber,shiftBy}=wOpts;let wbits=Number(n&mask),nextN=n>>shiftBy;wbits>windowSize&&(wbits-=maxNumber,nextN+=curve_1n);const offsetStart=window*windowSize;return{nextN,offset:offsetStart+Math.abs(wbits)-1,isZero:0===wbits,isNeg:wbits<0,isNegF:window%2!=0,offsetF:offsetStart}}function validateMSMPoints(points,c){if(!Array.isArray(points))throw new Error("array expected");points.forEach((p,i)=>{if(!(p instanceof c))throw new Error("invalid point at index "+i)})}function validateMSMScalars(scalars,field){if(!Array.isArray(scalars))throw new Error("array of scalars expected");scalars.forEach((s,i)=>{if(!field.isValid(s))throw new Error("invalid scalar at index "+i)})}const pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(P){return pointWindowSizes.get(P)||1}function assert0(n){if(n!==curve_0n)throw new Error("invalid wNAF")}function wNAF(c,bits){return{constTimeNegate:negateCt,hasPrecomputes:elm=>1!==getW(elm),unsafeLadder(elm,n,p=c.ZERO){let d=elm;for(;n>curve_0n;)n&curve_1n&&(p=p.add(d)),d=d.double(),n>>=curve_1n;return p},precomputeWindow(elm,W){const{windows,windowSize}=calcWOpts(W,bits),points=[];let p=elm,base=p;for(let window=0;window_0n;n>>=_1n,len+=1);return len}(BigInt(plength));let windowSize=1;wbits>12?windowSize=wbits-3:wbits>4?windowSize=wbits-2:wbits>0&&(windowSize=2);const MASK=utils_bitMask(windowSize),buckets=new Array(Number(MASK)+1).fill(zero);let sum=zero;for(let i=Math.floor((fieldN.BITS-1)/windowSize)*windowSize;i>=0;i-=windowSize){buckets.fill(zero);for(let j=0;j>BigInt(i)&MASK);buckets[wbits]=buckets[wbits].add(points[j])}let resI=zero;for(let j=buckets.length-1,sumI=zero;j>0;j--)sumI=sumI.add(buckets[j]),resI=resI.add(sumI);if(sum=sum.add(resI),0!==i)for(let j=0;j(map[val]="function",map),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});return _validateObject(field,opts),field}(field),field}return modular_Field(order)}function _createCurveFields(type,CURVE,curveOpts={}){if(!CURVE||"object"!=typeof CURVE)throw new Error(`expected valid ${type} CURVE object`);for(const p of["p","n","h"]){const val=CURVE[p];if(!("bigint"==typeof val&&val>curve_0n))throw new Error(`CURVE.${p} must be positive bigint`)}const Fp=createField(CURVE.p,curveOpts.Fp),Fn=createField(CURVE.n,curveOpts.Fn),params=["Gx","Gy","a","weierstrass"===type?"b":"d"];for(const p of params)if(!Fp.isValid(CURVE[p]))throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);return{Fp,Fn}}const edwards_0n=BigInt(0),edwards_1n=BigInt(1),edwards_2n=BigInt(2),edwards_8n=BigInt(8),VERIFY_DEFAULT={zip215:!0};function eddsa(Point,eddsaOpts){_validateObject(eddsaOpts,{hash:"function"},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash,hash:cHash}=eddsaOpts,{BASE:G,Fp,Fn}=Point,CURVE_ORDER=Fn.ORDER,randomBytes_=eddsaOpts.randomBytes||utils_randomBytes,adjustScalarBytes=eddsaOpts.adjustScalarBytes||(bytes=>bytes),domain=eddsaOpts.domain||((data,ctx,phflag)=>{if(abool("phflag",phflag),ctx.length||phflag)throw new Error("Contexts/pre-hash are not supported");return data});function modN(a){return Fn.create(a)}function modN_LE(hash){return modN(utils_bytesToNumberLE(hash))}function getExtendedPublicKey(key){const{head,prefix,scalar}=function getPrivateScalar(key){const len=Fp.BYTES;key=utils_ensureBytes("private key",key,len);const hashed=utils_ensureBytes("hashed private key",cHash(key),2*len),head=adjustScalarBytes(hashed.slice(0,len));return{head,prefix:hashed.slice(len,2*len),scalar:modN_LE(head)}}(key),point=G.multiply(scalar),pointBytes=point.toBytes();return{head,prefix,scalar,point,pointBytes}}function hashDomainToScalar(context=Uint8Array.of(),...msgs){const msg=utils_concatBytes(...msgs);return modN_LE(cHash(domain(msg,utils_ensureBytes("context",context),!!prehash)))}const verifyOpts=VERIFY_DEFAULT;G.precompute(8);return{getPublicKey:function getPublicKey(privKey){return getExtendedPublicKey(privKey).pointBytes},sign:function sign(msg,privKey,options={}){msg=utils_ensureBytes("message",msg),prehash&&(msg=prehash(msg));const{prefix,scalar,pointBytes}=getExtendedPublicKey(privKey),r=hashDomainToScalar(options.context,prefix,msg),R=G.multiply(r).toBytes(),s=modN(r+hashDomainToScalar(options.context,R,pointBytes,msg)*scalar);utils_aInRange("signature.s",s,edwards_0n,CURVE_ORDER);const L=Fp.BYTES;return utils_ensureBytes("result",utils_concatBytes(R,utils_numberToBytesLE(s,L)),2*L)},verify:function verify(sig,msg,publicKey,options=verifyOpts){const{context,zip215}=options,len=Fp.BYTES;sig=utils_ensureBytes("signature",sig,2*len),msg=utils_ensureBytes("message",msg),publicKey=utils_ensureBytes("publicKey",publicKey,len),void 0!==zip215&&abool("zip215",zip215),prehash&&(msg=prehash(msg));const s=utils_bytesToNumberLE(sig.slice(len,2*len));let A,R,SB;try{A=Point.fromHex(publicKey,zip215),R=Point.fromHex(sig.slice(0,len),zip215),SB=G.multiplyUnsafe(s)}catch(error){return!1}if(!zip215&&A.isSmallOrder())return!1;const k=hashDomainToScalar(context,R.toBytes(),A.toBytes(),msg);return R.add(A.multiplyUnsafe(k)).subtract(SB).clearCofactor().is0()},utils:{getExtendedPublicKey,randomPrivateKey:()=>randomBytes_(Fp.BYTES),precompute:(windowSize=8,point=Point.BASE)=>point.precompute(windowSize,!1)},Point}}function edwards_twistedEdwards(c){const{CURVE,curveOpts,eddsaOpts}=function _eddsa_legacy_opts_to_new(c){const CURVE={a:c.a,d:c.d,p:c.Fp.ORDER,n:c.n,h:c.h,Gx:c.Gx,Gy:c.Gy};return{CURVE,curveOpts:{Fp:c.Fp,Fn:modular_Field(CURVE.n,c.nBitLength,!0),uvRatio:c.uvRatio},eddsaOpts:{hash:c.hash,randomBytes:c.randomBytes,adjustScalarBytes:c.adjustScalarBytes,domain:c.domain,prehash:c.prehash,mapToCurve:c.mapToCurve}}}(c),Point=function edwards(CURVE,curveOpts={}){const{Fp,Fn}=_createCurveFields("edwards",CURVE,curveOpts),{h:cofactor,n:CURVE_ORDER}=CURVE;_validateObject(curveOpts,{},{uvRatio:"function"});const MASK=edwards_2n<Fp.create(n),uvRatio=curveOpts.uvRatio||((u,v)=>{try{return{isValid:!0,value:Fp.sqrt(Fp.div(u,v))}}catch(e){return{isValid:!1,value:edwards_0n}}});if(!function isEdValidXY(Fp,CURVE,x,y){const x2=Fp.sqr(x),y2=Fp.sqr(y),left=Fp.add(Fp.mul(CURVE.a,x2),y2),right=Fp.add(Fp.ONE,Fp.mul(CURVE.d,Fp.mul(x2,y2)));return Fp.eql(left,right)}(Fp,CURVE,CURVE.Gx,CURVE.Gy))throw new Error("bad curve params: generator point");function acoord(title,n,banZero=!1){return utils_aInRange("coordinate "+title,n,banZero?edwards_1n:edwards_0n,MASK),n}function aextpoint(other){if(!(other instanceof Point))throw new Error("ExtendedPoint expected")}const toAffineMemo=memoized((p,iz)=>{const{ex:x,ey:y,ez:z}=p,is0=p.is0();null==iz&&(iz=is0?edwards_8n:Fp.inv(z));const ax=modP(x*iz),ay=modP(y*iz),zz=modP(z*iz);if(is0)return{x:edwards_0n,y:edwards_1n};if(zz!==edwards_1n)throw new Error("invZ was invalid");return{x:ax,y:ay}}),assertValidMemo=memoized(p=>{const{a,d}=CURVE;if(p.is0())throw new Error("bad point: ZERO");const{ex:X,ey:Y,ez:Z,et:T}=p,X2=modP(X*X),Y2=modP(Y*Y),Z2=modP(Z*Z),Z4=modP(Z2*Z2),aX2=modP(X2*a);if(modP(Z2*modP(aX2+Y2))!==modP(Z4+modP(d*modP(X2*Y2))))throw new Error("bad point: equation left != right (1)");if(modP(X*Y)!==modP(Z*T))throw new Error("bad point: equation left != right (2)");return!0});class Point{constructor(ex,ey,ez,et){this.ex=acoord("x",ex),this.ey=acoord("y",ey),this.ez=acoord("z",ez,!0),this.et=acoord("t",et),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(p){if(p instanceof Point)throw new Error("extended point not allowed");const{x,y}=p||{};return acoord("x",x),acoord("y",y),new Point(x,y,edwards_1n,modP(x*y))}static normalizeZ(points){return normalizeZ(Point,"ez",points)}static msm(points,scalars){return curve_pippenger(Point,Fn,points,scalars)}_setWindowSize(windowSize){this.precompute(windowSize)}precompute(windowSize=8,isLazy=!0){return wnaf.setWindowSize(this,windowSize),isLazy||this.multiply(edwards_2n),this}assertValidity(){assertValidMemo(this)}equals(other){aextpoint(other);const{ex:X1,ey:Y1,ez:Z1}=this,{ex:X2,ey:Y2,ez:Z2}=other,X1Z2=modP(X1*Z2),X2Z1=modP(X2*Z1),Y1Z2=modP(Y1*Z2),Y2Z1=modP(Y2*Z1);return X1Z2===X2Z1&&Y1Z2===Y2Z1}is0(){return this.equals(Point.ZERO)}negate(){return new Point(modP(-this.ex),this.ey,this.ez,modP(-this.et))}double(){const{a}=CURVE,{ex:X1,ey:Y1,ez:Z1}=this,A=modP(X1*X1),B=modP(Y1*Y1),C=modP(edwards_2n*modP(Z1*Z1)),D=modP(a*A),x1y1=X1+Y1,E=modP(modP(x1y1*x1y1)-A-B),G=D+B,F=G-C,H=D-B,X3=modP(E*F),Y3=modP(G*H),T3=modP(E*H),Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}add(other){aextpoint(other);const{a,d}=CURVE,{ex:X1,ey:Y1,ez:Z1,et:T1}=this,{ex:X2,ey:Y2,ez:Z2,et:T2}=other,A=modP(X1*X2),B=modP(Y1*Y2),C=modP(T1*d*T2),D=modP(Z1*Z2),E=modP((X1+Y1)*(X2+Y2)-A-B),F=D-C,G=D+C,H=modP(B-a*A),X3=modP(E*F),Y3=modP(G*H),T3=modP(E*H),Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}subtract(other){return this.add(other.negate())}multiply(scalar){const n=scalar;utils_aInRange("scalar",n,edwards_1n,CURVE_ORDER);const{p,f}=wnaf.wNAFCached(this,n,Point.normalizeZ);return Point.normalizeZ([p,f])[0]}multiplyUnsafe(scalar,acc=Point.ZERO){const n=scalar;return utils_aInRange("scalar",n,edwards_0n,CURVE_ORDER),n===edwards_0n?Point.ZERO:this.is0()||n===edwards_1n?this:wnaf.wNAFCachedUnsafe(this,n,Point.normalizeZ,acc)}isSmallOrder(){return this.multiplyUnsafe(cofactor).is0()}isTorsionFree(){return wnaf.wNAFCachedUnsafe(this,CURVE_ORDER).is0()}toAffine(invertedZ){return toAffineMemo(this,invertedZ)}clearCofactor(){return cofactor===edwards_1n?this:this.multiplyUnsafe(cofactor)}static fromBytes(bytes,zip215=!1){return utils_abytes(bytes),this.fromHex(bytes,zip215)}static fromHex(hex,zip215=!1){const{d,a}=CURVE,len=Fp.BYTES;hex=utils_ensureBytes("pointHex",hex,len),abool("zip215",zip215);const normed=hex.slice(),lastByte=hex[len-1];normed[len-1]=-129&lastByte;const y=utils_bytesToNumberLE(normed),max=zip215?MASK:Fp.ORDER;utils_aInRange("pointHex.y",y,edwards_0n,max);const y2=modP(y*y),u=modP(y2-edwards_1n),v=modP(d*y2-a);let{isValid,value:x}=uvRatio(u,v);if(!isValid)throw new Error("Point.fromHex: invalid y coordinate");const isXOdd=(x&edwards_1n)===edwards_1n,isLastByteOdd=!!(128&lastByte);if(!zip215&&x===edwards_0n&&isLastByteOdd)throw new Error("Point.fromHex: x=0 and x_0=1");return isLastByteOdd!==isXOdd&&(x=modP(-x)),Point.fromAffine({x,y})}static fromPrivateScalar(scalar){return Point.BASE.multiply(scalar)}toBytes(){const{x,y}=this.toAffine(),bytes=utils_numberToBytesLE(y,Fp.BYTES);return bytes[bytes.length-1]|=x&edwards_1n?128:0,bytes}toRawBytes(){return this.toBytes()}toHex(){return utils_bytesToHex(this.toBytes())}toString(){return``}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy,edwards_1n,modP(CURVE.Gx*CURVE.Gy)),Point.ZERO=new Point(edwards_0n,edwards_1n,edwards_1n,edwards_0n),Point.Fp=Fp,Point.Fn=Fn;const wnaf=wNAF(Point,8*Fn.BYTES);return Point}(CURVE,curveOpts);return function _eddsa_new_output_to_legacy(c,eddsa){return Object.assign({},eddsa,{ExtendedPoint:eddsa.Point,CURVE:c})}(c,eddsa(Point,eddsaOpts))}BigInt(0);const ed25519_1n=BigInt(1),ed25519_2n=BigInt(2),ed25519_5n=(BigInt(3),BigInt(5)),ed25519_8n=BigInt(8),ed25519_CURVE={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ed25519_8n,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ed25519_pow_2_252_3(x){const _10n=BigInt(10),_20n=BigInt(20),_40n=BigInt(40),_80n=BigInt(80),P=ed25519_CURVE.p,b2=x*x%P*x%P,b4=modular_pow2(b2,ed25519_2n,P)*b2%P,b5=modular_pow2(b4,ed25519_1n,P)*x%P,b10=modular_pow2(b5,ed25519_5n,P)*b5%P,b20=modular_pow2(b10,_10n,P)*b10%P,b40=modular_pow2(b20,_20n,P)*b20%P,b80=modular_pow2(b40,_40n,P)*b40%P,b160=modular_pow2(b80,_80n,P)*b80%P,b240=modular_pow2(b160,_80n,P)*b80%P,b250=modular_pow2(b240,_10n,P)*b10%P;return{pow_p_5_8:modular_pow2(b250,ed25519_2n,P)*x%P,b2}}function adjustScalarBytes(bytes){return bytes[0]&=248,bytes[31]&=127,bytes[31]|=64,bytes}const ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function uvRatio(u,v){const P=ed25519_CURVE.p,v3=modular_mod(v*v*v,P),v7=modular_mod(v3*v3*v,P);let x=modular_mod(u*v3*ed25519_pow_2_252_3(u*v7).pow_p_5_8,P);const vx2=modular_mod(v*x*x,P),root1=x,root2=modular_mod(x*ED25519_SQRT_M1,P),useRoot1=vx2===u,useRoot2=vx2===modular_mod(-u,P),noRoot=vx2===modular_mod(-u*ED25519_SQRT_M1,P);return useRoot1&&(x=root1),(useRoot2||noRoot)&&(x=root2),((num,modulo)=>(modular_mod(num,modulo)&modular_1n)===modular_1n)(x,P)&&(x=modular_mod(-x,P)),{isValid:useRoot1||useRoot2,value:x}}const Fp=(()=>modular_Field(ed25519_CURVE.p,void 0,!0))(),ed25519Defaults=(()=>({...ed25519_CURVE,Fp,hash:sha2_sha512,adjustScalarBytes,uvRatio}))(),ed25519=(()=>edwards_twistedEdwards(ed25519Defaults))();var bn=__webpack_require__("./node_modules/bn.js/lib/bn.js"),bn_default=__webpack_require__.n(bn),bs58=__webpack_require__("./node_modules/@solana/web3.js/node_modules/bs58/index.js"),bs58_default=__webpack_require__.n(bs58);const sha256_sha256=sha2_sha256;var lib=__webpack_require__("./node_modules/borsh/lib/index.js"),Layout=__webpack_require__("./node_modules/@solana/buffer-layout/lib/Layout.js");function encodeValue(value){if(Array.isArray(value)){return"%5B"+value.map(encodeValue).join("%2C%20")+"%5D"}return"bigint"==typeof value?`${value}n`:encodeURIComponent(String(null!=value&&null===Object.getPrototypeOf(value)?{...value}:value))}function encodeObjectContextEntry([key,value]){return`${key}=${encodeValue(value)}`}function getErrorMessage(code,context={}){{let decodingAdviceMessage=`Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`;return Object.keys(context).length&&(decodingAdviceMessage+=` '${function encodeContextObject(context){const searchParamsString=Object.entries(context).map(encodeObjectContextEntry).join("&");return btoa(searchParamsString)}(context)}'`),`${decodingAdviceMessage}\``}}var index_browser_SolanaError=class extends Error{cause=this.cause;context;constructor(...[code,contextAndErrorOptions]){let context,errorOptions;if(contextAndErrorOptions){const{cause,...contextRest}=contextAndErrorOptions;cause&&(errorOptions={cause}),Object.keys(contextRest).length>0&&(context=contextRest)}super(getErrorMessage(code,context),errorOptions),this.context={__code:code,...context},this.name="SolanaError"}};function getEncodedSize(value,encoder){return"fixedSize"in encoder?encoder.fixedSize:encoder.getSizeFromValue(value)}function index_browser_createEncoder(encoder){return Object.freeze({...encoder,encode:value=>{const bytes=new Uint8Array(getEncodedSize(value,encoder));return encoder.write(value,bytes,0),bytes}})}function index_browser_createDecoder(decoder){return Object.freeze({...decoder,decode:(bytes,offset=0)=>decoder.read(bytes,offset)[0]})}function isFixedSize(codec){return"fixedSize"in codec&&"number"==typeof codec.fixedSize}function index_browser_combineCodec(encoder,decoder){if(isFixedSize(encoder)!==isFixedSize(decoder))throw new index_browser_SolanaError(8078004);if(isFixedSize(encoder)&&isFixedSize(decoder)&&encoder.fixedSize!==decoder.fixedSize)throw new index_browser_SolanaError(8078005,{decoderFixedSize:decoder.fixedSize,encoderFixedSize:encoder.fixedSize});if(!isFixedSize(encoder)&&!isFixedSize(decoder)&&encoder.maxSize!==decoder.maxSize)throw new index_browser_SolanaError(8078006,{decoderMaxSize:decoder.maxSize,encoderMaxSize:encoder.maxSize});return{...decoder,...encoder,decode:decoder.decode,encode:encoder.encode,read:decoder.read,write:encoder.write}}function assertByteArrayHasEnoughBytesForCodec(codecDescription,expected,bytes,offset=0){const bytesLength=bytes.length-offset;if(bytesLengthmax)throw new index_browser_SolanaError(8078011,{codecDescription,max,min,value})}function isLittleEndian(config){return 1!==config?.endian}function numberEncoderFactory(input){return index_browser_createEncoder({fixedSize:input.size,write(value,bytes,offset){input.range&&assertNumberIsBetweenForCodec(input.name,input.range[0],input.range[1],value);const arrayBuffer=new ArrayBuffer(input.size);return input.set(new DataView(arrayBuffer),value,isLittleEndian(input.config)),bytes.set(new Uint8Array(arrayBuffer),offset),offset+input.size}})}function numberDecoderFactory(input){return index_browser_createDecoder({fixedSize:input.size,read(bytes,offset=0){!function assertByteArrayIsNotEmptyForCodec(codecDescription,bytes,offset=0){if(bytes.length-offset<=0)throw new index_browser_SolanaError(8078e3,{codecDescription})}(input.name,bytes,offset),assertByteArrayHasEnoughBytesForCodec(input.name,input.size,bytes,offset);const view=new DataView(function toArrayBuffer(bytes,offset,length){const bytesOffset=bytes.byteOffset+(offset??0),bytesLength=length??bytes.byteLength;return bytes.buffer.slice(bytesOffset,bytesOffset+bytesLength)}(bytes,offset,input.size));return[input.get(view,isLittleEndian(input.config)),offset+input.size]}})}var getU64Encoder=(config={})=>numberEncoderFactory({config,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(view,value,le)=>view.setBigUint64(0,BigInt(value),le),size:8}),getU64Codec=(config={})=>index_browser_combineCodec(getU64Encoder(config),((config={})=>numberDecoderFactory({config,get:(view,le)=>view.getBigUint64(0,le),name:"u64",size:8}))(config));class StructError extends TypeError{constructor(failure,failures){let cached;const{message,explanation,...rest}=failure,{path}=failure,msg=0===path.length?message:`At path: ${path.join(".")} -- ${message}`;super(explanation??msg),null!=explanation&&(this.cause=msg),Object.assign(this,rest),this.name=this.constructor.name,this.failures=()=>cached??(cached=[failure,...failures()])}}function isObject(x){return"object"==typeof x&&null!=x}function isNonArrayObject(x){return isObject(x)&&!Array.isArray(x)}function print(value){return"symbol"==typeof value?value.toString():"string"==typeof value?JSON.stringify(value):`${value}`}function toFailure(result,context,struct,value){if(!0===result)return;!1===result?result={}:"string"==typeof result&&(result={message:result});const{path,branch}=context,{type}=struct,{refinement,message=`Expected a value of type \`${type}\`${refinement?` with refinement \`${refinement}\``:""}, but received: \`${print(value)}\``}=result;return{value,type,refinement,key:path[path.length-1],path,branch,...result,message}}function*toFailures(result,context,struct,value){(function isIterable(x){return isObject(x)&&"function"==typeof x[Symbol.iterator]})(result)||(result=[result]);for(const r of result){const failure=toFailure(r,context,struct,value);failure&&(yield failure)}}function*run(value,struct,options={}){const{path=[],branch=[value],coerce=!1,mask=!1}=options,ctx={path,branch,mask};coerce&&(value=struct.coercer(value,ctx));let status="valid";for(const failure of struct.validator(value,ctx))failure.explanation=options.message,status="not_valid",yield[failure,void 0];for(let[k,v,s]of struct.entries(value,ctx)){const ts=run(v,s,{path:void 0===k?path:[...path,k],branch:void 0===k?branch:[...branch,v],coerce,mask,message:options.message});for(const t of ts)t[0]?(status=null!=t[0].refinement?"not_refined":"not_valid",yield[t[0],void 0]):coerce&&(v=t[1],void 0===k?value=v:value instanceof Map?value.set(k,v):value instanceof Set?value.add(v):isObject(value)&&(void 0!==v||k in value)&&(value[k]=v))}if("not_valid"!==status)for(const failure of struct.refiner(value,ctx))failure.explanation=options.message,status="not_refined",yield[failure,void 0];"valid"===status&&(yield[void 0,value])}class Struct{constructor(props){const{type,schema,validator,refiner,coercer=value=>value,entries=function*(){}}=props;this.type=type,this.schema=schema,this.entries=entries,this.coercer=coercer,this.validator=validator?(value,context)=>toFailures(validator(value,context),context,this,value):()=>[],this.refiner=refiner?(value,context)=>toFailures(refiner(value,context),context,this,value):()=>[]}assert(value,message){return assert(value,this,message)}create(value,message){return create(value,this,message)}is(value){return is(value,this)}mask(value,message){return function mask(value,struct,message){const result=validate(value,struct,{coerce:!0,mask:!0,message});if(result[0])throw result[0];return result[1]}(value,this,message)}validate(value,options={}){return validate(value,this,options)}}function assert(value,struct,message){const result=validate(value,struct,{message});if(result[0])throw result[0]}function create(value,struct,message){const result=validate(value,struct,{coerce:!0,message});if(result[0])throw result[0];return result[1]}function is(value,struct){return!validate(value,struct)[0]}function validate(value,struct,options={}){const tuples=run(value,struct,options),tuple=function shiftIterator(input){const{done,value}=input.next();return done?void 0:value}(tuples);if(tuple[0]){return[new StructError(tuple[0],function*(){for(const t of tuples)t[0]&&(yield t[0])}),void 0]}return[void 0,tuple[1]]}function dist_define(name,validator){return new Struct({type:name,schema:null,validator})}function array(Element){return new Struct({type:"array",schema:Element,*entries(value){if(Element&&Array.isArray(value))for(const[i,v]of value.entries())yield[i,v,Element]},coercer:value=>Array.isArray(value)?value.slice():value,validator:value=>Array.isArray(value)||`Expected an array value, but received: ${print(value)}`})}function dist_boolean(){return dist_define("boolean",value=>"boolean"==typeof value)}function instance(Class){return dist_define("instance",value=>value instanceof Class||`Expected a \`${Class.name}\` instance, but received: ${print(value)}`)}function literal(constant){const description=print(constant),t=typeof constant;return new Struct({type:"literal",schema:"string"===t||"number"===t||"boolean"===t?constant:null,validator:value=>value===constant||`Expected the literal \`${description}\`, but received: ${print(value)}`})}function never(){return dist_define("never",()=>!1)}function nullable(struct){return new Struct({...struct,validator:(value,ctx)=>null===value||struct.validator(value,ctx),refiner:(value,ctx)=>null===value||struct.refiner(value,ctx)})}function number(){return dist_define("number",value=>"number"==typeof value&&!isNaN(value)||`Expected a number, but received: ${print(value)}`)}function optional(struct){return new Struct({...struct,validator:(value,ctx)=>void 0===value||struct.validator(value,ctx),refiner:(value,ctx)=>void 0===value||struct.refiner(value,ctx)})}function record(Key,Value){return new Struct({type:"record",schema:null,*entries(value){if(isObject(value))for(const k in value){const v=value[k];yield[k,k,Key],yield[k,v,Value]}},validator:value=>isNonArrayObject(value)||`Expected an object, but received: ${print(value)}`,coercer:value=>isNonArrayObject(value)?{...value}:value})}function string(){return dist_define("string",value=>"string"==typeof value||`Expected a string, but received: ${print(value)}`)}function tuple(Structs){const Never=never();return new Struct({type:"tuple",schema:null,*entries(value){if(Array.isArray(value)){const length=Math.max(Structs.length,value.length);for(let i=0;iArray.isArray(value)||`Expected an array, but received: ${print(value)}`,coercer:value=>Array.isArray(value)?value.slice():value})}function type(schema){const keys=Object.keys(schema);return new Struct({type:"type",schema,*entries(value){if(isObject(value))for(const k of keys)yield[k,value[k],schema[k]]},validator:value=>isNonArrayObject(value)||`Expected an object, but received: ${print(value)}`,coercer:value=>isNonArrayObject(value)?{...value}:value})}function union(Structs){const description=Structs.map(s=>s.type).join(" | ");return new Struct({type:"union",schema:null,coercer(value,ctx){for(const S of Structs){const[error,coerced]=S.validate(value,{coerce:!0,mask:ctx.mask});if(!error)return coerced}return value},validator(value,ctx){const failures=[];for(const S of Structs){const[...tuples]=run(value,S,ctx),[first]=tuples;if(!first[0])return[];for(const[failure]of tuples)failure&&failures.push(failure)}return[`Expected the value to satisfy a union of \`${description}\`, but received: ${print(value)}`,...failures]}})}function unknown(){return dist_define("unknown",()=>!0)}function coerce(struct,condition,coercer){return new Struct({...struct,coercer:(value,ctx)=>is(value,condition)?struct.coercer(coercer(value,ctx),ctx):struct.coercer(value,ctx)})}var browser=__webpack_require__("./node_modules/jayson/lib/client/browser/index.js"),browser_default=__webpack_require__.n(browser),eventemitter3=__webpack_require__("./node_modules/eventemitter3/index.mjs"),WebSocketBrowserImpl=class extends eventemitter3.b{socket;constructor(address,options,protocols){super(),this.socket=new window.WebSocket(address,protocols),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=event=>this.emit("message",event.data),this.socket.onerror=error=>this.emit("error",error),this.socket.onclose=event=>{this.emit("close",event.code,event.reason)}}send(data,optionsOrCallback,callback){const cb=callback||optionsOrCallback;try{this.socket.send(data),cb()}catch(error){cb(error)}}close(code,reason){this.socket.close(code,reason)}addEventListener(type,listener,options){this.socket.addEventListener(type,listener,options)}};function WebSocket(address,options){return new WebSocketBrowserImpl(address,options)}var DefaultDataPack=class{encode(value){return JSON.stringify(value)}decode(value){return JSON.parse(value)}},CommonClient=class extends eventemitter3.b{address;rpc_id;queue;options;autoconnect;ready;reconnect;reconnect_timer_id;reconnect_interval;max_reconnects;rest_options;current_reconnects;generate_request_id;socket;webSocketFactory;dataPack;constructor(webSocketFactory,address="ws://localhost:8080",{autoconnect=!0,reconnect=!0,reconnect_interval=1e3,max_reconnects=5,...rest_options}={},generate_request_id,dataPack){super(),this.webSocketFactory=webSocketFactory,this.queue={},this.rpc_id=0,this.address=address,this.autoconnect=autoconnect,this.ready=!1,this.reconnect=reconnect,this.reconnect_timer_id=void 0,this.reconnect_interval=reconnect_interval,this.max_reconnects=max_reconnects,this.rest_options=rest_options,this.current_reconnects=0,this.generate_request_id=generate_request_id||(()=>"number"==typeof this.rpc_id?++this.rpc_id:Number(this.rpc_id)+1),this.dataPack=dataPack||new DefaultDataPack,this.autoconnect&&this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){this.socket||this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(method,params,timeout,ws_opts){return ws_opts||"object"!=typeof timeout||(ws_opts=timeout,timeout=null),new Promise((resolve,reject)=>{if(!this.ready)return reject(new Error("socket not ready"));const rpc_id=this.generate_request_id(method,params),message={jsonrpc:"2.0",method,params:params||void 0,id:rpc_id};this.socket.send(this.dataPack.encode(message),ws_opts,error=>{if(error)return reject(error);this.queue[rpc_id]={promise:[resolve,reject]},timeout&&(this.queue[rpc_id].timeout=setTimeout(()=>{delete this.queue[rpc_id],reject(new Error("reply timeout"))},timeout))})})}async login(params){const resp=await this.call("rpc.login",params);if(!resp)throw new Error("authentication failed");return resp}async listMethods(){return await this.call("__listMethods")}notify(method,params){return new Promise((resolve,reject)=>{if(!this.ready)return reject(new Error("socket not ready"));const message={jsonrpc:"2.0",method,params};this.socket.send(this.dataPack.encode(message),error=>{if(error)return reject(error);resolve()})})}async subscribe(event){"string"==typeof event&&(event=[event]);const result=await this.call("rpc.on",event);if("string"==typeof event&&"ok"!==result[event])throw new Error("Failed subscribing to an event '"+event+"' with: "+result[event]);return result}async unsubscribe(event){"string"==typeof event&&(event=[event]);const result=await this.call("rpc.off",event);if("string"==typeof event&&"ok"!==result[event])throw new Error("Failed unsubscribing from an event with: "+result);return result}close(code,data){this.socket.close(code||1e3,data)}setAutoReconnect(reconnect){this.reconnect=reconnect}setReconnectInterval(interval){this.reconnect_interval=interval}setMaxReconnects(max_reconnects){this.max_reconnects=max_reconnects}_connect(address,options){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(address,options),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:message})=>{message instanceof ArrayBuffer&&(message=node_modules_buffer.Buffer.from(message).toString());try{message=this.dataPack.decode(message)}catch(error){return}if(message.notification&&this.listeners(message.notification).length){if(!Object.keys(message.params).length)return this.emit(message.notification);const args=[message.notification];if(message.params.constructor===Object)args.push(message.params);else for(let i=0;i{this.emit.apply(this,args)})}if(!this.queue[message.id])return message.method?Promise.resolve().then(()=>{this.emit(message.method,message?.params)}):void 0;"error"in message=="result"in message&&this.queue[message.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[message.id].timeout&&clearTimeout(this.queue[message.id].timeout),message.error?this.queue[message.id].promise[1](message.error):this.queue[message.id].promise[0](message.result),delete this.queue[message.id]}),this.socket.addEventListener("error",error=>this.emit("error",error)),this.socket.addEventListener("close",({code,reason})=>{this.ready&&setTimeout(()=>this.emit("close",code,reason),0),this.ready=!1,this.socket=void 0,1e3!==code&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||0===this.max_reconnects)&&(this.reconnect_timer_id=setTimeout(()=>this._connect(address,options),this.reconnect_interval)))})}};const sha3_0n=BigInt(0),sha3_1n=BigInt(1),sha3_2n=BigInt(2),_7n=BigInt(7),_256n=BigInt(256),_0x71n=BigInt(113),SHA3_PI=[],SHA3_ROTL=[],_SHA3_IOTA=[];for(let round=0,R=sha3_1n,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5],SHA3_PI.push(2*(5*y+x)),SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=sha3_0n;for(let j=0;j<7;j++)R=(R<>_7n)*_0x71n)%_256n,R&sha3_2n&&(t^=sha3_1n<<(sha3_1n<s>32?rotlBH(h,l,s):rotlSH(h,l,s),rotlL=(h,l,s)=>s>32?rotlBL(h,l,s):rotlSL(h,l,s);class Keccak extends Hash{constructor(blockLen,suffix,outputLen,enableXOF=!1,rounds=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=blockLen,this.suffix=suffix,this.outputLen=outputLen,this.enableXOF=enableXOF,this.rounds=rounds,anumber(outputLen),!(0=blockLen&&this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos),this.posOut+=take,pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){return anumber(bytes),this.xofInto(new Uint8Array(bytes))}digestInto(out){if(aoutput(out,this),this.finished)throw new Error("digest() was already called");return this.writeInto(out),this.destroy(),out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,clean(this.state)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;return to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds)),to.state32.set(this.state32),to.pos=this.pos,to.posOut=this.posOut,to.finished=this.finished,to.rounds=rounds,to.suffix=suffix,to.outputLen=outputLen,to.enableXOF=enableXOF,to.destroyed=this.destroyed,to}}const gen=(suffix,blockLen,outputLen)=>utils_createHasher(()=>new Keccak(blockLen,suffix,outputLen)),keccak_256=(()=>gen(1,136,32))();class HMAC extends Hash{constructor(hash,_key){super(),this.finished=!1,this.destroyed=!1,function ahash(h){if("function"!=typeof h||"function"!=typeof h.create)throw new Error("Hash should be wrapped by utils.createHasher");anumber(h.outputLen),anumber(h.blockLen)}(hash);const key=toBytes(_key);if(this.iHash=hash.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const blockLen=this.blockLen,pad=new Uint8Array(blockLen);pad.set(key.length>blockLen?hash.create().update(key).digest():key);for(let i=0;inew HMAC(hash,key).update(message).digest();function validateSigVerOpts(opts){void 0!==opts.lowS&&abool("lowS",opts.lowS),void 0!==opts.prehash&&abool("prehash",opts.prehash)}hmac.create=(hash,key)=>new HMAC(hash,key);class DERErr extends Error{constructor(m=""){super(m)}}const DER={Err:DERErr,_tlv:{encode:(tag,data)=>{const{Err:E}=DER;if(tag<0||tag>256)throw new E("tlv.encode: wrong tag");if(1&data.length)throw new E("tlv.encode: unpadded data");const dataLen=data.length/2,len=numberToHexUnpadded(dataLen);if(len.length/2&128)throw new E("tlv.encode: long form length too big");const lenLen=dataLen>127?numberToHexUnpadded(len.length/2|128):"";return numberToHexUnpadded(tag)+lenLen+len+data},decode(tag,data){const{Err:E}=DER;let pos=0;if(tag<0||tag>256)throw new E("tlv.encode: wrong tag");if(data.length<2||data[pos++]!==tag)throw new E("tlv.decode: wrong tlv");const first=data[pos++];let length=0;if(!!(128&first)){const lenLen=127&first;if(!lenLen)throw new E("tlv.decode(long): indefinite length not supported");if(lenLen>4)throw new E("tlv.decode(long): byte length is too big");const lengthBytes=data.subarray(pos,pos+lenLen);if(lengthBytes.length!==lenLen)throw new E("tlv.decode: length bytes not complete");if(0===lengthBytes[0])throw new E("tlv.decode(long): zero leftmost byte");for(const b of lengthBytes)length=length<<8|b;if(pos+=lenLen,length<128)throw new E("tlv.decode(long): not minimal encoding")}else length=first;const v=data.subarray(pos,pos+length);if(v.length!==length)throw new E("tlv.decode: wrong value length");return{v,l:data.subarray(pos+length)}}},_int:{encode(num){const{Err:E}=DER;if(num{const{px:x,py:y,pz:z}=p;if(Fp.eql(z,Fp.ONE))return{x,y};const is0=p.is0();null==iz&&(iz=is0?Fp.ONE:Fp.inv(z));const ax=Fp.mul(x,iz),ay=Fp.mul(y,iz),zz=Fp.mul(z,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw new Error("invZ was invalid");return{x:ax,y:ay}}),assertValidMemo=memoized(p=>{if(p.is0()){if(curveOpts.allowInfinityPoint&&!Fp.is0(p.py))return;throw new Error("bad point: ZERO")}const{x,y}=p.toAffine();if(!Fp.isValid(x)||!Fp.isValid(y))throw new Error("bad point: x or y not field elements");if(!isValidXY(x,y))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function finishEndo(endoBeta,k1p,k2p,k1neg,k2neg){return k2p=new Point(Fp.mul(k2p.px,endoBeta),k2p.py,k2p.pz),k1p=negateCt(k1neg,k1p),k2p=negateCt(k2neg,k2p),k1p.add(k2p)}class Point{constructor(px,py,pz){this.px=acoord("x",px),this.py=acoord("y",py,!0),this.pz=acoord("z",pz),Object.freeze(this)}static fromAffine(p){const{x,y}=p||{};if(!p||!Fp.isValid(x)||!Fp.isValid(y))throw new Error("invalid affine point");if(p instanceof Point)throw new Error("projective point not allowed");return Fp.is0(x)&&Fp.is0(y)?Point.ZERO:new Point(x,y,Fp.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(points){return normalizeZ(Point,"pz",points)}static fromBytes(bytes){return utils_abytes(bytes),Point.fromHex(bytes)}static fromHex(hex){const P=Point.fromAffine(fromBytes(utils_ensureBytes("pointHex",hex)));return P.assertValidity(),P}static fromPrivateKey(privateKey){const normPrivateKeyToScalar=_legacyHelperNormPriv(Fn,curveOpts.allowedPrivateKeyLengths,curveOpts.wrapPrivateKey);return Point.BASE.multiply(normPrivateKeyToScalar(privateKey))}static msm(points,scalars){return curve_pippenger(Point,Fn,points,scalars)}precompute(windowSize=8,isLazy=!0){return wnaf.setWindowSize(this,windowSize),isLazy||this.multiply(weierstrass_3n),this}_setWindowSize(windowSize){this.precompute(windowSize)}assertValidity(){assertValidMemo(this)}hasEvenY(){const{y}=this.toAffine();if(!Fp.isOdd)throw new Error("Field doesn't support isOdd");return!Fp.isOdd(y)}equals(other){aprjpoint(other);const{px:X1,py:Y1,pz:Z1}=this,{px:X2,py:Y2,pz:Z2}=other,U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1)),U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point(this.px,Fp.neg(this.py),this.pz)}double(){const{a,b}=CURVE,b3=Fp.mul(b,weierstrass_3n),{px:X1,py:Y1,pz:Z1}=this;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO,t0=Fp.mul(X1,X1),t1=Fp.mul(Y1,Y1),t2=Fp.mul(Z1,Z1),t3=Fp.mul(X1,Y1);return t3=Fp.add(t3,t3),Z3=Fp.mul(X1,Z1),Z3=Fp.add(Z3,Z3),X3=Fp.mul(a,Z3),Y3=Fp.mul(b3,t2),Y3=Fp.add(X3,Y3),X3=Fp.sub(t1,Y3),Y3=Fp.add(t1,Y3),Y3=Fp.mul(X3,Y3),X3=Fp.mul(t3,X3),Z3=Fp.mul(b3,Z3),t2=Fp.mul(a,t2),t3=Fp.sub(t0,t2),t3=Fp.mul(a,t3),t3=Fp.add(t3,Z3),Z3=Fp.add(t0,t0),t0=Fp.add(Z3,t0),t0=Fp.add(t0,t2),t0=Fp.mul(t0,t3),Y3=Fp.add(Y3,t0),t2=Fp.mul(Y1,Z1),t2=Fp.add(t2,t2),t0=Fp.mul(t2,t3),X3=Fp.sub(X3,t0),Z3=Fp.mul(t2,t1),Z3=Fp.add(Z3,Z3),Z3=Fp.add(Z3,Z3),new Point(X3,Y3,Z3)}add(other){aprjpoint(other);const{px:X1,py:Y1,pz:Z1}=this,{px:X2,py:Y2,pz:Z2}=other;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;const a=CURVE.a,b3=Fp.mul(CURVE.b,weierstrass_3n);let t0=Fp.mul(X1,X2),t1=Fp.mul(Y1,Y2),t2=Fp.mul(Z1,Z2),t3=Fp.add(X1,Y1),t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4),t4=Fp.add(t0,t1),t3=Fp.sub(t3,t4),t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);return t4=Fp.mul(t4,t5),t5=Fp.add(t0,t2),t4=Fp.sub(t4,t5),t5=Fp.add(Y1,Z1),X3=Fp.add(Y2,Z2),t5=Fp.mul(t5,X3),X3=Fp.add(t1,t2),t5=Fp.sub(t5,X3),Z3=Fp.mul(a,t4),X3=Fp.mul(b3,t2),Z3=Fp.add(X3,Z3),X3=Fp.sub(t1,Z3),Z3=Fp.add(t1,Z3),Y3=Fp.mul(X3,Z3),t1=Fp.add(t0,t0),t1=Fp.add(t1,t0),t2=Fp.mul(a,t2),t4=Fp.mul(b3,t4),t1=Fp.add(t1,t2),t2=Fp.sub(t0,t2),t2=Fp.mul(a,t2),t4=Fp.add(t4,t2),t0=Fp.mul(t1,t4),Y3=Fp.add(Y3,t0),t0=Fp.mul(t5,t4),X3=Fp.mul(t3,X3),X3=Fp.sub(X3,t0),t0=Fp.mul(t3,t1),Z3=Fp.mul(t5,Z3),Z3=Fp.add(Z3,t0),new Point(X3,Y3,Z3)}subtract(other){return this.add(other.negate())}is0(){return this.equals(Point.ZERO)}multiply(scalar){const{endo}=curveOpts;if(!Fn.isValidNot0(scalar))throw new Error("invalid scalar: out of range");let point,fake;const mul=n=>wnaf.wNAFCached(this,n,Point.normalizeZ);if(endo){const{k1neg,k1,k2neg,k2}=endo.splitScalar(scalar),{p:k1p,f:k1f}=mul(k1),{p:k2p,f:k2f}=mul(k2);fake=k1f.add(k2f),point=finishEndo(endo.beta,k1p,k2p,k1neg,k2neg)}else{const{p,f}=mul(scalar);point=p,fake=f}return Point.normalizeZ([point,fake])[0]}multiplyUnsafe(sc){const{endo}=curveOpts,p=this;if(!Fn.isValid(sc))throw new Error("invalid scalar: out of range");if(sc===weierstrass_0n||p.is0())return Point.ZERO;if(sc===weierstrass_1n)return p;if(wnaf.hasPrecomputes(this))return this.multiply(sc);if(endo){const{k1neg,k1,k2neg,k2}=endo.splitScalar(sc),{p1,p2}=function mulEndoUnsafe(c,point,k1,k2){let acc=point,p1=c.ZERO,p2=c.ZERO;for(;k1>curve_0n||k2>curve_0n;)k1&curve_1n&&(p1=p1.add(acc)),k2&curve_1n&&(p2=p2.add(acc)),acc=acc.double(),k1>>=curve_1n,k2>>=curve_1n;return{p1,p2}}(Point,p,k1,k2);return finishEndo(endo.beta,p1,p2,k1neg,k2neg)}return wnaf.wNAFCachedUnsafe(p,sc)}multiplyAndAddUnsafe(Q,a,b){const sum=this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));return sum.is0()?void 0:sum}toAffine(invertedZ){return toAffineMemo(this,invertedZ)}isTorsionFree(){const{isTorsionFree}=curveOpts;return cofactor===weierstrass_1n||(isTorsionFree?isTorsionFree(Point,this):wnaf.wNAFCachedUnsafe(this,CURVE_ORDER).is0())}clearCofactor(){const{clearCofactor}=curveOpts;return cofactor===weierstrass_1n?this:clearCofactor?clearCofactor(Point,this):this.multiplyUnsafe(cofactor)}toBytes(isCompressed=!0){return abool("isCompressed",isCompressed),this.assertValidity(),toBytes(Point,this,isCompressed)}toRawBytes(isCompressed=!0){return this.toBytes(isCompressed)}toHex(isCompressed=!0){return utils_bytesToHex(this.toBytes(isCompressed))}toString(){return``}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy,Fp.ONE),Point.ZERO=new Point(Fp.ZERO,Fp.ONE,Fp.ZERO),Point.Fp=Fp,Point.Fn=Fn;const bits=Fn.BITS,wnaf=wNAF(Point,curveOpts.endo?Math.ceil(bits/2):bits);return Point}function pprefix(hasEvenY){return Uint8Array.of(hasEvenY?2:3)}function ecdsa(Point,ecdsaOpts,curveOpts={}){_validateObject(ecdsaOpts,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const randomBytes_=ecdsaOpts.randomBytes||utils_randomBytes,hmac_=ecdsaOpts.hmac||((key,...msgs)=>hmac(ecdsaOpts.hash,key,utils_concatBytes(...msgs))),{Fp,Fn}=Point,{ORDER:CURVE_ORDER,BITS:fnBits}=Fn;function isBiggerThanHalfOrder(number){return number>CURVE_ORDER>>weierstrass_1n}function aValidRS(title,num){if(!Fn.isValidNot0(num))throw new Error(`invalid signature ${title}: out of range 1..CURVE.n`)}class Signature{constructor(r,s,recovery){aValidRS("r",r),aValidRS("s",s),this.r=r,this.s=s,null!=recovery&&(this.recovery=recovery),Object.freeze(this)}static fromCompact(hex){const L=Fn.BYTES,b=utils_ensureBytes("compactSignature",hex,2*L);return new Signature(Fn.fromBytes(b.subarray(0,L)),Fn.fromBytes(b.subarray(L,2*L)))}static fromDER(hex){const{r,s}=DER.toSig(utils_ensureBytes("DER",hex));return new Signature(r,s)}assertValidity(){}addRecoveryBit(recovery){return new Signature(this.r,this.s,recovery)}recoverPublicKey(msgHash){const FIELD_ORDER=Fp.ORDER,{r,s,recovery:rec}=this;if(null==rec||![0,1,2,3].includes(rec))throw new Error("recovery id invalid");if(CURVE_ORDER*weierstrass_2n1)throw new Error("recovery id is ambiguous for h>1 curve");const radj=2===rec||3===rec?r+CURVE_ORDER:r;if(!Fp.isValid(radj))throw new Error("recovery id 2 or 3 invalid");const x=Fp.toBytes(radj),R=Point.fromHex(utils_concatBytes(pprefix(!(1&rec)),x)),ir=Fn.inv(radj),h=bits2int_modN(utils_ensureBytes("msgHash",msgHash)),u1=Fn.create(-h*ir),u2=Fn.create(s*ir),Q=Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));if(Q.is0())throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return isBiggerThanHalfOrder(this.s)}normalizeS(){return this.hasHighS()?new Signature(this.r,Fn.neg(this.s),this.recovery):this}toBytes(format){if("compact"===format)return utils_concatBytes(Fn.toBytes(this.r),Fn.toBytes(this.s));if("der"===format)return hexToBytes(DER.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return utils_bytesToHex(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return utils_bytesToHex(this.toBytes("compact"))}}const normPrivateKeyToScalar=_legacyHelperNormPriv(Fn,curveOpts.allowedPrivateKeyLengths,curveOpts.wrapPrivateKey),utils={isValidPrivateKey(privateKey){try{return normPrivateKeyToScalar(privateKey),!0}catch(error){return!1}},normPrivateKeyToScalar,randomPrivateKey:()=>{const n=CURVE_ORDER;return function mapHashToField(key,fieldOrder,isLE=!1){const len=key.length,fieldLen=getFieldBytesLength(fieldOrder),minLen=getMinHashLength(fieldOrder);if(len<16||len1024)throw new Error("expected "+minLen+"-1024 bytes of input, got "+len);const reduced=modular_mod(isLE?utils_bytesToNumberLE(key):utils_bytesToNumberBE(key),fieldOrder-modular_1n)+modular_1n;return isLE?utils_numberToBytesLE(reduced,fieldLen):utils_numberToBytesBE(reduced,fieldLen)}(randomBytes_(getMinHashLength(n)),n)},precompute:(windowSize=8,point=Point.BASE)=>point.precompute(windowSize,!1)};function isProbPub(item){if("bigint"==typeof item)return!1;if(item instanceof Point)return!0;const length=utils_ensureBytes("key",item).length,L=Fp.BYTES,LC=L+1,LU=2*L+1;return curveOpts.allowedPrivateKeyLengths||Fn.BYTES===LC?void 0:length===LC||length===LU}const bits2int=ecdsaOpts.bits2int||function(bytes){if(bytes.length>8192)throw new Error("input is too large");const num=utils_bytesToNumberBE(bytes),delta=8*bytes.length-fnBits;return delta>0?num>>BigInt(delta):num},bits2int_modN=ecdsaOpts.bits2int_modN||function(bytes){return Fn.create(bits2int(bytes))},ORDER_MASK=utils_bitMask(fnBits);function int2octets(num){return utils_aInRange("num < 2^"+fnBits,num,weierstrass_0n,ORDER_MASK),Fn.toBytes(num)}function prepSig(msgHash,privateKey,opts=defaultSigOpts){if(["recovered","canonical"].some(k=>k in opts))throw new Error("sign() legacy options not supported");const{hash}=ecdsaOpts;let{lowS,prehash,extraEntropy:ent}=opts;null==lowS&&(lowS=!0),msgHash=utils_ensureBytes("msgHash",msgHash),validateSigVerOpts(opts),prehash&&(msgHash=utils_ensureBytes("prehashed msgHash",hash(msgHash)));const h1int=bits2int_modN(msgHash),d=normPrivateKeyToScalar(privateKey),seedArgs=[int2octets(d),int2octets(h1int)];if(null!=ent&&!1!==ent){const e=!0===ent?randomBytes_(Fp.BYTES):ent;seedArgs.push(utils_ensureBytes("extraEntropy",e))}const seed=utils_concatBytes(...seedArgs),m=h1int;return{seed,k2sig:function k2sig(kBytes){const k=bits2int(kBytes);if(!Fn.isValidNot0(k))return;const ik=Fn.inv(k),q=Point.BASE.multiply(k).toAffine(),r=Fn.create(q.x);if(r===weierstrass_0n)return;const s=Fn.create(ik*Fn.create(m+r*d));if(s===weierstrass_0n)return;let recovery=(q.x===r?0:2)|Number(q.y&weierstrass_1n),normS=s;return lowS&&isBiggerThanHalfOrder(s)&&(normS=function normalizeS(s){return isBiggerThanHalfOrder(s)?Fn.neg(s):s}(s),recovery^=1),new Signature(r,normS,recovery)}}}const defaultSigOpts={lowS:ecdsaOpts.lowS,prehash:!1},defaultVerOpts={lowS:ecdsaOpts.lowS,prehash:!1};return Point.BASE.precompute(8),Object.freeze({getPublicKey:function getPublicKey(privateKey,isCompressed=!0){return Point.fromPrivateKey(privateKey).toBytes(isCompressed)},getSharedSecret:function getSharedSecret(privateA,publicB,isCompressed=!0){if(!0===isProbPub(privateA))throw new Error("first arg must be private key");if(!1===isProbPub(publicB))throw new Error("second arg must be public key");return Point.fromHex(publicB).multiply(normPrivateKeyToScalar(privateA)).toBytes(isCompressed)},sign:function sign(msgHash,privKey,opts=defaultSigOpts){const{seed,k2sig}=prepSig(msgHash,privKey,opts),drbg=function createHmacDrbg(hashLen,qByteLen,hmacFn){if("number"!=typeof hashLen||hashLen<2)throw new Error("hashLen must be a number");if("number"!=typeof qByteLen||qByteLen<2)throw new Error("qByteLen must be a number");if("function"!=typeof hmacFn)throw new Error("hmacFn must be a function");const u8n=len=>new Uint8Array(len),u8of=byte=>Uint8Array.of(byte);let v=u8n(hashLen),k=u8n(hashLen),i=0;const reset=()=>{v.fill(1),k.fill(0),i=0},h=(...b)=>hmacFn(k,v,...b),reseed=(seed=u8n(0))=>{k=h(u8of(0),seed),v=h(),0!==seed.length&&(k=h(u8of(1),seed),v=h())},gen=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let len=0;const out=[];for(;len{let res;for(reset(),reseed(seed);!(res=pred(gen()));)reseed();return reset(),res}}(ecdsaOpts.hash.outputLen,Fn.BYTES,hmac_);return drbg(seed,k2sig)},verify:function verify(signature,msgHash,publicKey,opts=defaultVerOpts){const sg=signature;msgHash=utils_ensureBytes("msgHash",msgHash),publicKey=utils_ensureBytes("publicKey",publicKey),validateSigVerOpts(opts);const{lowS,prehash,format}=opts;if("strict"in opts)throw new Error("options.strict was renamed to lowS");if(void 0!==format&&!["compact","der","js"].includes(format))throw new Error('format must be "compact", "der" or "js"');const isHex="string"==typeof sg||isBytes(sg),isObj=!isHex&&!format&&"object"==typeof sg&&null!==sg&&"bigint"==typeof sg.r&&"bigint"==typeof sg.s;if(!isHex&&!isObj)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let _sig,P;try{if(isObj){if(void 0!==format&&"js"!==format)throw new Error("invalid format");_sig=new Signature(sg.r,sg.s)}if(isHex){try{"compact"!==format&&(_sig=Signature.fromDER(sg))}catch(derError){if(!(derError instanceof DER.Err))throw derError}_sig||"der"===format||(_sig=Signature.fromCompact(sg))}P=Point.fromHex(publicKey)}catch(error){return!1}if(!_sig)return!1;if(lowS&&_sig.hasHighS())return!1;prehash&&(msgHash=ecdsaOpts.hash(msgHash));const{r,s}=_sig,h=bits2int_modN(msgHash),is=Fn.inv(s),u1=Fn.create(h*is),u2=Fn.create(r*is),R=Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));return!R.is0()&&Fn.create(R.x)===r},utils,Point,Signature})}function _weierstrass_legacy_opts_to_new(c){const CURVE={a:c.a,b:c.b,p:c.Fp.ORDER,n:c.n,h:c.h,Gx:c.Gx,Gy:c.Gy};return{CURVE,curveOpts:{Fp:c.Fp,Fn:modular_Field(CURVE.n,c.nBitLength),allowedPrivateKeyLengths:c.allowedPrivateKeyLengths,allowInfinityPoint:c.allowInfinityPoint,endo:c.endo,wrapPrivateKey:c.wrapPrivateKey,isTorsionFree:c.isTorsionFree,clearCofactor:c.clearCofactor,fromBytes:c.fromBytes,toBytes:c.toBytes}}}function weierstrass(c){const{CURVE,curveOpts,ecdsaOpts}=function _ecdsa_legacy_opts_to_new(c){const{CURVE,curveOpts}=_weierstrass_legacy_opts_to_new(c);return{CURVE,curveOpts,ecdsaOpts:{hash:c.hash,hmac:c.hmac,randomBytes:c.randomBytes,lowS:c.lowS,bits2int:c.bits2int,bits2int_modN:c.bits2int_modN}}}(c);return function _ecdsa_new_output_to_legacy(c,ecdsa){return Object.assign({},ecdsa,{ProjectivePoint:ecdsa.Point,CURVE:c})}(c,ecdsa(weierstrassN(CURVE,curveOpts),ecdsaOpts,curveOpts))}const secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},secp256k1_1n=(BigInt(0),BigInt(1)),secp256k1_2n=BigInt(2),divNearest=(a,b)=>(a+b/secp256k1_2n)/b;function sqrtMod(y){const P=secp256k1_CURVE.p,_3n=BigInt(3),_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22),_23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88),b2=y*y*y%P,b3=b2*b2*y%P,b6=modular_pow2(b3,_3n,P)*b3%P,b9=modular_pow2(b6,_3n,P)*b3%P,b11=modular_pow2(b9,secp256k1_2n,P)*b2%P,b22=modular_pow2(b11,_11n,P)*b11%P,b44=modular_pow2(b22,_22n,P)*b22%P,b88=modular_pow2(b44,_44n,P)*b44%P,b176=modular_pow2(b88,_88n,P)*b88%P,b220=modular_pow2(b176,_44n,P)*b44%P,b223=modular_pow2(b220,_3n,P)*b3%P,t1=modular_pow2(b223,_23n,P)*b22%P,t2=modular_pow2(t1,_6n,P)*b2%P,root=modular_pow2(t2,secp256k1_2n,P);if(!Fpk1.eql(Fpk1.sqr(root),y))throw new Error("Cannot find square root");return root}const Fpk1=modular_Field(secp256k1_CURVE.p,void 0,void 0,{sqrt:sqrtMod}),secp256k1=function createCurve(curveDef,defHash){const create=hash=>weierstrass({...curveDef,hash});return{...create(defHash),create}}({...secp256k1_CURVE,Fp:Fpk1,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:k=>{const n=secp256k1_CURVE.n,a1=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),b1=-secp256k1_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),a2=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),b2=a1,POW_2_128=BigInt("0x100000000000000000000000000000000"),c1=divNearest(b2*k,n),c2=divNearest(-b1*k,n);let k1=modular_mod(k-c1*a1-c2*a2,n),k2=modular_mod(-c1*b1-c2*b2,n);const k1neg=k1>POW_2_128,k2neg=k2>POW_2_128;if(k1neg&&(k1=n-k1),k2neg&&(k2=n-k2),k1>POW_2_128||k2>POW_2_128)throw new Error("splitScalar: Endomorphism failed, k="+k);return{k1neg,k1,k2neg,k2}}}},sha2_sha256);const generatePrivateKey=ed25519.utils.randomPrivateKey,generateKeypair=()=>{const privateScalar=ed25519.utils.randomPrivateKey(),publicKey=getPublicKey(privateScalar),secretKey=new Uint8Array(64);return secretKey.set(privateScalar),secretKey.set(publicKey,32),{publicKey,secretKey}},getPublicKey=ed25519.getPublicKey;function isOnCurve(publicKey){try{return ed25519.ExtendedPoint.fromHex(publicKey),!0}catch{return!1}}const sign=(message,secretKey)=>ed25519.sign(message,secretKey.slice(0,32)),verify=ed25519.verify,toBuffer=arr=>node_modules_buffer.Buffer.isBuffer(arr)?arr:arr instanceof Uint8Array?node_modules_buffer.Buffer.from(arr.buffer,arr.byteOffset,arr.byteLength):node_modules_buffer.Buffer.from(arr);class index_browser_esm_Struct{constructor(properties){Object.assign(this,properties)}encode(){return node_modules_buffer.Buffer.from((0,lib.serialize)(SOLANA_SCHEMA,this))}static decode(data){return(0,lib.deserialize)(SOLANA_SCHEMA,this,data)}static decodeUnchecked(data){return(0,lib.deserializeUnchecked)(SOLANA_SCHEMA,this,data)}}class Enum extends index_browser_esm_Struct{constructor(properties){if(super(properties),this.enum="",1!==Object.keys(properties).length)throw new Error("Enum can only take single value");Object.keys(properties).map(key=>{this.enum=key})}}const SOLANA_SCHEMA=new Map;var _PublicKey;const MAX_SEED_LENGTH=32,PUBLIC_KEY_LENGTH=32;let uniquePublicKeyCounter=1;class PublicKey extends index_browser_esm_Struct{constructor(value){if(super({}),this._bn=void 0,function isPublicKeyData(value){return void 0!==value._bn}(value))this._bn=value._bn;else{if("string"==typeof value){const decoded=bs58_default().decode(value);if(decoded.length!=PUBLIC_KEY_LENGTH)throw new Error("Invalid public key input");this._bn=new(bn_default())(decoded)}else this._bn=new(bn_default())(value);if(this._bn.byteLength()>PUBLIC_KEY_LENGTH)throw new Error("Invalid public key input")}}static unique(){const key=new PublicKey(uniquePublicKeyCounter);return uniquePublicKeyCounter+=1,new PublicKey(key.toBuffer())}equals(publicKey){return this._bn.eq(publicKey._bn)}toBase58(){return bs58_default().encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const buf=this.toBuffer();return new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength)}toBuffer(){const b=this._bn.toArrayLike(node_modules_buffer.Buffer);if(b.length===PUBLIC_KEY_LENGTH)return b;const zeroPad=node_modules_buffer.Buffer.alloc(32);return b.copy(zeroPad,32-b.length),zeroPad}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(fromPublicKey,seed,programId){const buffer=node_modules_buffer.Buffer.concat([fromPublicKey.toBuffer(),node_modules_buffer.Buffer.from(seed),programId.toBuffer()]),publicKeyBytes=sha256_sha256(buffer);return new PublicKey(publicKeyBytes)}static createProgramAddressSync(seeds,programId){let buffer=node_modules_buffer.Buffer.alloc(0);seeds.forEach(function(seed){if(seed.length>MAX_SEED_LENGTH)throw new TypeError("Max seed length exceeded");buffer=node_modules_buffer.Buffer.concat([buffer,toBuffer(seed)])}),buffer=node_modules_buffer.Buffer.concat([buffer,programId.toBuffer(),node_modules_buffer.Buffer.from("ProgramDerivedAddress")]);const publicKeyBytes=sha256_sha256(buffer);if(isOnCurve(publicKeyBytes))throw new Error("Invalid seeds, address must fall off the curve");return new PublicKey(publicKeyBytes)}static async createProgramAddress(seeds,programId){return this.createProgramAddressSync(seeds,programId)}static findProgramAddressSync(seeds,programId){let address,nonce=255;for(;0!=nonce;){try{const seedsWithNonce=seeds.concat(node_modules_buffer.Buffer.from([nonce]));address=this.createProgramAddressSync(seedsWithNonce,programId)}catch(err){if(err instanceof TypeError)throw err;nonce--;continue}return[address,nonce]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(seeds,programId){return this.findProgramAddressSync(seeds,programId)}static isOnCurve(pubkeyData){return isOnCurve(new PublicKey(pubkeyData).toBytes())}}_PublicKey=PublicKey,PublicKey.default=new _PublicKey("11111111111111111111111111111111"),SOLANA_SCHEMA.set(PublicKey,{kind:"struct",fields:[["_bn","u256"]]});class Account{constructor(secretKey){if(this._publicKey=void 0,this._secretKey=void 0,secretKey){const secretKeyBuffer=toBuffer(secretKey);if(64!==secretKey.length)throw new Error("bad secret key size");this._publicKey=secretKeyBuffer.slice(32,64),this._secretKey=secretKeyBuffer.slice(0,32)}else this._secretKey=toBuffer(generatePrivateKey()),this._publicKey=toBuffer(getPublicKey(this._secretKey))}get publicKey(){return new PublicKey(this._publicKey)}get secretKey(){return node_modules_buffer.Buffer.concat([this._secretKey,this._publicKey],64)}}const BPF_LOADER_DEPRECATED_PROGRAM_ID=new PublicKey("BPFLoader1111111111111111111111111111111111"),PACKET_DATA_SIZE=1232,VERSION_PREFIX_MASK=127,SIGNATURE_LENGTH_IN_BYTES=64;class TransactionExpiredBlockheightExceededError extends Error{constructor(signature){super(`Signature ${signature} has expired: block height exceeded.`),this.signature=void 0,this.signature=signature}}Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class TransactionExpiredTimeoutError extends Error{constructor(signature,timeoutSeconds){super(`Transaction was not confirmed in ${timeoutSeconds.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=signature}}Object.defineProperty(TransactionExpiredTimeoutError.prototype,"name",{value:"TransactionExpiredTimeoutError"});class TransactionExpiredNonceInvalidError extends Error{constructor(signature){super(`Signature ${signature} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=signature}}Object.defineProperty(TransactionExpiredNonceInvalidError.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class MessageAccountKeys{constructor(staticAccountKeys,accountKeysFromLookups){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=staticAccountKeys,this.accountKeysFromLookups=accountKeysFromLookups}keySegments(){const keySegments=[this.staticAccountKeys];return this.accountKeysFromLookups&&(keySegments.push(this.accountKeysFromLookups.writable),keySegments.push(this.accountKeysFromLookups.readonly)),keySegments}get(index){for(const keySegment of this.keySegments()){if(index256)throw new Error("Account index overflow encountered during compilation");const keyIndexMap=new Map;this.keySegments().flat().forEach((key,index)=>{keyIndexMap.set(key.toBase58(),index)});const findKeyIndex=key=>{const keyIndex=keyIndexMap.get(key.toBase58());if(void 0===keyIndex)throw new Error("Encountered an unknown instruction account key during compilation");return keyIndex};return instructions.map(instruction=>({programIdIndex:findKeyIndex(instruction.programId),accountKeyIndexes:instruction.keys.map(meta=>findKeyIndex(meta.pubkey)),data:instruction.data}))}}const publicKey=(property="publicKey")=>Layout.av(32,property),signature=(property="signature")=>Layout.av(64,property),rustString=(property="string")=>{const rsl=Layout.w3([Layout.DH("length"),Layout.DH("lengthPadding"),Layout.av(Layout.cY(Layout.DH(),-8),"chars")],property),_decode=rsl.decode.bind(rsl),_encode=rsl.encode.bind(rsl),rslShim=rsl;return rslShim.decode=(b,offset)=>_decode(b,offset).chars.toString(),rslShim.encode=(str,b,offset)=>{const data={chars:node_modules_buffer.Buffer.from(str,"utf8")};return _encode(data,b,offset)},rslShim.alloc=str=>Layout.DH().span+Layout.DH().span+node_modules_buffer.Buffer.from(str,"utf8").length,rslShim};function getAlloc(type,fields){const getItemAlloc=item=>{if(item.span>=0)return item.span;if("function"==typeof item.alloc)return item.alloc(fields[item.property]);if("count"in item&&"elementLayout"in item){const field=fields[item.property];if(Array.isArray(field))return field.length*getItemAlloc(item.elementLayout)}else if("fields"in item)return getAlloc({layout:item},fields[item.property]);return 0};let alloc=0;return type.layout.fields.forEach(item=>{alloc+=getItemAlloc(item)}),alloc}function decodeLength(bytes){let len=0,size=0;for(;;){let elem=bytes.shift();if(len|=(127&elem)<<7*size,size+=1,!(128&elem))break}return len}function encodeLength(bytes,len){let rem_len=len;for(;;){let elem=127&rem_len;if(rem_len>>=7,0==rem_len){bytes.push(elem);break}elem|=128,bytes.push(elem)}}function index_browser_esm_assert(condition,message){if(!condition)throw new Error(message||"Assertion failed")}class CompiledKeys{constructor(payer,keyMetaMap){this.payer=void 0,this.keyMetaMap=void 0,this.payer=payer,this.keyMetaMap=keyMetaMap}static compile(instructions,payer){const keyMetaMap=new Map,getOrInsertDefault=pubkey=>{const address=pubkey.toBase58();let keyMeta=keyMetaMap.get(address);return void 0===keyMeta&&(keyMeta={isSigner:!1,isWritable:!1,isInvoked:!1},keyMetaMap.set(address,keyMeta)),keyMeta},payerKeyMeta=getOrInsertDefault(payer);payerKeyMeta.isSigner=!0,payerKeyMeta.isWritable=!0;for(const ix of instructions){getOrInsertDefault(ix.programId).isInvoked=!0;for(const accountMeta of ix.keys){const keyMeta=getOrInsertDefault(accountMeta.pubkey);keyMeta.isSigner||=accountMeta.isSigner,keyMeta.isWritable||=accountMeta.isWritable}}return new CompiledKeys(payer,keyMetaMap)}getMessageComponents(){const mapEntries=[...this.keyMetaMap.entries()];index_browser_esm_assert(mapEntries.length<=256,"Max static account keys length exceeded");const writableSigners=mapEntries.filter(([,meta])=>meta.isSigner&&meta.isWritable),readonlySigners=mapEntries.filter(([,meta])=>meta.isSigner&&!meta.isWritable),writableNonSigners=mapEntries.filter(([,meta])=>!meta.isSigner&&meta.isWritable),readonlyNonSigners=mapEntries.filter(([,meta])=>!meta.isSigner&&!meta.isWritable),header={numRequiredSignatures:writableSigners.length+readonlySigners.length,numReadonlySignedAccounts:readonlySigners.length,numReadonlyUnsignedAccounts:readonlyNonSigners.length};{index_browser_esm_assert(writableSigners.length>0,"Expected at least one writable signer key");const[payerAddress]=writableSigners[0];index_browser_esm_assert(payerAddress===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[header,[...writableSigners.map(([address])=>new PublicKey(address)),...readonlySigners.map(([address])=>new PublicKey(address)),...writableNonSigners.map(([address])=>new PublicKey(address)),...readonlyNonSigners.map(([address])=>new PublicKey(address))]]}extractTableLookup(lookupTable){const[writableIndexes,drainedWritableKeys]=this.drainKeysFoundInLookupTable(lookupTable.state.addresses,keyMeta=>!keyMeta.isSigner&&!keyMeta.isInvoked&&keyMeta.isWritable),[readonlyIndexes,drainedReadonlyKeys]=this.drainKeysFoundInLookupTable(lookupTable.state.addresses,keyMeta=>!keyMeta.isSigner&&!keyMeta.isInvoked&&!keyMeta.isWritable);if(0!==writableIndexes.length||0!==readonlyIndexes.length)return[{accountKey:lookupTable.key,writableIndexes,readonlyIndexes},{writable:drainedWritableKeys,readonly:drainedReadonlyKeys}]}drainKeysFoundInLookupTable(lookupTableEntries,keyMetaFilter){const lookupTableIndexes=new Array,drainedKeys=new Array;for(const[address,keyMeta]of this.keyMetaMap.entries())if(keyMetaFilter(keyMeta)){const key=new PublicKey(address),lookupTableIndex=lookupTableEntries.findIndex(entry=>entry.equals(key));lookupTableIndex>=0&&(index_browser_esm_assert(lookupTableIndex<256,"Max lookup table index exceeded"),lookupTableIndexes.push(lookupTableIndex),drainedKeys.push(key),this.keyMetaMap.delete(address))}return[lookupTableIndexes,drainedKeys]}}function guardedShift(byteArray){if(0===byteArray.length)throw new Error("Reached end of buffer unexpectedly");return byteArray.shift()}function guardedSplice(byteArray,...args){const[start]=args;if(2===args.length?start+(args[1]??0)>byteArray.length:start>=byteArray.length)throw new Error("Reached end of buffer unexpectedly");return byteArray.splice(...args)}class Message{constructor(args){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=args.header,this.accountKeys=args.accountKeys.map(account=>new PublicKey(account)),this.recentBlockhash=args.recentBlockhash,this.instructions=args.instructions,this.instructions.forEach(ix=>this.indexToProgramIds.set(ix.programIdIndex,this.accountKeys[ix.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(ix=>({programIdIndex:ix.programIdIndex,accountKeyIndexes:ix.accounts,data:bs58_default().decode(ix.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new MessageAccountKeys(this.staticAccountKeys)}static compile(args){const compiledKeys=CompiledKeys.compile(args.instructions,args.payerKey),[header,staticAccountKeys]=compiledKeys.getMessageComponents(),instructions=new MessageAccountKeys(staticAccountKeys).compileInstructions(args.instructions).map(ix=>({programIdIndex:ix.programIdIndex,accounts:ix.accountKeyIndexes,data:bs58_default().encode(ix.data)}));return new Message({header,accountKeys:staticAccountKeys,recentBlockhash:args.recentBlockhash,instructions})}isAccountSigner(index){return index=this.header.numRequiredSignatures){return index-numSignedAccounts!this.isProgramId(index))}serialize(){const numKeys=this.accountKeys.length;let keyCount=[];encodeLength(keyCount,numKeys);const instructions=this.instructions.map(instruction=>{const{accounts,programIdIndex}=instruction,data=Array.from(bs58_default().decode(instruction.data));let keyIndicesCount=[];encodeLength(keyIndicesCount,accounts.length);let dataCount=[];return encodeLength(dataCount,data.length),{programIdIndex,keyIndicesCount:node_modules_buffer.Buffer.from(keyIndicesCount),keyIndices:accounts,dataLength:node_modules_buffer.Buffer.from(dataCount),data}});let instructionCount=[];encodeLength(instructionCount,instructions.length);let instructionBuffer=node_modules_buffer.Buffer.alloc(PACKET_DATA_SIZE);node_modules_buffer.Buffer.from(instructionCount).copy(instructionBuffer);let instructionBufferLength=instructionCount.length;instructions.forEach(instruction=>{const length=Layout.w3([Layout.u8("programIdIndex"),Layout.av(instruction.keyIndicesCount.length,"keyIndicesCount"),Layout.O6(Layout.u8("keyIndex"),instruction.keyIndices.length,"keyIndices"),Layout.av(instruction.dataLength.length,"dataLength"),Layout.O6(Layout.u8("userdatum"),instruction.data.length,"data")]).encode(instruction,instructionBuffer,instructionBufferLength);instructionBufferLength+=length}),instructionBuffer=instructionBuffer.slice(0,instructionBufferLength);const signDataLayout=Layout.w3([Layout.av(1,"numRequiredSignatures"),Layout.av(1,"numReadonlySignedAccounts"),Layout.av(1,"numReadonlyUnsignedAccounts"),Layout.av(keyCount.length,"keyCount"),Layout.O6(publicKey("key"),numKeys,"keys"),publicKey("recentBlockhash")]),transaction={numRequiredSignatures:node_modules_buffer.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:node_modules_buffer.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:node_modules_buffer.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:node_modules_buffer.Buffer.from(keyCount),keys:this.accountKeys.map(key=>toBuffer(key.toBytes())),recentBlockhash:bs58_default().decode(this.recentBlockhash)};let signData=node_modules_buffer.Buffer.alloc(2048);const length=signDataLayout.encode(transaction,signData);return instructionBuffer.copy(signData,length),signData.slice(0,length+instructionBuffer.length)}static from(buffer){let byteArray=[...buffer];const numRequiredSignatures=guardedShift(byteArray);if(numRequiredSignatures!==(numRequiredSignatures&VERSION_PREFIX_MASK))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const numReadonlySignedAccounts=guardedShift(byteArray),numReadonlyUnsignedAccounts=guardedShift(byteArray),accountCount=decodeLength(byteArray);let accountKeys=[];for(let i=0;i0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new MessageAccountKeys(this.staticAccountKeys,accountKeysFromLookups)}isAccountSigner(index){return index=numStaticAccountKeys){return index-numStaticAccountKeyscount+lookup.writableIndexes.length,0)}if(index>=this.header.numRequiredSignatures){return index-numSignedAccountsaccount.key.equals(tableLookup.accountKey));if(!tableAccount)throw new Error(`Failed to find address lookup table account for table key ${tableLookup.accountKey.toBase58()}`);for(const index of tableLookup.writableIndexes){if(!(indexkey.toBytes()),recentBlockhash:bs58_default().decode(this.recentBlockhash),instructionsLength:new Uint8Array(encodedInstructionsLength),serializedInstructions,addressTableLookupsLength:new Uint8Array(encodedAddressTableLookupsLength),serializedAddressTableLookups},serializedMessage);return serializedMessage.slice(0,serializedMessageLength)}serializeInstructions(){let serializedLength=0;const serializedInstructions=new Uint8Array(PACKET_DATA_SIZE);for(const instruction of this.compiledInstructions){const encodedAccountKeyIndexesLength=Array();encodeLength(encodedAccountKeyIndexesLength,instruction.accountKeyIndexes.length);const encodedDataLength=Array();encodeLength(encodedDataLength,instruction.data.length);serializedLength+=Layout.w3([Layout.u8("programIdIndex"),Layout.av(encodedAccountKeyIndexesLength.length,"encodedAccountKeyIndexesLength"),Layout.O6(Layout.u8(),instruction.accountKeyIndexes.length,"accountKeyIndexes"),Layout.av(encodedDataLength.length,"encodedDataLength"),Layout.av(instruction.data.length,"data")]).encode({programIdIndex:instruction.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(encodedAccountKeyIndexesLength),accountKeyIndexes:instruction.accountKeyIndexes,encodedDataLength:new Uint8Array(encodedDataLength),data:instruction.data},serializedInstructions,serializedLength)}return serializedInstructions.slice(0,serializedLength)}serializeAddressTableLookups(){let serializedLength=0;const serializedAddressTableLookups=new Uint8Array(PACKET_DATA_SIZE);for(const lookup of this.addressTableLookups){const encodedWritableIndexesLength=Array();encodeLength(encodedWritableIndexesLength,lookup.writableIndexes.length);const encodedReadonlyIndexesLength=Array();encodeLength(encodedReadonlyIndexesLength,lookup.readonlyIndexes.length);serializedLength+=Layout.w3([publicKey("accountKey"),Layout.av(encodedWritableIndexesLength.length,"encodedWritableIndexesLength"),Layout.O6(Layout.u8(),lookup.writableIndexes.length,"writableIndexes"),Layout.av(encodedReadonlyIndexesLength.length,"encodedReadonlyIndexesLength"),Layout.O6(Layout.u8(),lookup.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:lookup.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(encodedWritableIndexesLength),writableIndexes:lookup.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(encodedReadonlyIndexesLength),readonlyIndexes:lookup.readonlyIndexes},serializedAddressTableLookups,serializedLength)}return serializedAddressTableLookups.slice(0,serializedLength)}static deserialize(serializedMessage){let byteArray=[...serializedMessage];const prefix=guardedShift(byteArray),maskedPrefix=prefix&VERSION_PREFIX_MASK;index_browser_esm_assert(prefix!==maskedPrefix,"Expected versioned message but received legacy message");index_browser_esm_assert(0===maskedPrefix,`Expected versioned message with version 0 but found version ${maskedPrefix}`);const header={numRequiredSignatures:guardedShift(byteArray),numReadonlySignedAccounts:guardedShift(byteArray),numReadonlyUnsignedAccounts:guardedShift(byteArray)},staticAccountKeys=[],staticAccountKeysLength=decodeLength(byteArray);for(let i=0;i{const version=VersionedMessage.deserializeMessageVersion(serializedMessage);if("legacy"===version)return Message.from(serializedMessage);if(0===version)return MessageV0.deserialize(serializedMessage);throw new Error(`Transaction message version ${version} deserialization is not supported`)}};let TransactionStatus=function(TransactionStatus){return TransactionStatus[TransactionStatus.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",TransactionStatus[TransactionStatus.PROCESSED=1]="PROCESSED",TransactionStatus[TransactionStatus.TIMED_OUT=2]="TIMED_OUT",TransactionStatus[TransactionStatus.NONCE_INVALID=3]="NONCE_INVALID",TransactionStatus}({});const DEFAULT_SIGNATURE=node_modules_buffer.Buffer.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0);class TransactionInstruction{constructor(opts){this.keys=void 0,this.programId=void 0,this.data=node_modules_buffer.Buffer.alloc(0),this.programId=opts.programId,this.keys=opts.keys,opts.data&&(this.data=opts.data)}toJSON(){return{keys:this.keys.map(({pubkey,isSigner,isWritable})=>({pubkey:pubkey.toJSON(),isSigner,isWritable})),programId:this.programId.toJSON(),data:[...this.data]}}}class Transaction{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(opts){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,opts)if(opts.feePayer&&(this.feePayer=opts.feePayer),opts.signatures&&(this.signatures=opts.signatures),Object.prototype.hasOwnProperty.call(opts,"nonceInfo")){const{minContextSlot,nonceInfo}=opts;this.minNonceContextSlot=minContextSlot,this.nonceInfo=nonceInfo}else if(Object.prototype.hasOwnProperty.call(opts,"lastValidBlockHeight")){const{blockhash,lastValidBlockHeight}=opts;this.recentBlockhash=blockhash,this.lastValidBlockHeight=lastValidBlockHeight}else{const{recentBlockhash,nonceInfo}=opts;nonceInfo&&(this.nonceInfo=nonceInfo),this.recentBlockhash=recentBlockhash}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(instruction=>instruction.toJSON()),signers:this.signatures.map(({publicKey})=>publicKey.toJSON())}}add(...items){if(0===items.length)throw new Error("No instructions");return items.forEach(item=>{"instructions"in item?this.instructions=this.instructions.concat(item.instructions):"data"in item&&"programId"in item&&"keys"in item?this.instructions.push(item):this.instructions.push(new TransactionInstruction(item))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let recentBlockhash,instructions,feePayer;if(this.nonceInfo?(recentBlockhash=this.nonceInfo.nonce,instructions=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(recentBlockhash=this.recentBlockhash,instructions=this.instructions),!recentBlockhash)throw new Error("Transaction recentBlockhash required");if(instructions.length<1&&console.warn("No instructions provided"),this.feePayer)feePayer=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");feePayer=this.signatures[0].publicKey}for(let i=0;i{instruction.keys.forEach(accountMeta=>{accountMetas.push({...accountMeta})});const programId=instruction.programId.toString();programIds.includes(programId)||programIds.push(programId)}),programIds.forEach(programId=>{accountMetas.push({pubkey:new PublicKey(programId),isSigner:!1,isWritable:!1})});const uniqueMetas=[];accountMetas.forEach(accountMeta=>{const pubkeyString=accountMeta.pubkey.toString(),uniqueIndex=uniqueMetas.findIndex(x=>x.pubkey.toString()===pubkeyString);uniqueIndex>-1?(uniqueMetas[uniqueIndex].isWritable=uniqueMetas[uniqueIndex].isWritable||accountMeta.isWritable,uniqueMetas[uniqueIndex].isSigner=uniqueMetas[uniqueIndex].isSigner||accountMeta.isSigner):uniqueMetas.push(accountMeta)}),uniqueMetas.sort(function(x,y){if(x.isSigner!==y.isSigner)return x.isSigner?-1:1;if(x.isWritable!==y.isWritable)return x.isWritable?-1:1;return x.pubkey.toBase58().localeCompare(y.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const feePayerIndex=uniqueMetas.findIndex(x=>x.pubkey.equals(feePayer));if(feePayerIndex>-1){const[payerMeta]=uniqueMetas.splice(feePayerIndex,1);payerMeta.isSigner=!0,payerMeta.isWritable=!0,uniqueMetas.unshift(payerMeta)}else uniqueMetas.unshift({pubkey:feePayer,isSigner:!0,isWritable:!0});for(const signature of this.signatures){const uniqueIndex=uniqueMetas.findIndex(x=>x.pubkey.equals(signature.publicKey));if(!(uniqueIndex>-1))throw new Error(`unknown signer: ${signature.publicKey.toString()}`);uniqueMetas[uniqueIndex].isSigner||(uniqueMetas[uniqueIndex].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."))}let numRequiredSignatures=0,numReadonlySignedAccounts=0,numReadonlyUnsignedAccounts=0;const signedKeys=[],unsignedKeys=[];uniqueMetas.forEach(({pubkey,isSigner,isWritable})=>{isSigner?(signedKeys.push(pubkey.toString()),numRequiredSignatures+=1,isWritable||(numReadonlySignedAccounts+=1)):(unsignedKeys.push(pubkey.toString()),isWritable||(numReadonlyUnsignedAccounts+=1))});const accountKeys=signedKeys.concat(unsignedKeys),compiledInstructions=instructions.map(instruction=>{const{data,programId}=instruction;return{programIdIndex:accountKeys.indexOf(programId.toString()),accounts:instruction.keys.map(meta=>accountKeys.indexOf(meta.pubkey.toString())),data:bs58_default().encode(data)}});return compiledInstructions.forEach(instruction=>{index_browser_esm_assert(instruction.programIdIndex>=0),instruction.accounts.forEach(keyIndex=>index_browser_esm_assert(keyIndex>=0))}),new Message({header:{numRequiredSignatures,numReadonlySignedAccounts,numReadonlyUnsignedAccounts},accountKeys,recentBlockhash,instructions:compiledInstructions})}_compile(){const message=this.compileMessage(),signedKeys=message.accountKeys.slice(0,message.header.numRequiredSignatures);if(this.signatures.length===signedKeys.length){if(this.signatures.every((pair,index)=>signedKeys[index].equals(pair.publicKey)))return message}return this.signatures=signedKeys.map(publicKey=>({signature:null,publicKey})),message}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(connection){return(await connection.getFeeForMessage(this.compileMessage())).value}setSigners(...signers){if(0===signers.length)throw new Error("No signers");const seen=new Set;this.signatures=signers.filter(publicKey=>{const key=publicKey.toString();return!seen.has(key)&&(seen.add(key),!0)}).map(publicKey=>({signature:null,publicKey}))}sign(...signers){if(0===signers.length)throw new Error("No signers");const seen=new Set,uniqueSigners=[];for(const signer of signers){const key=signer.publicKey.toString();seen.has(key)||(seen.add(key),uniqueSigners.push(signer))}this.signatures=uniqueSigners.map(signer=>({signature:null,publicKey:signer.publicKey}));const message=this._compile();this._partialSign(message,...uniqueSigners)}partialSign(...signers){if(0===signers.length)throw new Error("No signers");const seen=new Set,uniqueSigners=[];for(const signer of signers){const key=signer.publicKey.toString();seen.has(key)||(seen.add(key),uniqueSigners.push(signer))}const message=this._compile();this._partialSign(message,...uniqueSigners)}_partialSign(message,...signers){const signData=message.serialize();signers.forEach(signer=>{const signature=sign(signData,signer.secretKey);this._addSignature(signer.publicKey,toBuffer(signature))})}addSignature(pubkey,signature){this._compile(),this._addSignature(pubkey,signature)}_addSignature(pubkey,signature){index_browser_esm_assert(64===signature.length);const index=this.signatures.findIndex(sigpair=>pubkey.equals(sigpair.publicKey));if(index<0)throw new Error(`unknown signer: ${pubkey.toString()}`);this.signatures[index].signature=node_modules_buffer.Buffer.from(signature)}verifySignatures(requireAllSignatures=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),requireAllSignatures)}_getMessageSignednessErrors(message,requireAllSignatures){const errors={};for(const{signature,publicKey}of this.signatures)null===signature?requireAllSignatures&&(errors.missing||=[]).push(publicKey):verify(signature,message,publicKey.toBytes())||(errors.invalid||=[]).push(publicKey);return errors.invalid||errors.missing?errors:void 0}serialize(config){const{requireAllSignatures,verifySignatures}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},config),signData=this.serializeMessage();if(verifySignatures){const sigErrors=this._getMessageSignednessErrors(signData,requireAllSignatures);if(sigErrors){let errorMessage="Signature verification failed.";throw sigErrors.invalid&&(errorMessage+=`\nInvalid signature for public key${1===sigErrors.invalid.length?"":"(s)"} [\`${sigErrors.invalid.map(p=>p.toBase58()).join("`, `")}\`].`),sigErrors.missing&&(errorMessage+=`\nMissing signature for public key${1===sigErrors.missing.length?"":"(s)"} [\`${sigErrors.missing.map(p=>p.toBase58()).join("`, `")}\`].`),new Error(errorMessage)}}return this._serialize(signData)}_serialize(signData){const{signatures}=this,signatureCount=[];encodeLength(signatureCount,signatures.length);const transactionLength=signatureCount.length+64*signatures.length+signData.length,wireTransaction=node_modules_buffer.Buffer.alloc(transactionLength);return index_browser_esm_assert(signatures.length<256),node_modules_buffer.Buffer.from(signatureCount).copy(wireTransaction,0),signatures.forEach(({signature},index)=>{null!==signature&&(index_browser_esm_assert(64===signature.length,"signature has invalid length"),node_modules_buffer.Buffer.from(signature).copy(wireTransaction,signatureCount.length+64*index))}),signData.copy(wireTransaction,signatureCount.length+64*signatures.length),index_browser_esm_assert(wireTransaction.length<=PACKET_DATA_SIZE,`Transaction too large: ${wireTransaction.length} > ${PACKET_DATA_SIZE}`),wireTransaction}get keys(){return index_browser_esm_assert(1===this.instructions.length),this.instructions[0].keys.map(keyObj=>keyObj.pubkey)}get programId(){return index_browser_esm_assert(1===this.instructions.length),this.instructions[0].programId}get data(){return index_browser_esm_assert(1===this.instructions.length),this.instructions[0].data}static from(buffer){let byteArray=[...buffer];const signatureCount=decodeLength(byteArray);let signatures=[];for(let i=0;i0&&(transaction.feePayer=message.accountKeys[0]),signatures.forEach((signature,index)=>{const sigPubkeyPair={signature:signature==bs58_default().encode(DEFAULT_SIGNATURE)?null:bs58_default().decode(signature),publicKey:message.accountKeys[index]};transaction.signatures.push(sigPubkeyPair)}),message.instructions.forEach(instruction=>{const keys=instruction.accounts.map(account=>{const pubkey=message.accountKeys[account];return{pubkey,isSigner:transaction.signatures.some(keyObj=>keyObj.publicKey.toString()===pubkey.toString())||message.isAccountSigner(account),isWritable:message.isAccountWritable(account)}});transaction.instructions.push(new TransactionInstruction({keys,programId:message.accountKeys[instruction.programIdIndex],data:bs58_default().decode(instruction.data)}))}),transaction._message=message,transaction._json=transaction.toJSON(),transaction}}class TransactionMessage{constructor(args){this.payerKey=void 0,this.instructions=void 0,this.recentBlockhash=void 0,this.payerKey=args.payerKey,this.instructions=args.instructions,this.recentBlockhash=args.recentBlockhash}static decompile(message,args){const{header,compiledInstructions,recentBlockhash}=message,{numRequiredSignatures,numReadonlySignedAccounts,numReadonlyUnsignedAccounts}=header,numWritableSignedAccounts=numRequiredSignatures-numReadonlySignedAccounts;index_browser_esm_assert(numWritableSignedAccounts>0,"Message header is invalid");const numWritableUnsignedAccounts=message.staticAccountKeys.length-numRequiredSignatures-numReadonlyUnsignedAccounts;index_browser_esm_assert(numWritableUnsignedAccounts>=0,"Message header is invalid");const accountKeys=message.getAccountKeys(args),payerKey=accountKeys.get(0);if(void 0===payerKey)throw new Error("Failed to decompile message because no account keys were found");const instructions=[];for(const compiledIx of compiledInstructions){const keys=[];for(const keyIndex of compiledIx.accountKeyIndexes){const pubkey=accountKeys.get(keyIndex);if(void 0===pubkey)throw new Error(`Failed to find key for account key index ${keyIndex}`);let isWritable;isWritable=keyIndexpubkey.equals(signer.publicKey));index_browser_esm_assert(signerIndex>=0,`Cannot sign with non signer key ${signer.publicKey.toBase58()}`),this.signatures[signerIndex]=sign(messageData,signer.secretKey)}}addSignature(publicKey,signature){index_browser_esm_assert(64===signature.byteLength,"Signature must be 64 bytes long");const signerIndex=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures).findIndex(pubkey=>pubkey.equals(publicKey));index_browser_esm_assert(signerIndex>=0,`Can not add signature; \`${publicKey.toBase58()}\` is not required to sign this transaction`),this.signatures[signerIndex]=signature}}const SYSVAR_CLOCK_PUBKEY=new PublicKey("SysvarC1ock11111111111111111111111111111111"),SYSVAR_EPOCH_SCHEDULE_PUBKEY=new PublicKey("SysvarEpochSchedu1e111111111111111111111111"),SYSVAR_INSTRUCTIONS_PUBKEY=new PublicKey("Sysvar1nstructions1111111111111111111111111"),SYSVAR_RECENT_BLOCKHASHES_PUBKEY=new PublicKey("SysvarRecentB1ockHashes11111111111111111111"),SYSVAR_RENT_PUBKEY=new PublicKey("SysvarRent111111111111111111111111111111111"),SYSVAR_REWARDS_PUBKEY=new PublicKey("SysvarRewards111111111111111111111111111111"),SYSVAR_SLOT_HASHES_PUBKEY=new PublicKey("SysvarS1otHashes111111111111111111111111111"),SYSVAR_SLOT_HISTORY_PUBKEY=new PublicKey("SysvarS1otHistory11111111111111111111111111"),SYSVAR_STAKE_HISTORY_PUBKEY=new PublicKey("SysvarStakeHistory1111111111111111111111111");class SendTransactionError extends Error{constructor({action,signature,transactionMessage,logs}){const maybeLogsOutput=logs?`Logs: \n${JSON.stringify(logs.slice(-10),null,2)}. `:"",guideText="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let message;switch(action){case"send":message=`Transaction ${signature} resulted in an error. \n${transactionMessage}. `+maybeLogsOutput+guideText;break;case"simulate":message=`Simulation failed. \nMessage: ${transactionMessage}. \n`+maybeLogsOutput+guideText;break;default:message=`Unknown action '${action}'`}super(message),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=signature,this.transactionMessage=transactionMessage,this.transactionLogs=logs||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const cachedLogs=this.transactionLogs;if(null==cachedLogs||"object"!=typeof cachedLogs||!("then"in cachedLogs))return cachedLogs}async getLogs(connection){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((resolve,reject)=>{connection.getTransaction(this.signature).then(tx=>{if(tx&&tx.meta&&tx.meta.logMessages){const logs=tx.meta.logMessages;this.transactionLogs=logs,resolve(logs)}else reject(new Error("Log messages not found"))}).catch(reject)})),await this.transactionLogs}}const SolanaJSONRPCErrorCode={JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP:-32001,JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE:-32002,JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE:-32003,JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE:-32004,JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY:-32005,JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:-32006,JSON_RPC_SERVER_ERROR_SLOT_SKIPPED:-32007,JSON_RPC_SERVER_ERROR_NO_SNAPSHOT:-32008,JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:-32009,JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:-32010,JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE:-32011,JSON_RPC_SCAN_ERROR:-32012,JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH:-32013,JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:-32014,JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:-32015,JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED:-32016};class SolanaJSONRPCError extends Error{constructor({code,message,data},customMessage){super(null!=customMessage?`${customMessage}: ${message}`:message),this.code=void 0,this.data=void 0,this.code=code,this.data=data,this.name="SolanaJSONRPCError"}}async function sendAndConfirmTransaction(connection,transaction,signers,options){const sendOptions=options&&{skipPreflight:options.skipPreflight,preflightCommitment:options.preflightCommitment||options.commitment,maxRetries:options.maxRetries,minContextSlot:options.minContextSlot},signature=await connection.sendTransaction(transaction,signers,sendOptions);let status;if(null!=transaction.recentBlockhash&&null!=transaction.lastValidBlockHeight)status=(await connection.confirmTransaction({abortSignal:options?.abortSignal,signature,blockhash:transaction.recentBlockhash,lastValidBlockHeight:transaction.lastValidBlockHeight},options&&options.commitment)).value;else if(null!=transaction.minNonceContextSlot&&null!=transaction.nonceInfo){const{nonceInstruction}=transaction.nonceInfo,nonceAccountPubkey=nonceInstruction.keys[0].pubkey;status=(await connection.confirmTransaction({abortSignal:options?.abortSignal,minContextSlot:transaction.minNonceContextSlot,nonceAccountPubkey,nonceValue:transaction.nonceInfo.nonce,signature},options&&options.commitment)).value}else null!=options?.abortSignal&&console.warn("sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` or a combination of `nonceInfo` and `minNonceContextSlot` are abortable."),status=(await connection.confirmTransaction(signature,options&&options.commitment)).value;if(status.err){if(null!=signature)throw new SendTransactionError({action:"send",signature,transactionMessage:`Status: (${JSON.stringify(status)})`});throw new Error(`Transaction ${signature} failed (${JSON.stringify(status)})`)}return signature}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function encodeData(type,fields){const allocLength=type.layout.span>=0?type.layout.span:getAlloc(type,fields),data=node_modules_buffer.Buffer.alloc(allocLength),layoutFields=Object.assign({instruction:type.index},fields);return type.layout.encode(layoutFields,data),data}function decodeData$1(type,buffer){let data;try{data=type.layout.decode(buffer)}catch(err){throw new Error("invalid instruction; "+err)}if(data.instruction!==type.index)throw new Error(`invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`);return data}const FeeCalculatorLayout=Layout.I0("lamportsPerSignature"),NonceAccountLayout=Layout.w3([Layout.DH("version"),Layout.DH("state"),publicKey("authorizedPubkey"),publicKey("nonce"),Layout.w3([FeeCalculatorLayout],"feeCalculator")]),NONCE_ACCOUNT_LENGTH=NonceAccountLayout.span;class NonceAccount{constructor(args){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=args.authorizedPubkey,this.nonce=args.nonce,this.feeCalculator=args.feeCalculator}static fromAccountData(buffer){const nonceAccount=NonceAccountLayout.decode(toBuffer(buffer),0);return new NonceAccount({authorizedPubkey:new PublicKey(nonceAccount.authorizedPubkey),nonce:new PublicKey(nonceAccount.nonce).toString(),feeCalculator:nonceAccount.feeCalculator})}}function index_browser_esm_u64(property){const layout=(0,Layout.av)(8,property),decode=layout.decode.bind(layout),encode=layout.encode.bind(layout),bigIntLayout=layout,codec=getU64Codec();return bigIntLayout.decode=(buffer,offset)=>{const src=decode(buffer,offset);return codec.decode(src)},bigIntLayout.encode=(bigInt,buffer,offset)=>{const src=codec.encode(bigInt);return encode(src,buffer,offset)},bigIntLayout}class SystemInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const typeIndex=Layout.DH("instruction").decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS))if(layout.index==typeIndex){type=ixType;break}if(!type)throw new Error("Instruction type incorrect; not a SystemInstruction");return type}static decodeCreateAccount(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,2);const{lamports,space,programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Create,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,newAccountPubkey:instruction.keys[1].pubkey,lamports,space,programId:new PublicKey(programId)}}static decodeTransfer(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,2);const{lamports}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Transfer,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,lamports}}static decodeTransferWithSeed(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3);const{lamports,seed,programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,basePubkey:instruction.keys[1].pubkey,toPubkey:instruction.keys[2].pubkey,lamports,seed,programId:new PublicKey(programId)}}static decodeAllocate(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,1);const{space}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Allocate,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,space}}static decodeAllocateWithSeed(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,1);const{base,seed,space,programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,basePubkey:new PublicKey(base),seed,space,programId:new PublicKey(programId)}}static decodeAssign(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,1);const{programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Assign,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,programId:new PublicKey(programId)}}static decodeAssignWithSeed(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,1);const{base,seed,programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,basePubkey:new PublicKey(base),seed,programId:new PublicKey(programId)}}static decodeCreateWithSeed(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,2);const{base,seed,lamports,space,programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,newAccountPubkey:instruction.keys[1].pubkey,basePubkey:new PublicKey(base),seed,lamports,space,programId:new PublicKey(programId)}}static decodeNonceInitialize(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3);const{authorized}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:new PublicKey(authorized)}}static decodeNonceAdvance(instruction){return this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3),decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount,instruction.data),{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey}}static decodeNonceWithdraw(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,5);const{lamports}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey,lamports}}static decodeNonceAuthorize(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,2);const{authorized}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[1].pubkey,newAuthorizedPubkey:new PublicKey(authorized)}}static checkProgramId(programId){if(!programId.equals(SystemProgram.programId))throw new Error("invalid instruction; programId is not SystemProgram")}static checkKeyLength(keys,expectedLength){if(keys.length0?balanceNeeded:1,space:data.length,programId}));null!==transaction&&await sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"})}const dataLayout=Layout.w3([Layout.DH("instruction"),Layout.DH("offset"),Layout.DH("bytesLength"),Layout.DH("bytesLengthPadding"),Layout.O6(Layout.u8("byte"),Layout.cY(Layout.DH(),-8),"bytes")]),chunkSize=Loader.chunkSize;let offset=0,array=data,transactions=[];for(;array.length>0;){const bytes=array.slice(0,chunkSize),data=node_modules_buffer.Buffer.alloc(chunkSize+16);dataLayout.encode({instruction:0,offset,bytes,bytesLength:0,bytesLengthPadding:0},data);const transaction=(new Transaction).add({keys:[{pubkey:program.publicKey,isSigner:!0,isWritable:!0}],programId,data});if(transactions.push(sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"})),connection._rpcEndpoint.includes("solana.com")){const REQUESTS_PER_SECOND=4;await sleep(1e3/REQUESTS_PER_SECOND)}offset+=chunkSize,array=array.slice(chunkSize)}await Promise.all(transactions);{const dataLayout=Layout.w3([Layout.DH("instruction")]),data=node_modules_buffer.Buffer.alloc(dataLayout.span);dataLayout.encode({instruction:1},data);const transaction=(new Transaction).add({keys:[{pubkey:program.publicKey,isSigner:!0,isWritable:!0},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:!1,isWritable:!1}],programId,data}),deployCommitment="processed",finalizeSignature=await connection.sendTransaction(transaction,[payer,program],{preflightCommitment:deployCommitment}),{context,value}=await connection.confirmTransaction({signature:finalizeSignature,lastValidBlockHeight:transaction.lastValidBlockHeight,blockhash:transaction.recentBlockhash},deployCommitment);if(value.err)throw new Error(`Transaction ${finalizeSignature} failed (${JSON.stringify(value)})`);for(;;){try{if(await connection.getSlot({commitment:deployCommitment})>context.slot)break}catch{}await new Promise(resolve=>setTimeout(resolve,Math.round(200)))}}return!0}}Loader.chunkSize=CHUNK_SIZE;const BPF_LOADER_PROGRAM_ID=new PublicKey("BPFLoader2111111111111111111111111111111111");class BpfLoader{static getMinNumSignatures(dataLength){return Loader.getMinNumSignatures(dataLength)}static load(connection,payer,program,elf,loaderProgramId){return Loader.load(connection,payer,program,loaderProgramId,elf)}}function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}var fastStableStringify$1,hasRequiredFastStableStringify;function requireFastStableStringify(){if(hasRequiredFastStableStringify)return fastStableStringify$1;hasRequiredFastStableStringify=1;var objToString=Object.prototype.toString,objKeys=Object.keys||function(obj){var keys=[];for(var name in obj)keys.push(name);return keys};function stringify(val,isArrayProp){var i,max,str,keys,key,propVal,toStr;if(!0===val)return"true";if(!1===val)return"false";switch(typeof val){case"object":if(null===val)return null;if(val.toJSON&&"function"==typeof val.toJSON)return stringify(val.toJSON(),isArrayProp);if("[object Array]"===(toStr=objToString.call(val))){for(str="[",max=val.length-1,i=0;i-1&&(str+=stringify(val[i],!0)),str+"]"}if("[object Object]"===toStr){for(max=(keys=objKeys(val).sort()).length,str="",i=0;i1;)n/=2,trailingZeros++;return trailingZeros}class EpochSchedule{constructor(slotsPerEpoch,leaderScheduleSlotOffset,warmup,firstNormalEpoch,firstNormalSlot){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=slotsPerEpoch,this.leaderScheduleSlotOffset=leaderScheduleSlotOffset,this.warmup=warmup,this.firstNormalEpoch=firstNormalEpoch,this.firstNormalSlot=firstNormalSlot}getEpoch(slot){return this.getEpochAndSlotIndex(slot)[0]}getEpochAndSlotIndex(slot){if(slot>1,n|=n>>2,n|=n>>4,n|=n>>8,n|=n>>16,1+(n|=n>>32))}(slot+32+1))-trailingZeros(32)-1;return[epoch,slot-(this.getSlotsInEpoch(epoch)-32)]}{const normalSlotIndex=slot-this.firstNormalSlot,normalEpochIndex=Math.floor(normalSlotIndex/this.slotsPerEpoch);return[this.firstNormalEpoch+normalEpochIndex,normalSlotIndex%this.slotsPerEpoch]}}getFirstSlotInEpoch(epoch){return epoch<=this.firstNormalEpoch?32*(Math.pow(2,epoch)-1):(epoch-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(epoch){return this.getFirstSlotInEpoch(epoch)+this.getSlotsInEpoch(epoch)-1}getSlotsInEpoch(epoch){return epoch{const rpc=WebSocket(url,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...options});return this.underlyingSocket="socket"in rpc?rpc.socket:rpc,rpc},address,options,generate_request_id),this.underlyingSocket=void 0}call(...args){const readyState=this.underlyingSocket?.readyState;return 1===readyState?super.call(...args):Promise.reject(new Error("Tried to call a JSON-RPC method `"+args[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+readyState+")"))}notify(...args){const readyState=this.underlyingSocket?.readyState;return 1===readyState?super.notify(...args):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+args[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+readyState+")"))}}class AddressLookupTableAccount{constructor(args){this.key=void 0,this.state=void 0,this.key=args.key,this.state=args.state}isActive(){const U64_MAX=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===U64_MAX}static deserialize(accountData){const meta=function decodeData(type,data){let decoded;try{decoded=type.layout.decode(data)}catch(err){throw new Error("invalid instruction; "+err)}if(decoded.typeIndex!==type.index)throw new Error(`invalid account data; account type mismatch ${decoded.typeIndex} != ${type.index}`);return decoded}(LookupTableMetaLayout,accountData),serializedAddressesLen=accountData.length-56;index_browser_esm_assert(serializedAddressesLen>=0,"lookup table is invalid"),index_browser_esm_assert(serializedAddressesLen%32==0,"lookup table is invalid");const numSerializedAddresses=serializedAddressesLen/32,{addresses}=Layout.w3([Layout.O6(publicKey(),numSerializedAddresses,"addresses")]).decode(accountData.slice(56));return{deactivationSlot:meta.deactivationSlot,lastExtendedSlot:meta.lastExtendedSlot,lastExtendedSlotStartIndex:meta.lastExtendedStartIndex,authority:0!==meta.authority.length?new PublicKey(meta.authority[0]):void 0,addresses:addresses.map(address=>new PublicKey(address))}}}const LookupTableMetaLayout={index:1,layout:Layout.w3([Layout.DH("typeIndex"),index_browser_esm_u64("deactivationSlot"),Layout.I0("lastExtendedSlot"),Layout.u8("lastExtendedStartIndex"),Layout.u8(),Layout.O6(publicKey(),Layout.cY(Layout.u8(),-1),"authority")])},URL_RE=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const PublicKeyFromString=coerce(instance(PublicKey),string(),value=>new PublicKey(value)),RawAccountDataResult=tuple([string(),literal("base64")]),BufferFromRawAccountData=coerce(instance(node_modules_buffer.Buffer),RawAccountDataResult,value=>node_modules_buffer.Buffer.from(value[0],"base64")),BLOCKHASH_CACHE_TIMEOUT_MS=3e4;function extractCommitmentFromConfig(commitmentOrConfig){let commitment,config;if("string"==typeof commitmentOrConfig)commitment=commitmentOrConfig;else if(commitmentOrConfig){const{commitment:specifiedCommitment,...specifiedConfig}=commitmentOrConfig;commitment=specifiedCommitment,config=specifiedConfig}return{commitment,config}}function applyDefaultMemcmpEncodingToFilters(filters){return filters.map(filter=>"memcmp"in filter?{...filter,memcmp:{...filter.memcmp,encoding:filter.memcmp.encoding??"base58"}}:filter)}function createRpcResult(result){return union([type({jsonrpc:literal("2.0"),id:string(),result}),type({jsonrpc:literal("2.0"),id:string(),error:type({code:unknown(),message:string(),data:optional(dist_define("any",()=>!0))})})])}const UnknownRpcResult=createRpcResult(unknown());function jsonRpcResult(schema){return coerce(createRpcResult(schema),UnknownRpcResult,value=>"error"in value?value:{...value,result:create(value.result,schema)})}function jsonRpcResultAndContext(value){return jsonRpcResult(type({context:type({slot:number()}),value}))}function notificationResultAndContext(value){return type({context:type({slot:number()}),value})}function versionedMessageFromResponse(version,response){return 0===version?new MessageV0({header:response.header,staticAccountKeys:response.accountKeys.map(accountKey=>new PublicKey(accountKey)),recentBlockhash:response.recentBlockhash,compiledInstructions:response.instructions.map(ix=>({programIdIndex:ix.programIdIndex,accountKeyIndexes:ix.accounts,data:bs58_default().decode(ix.data)})),addressTableLookups:response.addressTableLookups}):new Message(response)}const GetInflationGovernorResult=type({foundation:number(),foundationTerm:number(),initial:number(),taper:number(),terminal:number()}),GetInflationRewardResult=jsonRpcResult(array(nullable(type({epoch:number(),effectiveSlot:number(),amount:number(),postBalance:number(),commission:optional(nullable(number()))})))),GetRecentPrioritizationFeesResult=array(type({slot:number(),prioritizationFee:number()})),GetInflationRateResult=type({total:number(),validator:number(),foundation:number(),epoch:number()}),GetEpochInfoResult=type({epoch:number(),slotIndex:number(),slotsInEpoch:number(),absoluteSlot:number(),blockHeight:optional(number()),transactionCount:optional(number())}),GetEpochScheduleResult=type({slotsPerEpoch:number(),leaderScheduleSlotOffset:number(),warmup:dist_boolean(),firstNormalEpoch:number(),firstNormalSlot:number()}),GetLeaderScheduleResult=record(string(),array(number())),TransactionErrorResult=nullable(union([type({}),string()])),SignatureStatusResult=type({err:TransactionErrorResult}),SignatureReceivedResult=literal("receivedSignature"),VersionResult=type({"solana-core":string(),"feature-set":optional(number())}),ParsedInstructionStruct=type({program:string(),programId:PublicKeyFromString,parsed:unknown()}),PartiallyDecodedInstructionStruct=type({programId:PublicKeyFromString,accounts:array(PublicKeyFromString),data:string()}),SimulatedTransactionResponseStruct=jsonRpcResultAndContext(type({err:nullable(union([type({}),string()])),logs:nullable(array(string())),accounts:optional(nullable(array(nullable(type({executable:dist_boolean(),owner:string(),lamports:number(),data:array(string()),rentEpoch:optional(number())}))))),unitsConsumed:optional(number()),returnData:optional(nullable(type({programId:string(),data:tuple([string(),literal("base64")])}))),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(union([ParsedInstructionStruct,PartiallyDecodedInstructionStruct]))}))))})),BlockProductionResponseStruct=jsonRpcResultAndContext(type({byIdentity:record(string(),array(number())),range:type({firstSlot:number(),lastSlot:number()})}));const GetInflationGovernorRpcResult=jsonRpcResult(GetInflationGovernorResult),GetInflationRateRpcResult=jsonRpcResult(GetInflationRateResult),GetRecentPrioritizationFeesRpcResult=jsonRpcResult(GetRecentPrioritizationFeesResult),GetEpochInfoRpcResult=jsonRpcResult(GetEpochInfoResult),GetEpochScheduleRpcResult=jsonRpcResult(GetEpochScheduleResult),GetLeaderScheduleRpcResult=jsonRpcResult(GetLeaderScheduleResult),SlotRpcResult=jsonRpcResult(number()),GetSupplyRpcResult=jsonRpcResultAndContext(type({total:number(),circulating:number(),nonCirculating:number(),nonCirculatingAccounts:array(PublicKeyFromString)})),TokenAmountResult=type({amount:string(),uiAmount:nullable(number()),decimals:number(),uiAmountString:optional(string())}),GetTokenLargestAccountsResult=jsonRpcResultAndContext(array(type({address:PublicKeyFromString,amount:string(),uiAmount:nullable(number()),decimals:number(),uiAmountString:optional(string())}))),GetTokenAccountsByOwner=jsonRpcResultAndContext(array(type({pubkey:PublicKeyFromString,account:type({executable:dist_boolean(),owner:PublicKeyFromString,lamports:number(),data:BufferFromRawAccountData,rentEpoch:number()})}))),ParsedAccountDataResult=type({program:string(),parsed:unknown(),space:number()}),GetParsedTokenAccountsByOwner=jsonRpcResultAndContext(array(type({pubkey:PublicKeyFromString,account:type({executable:dist_boolean(),owner:PublicKeyFromString,lamports:number(),data:ParsedAccountDataResult,rentEpoch:number()})}))),GetLargestAccountsRpcResult=jsonRpcResultAndContext(array(type({lamports:number(),address:PublicKeyFromString}))),AccountInfoResult=type({executable:dist_boolean(),owner:PublicKeyFromString,lamports:number(),data:BufferFromRawAccountData,rentEpoch:number()}),KeyedAccountInfoResult=type({pubkey:PublicKeyFromString,account:AccountInfoResult}),ParsedOrRawAccountData=coerce(union([instance(node_modules_buffer.Buffer),ParsedAccountDataResult]),union([RawAccountDataResult,ParsedAccountDataResult]),value=>Array.isArray(value)?create(value,BufferFromRawAccountData):value),ParsedAccountInfoResult=type({executable:dist_boolean(),owner:PublicKeyFromString,lamports:number(),data:ParsedOrRawAccountData,rentEpoch:number()}),KeyedParsedAccountInfoResult=type({pubkey:PublicKeyFromString,account:ParsedAccountInfoResult}),StakeActivationResult=type({state:union([literal("active"),literal("inactive"),literal("activating"),literal("deactivating")]),active:number(),inactive:number()}),GetConfirmedSignaturesForAddress2RpcResult=jsonRpcResult(array(type({signature:string(),slot:number(),err:TransactionErrorResult,memo:nullable(string()),blockTime:optional(nullable(number()))}))),GetSignaturesForAddressRpcResult=jsonRpcResult(array(type({signature:string(),slot:number(),err:TransactionErrorResult,memo:nullable(string()),blockTime:optional(nullable(number()))}))),AccountNotificationResult=type({subscription:number(),result:notificationResultAndContext(AccountInfoResult)}),ProgramAccountInfoResult=type({pubkey:PublicKeyFromString,account:AccountInfoResult}),ProgramAccountNotificationResult=type({subscription:number(),result:notificationResultAndContext(ProgramAccountInfoResult)}),SlotInfoResult=type({parent:number(),slot:number(),root:number()}),SlotNotificationResult=type({subscription:number(),result:SlotInfoResult}),SlotUpdateResult=union([type({type:union([literal("firstShredReceived"),literal("completed"),literal("optimisticConfirmation"),literal("root")]),slot:number(),timestamp:number()}),type({type:literal("createdBank"),parent:number(),slot:number(),timestamp:number()}),type({type:literal("frozen"),slot:number(),timestamp:number(),stats:type({numTransactionEntries:number(),numSuccessfulTransactions:number(),numFailedTransactions:number(),maxTransactionsPerEntry:number()})}),type({type:literal("dead"),slot:number(),timestamp:number(),err:string()})]),SlotUpdateNotificationResult=type({subscription:number(),result:SlotUpdateResult}),SignatureNotificationResult=type({subscription:number(),result:notificationResultAndContext(union([SignatureStatusResult,SignatureReceivedResult]))}),RootNotificationResult=type({subscription:number(),result:number()}),ContactInfoResult=type({pubkey:string(),gossip:nullable(string()),tpu:nullable(string()),rpc:nullable(string()),version:nullable(string())}),VoteAccountInfoResult=type({votePubkey:string(),nodePubkey:string(),activatedStake:number(),epochVoteAccount:dist_boolean(),epochCredits:array(tuple([number(),number(),number()])),commission:number(),lastVote:number(),rootSlot:nullable(number())}),GetVoteAccounts=jsonRpcResult(type({current:array(VoteAccountInfoResult),delinquent:array(VoteAccountInfoResult)})),ConfirmationStatus=union([literal("processed"),literal("confirmed"),literal("finalized")]),SignatureStatusResponse=type({slot:number(),confirmations:nullable(number()),err:TransactionErrorResult,confirmationStatus:optional(ConfirmationStatus)}),GetSignatureStatusesRpcResult=jsonRpcResultAndContext(array(nullable(SignatureStatusResponse))),GetMinimumBalanceForRentExemptionRpcResult=jsonRpcResult(number()),AddressTableLookupStruct=type({accountKey:PublicKeyFromString,writableIndexes:array(number()),readonlyIndexes:array(number())}),ConfirmedTransactionResult=type({signatures:array(string()),message:type({accountKeys:array(string()),header:type({numRequiredSignatures:number(),numReadonlySignedAccounts:number(),numReadonlyUnsignedAccounts:number()}),instructions:array(type({accounts:array(number()),data:string(),programIdIndex:number()})),recentBlockhash:string(),addressTableLookups:optional(array(AddressTableLookupStruct))})}),AnnotatedAccountKey=type({pubkey:PublicKeyFromString,signer:dist_boolean(),writable:dist_boolean(),source:optional(union([literal("transaction"),literal("lookupTable")]))}),ConfirmedTransactionAccountsModeResult=type({accountKeys:array(AnnotatedAccountKey),signatures:array(string())}),ParsedInstructionResult=type({parsed:unknown(),program:string(),programId:PublicKeyFromString}),RawInstructionResult=type({accounts:array(PublicKeyFromString),data:string(),programId:PublicKeyFromString}),ParsedOrRawInstruction=coerce(union([RawInstructionResult,ParsedInstructionResult]),union([type({parsed:unknown(),program:string(),programId:string()}),type({accounts:array(string()),data:string(),programId:string()})]),value=>create(value,"accounts"in value?RawInstructionResult:ParsedInstructionResult)),ParsedConfirmedTransactionResult=type({signatures:array(string()),message:type({accountKeys:array(AnnotatedAccountKey),instructions:array(ParsedOrRawInstruction),recentBlockhash:string(),addressTableLookups:optional(nullable(array(AddressTableLookupStruct)))})}),TokenBalanceResult=type({accountIndex:number(),mint:string(),owner:optional(string()),programId:optional(string()),uiTokenAmount:TokenAmountResult}),LoadedAddressesResult=type({writable:array(PublicKeyFromString),readonly:array(PublicKeyFromString)}),ConfirmedTransactionMetaResult=type({err:TransactionErrorResult,fee:number(),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(type({accounts:array(number()),data:string(),programIdIndex:number()}))})))),preBalances:array(number()),postBalances:array(number()),logMessages:optional(nullable(array(string()))),preTokenBalances:optional(nullable(array(TokenBalanceResult))),postTokenBalances:optional(nullable(array(TokenBalanceResult))),loadedAddresses:optional(LoadedAddressesResult),computeUnitsConsumed:optional(number())}),ParsedConfirmedTransactionMetaResult=type({err:TransactionErrorResult,fee:number(),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(ParsedOrRawInstruction)})))),preBalances:array(number()),postBalances:array(number()),logMessages:optional(nullable(array(string()))),preTokenBalances:optional(nullable(array(TokenBalanceResult))),postTokenBalances:optional(nullable(array(TokenBalanceResult))),loadedAddresses:optional(LoadedAddressesResult),computeUnitsConsumed:optional(number())}),TransactionVersionStruct=union([literal(0),literal("legacy")]),RewardsResult=type({pubkey:string(),lamports:number(),postBalance:nullable(number()),rewardType:nullable(string()),commission:optional(nullable(number()))}),GetBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionResult,meta:nullable(ConfirmedTransactionMetaResult),version:optional(TransactionVersionStruct)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())}))),GetNoneModeBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())}))),GetAccountsModeBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionAccountsModeResult,meta:nullable(ConfirmedTransactionMetaResult),version:optional(TransactionVersionStruct)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())}))),GetParsedBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ParsedConfirmedTransactionResult,meta:nullable(ParsedConfirmedTransactionMetaResult),version:optional(TransactionVersionStruct)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())}))),GetParsedAccountsModeBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionAccountsModeResult,meta:nullable(ParsedConfirmedTransactionMetaResult),version:optional(TransactionVersionStruct)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())}))),GetParsedNoneModeBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())}))),GetConfirmedBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionResult,meta:nullable(ConfirmedTransactionMetaResult)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number())}))),GetBlockSignaturesRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),signatures:array(string()),blockTime:nullable(number())}))),GetTransactionRpcResult=jsonRpcResult(nullable(type({slot:number(),meta:nullable(ConfirmedTransactionMetaResult),blockTime:optional(nullable(number())),transaction:ConfirmedTransactionResult,version:optional(TransactionVersionStruct)}))),GetParsedTransactionRpcResult=jsonRpcResult(nullable(type({slot:number(),transaction:ParsedConfirmedTransactionResult,meta:nullable(ParsedConfirmedTransactionMetaResult),blockTime:optional(nullable(number())),version:optional(TransactionVersionStruct)}))),GetLatestBlockhashRpcResult=jsonRpcResultAndContext(type({blockhash:string(),lastValidBlockHeight:number()})),IsBlockhashValidRpcResult=jsonRpcResultAndContext(dist_boolean()),GetRecentPerformanceSamplesRpcResult=jsonRpcResult(array(type({slot:number(),numTransactions:number(),numSlots:number(),samplePeriodSecs:number()}))),GetFeeCalculatorRpcResult=jsonRpcResultAndContext(nullable(type({feeCalculator:type({lamportsPerSignature:number()})}))),RequestAirdropRpcResult=jsonRpcResult(string()),SendTransactionRpcResult=jsonRpcResult(string()),LogsResult=type({err:TransactionErrorResult,logs:array(string()),signature:string()}),LogsNotificationResult=type({result:notificationResultAndContext(LogsResult),subscription:number()}),COMMON_HTTP_HEADERS={"solana-client":"js/1.0.0-maintenance"};class Connection{constructor(endpoint,_commitmentOrConfig){let wsEndpoint,httpHeaders,fetch,fetchMiddleware,disableRetryOnRateLimit,httpAgent;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const requestPromises={};return async commitmentOrConfig=>{const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([],commitment,void 0,config),requestHash=fastStableStringify(args);return requestPromises[requestHash]=requestPromises[requestHash]??(async()=>{try{const res=create(await this._rpcRequest("getBlockHeight",args),jsonRpcResult(number()));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get block height information");return res.result}finally{delete requestPromises[requestHash]}})(),await requestPromises[requestHash]}})(),_commitmentOrConfig&&"string"==typeof _commitmentOrConfig?this._commitment=_commitmentOrConfig:_commitmentOrConfig&&(this._commitment=_commitmentOrConfig.commitment,this._confirmTransactionInitialTimeout=_commitmentOrConfig.confirmTransactionInitialTimeout,wsEndpoint=_commitmentOrConfig.wsEndpoint,httpHeaders=_commitmentOrConfig.httpHeaders,fetch=_commitmentOrConfig.fetch,fetchMiddleware=_commitmentOrConfig.fetchMiddleware,disableRetryOnRateLimit=_commitmentOrConfig.disableRetryOnRateLimit,httpAgent=_commitmentOrConfig.httpAgent),this._rpcEndpoint=function assertEndpointUrl(putativeUrl){if(!1===/^https?:/.test(putativeUrl))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return putativeUrl}(endpoint),this._rpcWsEndpoint=wsEndpoint||function makeWebsocketUrl(endpoint){const matches=endpoint.match(URL_RE);if(null==matches)throw TypeError(`Failed to validate endpoint URL \`${endpoint}\``);const[_,hostish,portWithColon,rest]=matches,protocol=endpoint.startsWith("https:")?"wss:":"ws:",startPort=null==portWithColon?null:parseInt(portWithColon.slice(1),10);return`${protocol}//${hostish}${null==startPort?"":`:${startPort+1}`}${rest}`}(endpoint),this._rpcClient=function createRpcClient(url,httpHeaders,customFetch,fetchMiddleware,disableRetryOnRateLimit,httpAgent){const fetch=customFetch||fetchImpl;let fetchWithMiddleware;return null!=httpAgent&&console.warn("You have supplied an `httpAgent` when creating a `Connection` in a browser environment.It has been ignored; `httpAgent` is only used in Node environments."),fetchMiddleware&&(fetchWithMiddleware=async(info,init)=>{const modifiedFetchArgs=await new Promise((resolve,reject)=>{try{fetchMiddleware(info,init,(modifiedInfo,modifiedInit)=>resolve([modifiedInfo,modifiedInit]))}catch(error){reject(error)}});return await fetch(...modifiedFetchArgs)}),new(browser_default())(async(request,callback)=>{const options={method:"POST",body:request,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},httpHeaders||{},COMMON_HTTP_HEADERS)};try{let res,too_many_requests_retries=5,waitTime=500;for(;res=fetchWithMiddleware?await fetchWithMiddleware(url,options):await fetch(url,options),429===res.status&&!0!==disableRetryOnRateLimit&&(too_many_requests_retries-=1,0!==too_many_requests_retries);)console.error(`Server responded with ${res.status} ${res.statusText}. Retrying after ${waitTime}ms delay...`),await sleep(waitTime),waitTime*=2;const text=await res.text();res.ok?callback(null,text):callback(new Error(`${res.status} ${res.statusText}: ${text}`))}catch(err){err instanceof Error&&callback(err)}},{})}(endpoint,httpHeaders,fetch,fetchMiddleware,disableRetryOnRateLimit,httpAgent),this._rpcRequest=function createRpcRequest(client){return(method,args)=>new Promise((resolve,reject)=>{client.request(method,args,(err,response)=>{err?reject(err):resolve(response)})})}(this._rpcClient),this._rpcBatchRequest=function createRpcBatchRequest(client){return requests=>new Promise((resolve,reject)=>{0===requests.length&&resolve([]);const batch=requests.map(params=>client.request(params.methodName,params.args));client.request(batch,(err,response)=>{err?reject(err):resolve(response)})})}(this._rpcClient),this._rpcWebSocket=new RpcWebSocketClient(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(publicKey,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([publicKey.toBase58()],commitment,void 0,config),res=create(await this._rpcRequest("getBalance",args),jsonRpcResultAndContext(number()));if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get balance for ${publicKey.toBase58()}`);return res.result}async getBalance(publicKey,commitmentOrConfig){return await this.getBalanceAndContext(publicKey,commitmentOrConfig).then(x=>x.value).catch(e=>{throw new Error("failed to get balance of account "+publicKey.toBase58()+": "+e)})}async getBlockTime(slot){const res=create(await this._rpcRequest("getBlockTime",[slot]),jsonRpcResult(nullable(number())));if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get block time for slot ${slot}`);return res.result}async getMinimumLedgerSlot(){const res=create(await this._rpcRequest("minimumLedgerSlot",[]),jsonRpcResult(number()));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get minimum ledger slot");return res.result}async getFirstAvailableBlock(){const res=create(await this._rpcRequest("getFirstAvailableBlock",[]),SlotRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get first available block");return res.result}async getSupply(config){let configArg={};configArg="string"==typeof config?{commitment:config}:config?{...config,commitment:config&&config.commitment||this.commitment}:{commitment:this.commitment};const res=create(await this._rpcRequest("getSupply",[configArg]),GetSupplyRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get supply");return res.result}async getTokenSupply(tokenMintAddress,commitment){const args=this._buildArgs([tokenMintAddress.toBase58()],commitment),res=create(await this._rpcRequest("getTokenSupply",args),jsonRpcResultAndContext(TokenAmountResult));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get token supply");return res.result}async getTokenAccountBalance(tokenAddress,commitment){const args=this._buildArgs([tokenAddress.toBase58()],commitment),res=create(await this._rpcRequest("getTokenAccountBalance",args),jsonRpcResultAndContext(TokenAmountResult));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get token account balance");return res.result}async getTokenAccountsByOwner(ownerAddress,filter,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig);let _args=[ownerAddress.toBase58()];"mint"in filter?_args.push({mint:filter.mint.toBase58()}):_args.push({programId:filter.programId.toBase58()});const args=this._buildArgs(_args,commitment,"base64",config),res=create(await this._rpcRequest("getTokenAccountsByOwner",args),GetTokenAccountsByOwner);if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get token accounts owned by account ${ownerAddress.toBase58()}`);return res.result}async getParsedTokenAccountsByOwner(ownerAddress,filter,commitment){let _args=[ownerAddress.toBase58()];"mint"in filter?_args.push({mint:filter.mint.toBase58()}):_args.push({programId:filter.programId.toBase58()});const args=this._buildArgs(_args,commitment,"jsonParsed"),res=create(await this._rpcRequest("getTokenAccountsByOwner",args),GetParsedTokenAccountsByOwner);if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get token accounts owned by account ${ownerAddress.toBase58()}`);return res.result}async getLargestAccounts(config){const arg={...config,commitment:config&&config.commitment||this.commitment},args=arg.filter||arg.commitment?[arg]:[],res=create(await this._rpcRequest("getLargestAccounts",args),GetLargestAccountsRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get largest accounts");return res.result}async getTokenLargestAccounts(mintAddress,commitment){const args=this._buildArgs([mintAddress.toBase58()],commitment),res=create(await this._rpcRequest("getTokenLargestAccounts",args),GetTokenLargestAccountsResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get token largest accounts");return res.result}async getAccountInfoAndContext(publicKey,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([publicKey.toBase58()],commitment,"base64",config),res=create(await this._rpcRequest("getAccountInfo",args),jsonRpcResultAndContext(nullable(AccountInfoResult)));if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get info about account ${publicKey.toBase58()}`);return res.result}async getParsedAccountInfo(publicKey,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([publicKey.toBase58()],commitment,"jsonParsed",config),res=create(await this._rpcRequest("getAccountInfo",args),jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)));if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get info about account ${publicKey.toBase58()}`);return res.result}async getAccountInfo(publicKey,commitmentOrConfig){try{return(await this.getAccountInfoAndContext(publicKey,commitmentOrConfig)).value}catch(e){throw new Error("failed to get info about account "+publicKey.toBase58()+": "+e)}}async getMultipleParsedAccounts(publicKeys,rawConfig){const{commitment,config}=extractCommitmentFromConfig(rawConfig),keys=publicKeys.map(key=>key.toBase58()),args=this._buildArgs([keys],commitment,"jsonParsed",config),res=create(await this._rpcRequest("getMultipleAccounts",args),jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult))));if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get info for accounts ${keys}`);return res.result}async getMultipleAccountsInfoAndContext(publicKeys,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),keys=publicKeys.map(key=>key.toBase58()),args=this._buildArgs([keys],commitment,"base64",config),res=create(await this._rpcRequest("getMultipleAccounts",args),jsonRpcResultAndContext(array(nullable(AccountInfoResult))));if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get info for accounts ${keys}`);return res.result}async getMultipleAccountsInfo(publicKeys,commitmentOrConfig){return(await this.getMultipleAccountsInfoAndContext(publicKeys,commitmentOrConfig)).value}async getStakeActivation(publicKey,commitmentOrConfig,epoch){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([publicKey.toBase58()],commitment,void 0,{...config,epoch:null!=epoch?epoch:config?.epoch}),res=create(await this._rpcRequest("getStakeActivation",args),jsonRpcResult(StakeActivationResult));if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get Stake Activation ${publicKey.toBase58()}`);return res.result}async getProgramAccounts(programId,configOrCommitment){const{commitment,config}=extractCommitmentFromConfig(configOrCommitment),{encoding,...configWithoutEncoding}=config||{},args=this._buildArgs([programId.toBase58()],commitment,encoding||"base64",{...configWithoutEncoding,...configWithoutEncoding.filters?{filters:applyDefaultMemcmpEncodingToFilters(configWithoutEncoding.filters)}:null}),unsafeRes=await this._rpcRequest("getProgramAccounts",args),baseSchema=array(KeyedAccountInfoResult),res=!0===configWithoutEncoding.withContext?create(unsafeRes,jsonRpcResultAndContext(baseSchema)):create(unsafeRes,jsonRpcResult(baseSchema));if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get accounts owned by program ${programId.toBase58()}`);return res.result}async getParsedProgramAccounts(programId,configOrCommitment){const{commitment,config}=extractCommitmentFromConfig(configOrCommitment),args=this._buildArgs([programId.toBase58()],commitment,"jsonParsed",config),res=create(await this._rpcRequest("getProgramAccounts",args),jsonRpcResult(array(KeyedParsedAccountInfoResult)));if("error"in res)throw new SolanaJSONRPCError(res.error,`failed to get accounts owned by program ${programId.toBase58()}`);return res.result}async confirmTransaction(strategy,commitment){let rawSignature,decodedSignature;if("string"==typeof strategy)rawSignature=strategy;else{const config=strategy;if(config.abortSignal?.aborted)return Promise.reject(config.abortSignal.reason);rawSignature=config.signature}try{decodedSignature=bs58_default().decode(rawSignature)}catch(err){throw new Error("signature must be base58 encoded: "+rawSignature)}return index_browser_esm_assert(64===decodedSignature.length,"signature has invalid length"),"string"==typeof strategy?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:commitment||this.commitment,signature:rawSignature}):"lastValidBlockHeight"in strategy?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:commitment||this.commitment,strategy}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:commitment||this.commitment,strategy})}getCancellationPromise(signal){return new Promise((_,reject)=>{null!=signal&&(signal.aborted?reject(signal.reason):signal.addEventListener("abort",()=>{reject(signal.reason)}))})}getTransactionConfirmationPromise({commitment,signature}){let signatureSubscriptionId,disposeSignatureSubscriptionStateChangeObserver,done=!1;return{abortConfirmation:()=>{disposeSignatureSubscriptionStateChangeObserver&&(disposeSignatureSubscriptionStateChangeObserver(),disposeSignatureSubscriptionStateChangeObserver=void 0),null!=signatureSubscriptionId&&(this.removeSignatureListener(signatureSubscriptionId),signatureSubscriptionId=void 0)},confirmationPromise:new Promise((resolve,reject)=>{try{signatureSubscriptionId=this.onSignature(signature,(result,context)=>{signatureSubscriptionId=void 0;const response={context,value:result};resolve({__type:TransactionStatus.PROCESSED,response})},commitment);const subscriptionSetupPromise=new Promise(resolveSubscriptionSetup=>{null==signatureSubscriptionId?resolveSubscriptionSetup():disposeSignatureSubscriptionStateChangeObserver=this._onSubscriptionStateChange(signatureSubscriptionId,nextState=>{"subscribed"===nextState&&resolveSubscriptionSetup()})});(async()=>{if(await subscriptionSetupPromise,done)return;const response=await this.getSignatureStatus(signature);if(done)return;if(null==response)return;const{context,value}=response;if(null!=value)if(value?.err)reject(value.err);else{switch(commitment){case"confirmed":case"single":case"singleGossip":if("processed"===value.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===value.confirmationStatus||"confirmed"===value.confirmationStatus)return}done=!0,resolve({__type:TransactionStatus.PROCESSED,response:{context,value}})}})()}catch(err){reject(err)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment,strategy:{abortSignal,lastValidBlockHeight,signature}}){let done=!1;const expiryPromise=new Promise(resolve=>{const checkBlockHeight=async()=>{try{return await this.getBlockHeight(commitment)}catch(_e){return-1}};(async()=>{let currentBlockHeight=await checkBlockHeight();if(!done){for(;currentBlockHeight<=lastValidBlockHeight;){if(await sleep(1e3),done)return;if(currentBlockHeight=await checkBlockHeight(),done)return}resolve({__type:TransactionStatus.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation,confirmationPromise}=this.getTransactionConfirmationPromise({commitment,signature}),cancellationPromise=this.getCancellationPromise(abortSignal);let result;try{const outcome=await Promise.race([cancellationPromise,confirmationPromise,expiryPromise]);if(outcome.__type!==TransactionStatus.PROCESSED)throw new TransactionExpiredBlockheightExceededError(signature);result=outcome.response}finally{done=!0,abortConfirmation()}return result}async confirmTransactionUsingDurableNonceStrategy({commitment,strategy:{abortSignal,minContextSlot,nonceAccountPubkey,nonceValue,signature}}){let done=!1;const expiryPromise=new Promise(resolve=>{let currentNonceValue=nonceValue,lastCheckedSlot=null;const getCurrentNonceValue=async()=>{try{const{context,value:nonceAccount}=await this.getNonceAndContext(nonceAccountPubkey,{commitment,minContextSlot});return lastCheckedSlot=context.slot,nonceAccount?.nonce}catch(e){return currentNonceValue}};(async()=>{if(currentNonceValue=await getCurrentNonceValue(),!done)for(;;){if(nonceValue!==currentNonceValue)return void resolve({__type:TransactionStatus.NONCE_INVALID,slotInWhichNonceDidAdvance:lastCheckedSlot});if(await sleep(2e3),done)return;if(currentNonceValue=await getCurrentNonceValue(),done)return}})()}),{abortConfirmation,confirmationPromise}=this.getTransactionConfirmationPromise({commitment,signature}),cancellationPromise=this.getCancellationPromise(abortSignal);let result;try{const outcome=await Promise.race([cancellationPromise,confirmationPromise,expiryPromise]);if(outcome.__type===TransactionStatus.PROCESSED)result=outcome.response;else{let signatureStatus;for(;;){const status=await this.getSignatureStatus(signature);if(null==status)break;if(!(status.context.slot<(outcome.slotInWhichNonceDidAdvance??minContextSlot))){signatureStatus=status;break}await sleep(400)}if(!signatureStatus?.value)throw new TransactionExpiredNonceInvalidError(signature);{const commitmentForStatus=commitment||"finalized",{confirmationStatus}=signatureStatus.value;switch(commitmentForStatus){case"processed":case"recent":if("processed"!==confirmationStatus&&"confirmed"!==confirmationStatus&&"finalized"!==confirmationStatus)throw new TransactionExpiredNonceInvalidError(signature);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==confirmationStatus&&"finalized"!==confirmationStatus)throw new TransactionExpiredNonceInvalidError(signature);break;case"finalized":case"max":case"root":if("finalized"!==confirmationStatus)throw new TransactionExpiredNonceInvalidError(signature)}result={context:signatureStatus.context,value:{err:signatureStatus.value.err}}}}}finally{done=!0,abortConfirmation()}return result}async confirmTransactionUsingLegacyTimeoutStrategy({commitment,signature}){let timeoutId;const expiryPromise=new Promise(resolve=>{let timeoutMs=this._confirmTransactionInitialTimeout||6e4;switch(commitment){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":timeoutMs=this._confirmTransactionInitialTimeout||3e4}timeoutId=setTimeout(()=>resolve({__type:TransactionStatus.TIMED_OUT,timeoutMs}),timeoutMs)}),{abortConfirmation,confirmationPromise}=this.getTransactionConfirmationPromise({commitment,signature});let result;try{const outcome=await Promise.race([confirmationPromise,expiryPromise]);if(outcome.__type!==TransactionStatus.PROCESSED)throw new TransactionExpiredTimeoutError(signature,outcome.timeoutMs/1e3);result=outcome.response}finally{clearTimeout(timeoutId),abortConfirmation()}return result}async getClusterNodes(){const res=create(await this._rpcRequest("getClusterNodes",[]),jsonRpcResult(array(ContactInfoResult)));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get cluster nodes");return res.result}async getVoteAccounts(commitment){const args=this._buildArgs([],commitment),res=create(await this._rpcRequest("getVoteAccounts",args),GetVoteAccounts);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get vote accounts");return res.result}async getSlot(commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([],commitment,void 0,config),res=create(await this._rpcRequest("getSlot",args),jsonRpcResult(number()));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get slot");return res.result}async getSlotLeader(commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([],commitment,void 0,config),res=create(await this._rpcRequest("getSlotLeader",args),jsonRpcResult(string()));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get slot leader");return res.result}async getSlotLeaders(startSlot,limit){const args=[startSlot,limit],res=create(await this._rpcRequest("getSlotLeaders",args),jsonRpcResult(array(PublicKeyFromString)));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get slot leaders");return res.result}async getSignatureStatus(signature,config){const{context,value:values}=await this.getSignatureStatuses([signature],config);index_browser_esm_assert(1===values.length);return{context,value:values[0]}}async getSignatureStatuses(signatures,config){const params=[signatures];config&¶ms.push(config);const res=create(await this._rpcRequest("getSignatureStatuses",params),GetSignatureStatusesRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get signature status");return res.result}async getTransactionCount(commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([],commitment,void 0,config),res=create(await this._rpcRequest("getTransactionCount",args),jsonRpcResult(number()));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get transaction count");return res.result}async getTotalSupply(commitment){return(await this.getSupply({commitment,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(commitment){const args=this._buildArgs([],commitment),res=create(await this._rpcRequest("getInflationGovernor",args),GetInflationGovernorRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get inflation");return res.result}async getInflationReward(addresses,epoch,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([addresses.map(pubkey=>pubkey.toBase58())],commitment,void 0,{...config,epoch:null!=epoch?epoch:config?.epoch}),res=create(await this._rpcRequest("getInflationReward",args),GetInflationRewardResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get inflation reward");return res.result}async getInflationRate(){const res=create(await this._rpcRequest("getInflationRate",[]),GetInflationRateRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get inflation rate");return res.result}async getEpochInfo(commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([],commitment,void 0,config),res=create(await this._rpcRequest("getEpochInfo",args),GetEpochInfoRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get epoch info");return res.result}async getEpochSchedule(){const res=create(await this._rpcRequest("getEpochSchedule",[]),GetEpochScheduleRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get epoch schedule");const epochSchedule=res.result;return new EpochSchedule(epochSchedule.slotsPerEpoch,epochSchedule.leaderScheduleSlotOffset,epochSchedule.warmup,epochSchedule.firstNormalEpoch,epochSchedule.firstNormalSlot)}async getLeaderSchedule(){const res=create(await this._rpcRequest("getLeaderSchedule",[]),GetLeaderScheduleRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get leader schedule");return res.result}async getMinimumBalanceForRentExemption(dataLength,commitment){const args=this._buildArgs([dataLength],commitment),res=create(await this._rpcRequest("getMinimumBalanceForRentExemption",args),GetMinimumBalanceForRentExemptionRpcResult);return"error"in res?(console.warn("Unable to fetch minimum balance for rent exemption"),0):res.result}async getRecentBlockhashAndContext(commitment){const{context,value:{blockhash}}=await this.getLatestBlockhashAndContext(commitment);return{context,value:{blockhash,feeCalculator:{get lamportsPerSignature(){throw new Error("The capability to fetch `lamportsPerSignature` using the `getRecentBlockhash` API is no longer offered by the network. Use the `getFeeForMessage` API to obtain the fee for a given message.")},toJSON:()=>({})}}}}async getRecentPerformanceSamples(limit){const res=create(await this._rpcRequest("getRecentPerformanceSamples",limit?[limit]:[]),GetRecentPerformanceSamplesRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get recent performance samples");return res.result}async getFeeCalculatorForBlockhash(blockhash,commitment){const args=this._buildArgs([blockhash],commitment),res=create(await this._rpcRequest("getFeeCalculatorForBlockhash",args),GetFeeCalculatorRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get fee calculator");const{context,value}=res.result;return{context,value:null!==value?value.feeCalculator:null}}async getFeeForMessage(message,commitment){const wireMessage=toBuffer(message.serialize()).toString("base64"),args=this._buildArgs([wireMessage],commitment),res=create(await this._rpcRequest("getFeeForMessage",args),jsonRpcResultAndContext(nullable(number())));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get fee for message");if(null===res.result)throw new Error("invalid blockhash");return res.result}async getRecentPrioritizationFees(config){const accounts=config?.lockedWritableAccounts?.map(key=>key.toBase58()),args=accounts?.length?[accounts]:[],res=create(await this._rpcRequest("getRecentPrioritizationFees",args),GetRecentPrioritizationFeesRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get recent prioritization fees");return res.result}async getRecentBlockhash(commitment){try{return(await this.getRecentBlockhashAndContext(commitment)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhash(commitmentOrConfig){try{return(await this.getLatestBlockhashAndContext(commitmentOrConfig)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhashAndContext(commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([],commitment,void 0,config),res=create(await this._rpcRequest("getLatestBlockhash",args),GetLatestBlockhashRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get latest blockhash");return res.result}async isBlockhashValid(blockhash,rawConfig){const{commitment,config}=extractCommitmentFromConfig(rawConfig),args=this._buildArgs([blockhash],commitment,void 0,config),res=create(await this._rpcRequest("isBlockhashValid",args),IsBlockhashValidRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to determine if the blockhash `"+blockhash+"`is valid");return res.result}async getVersion(){const res=create(await this._rpcRequest("getVersion",[]),jsonRpcResult(VersionResult));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get version");return res.result}async getGenesisHash(){const res=create(await this._rpcRequest("getGenesisHash",[]),jsonRpcResult(string()));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get genesis hash");return res.result}async getBlock(slot,rawConfig){const{commitment,config}=extractCommitmentFromConfig(rawConfig),args=this._buildArgsAtLeastConfirmed([slot],commitment,void 0,config),unsafeRes=await this._rpcRequest("getBlock",args);try{switch(config?.transactionDetails){case"accounts":{const res=create(unsafeRes,GetAccountsModeBlockRpcResult);if("error"in res)throw res.error;return res.result}case"none":{const res=create(unsafeRes,GetNoneModeBlockRpcResult);if("error"in res)throw res.error;return res.result}default:{const res=create(unsafeRes,GetBlockRpcResult);if("error"in res)throw res.error;const{result}=res;return result?{...result,transactions:result.transactions.map(({transaction,meta,version})=>({meta,transaction:{...transaction,message:versionedMessageFromResponse(version,transaction.message)},version}))}:null}}}catch(e){throw new SolanaJSONRPCError(e,"failed to get confirmed block")}}async getParsedBlock(slot,rawConfig){const{commitment,config}=extractCommitmentFromConfig(rawConfig),args=this._buildArgsAtLeastConfirmed([slot],commitment,"jsonParsed",config),unsafeRes=await this._rpcRequest("getBlock",args);try{switch(config?.transactionDetails){case"accounts":{const res=create(unsafeRes,GetParsedAccountsModeBlockRpcResult);if("error"in res)throw res.error;return res.result}case"none":{const res=create(unsafeRes,GetParsedNoneModeBlockRpcResult);if("error"in res)throw res.error;return res.result}default:{const res=create(unsafeRes,GetParsedBlockRpcResult);if("error"in res)throw res.error;return res.result}}}catch(e){throw new SolanaJSONRPCError(e,"failed to get block")}}async getBlockProduction(configOrCommitment){let extra,commitment;if("string"==typeof configOrCommitment)commitment=configOrCommitment;else if(configOrCommitment){const{commitment:c,...rest}=configOrCommitment;commitment=c,extra=rest}const args=this._buildArgs([],commitment,"base64",extra),res=create(await this._rpcRequest("getBlockProduction",args),BlockProductionResponseStruct);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get block production information");return res.result}async getTransaction(signature,rawConfig){const{commitment,config}=extractCommitmentFromConfig(rawConfig),args=this._buildArgsAtLeastConfirmed([signature],commitment,void 0,config),res=create(await this._rpcRequest("getTransaction",args),GetTransactionRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get transaction");const result=res.result;return result?{...result,transaction:{...result.transaction,message:versionedMessageFromResponse(result.version,result.transaction.message)}}:result}async getParsedTransaction(signature,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed",config),res=create(await this._rpcRequest("getTransaction",args),GetParsedTransactionRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get transaction");return res.result}async getParsedTransactions(signatures,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),batch=signatures.map(signature=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed",config)}));return(await this._rpcBatchRequest(batch)).map(unsafeRes=>{const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get transactions");return res.result})}async getTransactions(signatures,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),batch=signatures.map(signature=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([signature],commitment,void 0,config)}));return(await this._rpcBatchRequest(batch)).map(unsafeRes=>{const res=create(unsafeRes,GetTransactionRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get transactions");const result=res.result;return result?{...result,transaction:{...result.transaction,message:versionedMessageFromResponse(result.version,result.transaction.message)}}:result})}async getConfirmedBlock(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment),res=create(await this._rpcRequest("getBlock",args),GetConfirmedBlockRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get confirmed block");const result=res.result;if(!result)throw new Error("Confirmed block "+slot+" not found");const block={...result,transactions:result.transactions.map(({transaction,meta})=>{const message=new Message(transaction.message);return{meta,transaction:{...transaction,message}}})};return{...block,transactions:block.transactions.map(({transaction,meta})=>({meta,transaction:Transaction.populate(transaction.message,transaction.signatures)}))}}async getBlocks(startSlot,endSlot,commitment){const args=this._buildArgsAtLeastConfirmed(void 0!==endSlot?[startSlot,endSlot]:[startSlot],commitment),res=create(await this._rpcRequest("getBlocks",args),jsonRpcResult(array(number())));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get blocks");return res.result}async getBlockSignatures(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment,void 0,{transactionDetails:"signatures",rewards:!1}),res=create(await this._rpcRequest("getBlock",args),GetBlockSignaturesRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get block");const result=res.result;if(!result)throw new Error("Block "+slot+" not found");return result}async getConfirmedBlockSignatures(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment,void 0,{transactionDetails:"signatures",rewards:!1}),res=create(await this._rpcRequest("getBlock",args),GetBlockSignaturesRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get confirmed block");const result=res.result;if(!result)throw new Error("Confirmed block "+slot+" not found");return result}async getConfirmedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment),res=create(await this._rpcRequest("getTransaction",args),GetTransactionRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get transaction");const result=res.result;if(!result)return result;const message=new Message(result.transaction.message),signatures=result.transaction.signatures;return{...result,transaction:Transaction.populate(message,signatures)}}async getParsedConfirmedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed"),res=create(await this._rpcRequest("getTransaction",args),GetParsedTransactionRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get confirmed transaction");return res.result}async getParsedConfirmedTransactions(signatures,commitment){const batch=signatures.map(signature=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed")}));return(await this._rpcBatchRequest(batch)).map(unsafeRes=>{const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get confirmed transactions");return res.result})}async getConfirmedSignaturesForAddress(address,startSlot,endSlot){let options={},firstAvailableBlock=await this.getFirstAvailableBlock();for(;!("until"in options)&&!(--startSlot<=0||startSlot0&&(options.until=block.signatures[block.signatures.length-1].toString())}catch(err){if(err instanceof Error&&err.message.includes("skipped"))continue;throw err}let highestConfirmedRoot=await this.getSlot("finalized");for(;!("before"in options||++endSlot>highestConfirmedRoot);)try{const block=await this.getConfirmedBlockSignatures(endSlot);block.signatures.length>0&&(options.before=block.signatures[block.signatures.length-1].toString())}catch(err){if(err instanceof Error&&err.message.includes("skipped"))continue;throw err}return(await this.getConfirmedSignaturesForAddress2(address,options)).map(info=>info.signature)}async getConfirmedSignaturesForAddress2(address,options,commitment){const args=this._buildArgsAtLeastConfirmed([address.toBase58()],commitment,void 0,options),res=create(await this._rpcRequest("getConfirmedSignaturesForAddress2",args),GetConfirmedSignaturesForAddress2RpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get confirmed signatures for address");return res.result}async getSignaturesForAddress(address,options,commitment){const args=this._buildArgsAtLeastConfirmed([address.toBase58()],commitment,void 0,options),res=create(await this._rpcRequest("getSignaturesForAddress",args),GetSignaturesForAddressRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get signatures for address");return res.result}async getAddressLookupTable(accountKey,config){const{context,value:accountInfo}=await this.getAccountInfoAndContext(accountKey,config);let value=null;return null!==accountInfo&&(value=new AddressLookupTableAccount({key:accountKey,state:AddressLookupTableAccount.deserialize(accountInfo.data)})),{context,value}}async getNonceAndContext(nonceAccount,commitmentOrConfig){const{context,value:accountInfo}=await this.getAccountInfoAndContext(nonceAccount,commitmentOrConfig);let value=null;return null!==accountInfo&&(value=NonceAccount.fromAccountData(accountInfo.data)),{context,value}}async getNonce(nonceAccount,commitmentOrConfig){return await this.getNonceAndContext(nonceAccount,commitmentOrConfig).then(x=>x.value).catch(e=>{throw new Error("failed to get nonce for account "+nonceAccount.toBase58()+": "+e)})}async requestAirdrop(to,lamports){const res=create(await this._rpcRequest("requestAirdrop",[to.toBase58(),lamports]),RequestAirdropRpcResult);if("error"in res)throw new SolanaJSONRPCError(res.error,`airdrop to ${to.toBase58()} failed`);return res.result}async _blockhashWithExpiryBlockHeight(disableCache){if(!disableCache){for(;this._pollingBlockhash;)await sleep(100);const expired=Date.now()-this._blockhashInfo.lastFetch>=BLOCKHASH_CACHE_TIMEOUT_MS;if(null!==this._blockhashInfo.latestBlockhash&&!expired)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const startTime=Date.now(),cachedLatestBlockhash=this._blockhashInfo.latestBlockhash,cachedBlockhash=cachedLatestBlockhash?cachedLatestBlockhash.blockhash:null;for(let i=0;i<50;i++){const latestBlockhash=await this.getLatestBlockhash("finalized");if(cachedBlockhash!==latestBlockhash.blockhash)return this._blockhashInfo={latestBlockhash,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},latestBlockhash;await sleep(200)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-startTime}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(config){const{commitment,config:configArg}=extractCommitmentFromConfig(config),args=this._buildArgs([],commitment,"base64",configArg),res=create(await this._rpcRequest("getStakeMinimumDelegation",args),jsonRpcResultAndContext(number()));if("error"in res)throw new SolanaJSONRPCError(res.error,"failed to get stake minimum delegation");return res.result}async simulateTransaction(transactionOrMessage,configOrSigners,includeAccounts){if("message"in transactionOrMessage){const wireTransaction=transactionOrMessage.serialize(),encodedTransaction=node_modules_buffer.Buffer.from(wireTransaction).toString("base64");if(Array.isArray(configOrSigners)||void 0!==includeAccounts)throw new Error("Invalid arguments");const config=configOrSigners||{};config.encoding="base64","commitment"in config||(config.commitment=this.commitment),configOrSigners&&"object"==typeof configOrSigners&&"innerInstructions"in configOrSigners&&(config.innerInstructions=configOrSigners.innerInstructions);const args=[encodedTransaction,config],res=create(await this._rpcRequest("simulateTransaction",args),SimulatedTransactionResponseStruct);if("error"in res)throw new Error("failed to simulate transaction: "+res.error.message);return res.result}let transaction;if(transactionOrMessage instanceof Transaction){let originalTx=transactionOrMessage;transaction=new Transaction,transaction.feePayer=originalTx.feePayer,transaction.instructions=transactionOrMessage.instructions,transaction.nonceInfo=originalTx.nonceInfo,transaction.signatures=originalTx.signatures}else transaction=Transaction.populate(transactionOrMessage),transaction._message=transaction._json=void 0;if(void 0!==configOrSigners&&!Array.isArray(configOrSigners))throw new Error("Invalid arguments");const signers=configOrSigners;if(transaction.nonceInfo&&signers)transaction.sign(...signers);else{let disableCache=this._disableBlockhashCaching;for(;;){const latestBlockhash=await this._blockhashWithExpiryBlockHeight(disableCache);if(transaction.lastValidBlockHeight=latestBlockhash.lastValidBlockHeight,transaction.recentBlockhash=latestBlockhash.blockhash,!signers)break;if(transaction.sign(...signers),!transaction.signature)throw new Error("!signature");const signature=transaction.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(signature)&&!this._blockhashInfo.transactionSignatures.includes(signature)){this._blockhashInfo.simulatedSignatures.push(signature);break}disableCache=!0}}const message=transaction._compile(),signData=message.serialize(),encodedTransaction=transaction._serialize(signData).toString("base64"),config={encoding:"base64",commitment:this.commitment};if(includeAccounts){const addresses=(Array.isArray(includeAccounts)?includeAccounts:message.nonProgramIds()).map(key=>key.toBase58());config.accounts={encoding:"base64",addresses}}signers&&(config.sigVerify=!0),configOrSigners&&"object"==typeof configOrSigners&&"innerInstructions"in configOrSigners&&(config.innerInstructions=configOrSigners.innerInstructions);const args=[encodedTransaction,config],res=create(await this._rpcRequest("simulateTransaction",args),SimulatedTransactionResponseStruct);if("error"in res){let logs;if("data"in res.error&&(logs=res.error.data.logs,logs&&Array.isArray(logs))){const traceIndent="\n ",logTrace=traceIndent+logs.join(traceIndent);console.error(res.error.message,logTrace)}throw new SendTransactionError({action:"simulate",signature:"",transactionMessage:res.error.message,logs})}return res.result}async sendTransaction(transaction,signersOrOptions,options){if("version"in transaction){if(signersOrOptions&&Array.isArray(signersOrOptions))throw new Error("Invalid arguments");const wireTransaction=transaction.serialize();return await this.sendRawTransaction(wireTransaction,signersOrOptions)}if(void 0===signersOrOptions||!Array.isArray(signersOrOptions))throw new Error("Invalid arguments");const signers=signersOrOptions;if(transaction.nonceInfo)transaction.sign(...signers);else{let disableCache=this._disableBlockhashCaching;for(;;){const latestBlockhash=await this._blockhashWithExpiryBlockHeight(disableCache);if(transaction.lastValidBlockHeight=latestBlockhash.lastValidBlockHeight,transaction.recentBlockhash=latestBlockhash.blockhash,transaction.sign(...signers),!transaction.signature)throw new Error("!signature");const signature=transaction.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(signature)){this._blockhashInfo.transactionSignatures.push(signature);break}disableCache=!0}}const wireTransaction=transaction.serialize();return await this.sendRawTransaction(wireTransaction,options)}async sendRawTransaction(rawTransaction,options){const encodedTransaction=toBuffer(rawTransaction).toString("base64");return await this.sendEncodedTransaction(encodedTransaction,options)}async sendEncodedTransaction(encodedTransaction,options){const config={encoding:"base64"},skipPreflight=options&&options.skipPreflight,preflightCommitment=!0===skipPreflight?"processed":options&&options.preflightCommitment||this.commitment;options&&null!=options.maxRetries&&(config.maxRetries=options.maxRetries),options&&null!=options.minContextSlot&&(config.minContextSlot=options.minContextSlot),skipPreflight&&(config.skipPreflight=skipPreflight),preflightCommitment&&(config.preflightCommitment=preflightCommitment);const args=[encodedTransaction,config],res=create(await this._rpcRequest("sendTransaction",args),SendTransactionRpcResult);if("error"in res){let logs;throw"data"in res.error&&(logs=res.error.data.logs),new SendTransactionError({action:skipPreflight?"send":"simulate",signature:"",transactionMessage:res.error.message,logs})}return res.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(err){this._rpcWebSocketConnected=!1,console.error("ws error:",err.message)}_wsOnClose(code){this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3!==code?(this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([hash,subscription])=>{this._setSubscription(hash,{...subscription,state:"pending"})})):this._updateSubscriptions()}_setSubscription(hash,nextSubscription){const prevState=this._subscriptionsByHash[hash]?.state;if(this._subscriptionsByHash[hash]=nextSubscription,prevState!==nextSubscription.state){const stateChangeCallbacks=this._subscriptionStateChangeCallbacksByHash[hash];stateChangeCallbacks&&stateChangeCallbacks.forEach(cb=>{try{cb(nextSubscription.state)}catch{}})}}_onSubscriptionStateChange(clientSubscriptionId,callback){const hash=this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];if(null==hash)return()=>{};const stateChangeCallbacks=this._subscriptionStateChangeCallbacksByHash[hash]||=new Set;return stateChangeCallbacks.add(callback),()=>{stateChangeCallbacks.delete(callback),0===stateChangeCallbacks.size&&delete this._subscriptionStateChangeCallbacksByHash[hash]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length)return void(this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(err){err instanceof Error&&console.log(`Error when closing socket connection: ${err.message}`)}},500)));if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected)return void this._rpcWebSocket.connect();const activeWebSocketGeneration=this._rpcWebSocketGeneration,isCurrentConnectionStillActive=()=>activeWebSocketGeneration===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async hash=>{const subscription=this._subscriptionsByHash[hash];if(void 0!==subscription)switch(subscription.state){case"pending":case"unsubscribed":if(0===subscription.callbacks.size)return delete this._subscriptionsByHash[hash],"unsubscribed"===subscription.state&&delete this._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId],void await this._updateSubscriptions();await(async()=>{const{args,method}=subscription;try{this._setSubscription(hash,{...subscription,state:"subscribing"});const serverSubscriptionId=await this._rpcWebSocket.call(method,args);this._setSubscription(hash,{...subscription,serverSubscriptionId,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId]=subscription.callbacks,await this._updateSubscriptions()}catch(e){if(console.error(`Received ${e instanceof Error?"":"JSON-RPC "}error calling \`${method}\``,{args,error:e}),!isCurrentConnectionStillActive())return;this._setSubscription(hash,{...subscription,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===subscription.callbacks.size&&await(async()=>{const{serverSubscriptionId,unsubscribeMethod}=subscription;if(this._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId))this._subscriptionsAutoDisposedByRpc.delete(serverSubscriptionId);else{this._setSubscription(hash,{...subscription,state:"unsubscribing"}),this._setSubscription(hash,{...subscription,state:"unsubscribing"});try{await this._rpcWebSocket.call(unsubscribeMethod,[serverSubscriptionId])}catch(e){if(e instanceof Error&&console.error(`${unsubscribeMethod} error:`,e.message),!isCurrentConnectionStillActive())return;return this._setSubscription(hash,{...subscription,state:"subscribed"}),void await this._updateSubscriptions()}}this._setSubscription(hash,{...subscription,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(serverSubscriptionId,callbackArgs){const callbacks=this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId];void 0!==callbacks&&callbacks.forEach(cb=>{try{cb(...callbackArgs)}catch(e){console.error(e)}})}_wsOnAccountNotification(notification){const{result,subscription}=create(notification,AccountNotificationResult);this._handleServerNotification(subscription,[result.value,result.context])}_makeSubscription(subscriptionConfig,args){const clientSubscriptionId=this._nextClientSubscriptionId++,hash=fastStableStringify([subscriptionConfig.method,args]),existingSubscription=this._subscriptionsByHash[hash];return void 0===existingSubscription?this._subscriptionsByHash[hash]={...subscriptionConfig,args,callbacks:new Set([subscriptionConfig.callback]),state:"pending"}:existingSubscription.callbacks.add(subscriptionConfig.callback),this._subscriptionHashByClientSubscriptionId[clientSubscriptionId]=hash,this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId],delete this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];const subscription=this._subscriptionsByHash[hash];index_browser_esm_assert(void 0!==subscription,`Could not find a \`Subscription\` when tearing down client subscription #${clientSubscriptionId}`),subscription.callbacks.delete(subscriptionConfig.callback),await this._updateSubscriptions()},this._updateSubscriptions(),clientSubscriptionId}onAccountChange(publicKey,callback,commitmentOrConfig){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([publicKey.toBase58()],commitment||this._commitment||"finalized","base64",config);return this._makeSubscription({callback,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},args)}async removeAccountChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"account change")}_wsOnProgramAccountNotification(notification){const{result,subscription}=create(notification,ProgramAccountNotificationResult);this._handleServerNotification(subscription,[{accountId:result.value.pubkey,accountInfo:result.value.account},result.context])}onProgramAccountChange(programId,callback,commitmentOrConfig,maybeFilters){const{commitment,config}=extractCommitmentFromConfig(commitmentOrConfig),args=this._buildArgs([programId.toBase58()],commitment||this._commitment||"finalized","base64",config||(maybeFilters?{filters:applyDefaultMemcmpEncodingToFilters(maybeFilters)}:void 0));return this._makeSubscription({callback,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},args)}async removeProgramAccountChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"program account change")}onLogs(filter,callback,commitment){const args=this._buildArgs(["object"==typeof filter?{mentions:[filter.toString()]}:filter],commitment||this._commitment||"finalized");return this._makeSubscription({callback,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},args)}async removeOnLogsListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"logs")}_wsOnLogsNotification(notification){const{result,subscription}=create(notification,LogsNotificationResult);this._handleServerNotification(subscription,[result.value,result.context])}_wsOnSlotNotification(notification){const{result,subscription}=create(notification,SlotNotificationResult);this._handleServerNotification(subscription,[result])}onSlotChange(callback){return this._makeSubscription({callback,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"slot change")}_wsOnSlotUpdatesNotification(notification){const{result,subscription}=create(notification,SlotUpdateNotificationResult);this._handleServerNotification(subscription,[result])}onSlotUpdate(callback){return this._makeSubscription({callback,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"slot update")}async _unsubscribeClientSubscription(clientSubscriptionId,subscriptionName){const dispose=this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];dispose?await dispose():console.warn(`Ignored unsubscribe request because an active subscription with id \`${clientSubscriptionId}\` for '${subscriptionName}' events could not be found.`)}_buildArgs(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment||encoding||extra){let options={};encoding&&(options.encoding=encoding),commitment&&(options.commitment=commitment),extra&&(options=Object.assign(options,extra)),args.push(options)}return args}_buildArgsAtLeastConfirmed(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment&&!["confirmed","finalized"].includes(commitment))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(args,override,encoding,extra)}_wsOnSignatureNotification(notification){const{result,subscription}=create(notification,SignatureNotificationResult);"receivedSignature"!==result.value&&this._subscriptionsAutoDisposedByRpc.add(subscription),this._handleServerNotification(subscription,"receivedSignature"===result.value?[{type:"received"},result.context]:[{type:"status",result:result.value},result.context])}onSignature(signature,callback,commitment){const args=this._buildArgs([signature],commitment||this._commitment||"finalized"),clientSubscriptionId=this._makeSubscription({callback:(notification,context)=>{if("status"===notification.type){callback(notification.result,context);try{this.removeSignatureListener(clientSubscriptionId)}catch(_err){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},args);return clientSubscriptionId}onSignatureWithOptions(signature,callback,options){const{commitment,...extra}={...options,commitment:options&&options.commitment||this._commitment||"finalized"},args=this._buildArgs([signature],commitment,void 0,extra),clientSubscriptionId=this._makeSubscription({callback:(notification,context)=>{callback(notification,context);try{this.removeSignatureListener(clientSubscriptionId)}catch(_err){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},args);return clientSubscriptionId}async removeSignatureListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"signature result")}_wsOnRootNotification(notification){const{result,subscription}=create(notification,RootNotificationResult);this._handleServerNotification(subscription,[result])}onRootChange(callback){return this._makeSubscription({callback,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"root change")}}class Keypair{constructor(keypair){this._keypair=void 0,this._keypair=keypair??generateKeypair()}static generate(){return new Keypair(generateKeypair())}static fromSecretKey(secretKey,options){if(64!==secretKey.byteLength)throw new Error("bad secret key size");const publicKey=secretKey.slice(32,64);if(!options||!options.skipValidation){const privateScalar=secretKey.slice(0,32),computedPublicKey=getPublicKey(privateScalar);for(let ii=0;ii<32;ii++)if(publicKey[ii]!==computedPublicKey[ii])throw new Error("provided secretKey is invalid")}return new Keypair({publicKey,secretKey})}static fromSeed(seed){const publicKey=getPublicKey(seed),secretKey=new Uint8Array(64);return secretKey.set(seed),secretKey.set(publicKey,32),new Keypair({publicKey,secretKey})}get publicKey(){return new PublicKey(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}const LOOKUP_TABLE_INSTRUCTION_LAYOUTS=Object.freeze({CreateLookupTable:{index:0,layout:Layout.w3([Layout.DH("instruction"),index_browser_esm_u64("recentSlot"),Layout.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:Layout.w3([Layout.DH("instruction")])},ExtendLookupTable:{index:2,layout:Layout.w3([Layout.DH("instruction"),index_browser_esm_u64(),Layout.O6(publicKey(),Layout.cY(Layout.DH(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:Layout.w3([Layout.DH("instruction")])},CloseLookupTable:{index:4,layout:Layout.w3([Layout.DH("instruction")])}});class AddressLookupTableInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const index=Layout.DH("instruction").decode(instruction.data);let type;for(const[layoutType,layout]of Object.entries(LOOKUP_TABLE_INSTRUCTION_LAYOUTS))if(layout.index==index){type=layoutType;break}if(!type)throw new Error("Invalid Instruction. Should be a LookupTable Instruction");return type}static decodeCreateLookupTable(instruction){this.checkProgramId(instruction.programId),this.checkKeysLength(instruction.keys,4);const{recentSlot}=decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable,instruction.data);return{authority:instruction.keys[1].pubkey,payer:instruction.keys[2].pubkey,recentSlot:Number(recentSlot)}}static decodeExtendLookupTable(instruction){if(this.checkProgramId(instruction.programId),instruction.keys.length<2)throw new Error(`invalid instruction; found ${instruction.keys.length} keys, expected at least 2`);const{addresses}=decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable,instruction.data);return{lookupTable:instruction.keys[0].pubkey,authority:instruction.keys[1].pubkey,payer:instruction.keys.length>2?instruction.keys[2].pubkey:void 0,addresses:addresses.map(buffer=>new PublicKey(buffer))}}static decodeCloseLookupTable(instruction){return this.checkProgramId(instruction.programId),this.checkKeysLength(instruction.keys,3),{lookupTable:instruction.keys[0].pubkey,authority:instruction.keys[1].pubkey,recipient:instruction.keys[2].pubkey}}static decodeFreezeLookupTable(instruction){return this.checkProgramId(instruction.programId),this.checkKeysLength(instruction.keys,2),{lookupTable:instruction.keys[0].pubkey,authority:instruction.keys[1].pubkey}}static decodeDeactivateLookupTable(instruction){return this.checkProgramId(instruction.programId),this.checkKeysLength(instruction.keys,2),{lookupTable:instruction.keys[0].pubkey,authority:instruction.keys[1].pubkey}}static checkProgramId(programId){if(!programId.equals(AddressLookupTableProgram.programId))throw new Error("invalid instruction; programId is not AddressLookupTable Program")}static checkKeysLength(keys,expectedLength){if(keys.lengthaddr.toBytes())}),keys=[{pubkey:params.lookupTable,isSigner:!1,isWritable:!0},{pubkey:params.authority,isSigner:!0,isWritable:!1}];return params.payer&&keys.push({pubkey:params.payer,isSigner:!0,isWritable:!0},{pubkey:SystemProgram.programId,isSigner:!1,isWritable:!1}),new TransactionInstruction({programId:this.programId,keys,data})}static deactivateLookupTable(params){const data=encodeData(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable),keys=[{pubkey:params.lookupTable,isSigner:!1,isWritable:!0},{pubkey:params.authority,isSigner:!0,isWritable:!1}];return new TransactionInstruction({programId:this.programId,keys,data})}static closeLookupTable(params){const data=encodeData(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable),keys=[{pubkey:params.lookupTable,isSigner:!1,isWritable:!0},{pubkey:params.authority,isSigner:!0,isWritable:!1},{pubkey:params.recipient,isSigner:!1,isWritable:!0}];return new TransactionInstruction({programId:this.programId,keys,data})}}AddressLookupTableProgram.programId=new PublicKey("AddressLookupTab1e1111111111111111111111111");class ComputeBudgetInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const typeIndex=Layout.u8("instruction").decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS))if(layout.index==typeIndex){type=ixType;break}if(!type)throw new Error("Instruction type incorrect; not a ComputeBudgetInstruction");return type}static decodeRequestUnits(instruction){this.checkProgramId(instruction.programId);const{units,additionalFee}=decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits,instruction.data);return{units,additionalFee}}static decodeRequestHeapFrame(instruction){this.checkProgramId(instruction.programId);const{bytes}=decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame,instruction.data);return{bytes}}static decodeSetComputeUnitLimit(instruction){this.checkProgramId(instruction.programId);const{units}=decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit,instruction.data);return{units}}static decodeSetComputeUnitPrice(instruction){this.checkProgramId(instruction.programId);const{microLamports}=decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice,instruction.data);return{microLamports}}static checkProgramId(programId){if(!programId.equals(ComputeBudgetProgram.programId))throw new Error("invalid instruction; programId is not ComputeBudgetProgram")}}const COMPUTE_BUDGET_INSTRUCTION_LAYOUTS=Object.freeze({RequestUnits:{index:0,layout:Layout.w3([Layout.u8("instruction"),Layout.DH("units"),Layout.DH("additionalFee")])},RequestHeapFrame:{index:1,layout:Layout.w3([Layout.u8("instruction"),Layout.DH("bytes")])},SetComputeUnitLimit:{index:2,layout:Layout.w3([Layout.u8("instruction"),Layout.DH("units")])},SetComputeUnitPrice:{index:3,layout:Layout.w3([Layout.u8("instruction"),index_browser_esm_u64("microLamports")])}});class ComputeBudgetProgram{constructor(){}static requestUnits(params){const data=encodeData(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits,params);return new TransactionInstruction({keys:[],programId:this.programId,data})}static requestHeapFrame(params){const data=encodeData(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame,params);return new TransactionInstruction({keys:[],programId:this.programId,data})}static setComputeUnitLimit(params){const data=encodeData(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit,params);return new TransactionInstruction({keys:[],programId:this.programId,data})}static setComputeUnitPrice(params){const data=encodeData(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice,{microLamports:BigInt(params.microLamports)});return new TransactionInstruction({keys:[],programId:this.programId,data})}}ComputeBudgetProgram.programId=new PublicKey("ComputeBudget111111111111111111111111111111");const ED25519_INSTRUCTION_LAYOUT=Layout.w3([Layout.u8("numSignatures"),Layout.u8("padding"),Layout.NX("signatureOffset"),Layout.NX("signatureInstructionIndex"),Layout.NX("publicKeyOffset"),Layout.NX("publicKeyInstructionIndex"),Layout.NX("messageDataOffset"),Layout.NX("messageDataSize"),Layout.NX("messageInstructionIndex")]);class Ed25519Program{constructor(){}static createInstructionWithPublicKey(params){const{publicKey,message,signature,instructionIndex}=params;index_browser_esm_assert(32===publicKey.length,`Public Key must be 32 bytes but received ${publicKey.length} bytes`),index_browser_esm_assert(64===signature.length,`Signature must be 64 bytes but received ${signature.length} bytes`);const publicKeyOffset=ED25519_INSTRUCTION_LAYOUT.span,signatureOffset=publicKeyOffset+publicKey.length,messageDataOffset=signatureOffset+signature.length,instructionData=node_modules_buffer.Buffer.alloc(messageDataOffset+message.length),index=null==instructionIndex?65535:instructionIndex;return ED25519_INSTRUCTION_LAYOUT.encode({numSignatures:1,padding:0,signatureOffset,signatureInstructionIndex:index,publicKeyOffset,publicKeyInstructionIndex:index,messageDataOffset,messageDataSize:message.length,messageInstructionIndex:index},instructionData),instructionData.fill(publicKey,publicKeyOffset),instructionData.fill(signature,signatureOffset),instructionData.fill(message,messageDataOffset),new TransactionInstruction({keys:[],programId:Ed25519Program.programId,data:instructionData})}static createInstructionWithPrivateKey(params){const{privateKey,message,instructionIndex}=params;index_browser_esm_assert(64===privateKey.length,`Private key must be 64 bytes but received ${privateKey.length} bytes`);try{const keypair=Keypair.fromSecretKey(privateKey),publicKey=keypair.publicKey.toBytes(),signature=sign(message,keypair.secretKey);return this.createInstructionWithPublicKey({publicKey,message,signature,instructionIndex})}catch(error){throw new Error(`Error creating instruction; ${error}`)}}}Ed25519Program.programId=new PublicKey("Ed25519SigVerify111111111111111111111111111");secp256k1.utils.isValidPrivateKey;const publicKeyCreate=secp256k1.getPublicKey,SECP256K1_INSTRUCTION_LAYOUT=Layout.w3([Layout.u8("numSignatures"),Layout.NX("signatureOffset"),Layout.u8("signatureInstructionIndex"),Layout.NX("ethAddressOffset"),Layout.u8("ethAddressInstructionIndex"),Layout.NX("messageDataOffset"),Layout.NX("messageDataSize"),Layout.u8("messageInstructionIndex"),Layout.av(20,"ethAddress"),Layout.av(64,"signature"),Layout.u8("recoveryId")]);class Secp256k1Program{constructor(){}static publicKeyToEthAddress(publicKey){index_browser_esm_assert(64===publicKey.length,`Public key must be 64 bytes but received ${publicKey.length} bytes`);try{return node_modules_buffer.Buffer.from(keccak_256(toBuffer(publicKey))).slice(-20)}catch(error){throw new Error(`Error constructing Ethereum address: ${error}`)}}static createInstructionWithPublicKey(params){const{publicKey,message,signature,recoveryId,instructionIndex}=params;return Secp256k1Program.createInstructionWithEthAddress({ethAddress:Secp256k1Program.publicKeyToEthAddress(publicKey),message,signature,recoveryId,instructionIndex})}static createInstructionWithEthAddress(params){const{ethAddress:rawAddress,message,signature,recoveryId,instructionIndex=0}=params;let ethAddress;ethAddress="string"==typeof rawAddress?rawAddress.startsWith("0x")?node_modules_buffer.Buffer.from(rawAddress.substr(2),"hex"):node_modules_buffer.Buffer.from(rawAddress,"hex"):rawAddress,index_browser_esm_assert(20===ethAddress.length,`Address must be 20 bytes but received ${ethAddress.length} bytes`);const signatureOffset=12+ethAddress.length,messageDataOffset=signatureOffset+signature.length+1,instructionData=node_modules_buffer.Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span+message.length);return SECP256K1_INSTRUCTION_LAYOUT.encode({numSignatures:1,signatureOffset,signatureInstructionIndex:instructionIndex,ethAddressOffset:12,ethAddressInstructionIndex:instructionIndex,messageDataOffset,messageDataSize:message.length,messageInstructionIndex:instructionIndex,signature:toBuffer(signature),ethAddress:toBuffer(ethAddress),recoveryId},instructionData),instructionData.fill(toBuffer(message),SECP256K1_INSTRUCTION_LAYOUT.span),new TransactionInstruction({keys:[],programId:Secp256k1Program.programId,data:instructionData})}static createInstructionWithPrivateKey(params){const{privateKey:pkey,message,instructionIndex}=params;index_browser_esm_assert(32===pkey.length,`Private key must be 32 bytes but received ${pkey.length} bytes`);try{const privateKey=toBuffer(pkey),publicKey=publicKeyCreate(privateKey,!1).slice(1),messageHash=node_modules_buffer.Buffer.from(keccak_256(toBuffer(message))),[signature,recoveryId]=((msgHash,privKey)=>{const signature=secp256k1.sign(msgHash,privKey);return[signature.toCompactRawBytes(),signature.recovery]})(messageHash,privateKey);return this.createInstructionWithPublicKey({publicKey,message,signature,recoveryId,instructionIndex})}catch(error){throw new Error(`Error creating instruction; ${error}`)}}}var _Lockup;Secp256k1Program.programId=new PublicKey("KeccakSecp256k11111111111111111111111111111");const STAKE_CONFIG_ID=new PublicKey("StakeConfig11111111111111111111111111111111");class Authorized{constructor(staker,withdrawer){this.staker=void 0,this.withdrawer=void 0,this.staker=staker,this.withdrawer=withdrawer}}class Lockup{constructor(unixTimestamp,epoch,custodian){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=unixTimestamp,this.epoch=epoch,this.custodian=custodian}}_Lockup=Lockup,Lockup.default=new _Lockup(0,0,PublicKey.default);class StakeInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const typeIndex=Layout.DH("instruction").decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(STAKE_INSTRUCTION_LAYOUTS))if(layout.index==typeIndex){type=ixType;break}if(!type)throw new Error("Instruction type incorrect; not a StakeInstruction");return type}static decodeInitialize(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,2);const{authorized,lockup}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Initialize,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,authorized:new Authorized(new PublicKey(authorized.staker),new PublicKey(authorized.withdrawer)),lockup:new Lockup(lockup.unixTimestamp,lockup.epoch,new PublicKey(lockup.custodian))}}static decodeDelegate(instruction){return this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,6),decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Delegate,instruction.data),{stakePubkey:instruction.keys[0].pubkey,votePubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[5].pubkey}}static decodeAuthorize(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3);const{newAuthorized,stakeAuthorizationType}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Authorize,instruction.data),o={stakePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey,newAuthorizedPubkey:new PublicKey(newAuthorized),stakeAuthorizationType:{index:stakeAuthorizationType}};return instruction.keys.length>3&&(o.custodianPubkey=instruction.keys[3].pubkey),o}static decodeAuthorizeWithSeed(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,2);const{newAuthorized,stakeAuthorizationType,authoritySeed,authorityOwner}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,instruction.data),o={stakePubkey:instruction.keys[0].pubkey,authorityBase:instruction.keys[1].pubkey,authoritySeed,authorityOwner:new PublicKey(authorityOwner),newAuthorizedPubkey:new PublicKey(newAuthorized),stakeAuthorizationType:{index:stakeAuthorizationType}};return instruction.keys.length>3&&(o.custodianPubkey=instruction.keys[3].pubkey),o}static decodeSplit(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3);const{lamports}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Split,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,splitStakePubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[2].pubkey,lamports}}static decodeMerge(instruction){return this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3),decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Merge,instruction.data),{stakePubkey:instruction.keys[0].pubkey,sourceStakePubKey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey}}static decodeWithdraw(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,5);const{lamports}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Withdraw,instruction.data),o={stakePubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey,lamports};return instruction.keys.length>5&&(o.custodianPubkey=instruction.keys[5].pubkey),o}static decodeDeactivate(instruction){return this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3),decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Deactivate,instruction.data),{stakePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey}}static checkProgramId(programId){if(!programId.equals(StakeProgram.programId))throw new Error("invalid instruction; programId is not StakeProgram")}static checkKeyLength(keys,expectedLength){if(keys.lengthLayout.w3([publicKey("staker"),publicKey("withdrawer")],property))(),((property="lockup")=>Layout.w3([Layout.Wg("unixTimestamp"),Layout.Wg("epoch"),publicKey("custodian")],property))()])},Authorize:{index:1,layout:Layout.w3([Layout.DH("instruction"),publicKey("newAuthorized"),Layout.DH("stakeAuthorizationType")])},Delegate:{index:2,layout:Layout.w3([Layout.DH("instruction")])},Split:{index:3,layout:Layout.w3([Layout.DH("instruction"),Layout.Wg("lamports")])},Withdraw:{index:4,layout:Layout.w3([Layout.DH("instruction"),Layout.Wg("lamports")])},Deactivate:{index:5,layout:Layout.w3([Layout.DH("instruction")])},Merge:{index:7,layout:Layout.w3([Layout.DH("instruction")])},AuthorizeWithSeed:{index:8,layout:Layout.w3([Layout.DH("instruction"),publicKey("newAuthorized"),Layout.DH("stakeAuthorizationType"),rustString("authoritySeed"),publicKey("authorityOwner")])}}),StakeAuthorizationLayout=Object.freeze({Staker:{index:0},Withdrawer:{index:1}});class StakeProgram{constructor(){}static initialize(params){const{stakePubkey,authorized,lockup:maybeLockup}=params,lockup=maybeLockup||Lockup.default,data=encodeData(STAKE_INSTRUCTION_LAYOUTS.Initialize,{authorized:{staker:toBuffer(authorized.staker.toBuffer()),withdrawer:toBuffer(authorized.withdrawer.toBuffer())},lockup:{unixTimestamp:lockup.unixTimestamp,epoch:lockup.epoch,custodian:toBuffer(lockup.custodian.toBuffer())}}),instructionData={keys:[{pubkey:stakePubkey,isSigner:!1,isWritable:!0},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:!1,isWritable:!1}],programId:this.programId,data};return new TransactionInstruction(instructionData)}static createAccountWithSeed(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccountWithSeed({fromPubkey:params.fromPubkey,newAccountPubkey:params.stakePubkey,basePubkey:params.basePubkey,seed:params.seed,lamports:params.lamports,space:this.space,programId:this.programId}));const{stakePubkey,authorized,lockup}=params;return transaction.add(this.initialize({stakePubkey,authorized,lockup}))}static createAccount(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.stakePubkey,lamports:params.lamports,space:this.space,programId:this.programId}));const{stakePubkey,authorized,lockup}=params;return transaction.add(this.initialize({stakePubkey,authorized,lockup}))}static delegate(params){const{stakePubkey,authorizedPubkey,votePubkey}=params,data=encodeData(STAKE_INSTRUCTION_LAYOUTS.Delegate);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:!1,isWritable:!0},{pubkey:votePubkey,isSigner:!1,isWritable:!1},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:STAKE_CONFIG_ID,isSigner:!1,isWritable:!1},{pubkey:authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data})}static authorize(params){const{stakePubkey,authorizedPubkey,newAuthorizedPubkey,stakeAuthorizationType,custodianPubkey}=params,data=encodeData(STAKE_INSTRUCTION_LAYOUTS.Authorize,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),stakeAuthorizationType:stakeAuthorizationType.index}),keys=[{pubkey:stakePubkey,isSigner:!1,isWritable:!0},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:!1,isWritable:!0},{pubkey:authorizedPubkey,isSigner:!0,isWritable:!1}];return custodianPubkey&&keys.push({pubkey:custodianPubkey,isSigner:!0,isWritable:!1}),(new Transaction).add({keys,programId:this.programId,data})}static authorizeWithSeed(params){const{stakePubkey,authorityBase,authoritySeed,authorityOwner,newAuthorizedPubkey,stakeAuthorizationType,custodianPubkey}=params,data=encodeData(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),stakeAuthorizationType:stakeAuthorizationType.index,authoritySeed,authorityOwner:toBuffer(authorityOwner.toBuffer())}),keys=[{pubkey:stakePubkey,isSigner:!1,isWritable:!0},{pubkey:authorityBase,isSigner:!0,isWritable:!1},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:!1,isWritable:!1}];return custodianPubkey&&keys.push({pubkey:custodianPubkey,isSigner:!0,isWritable:!1}),(new Transaction).add({keys,programId:this.programId,data})}static splitInstruction(params){const{stakePubkey,authorizedPubkey,splitStakePubkey,lamports}=params,data=encodeData(STAKE_INSTRUCTION_LAYOUTS.Split,{lamports});return new TransactionInstruction({keys:[{pubkey:stakePubkey,isSigner:!1,isWritable:!0},{pubkey:splitStakePubkey,isSigner:!1,isWritable:!0},{pubkey:authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data})}static split(params,rentExemptReserve){const transaction=new Transaction;return transaction.add(SystemProgram.createAccount({fromPubkey:params.authorizedPubkey,newAccountPubkey:params.splitStakePubkey,lamports:rentExemptReserve,space:this.space,programId:this.programId})),transaction.add(this.splitInstruction(params))}static splitWithSeed(params,rentExemptReserve){const{stakePubkey,authorizedPubkey,splitStakePubkey,basePubkey,seed,lamports}=params,transaction=new Transaction;return transaction.add(SystemProgram.allocate({accountPubkey:splitStakePubkey,basePubkey,seed,space:this.space,programId:this.programId})),rentExemptReserve&&rentExemptReserve>0&&transaction.add(SystemProgram.transfer({fromPubkey:params.authorizedPubkey,toPubkey:splitStakePubkey,lamports:rentExemptReserve})),transaction.add(this.splitInstruction({stakePubkey,authorizedPubkey,splitStakePubkey,lamports}))}static merge(params){const{stakePubkey,sourceStakePubKey,authorizedPubkey}=params,data=encodeData(STAKE_INSTRUCTION_LAYOUTS.Merge);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:!1,isWritable:!0},{pubkey:sourceStakePubKey,isSigner:!1,isWritable:!0},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data})}static withdraw(params){const{stakePubkey,authorizedPubkey,toPubkey,lamports,custodianPubkey}=params,data=encodeData(STAKE_INSTRUCTION_LAYOUTS.Withdraw,{lamports}),keys=[{pubkey:stakePubkey,isSigner:!1,isWritable:!0},{pubkey:toPubkey,isSigner:!1,isWritable:!0},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:authorizedPubkey,isSigner:!0,isWritable:!1}];return custodianPubkey&&keys.push({pubkey:custodianPubkey,isSigner:!0,isWritable:!1}),(new Transaction).add({keys,programId:this.programId,data})}static deactivate(params){const{stakePubkey,authorizedPubkey}=params,data=encodeData(STAKE_INSTRUCTION_LAYOUTS.Deactivate);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:!1,isWritable:!0},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data})}}StakeProgram.programId=new PublicKey("Stake11111111111111111111111111111111111111"),StakeProgram.space=200;class VoteInit{constructor(nodePubkey,authorizedVoter,authorizedWithdrawer,commission){this.nodePubkey=void 0,this.authorizedVoter=void 0,this.authorizedWithdrawer=void 0,this.commission=void 0,this.nodePubkey=nodePubkey,this.authorizedVoter=authorizedVoter,this.authorizedWithdrawer=authorizedWithdrawer,this.commission=commission}}class VoteInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const typeIndex=Layout.DH("instruction").decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(VOTE_INSTRUCTION_LAYOUTS))if(layout.index==typeIndex){type=ixType;break}if(!type)throw new Error("Instruction type incorrect; not a VoteInstruction");return type}static decodeInitializeAccount(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,4);const{voteInit}=decodeData$1(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount,instruction.data);return{votePubkey:instruction.keys[0].pubkey,nodePubkey:instruction.keys[3].pubkey,voteInit:new VoteInit(new PublicKey(voteInit.nodePubkey),new PublicKey(voteInit.authorizedVoter),new PublicKey(voteInit.authorizedWithdrawer),voteInit.commission)}}static decodeAuthorize(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3);const{newAuthorized,voteAuthorizationType}=decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Authorize,instruction.data);return{votePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey,newAuthorizedPubkey:new PublicKey(newAuthorized),voteAuthorizationType:{index:voteAuthorizationType}}}static decodeAuthorizeWithSeed(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3);const{voteAuthorizeWithSeedArgs:{currentAuthorityDerivedKeyOwnerPubkey,currentAuthorityDerivedKeySeed,newAuthorized,voteAuthorizationType}}=decodeData$1(VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,instruction.data);return{currentAuthorityDerivedKeyBasePubkey:instruction.keys[2].pubkey,currentAuthorityDerivedKeyOwnerPubkey:new PublicKey(currentAuthorityDerivedKeyOwnerPubkey),currentAuthorityDerivedKeySeed,newAuthorizedPubkey:new PublicKey(newAuthorized),voteAuthorizationType:{index:voteAuthorizationType},votePubkey:instruction.keys[0].pubkey}}static decodeWithdraw(instruction){this.checkProgramId(instruction.programId),this.checkKeyLength(instruction.keys,3);const{lamports}=decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Withdraw,instruction.data);return{votePubkey:instruction.keys[0].pubkey,authorizedWithdrawerPubkey:instruction.keys[2].pubkey,lamports,toPubkey:instruction.keys[1].pubkey}}static checkProgramId(programId){if(!programId.equals(VoteProgram.programId))throw new Error("invalid instruction; programId is not VoteProgram")}static checkKeyLength(keys,expectedLength){if(keys.lengthLayout.w3([publicKey("nodePubkey"),publicKey("authorizedVoter"),publicKey("authorizedWithdrawer"),Layout.u8("commission")],property))()])},Authorize:{index:1,layout:Layout.w3([Layout.DH("instruction"),publicKey("newAuthorized"),Layout.DH("voteAuthorizationType")])},Withdraw:{index:3,layout:Layout.w3([Layout.DH("instruction"),Layout.Wg("lamports")])},UpdateValidatorIdentity:{index:4,layout:Layout.w3([Layout.DH("instruction")])},AuthorizeWithSeed:{index:10,layout:Layout.w3([Layout.DH("instruction"),((property="voteAuthorizeWithSeedArgs")=>Layout.w3([Layout.DH("voteAuthorizationType"),publicKey("currentAuthorityDerivedKeyOwnerPubkey"),rustString("currentAuthorityDerivedKeySeed"),publicKey("newAuthorized")],property))()])}}),VoteAuthorizationLayout=Object.freeze({Voter:{index:0},Withdrawer:{index:1}});class VoteProgram{constructor(){}static initializeAccount(params){const{votePubkey,nodePubkey,voteInit}=params,data=encodeData(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount,{voteInit:{nodePubkey:toBuffer(voteInit.nodePubkey.toBuffer()),authorizedVoter:toBuffer(voteInit.authorizedVoter.toBuffer()),authorizedWithdrawer:toBuffer(voteInit.authorizedWithdrawer.toBuffer()),commission:voteInit.commission}}),instructionData={keys:[{pubkey:votePubkey,isSigner:!1,isWritable:!0},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:nodePubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data};return new TransactionInstruction(instructionData)}static createAccount(params){const transaction=new Transaction;return transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.votePubkey,lamports:params.lamports,space:this.space,programId:this.programId})),transaction.add(this.initializeAccount({votePubkey:params.votePubkey,nodePubkey:params.voteInit.nodePubkey,voteInit:params.voteInit}))}static authorize(params){const{votePubkey,authorizedPubkey,newAuthorizedPubkey,voteAuthorizationType}=params,data=encodeData(VOTE_INSTRUCTION_LAYOUTS.Authorize,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),voteAuthorizationType:voteAuthorizationType.index}),keys=[{pubkey:votePubkey,isSigner:!1,isWritable:!0},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:authorizedPubkey,isSigner:!0,isWritable:!1}];return(new Transaction).add({keys,programId:this.programId,data})}static authorizeWithSeed(params){const{currentAuthorityDerivedKeyBasePubkey,currentAuthorityDerivedKeyOwnerPubkey,currentAuthorityDerivedKeySeed,newAuthorizedPubkey,voteAuthorizationType,votePubkey}=params,data=encodeData(VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,{voteAuthorizeWithSeedArgs:{currentAuthorityDerivedKeyOwnerPubkey:toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()),currentAuthorityDerivedKeySeed,newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),voteAuthorizationType:voteAuthorizationType.index}}),keys=[{pubkey:votePubkey,isSigner:!1,isWritable:!0},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:currentAuthorityDerivedKeyBasePubkey,isSigner:!0,isWritable:!1}];return(new Transaction).add({keys,programId:this.programId,data})}static withdraw(params){const{votePubkey,authorizedWithdrawerPubkey,lamports,toPubkey}=params,data=encodeData(VOTE_INSTRUCTION_LAYOUTS.Withdraw,{lamports}),keys=[{pubkey:votePubkey,isSigner:!1,isWritable:!0},{pubkey:toPubkey,isSigner:!1,isWritable:!0},{pubkey:authorizedWithdrawerPubkey,isSigner:!0,isWritable:!1}];return(new Transaction).add({keys,programId:this.programId,data})}static safeWithdraw(params,currentVoteAccountBalance,rentExemptMinimum){if(params.lamports>currentVoteAccountBalance-rentExemptMinimum)throw new Error("Withdraw will leave vote account with insufficient funds.");return VoteProgram.withdraw(params)}static updateValidatorIdentity(params){const{votePubkey,authorizedWithdrawerPubkey,nodePubkey}=params,data=encodeData(VOTE_INSTRUCTION_LAYOUTS.UpdateValidatorIdentity),keys=[{pubkey:votePubkey,isSigner:!1,isWritable:!0},{pubkey:nodePubkey,isSigner:!0,isWritable:!1},{pubkey:authorizedWithdrawerPubkey,isSigner:!0,isWritable:!1}];return(new Transaction).add({keys,programId:this.programId,data})}}VoteProgram.programId=new PublicKey("Vote111111111111111111111111111111111111111"),VoteProgram.space=3762;const VALIDATOR_INFO_KEY=new PublicKey("Va1idator1nfo111111111111111111111111111111"),InfoString=type({name:string(),website:optional(string()),details:optional(string()),iconUrl:optional(string()),keybaseUsername:optional(string())});class ValidatorInfo{constructor(key,info){this.key=void 0,this.info=void 0,this.key=key,this.info=info}static fromConfigData(buffer){let byteArray=[...buffer];if(2!==decodeLength(byteArray))return null;const configKeys=[];for(let i=0;i<2;i++){const publicKey=new PublicKey(guardedSplice(byteArray,0,PUBLIC_KEY_LENGTH)),isSigner=1===guardedShift(byteArray);configKeys.push({publicKey,isSigner})}if(configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)&&configKeys[1].isSigner){const rawInfo=rustString().decode(node_modules_buffer.Buffer.from(byteArray)),info=JSON.parse(rawInfo);return assert(info,InfoString),new ValidatorInfo(configKeys[1].publicKey,info)}return null}}const VOTE_PROGRAM_ID=new PublicKey("Vote111111111111111111111111111111111111111"),VoteAccountLayout=Layout.w3([publicKey("nodePubkey"),publicKey("authorizedWithdrawer"),Layout.u8("commission"),Layout.I0(),Layout.O6(Layout.w3([Layout.I0("slot"),Layout.DH("confirmationCount")]),Layout.cY(Layout.DH(),-8),"votes"),Layout.u8("rootSlotValid"),Layout.I0("rootSlot"),Layout.I0(),Layout.O6(Layout.w3([Layout.I0("epoch"),publicKey("authorizedVoter")]),Layout.cY(Layout.DH(),-8),"authorizedVoters"),Layout.w3([Layout.O6(Layout.w3([publicKey("authorizedPubkey"),Layout.I0("epochOfLastAuthorizedSwitch"),Layout.I0("targetEpoch")]),32,"buf"),Layout.I0("idx"),Layout.u8("isEmpty")],"priorVoters"),Layout.I0(),Layout.O6(Layout.w3([Layout.I0("epoch"),Layout.I0("credits"),Layout.I0("prevCredits")]),Layout.cY(Layout.DH(),-8),"epochCredits"),Layout.w3([Layout.I0("slot"),Layout.I0("timestamp")],"lastTimestamp")]);class VoteAccount{constructor(args){this.nodePubkey=void 0,this.authorizedWithdrawer=void 0,this.commission=void 0,this.rootSlot=void 0,this.votes=void 0,this.authorizedVoters=void 0,this.priorVoters=void 0,this.epochCredits=void 0,this.lastTimestamp=void 0,this.nodePubkey=args.nodePubkey,this.authorizedWithdrawer=args.authorizedWithdrawer,this.commission=args.commission,this.rootSlot=args.rootSlot,this.votes=args.votes,this.authorizedVoters=args.authorizedVoters,this.priorVoters=args.priorVoters,this.epochCredits=args.epochCredits,this.lastTimestamp=args.lastTimestamp}static fromAccountData(buffer){const va=VoteAccountLayout.decode(toBuffer(buffer),4);let rootSlot=va.rootSlot;return va.rootSlotValid||(rootSlot=null),new VoteAccount({nodePubkey:new PublicKey(va.nodePubkey),authorizedWithdrawer:new PublicKey(va.authorizedWithdrawer),commission:va.commission,votes:va.votes,rootSlot,authorizedVoters:va.authorizedVoters.map(parseAuthorizedVoter),priorVoters:getPriorVoters(va.priorVoters),epochCredits:va.epochCredits,lastTimestamp:va.lastTimestamp})}}function parseAuthorizedVoter({authorizedVoter,epoch}){return{epoch,authorizedVoter:new PublicKey(authorizedVoter)}}function parsePriorVoters({authorizedPubkey,epochOfLastAuthorizedSwitch,targetEpoch}){return{authorizedPubkey:new PublicKey(authorizedPubkey),epochOfLastAuthorizedSwitch,targetEpoch}}function getPriorVoters({buf,idx,isEmpty}){return isEmpty?[]:[...buf.slice(idx+1).map(parsePriorVoters),...buf.slice(0,idx).map(parsePriorVoters)]}const endpoint={http:{devnet:"http://api.devnet.solana.com",testnet:"http://api.testnet.solana.com","mainnet-beta":"http://api.mainnet-beta.solana.com/"},https:{devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com","mainnet-beta":"https://api.mainnet-beta.solana.com/"}};function clusterApiUrl(cluster,tls){const key=!1===tls?"http":"https";if(!cluster)return endpoint[key].devnet;const url=endpoint[key][cluster];if(!url)throw new Error(`Unknown ${key} cluster: ${cluster}`);return url}async function sendAndConfirmRawTransaction(connection,rawTransaction,confirmationStrategyOrConfirmOptions,maybeConfirmOptions){let confirmationStrategy,options;confirmationStrategyOrConfirmOptions&&Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions,"lastValidBlockHeight")||confirmationStrategyOrConfirmOptions&&Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions,"nonceValue")?(confirmationStrategy=confirmationStrategyOrConfirmOptions,options=maybeConfirmOptions):options=confirmationStrategyOrConfirmOptions;const sendOptions=options&&{skipPreflight:options.skipPreflight,preflightCommitment:options.preflightCommitment||options.commitment,minContextSlot:options.minContextSlot},signature=await connection.sendRawTransaction(rawTransaction,sendOptions),commitment=options&&options.commitment,confirmationPromise=confirmationStrategy?connection.confirmTransaction(confirmationStrategy,commitment):connection.confirmTransaction(signature,commitment),status=(await confirmationPromise).value;if(status.err){if(null!=signature)throw new SendTransactionError({action:sendOptions?.skipPreflight?"send":"simulate",signature,transactionMessage:`Status: (${JSON.stringify(status)})`});throw new Error(`Raw transaction ${signature} failed (${JSON.stringify(status)})`)}return signature}const LAMPORTS_PER_SOL=1e9},"./node_modules/@solana/web3.js/node_modules/base-x/src/index.js":(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var _Buffer=__webpack_require__("./node_modules/safe-buffer/index.js").Buffer;module.exports=function base(ALPHABET){if(ALPHABET.length>=255)throw new TypeError("Alphabet too long");for(var BASE_MAP=new Uint8Array(256),j=0;j>>0,b256=new Uint8Array(size);psz255)return;var carry=BASE_MAP[charCode];if(255===carry)return;for(var i=0,it3=size-1;(0!==carry||i>>0,b256[it3]=carry%256>>>0,carry=carry/256>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,psz++}for(var it4=size-length;it4!==size&&0===b256[it4];)it4++;var vch=_Buffer.allocUnsafe(zeroes+(size-it4));vch.fill(0,0,zeroes);for(var j=zeroes;it4!==size;)vch[j++]=b256[it4++];return vch}return{encode:function encode(source){if((Array.isArray(source)||source instanceof Uint8Array)&&(source=_Buffer.from(source)),!_Buffer.isBuffer(source))throw new TypeError("Expected Buffer");if(0===source.length)return"";for(var zeroes=0,length=0,pbegin=0,pend=source.length;pbegin!==pend&&0===source[pbegin];)pbegin++,zeroes++;for(var size=(pend-pbegin)*iFACTOR+1>>>0,b58=new Uint8Array(size);pbegin!==pend;){for(var carry=source[pbegin],i=0,it1=size-1;(0!==carry||i>>0,b58[it1]=carry%BASE>>>0,carry=carry/BASE>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,pbegin++}for(var it2=size-length;it2!==size&&0===b58[it2];)it2++;for(var str=LEADER.repeat(zeroes);it2{var basex=__webpack_require__("./node_modules/@solana/web3.js/node_modules/base-x/src/index.js");module.exports=basex("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},"./node_modules/@wallet-standard/features/lib/cjs/connect.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Connect=exports.StandardConnect=void 0,exports.StandardConnect="standard:connect",exports.Connect=exports.StandardConnect},"./node_modules/@wallet-standard/features/lib/cjs/disconnect.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Disconnect=exports.StandardDisconnect=void 0,exports.StandardDisconnect="standard:disconnect",exports.Disconnect=exports.StandardDisconnect},"./node_modules/@wallet-standard/features/lib/cjs/events.js":(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Events=exports.StandardEvents=void 0,exports.StandardEvents="standard:events",exports.Events=exports.StandardEvents},"./node_modules/@wallet-standard/features/lib/cjs/index.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__("./node_modules/@wallet-standard/features/lib/cjs/connect.js"),exports),__exportStar(__webpack_require__("./node_modules/@wallet-standard/features/lib/cjs/disconnect.js"),exports),__exportStar(__webpack_require__("./node_modules/@wallet-standard/features/lib/cjs/events.js"),exports)},"./node_modules/base64-js/index.js":(__unused_webpack_module,exports)=>{"use strict";exports.byteLength=function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen},exports.toByteArray=function toByteArray(b64){var tmp,i,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}(0,validLen,placeHoldersLen)),curByte=0,len=placeHoldersLen>0?validLen-4:validLen;for(i=0;i>16&255,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp;2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp);1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp);return arr},exports.fromByteArray=function fromByteArray(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,parts=[],i=0,len2=len-extraBytes;ilen2?len2:i+16383));1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"="));return parts.join("")};for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;function getLens(b64){var len=b64.length;if(len%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");return-1===validLen&&(validLen=len),[validLen,validLen===len?0:4-validLen%4]}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;i=48&&c<=57?c-48:c>=65&&c<=70?c-55:c>=97&&c<=102?c-87:void assert(!1,"Invalid character in "+string)}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c,assert(c>=0&&b0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this._strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{BN.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspect}catch(e){BN.prototype.inspect=inspect}else BN.prototype.inspect=inspect;function inspect(){return(this.red?""}var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215,(off+=2)>=26&&(off-=26,i--),out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!==0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!==0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16,2)},Buffer&&(BN.prototype.toBuffer=function toBuffer(endian,length){return this.toArrayLike(Buffer,endian,length)}),BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out._strip()}BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){this._strip();var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0");var res=function allocate(ArrayType,size){return ArrayType.allocUnsafe?ArrayType.allocUnsafe(size):new ArrayType(size)}(ArrayType,reqLength);return this["_toArrayLike"+("le"===endian?"LE":"BE")](res,byteLength),res},BN.prototype._toArrayLikeLE=function _toArrayLikeLE(res,byteLength){for(var position=0,carry=0,i=0,shift=0;i>8&255),position>16&255),6===shift?(position>24&255),carry=0,shift=0):(carry=word>>>24,shift+=2)}if(position=0&&(res[position--]=word>>8&255),position>=0&&(res[position--]=word>>16&255),6===shift?(position>=0&&(res[position--]=word>>24&255),carry=0,shift=0):(carry=word>>>24,shift+=2)}if(position>=0)for(res[position--]=carry;position>=0;)res[position--]=0},Math.clz32?BN.prototype._countBits=function _countBits(w){return 32-Math.clz32(w)}:BN.prototype._countBits=function _countBits(w){var t=w,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 8191&t||(r+=13,t>>>=13),127&t||(r+=7,t>>>=7),15&t||(r+=4,t>>>=4),3&t||(r+=2,t>>>=2),1&t||r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this._strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length;return 10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?bigMulTo(this,num,out):jumboMulTo(this,num,out)},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this.length=0===num?1:this.length,isNegNum?this.ineg():this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit&1}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q._strip(),a._strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!==(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modrn=function modrn(num){var isNegNum=num<0;isNegNum&&(num=-num),assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function modn(num){return this.modrn(num)},BN.prototype.idivn=function idivn(num){var isNegNum=num<0;isNegNum&&(num=-num),assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0===(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0===(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0===(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0===(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return!(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return!(1&~this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this._strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0===(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},"./node_modules/borsh/lib/index.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__decorate=this&&this.__decorate||function(decorators,target,key,desc){var d,c=arguments.length,r=c<3?target:null===desc?desc=Object.getOwnPropertyDescriptor(target,key):desc;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r},__importStar=this&&this.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k in mod)"default"!==k&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.deserializeUnchecked=exports.deserialize=exports.serialize=exports.BinaryReader=exports.BinaryWriter=exports.BorshError=exports.baseDecode=exports.baseEncode=void 0;const bn_js_1=__importDefault(__webpack_require__("./node_modules/bn.js/lib/bn.js")),bs58_1=__importDefault(__webpack_require__("./node_modules/borsh/node_modules/bs58/index.js")),encoding=__importStar(__webpack_require__("./node_modules/text-encoding-utf-8/lib/encoding.lib.js")),textDecoder=new("function"!=typeof TextDecoder?encoding.TextDecoder:TextDecoder)("utf-8",{fatal:!0});exports.baseEncode=function baseEncode(value){return"string"==typeof value&&(value=Buffer.from(value,"utf8")),bs58_1.default.encode(Buffer.from(value))},exports.baseDecode=function baseDecode(value){return Buffer.from(bs58_1.default.decode(value))};class BorshError extends Error{constructor(message){super(message),this.fieldPath=[],this.originalMessage=message}addToFieldPath(fieldName){this.fieldPath.splice(0,0,fieldName),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}exports.BorshError=BorshError;class BinaryWriter{constructor(){this.buf=Buffer.alloc(1024),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(1024)]))}writeU8(value){this.maybeResize(),this.buf.writeUInt8(value,this.length),this.length+=1}writeU16(value){this.maybeResize(),this.buf.writeUInt16LE(value,this.length),this.length+=2}writeU32(value){this.maybeResize(),this.buf.writeUInt32LE(value,this.length),this.length+=4}writeU64(value){this.maybeResize(),this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le",8)))}writeU128(value){this.maybeResize(),this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le",16)))}writeU256(value){this.maybeResize(),this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le",32)))}writeU512(value){this.maybeResize(),this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le",64)))}writeBuffer(buffer){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),buffer,Buffer.alloc(1024)]),this.length+=buffer.length}writeString(str){this.maybeResize();const b=Buffer.from(str,"utf8");this.writeU32(b.length),this.writeBuffer(b)}writeFixedArray(array){this.writeBuffer(Buffer.from(array))}writeArray(array,fn){this.maybeResize(),this.writeU32(array.length);for(const elem of array)this.maybeResize(),fn(elem)}toArray(){return this.buf.subarray(0,this.length)}}function handlingRangeError(target,propertyKey,propertyDescriptor){const originalMethod=propertyDescriptor.value;propertyDescriptor.value=function(...args){try{return originalMethod.apply(this,args)}catch(e){if(e instanceof RangeError){const code=e.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(code)>=0)throw new BorshError("Reached the end of buffer when deserializing")}throw e}}}exports.BinaryWriter=BinaryWriter;class BinaryReader{constructor(buf){this.buf=buf,this.offset=0}readU8(){const value=this.buf.readUInt8(this.offset);return this.offset+=1,value}readU16(){const value=this.buf.readUInt16LE(this.offset);return this.offset+=2,value}readU32(){const value=this.buf.readUInt32LE(this.offset);return this.offset+=4,value}readU64(){const buf=this.readBuffer(8);return new bn_js_1.default(buf,"le")}readU128(){const buf=this.readBuffer(16);return new bn_js_1.default(buf,"le")}readU256(){const buf=this.readBuffer(32);return new bn_js_1.default(buf,"le")}readU512(){const buf=this.readBuffer(64);return new bn_js_1.default(buf,"le")}readBuffer(len){if(this.offset+len>this.buf.length)throw new BorshError(`Expected buffer length ${len} isn't within bounds`);const result=this.buf.slice(this.offset,this.offset+len);return this.offset+=len,result}readString(){const len=this.readU32(),buf=this.readBuffer(len);try{return textDecoder.decode(buf)}catch(e){throw new BorshError(`Error decoding UTF-8 string: ${e}`)}}readFixedArray(len){return new Uint8Array(this.readBuffer(len))}readArray(fn){const len=this.readU32(),result=Array();for(let i=0;i{serializeField(schema,fieldName,item,fieldType[0],writer)});else if(void 0!==fieldType.kind)switch(fieldType.kind){case"option":null==value?writer.writeU8(0):(writer.writeU8(1),serializeField(schema,fieldName,value,fieldType.type,writer));break;case"map":writer.writeU32(value.size),value.forEach((val,key)=>{serializeField(schema,fieldName,key,fieldType.key,writer),serializeField(schema,fieldName,val,fieldType.value,writer)});break;default:throw new BorshError(`FieldType ${fieldType} unrecognized`)}else serializeStruct(schema,value,writer)}catch(error){throw error instanceof BorshError&&error.addToFieldPath(fieldName),error}}function serializeStruct(schema,obj,writer){if("function"==typeof obj.borshSerialize)return void obj.borshSerialize(writer);const structSchema=schema.get(obj.constructor);if(!structSchema)throw new BorshError(`Class ${obj.constructor.name} is missing in schema`);if("struct"===structSchema.kind)structSchema.fields.map(([fieldName,fieldType])=>{serializeField(schema,fieldName,obj[fieldName],fieldType,writer)});else{if("enum"!==structSchema.kind)throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${obj.constructor.name}`);{const name=obj[structSchema.field];for(let idx=0;idxdeserializeField(schema,fieldName,fieldType[0],reader))}if("option"===fieldType.kind){return reader.readU8()?deserializeField(schema,fieldName,fieldType.type,reader):void 0}if("map"===fieldType.kind){let map=new Map;const length=reader.readU32();for(let i=0;i=structSchema.values.length)throw new BorshError(`Enum index: ${idx} is out of range`);const[fieldName,fieldType]=structSchema.values[idx],fieldValue=deserializeField(schema,fieldName,fieldType,reader);return new classType({[fieldName]:fieldValue})}throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${classType.constructor.name}`)}__decorate([handlingRangeError],BinaryReader.prototype,"readU8",null),__decorate([handlingRangeError],BinaryReader.prototype,"readU16",null),__decorate([handlingRangeError],BinaryReader.prototype,"readU32",null),__decorate([handlingRangeError],BinaryReader.prototype,"readU64",null),__decorate([handlingRangeError],BinaryReader.prototype,"readU128",null),__decorate([handlingRangeError],BinaryReader.prototype,"readU256",null),__decorate([handlingRangeError],BinaryReader.prototype,"readU512",null),__decorate([handlingRangeError],BinaryReader.prototype,"readString",null),__decorate([handlingRangeError],BinaryReader.prototype,"readFixedArray",null),__decorate([handlingRangeError],BinaryReader.prototype,"readArray",null),exports.BinaryReader=BinaryReader,exports.serialize=function serialize(schema,obj,Writer=BinaryWriter){const writer=new Writer;return serializeStruct(schema,obj,writer),writer.toArray()},exports.deserialize=function deserialize(schema,classType,buffer,Reader=BinaryReader){const reader=new Reader(buffer),result=deserializeStruct(schema,classType,reader);if(reader.offset{"use strict";var _Buffer=__webpack_require__("./node_modules/safe-buffer/index.js").Buffer;module.exports=function base(ALPHABET){if(ALPHABET.length>=255)throw new TypeError("Alphabet too long");for(var BASE_MAP=new Uint8Array(256),j=0;j>>0,b256=new Uint8Array(size);psz255)return;var carry=BASE_MAP[charCode];if(255===carry)return;for(var i=0,it3=size-1;(0!==carry||i>>0,b256[it3]=carry%256>>>0,carry=carry/256>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,psz++}for(var it4=size-length;it4!==size&&0===b256[it4];)it4++;var vch=_Buffer.allocUnsafe(zeroes+(size-it4));vch.fill(0,0,zeroes);for(var j=zeroes;it4!==size;)vch[j++]=b256[it4++];return vch}return{encode:function encode(source){if((Array.isArray(source)||source instanceof Uint8Array)&&(source=_Buffer.from(source)),!_Buffer.isBuffer(source))throw new TypeError("Expected Buffer");if(0===source.length)return"";for(var zeroes=0,length=0,pbegin=0,pend=source.length;pbegin!==pend&&0===source[pbegin];)pbegin++,zeroes++;for(var size=(pend-pbegin)*iFACTOR+1>>>0,b58=new Uint8Array(size);pbegin!==pend;){for(var carry=source[pbegin],i=0,it1=size-1;(0!==carry||i>>0,b58[it1]=carry%BASE>>>0,carry=carry/BASE>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,pbegin++}for(var it2=size-length;it2!==size&&0===b58[it2];)it2++;for(var str=LEADER.repeat(zeroes);it2{var basex=__webpack_require__("./node_modules/borsh/node_modules/base-x/src/index.js");module.exports=basex("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},"./node_modules/buffer/index.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";const base64=__webpack_require__("./node_modules/base64-js/index.js"),ieee754=__webpack_require__("./node_modules/ieee754/index.js"),customInspectSymbol="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;exports.Buffer=Buffer,exports.SlowBuffer=function SlowBuffer(length){+length!=length&&(length=0);return Buffer.alloc(+length)},exports.INSPECT_MAX_BYTES=50;const K_MAX_LENGTH=2147483647;function createBuffer(length){if(length>K_MAX_LENGTH)throw new RangeError('The value "'+length+'" is invalid for option "size"');const buf=new Uint8Array(length);return Object.setPrototypeOf(buf,Buffer.prototype),buf}function Buffer(arg,encodingOrOffset,length){if("number"==typeof arg){if("string"==typeof encodingOrOffset)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}function from(value,encodingOrOffset,length){if("string"==typeof value)return function fromString(string,encoding){"string"==typeof encoding&&""!==encoding||(encoding="utf8");if(!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);const length=0|byteLength(string,encoding);let buf=createBuffer(length);const actual=buf.write(string,encoding);actual!==length&&(buf=buf.slice(0,actual));return buf}(value,encodingOrOffset);if(ArrayBuffer.isView(value))return function fromArrayView(arrayView){if(isInstance(arrayView,Uint8Array)){const copy=new Uint8Array(arrayView);return fromArrayBuffer(copy.buffer,copy.byteOffset,copy.byteLength)}return fromArrayLike(arrayView)}(value);if(null==value)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer))return fromArrayBuffer(value,encodingOrOffset,length);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(value,SharedArrayBuffer)||value&&isInstance(value.buffer,SharedArrayBuffer)))return fromArrayBuffer(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError('The "value" argument must not be of type number. Received type number');const valueOf=value.valueOf&&value.valueOf();if(null!=valueOf&&valueOf!==value)return Buffer.from(valueOf,encodingOrOffset,length);const b=function fromObject(obj){if(Buffer.isBuffer(obj)){const len=0|checked(obj.length),buf=createBuffer(len);return 0===buf.length||obj.copy(buf,0,0,len),buf}if(void 0!==obj.length)return"number"!=typeof obj.length||numberIsNaN(obj.length)?createBuffer(0):fromArrayLike(obj);if("Buffer"===obj.type&&Array.isArray(obj.data))return fromArrayLike(obj.data)}(value);if(b)return b;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof value[Symbol.toPrimitive])return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value)}function assertSize(size){if("number"!=typeof size)throw new TypeError('"size" argument must be of type number');if(size<0)throw new RangeError('The value "'+size+'" is invalid for option "size"')}function allocUnsafe(size){return assertSize(size),createBuffer(size<0?0:0|checked(size))}function fromArrayLike(array){const length=array.length<0?0:0|checked(array.length),buf=createBuffer(length);for(let i=0;i=K_MAX_LENGTH)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes");return 0|length}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof string);const len=string.length,mustMatch=arguments.length>2&&!0===arguments[2];if(!mustMatch&&0===len)return 0;let loweredCase=!1;for(;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){let loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if((end>>>=0)<=(start>>>=0))return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){const i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),numberIsNaN(byteOffset=+byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){let i,indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}if(dir){let foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){let found=!0;for(let j=0;jremaining&&(length=remaining):length=remaining;const strLen=string.length;let i;for(length>strLen/2&&(length=strLen/2),i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}(string,buf.length-offset),buf,offset,length)}function base64Slice(buf,start,end){return 0===start&&end===buf.length?base64.fromByteArray(buf):base64.fromByteArray(buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);const res=[];let i=start;for(;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){let secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,tempCodePoint>127&&(codePoint=tempCodePoint));break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint));break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,tempCodePoint>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint))}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return function decodeCodePointsArray(codePoints){const len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);let res="",i=0;for(;ibuffer.length?(Buffer.isBuffer(buf)||(buf=Buffer.from(buf)),buf.copy(buffer,pos)):Uint8Array.prototype.set.call(buffer,buf,pos);else{if(!Buffer.isBuffer(buf))throw new TypeError('"list" argument must be an Array of Buffers');buf.copy(buffer,pos)}pos+=buf.length}return buffer},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function swap16(){const len=this.length;if(len%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let i=0;imax&&(str+=" ... "),""},customInspectSymbol&&(Buffer.prototype[customInspectSymbol]=Buffer.prototype.inspect),Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof target);if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(this===target)return 0;let x=(thisEnd>>>=0)-(thisStart>>>=0),y=(end>>>=0)-(start>>>=0);const len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end);for(let i=0;i>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0)}const remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");let loweredCase=!1;for(;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":case"latin1":case"binary":return asciiWrite(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const MAX_ARGUMENTS_LENGTH=4096;function asciiSlice(buf,start,end){let ret="";end=Math.min(buf.length,end);for(let i=start;ilen)&&(end=len);let out="";for(let i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function wrtBigUInt64LE(buf,value,offset,min,max){checkIntBI(value,min,max,buf,offset,7);let lo=Number(value&BigInt(4294967295));buf[offset++]=lo,lo>>=8,buf[offset++]=lo,lo>>=8,buf[offset++]=lo,lo>>=8,buf[offset++]=lo;let hi=Number(value>>BigInt(32)&BigInt(4294967295));return buf[offset++]=hi,hi>>=8,buf[offset++]=hi,hi>>=8,buf[offset++]=hi,hi>>=8,buf[offset++]=hi,offset}function wrtBigUInt64BE(buf,value,offset,min,max){checkIntBI(value,min,max,buf,offset,7);let lo=Number(value&BigInt(4294967295));buf[offset+7]=lo,lo>>=8,buf[offset+6]=lo,lo>>=8,buf[offset+5]=lo,lo>>=8,buf[offset+4]=lo;let hi=Number(value>>BigInt(32)&BigInt(4294967295));return buf[offset+3]=hi,hi>>=8,buf[offset+2]=hi,hi>>=8,buf[offset+1]=hi,hi>>=8,buf[offset]=hi,offset+8}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,0,offset,4),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,0,offset,8),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}Buffer.prototype.slice=function slice(start,end){const len=this.length;(start=~~start)<0?(start+=len)<0&&(start=0):start>len&&(start=len),(end=void 0===end?len:~~end)<0?(end+=len)<0&&(end=0):end>len&&(end=len),end>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);let val=this[offset],mul=1,i=0;for(;++i>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);let val=this[offset+--byteLength],mul=1;for(;byteLength>0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readBigUInt64LE=defineBigIntMethod(function readBigUInt64LE(offset){validateNumber(offset>>>=0,"offset");const first=this[offset],last=this[offset+7];void 0!==first&&void 0!==last||boundsError(offset,this.length-8);const lo=first+256*this[++offset]+65536*this[++offset]+this[++offset]*2**24,hi=this[++offset]+256*this[++offset]+65536*this[++offset]+last*2**24;return BigInt(lo)+(BigInt(hi)<>>=0,"offset");const first=this[offset],last=this[offset+7];void 0!==first&&void 0!==last||boundsError(offset,this.length-8);const hi=first*2**24+65536*this[++offset]+256*this[++offset]+this[++offset],lo=this[++offset]*2**24+65536*this[++offset]+256*this[++offset]+last;return(BigInt(hi)<>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);let val=this[offset],mul=1,i=0;for(;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);let i=byteLength,mul=1,val=this[offset+--i];for(;i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function readInt8(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);const val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);const val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readBigInt64LE=defineBigIntMethod(function readBigInt64LE(offset){validateNumber(offset>>>=0,"offset");const first=this[offset],last=this[offset+7];void 0!==first&&void 0!==last||boundsError(offset,this.length-8);const val=this[offset+4]+256*this[offset+5]+65536*this[offset+6]+(last<<24);return(BigInt(val)<>>=0,"offset");const first=this[offset],last=this[offset+7];void 0!==first&&void 0!==last||boundsError(offset,this.length-8);const val=(first<<24)+65536*this[++offset]+256*this[++offset]+this[++offset];return(BigInt(val)<>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,byteLength>>>=0,!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0)}let mul=1,i=0;for(this[offset]=255&value;++i>>=0,byteLength>>>=0,!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0)}let i=byteLength-1,mul=1;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeBigUInt64LE=defineBigIntMethod(function writeBigUInt64LE(value,offset=0){return wrtBigUInt64LE(this,value,offset,BigInt(0),BigInt("0xffffffffffffffff"))}),Buffer.prototype.writeBigUInt64BE=defineBigIntMethod(function writeBigUInt64BE(value,offset=0){return wrtBigUInt64BE(this,value,offset,BigInt(0),BigInt("0xffffffffffffffff"))}),Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){const limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}let i=0,mul=1,sub=0;for(this[offset]=255&value;++i>>=0,!noAssert){const limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}let i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul|0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeBigInt64LE=defineBigIntMethod(function writeBigInt64LE(value,offset=0){return wrtBigUInt64LE(this,value,offset,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),Buffer.prototype.writeBigInt64BE=defineBigIntMethod(function writeBigInt64BE(value,offset=0){return wrtBigUInt64BE(this,value,offset,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart>>=0,end=void 0===end?this.length:end>>>0,val||(val=0),"number"==typeof val)for(i=start;i=start+4;i-=3)res=`_${val.slice(i-3,i)}${res}`;return`${val.slice(0,i)}${res}`}function checkIntBI(value,min,max,buf,offset,byteLength){if(value>max||value3?0===min||min===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(byteLength+1)}${n}`:`>= -(2${n} ** ${8*(byteLength+1)-1}${n}) and < 2 ** ${8*(byteLength+1)-1}${n}`:`>= ${min}${n} and <= ${max}${n}`,new errors.ERR_OUT_OF_RANGE("value",range,value)}!function checkBounds(buf,offset,byteLength){validateNumber(offset,"offset"),void 0!==buf[offset]&&void 0!==buf[offset+byteLength]||boundsError(offset,buf.length-(byteLength+1))}(buf,offset,byteLength)}function validateNumber(value,name){if("number"!=typeof value)throw new errors.ERR_INVALID_ARG_TYPE(name,"number",value)}function boundsError(value,length,type){if(Math.floor(value)!==value)throw validateNumber(value,type),new errors.ERR_OUT_OF_RANGE(type||"offset","an integer",value);if(length<0)throw new errors.ERR_BUFFER_OUT_OF_BOUNDS;throw new errors.ERR_OUT_OF_RANGE(type||"offset",`>= ${type?1:0} and <= ${length}`,value)}E("ERR_BUFFER_OUT_OF_BOUNDS",function(name){return name?`${name} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),E("ERR_INVALID_ARG_TYPE",function(name,actual){return`The "${name}" argument must be of type number. Received type ${typeof actual}`},TypeError),E("ERR_OUT_OF_RANGE",function(str,range,input){let msg=`The value of "${str}" is out of range.`,received=input;return Number.isInteger(input)&&Math.abs(input)>2**32?received=addNumericalSeparator(String(input)):"bigint"==typeof input&&(received=String(input),(input>BigInt(2)**BigInt(32)||input<-(BigInt(2)**BigInt(32)))&&(received=addNumericalSeparator(received)),received+="n"),msg+=` It must be ${range}. Received ${received}`,msg},RangeError);const INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function utf8ToBytes(string,units){let codePoint;units=units||1/0;const length=string.length;let leadSurrogate=null;const bytes=[];for(let i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function base64ToBytes(str){return base64.toByteArray(function base64clean(str){if((str=(str=str.split("=")[0]).trim().replace(INVALID_BASE64_RE,"")).length<2)return"";for(;str.length%4!=0;)str+="=";return str}(str))}function blitBuffer(src,dst,offset,length){let i;for(i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!=obj}const hexSliceLookupTable=function(){const table=new Array(256);for(let i=0;i<16;++i){const i16=16*i;for(let j=0;j<16;++j)table[i16+j]="0123456789abcdef"[i]+"0123456789abcdef"[j]}return table}();function defineBigIntMethod(fn){return"undefined"==typeof BigInt?BufferBigIntNotDefined:fn}function BufferBigIntNotDefined(){throw new Error("BigInt not supported")}},"./node_modules/css-loader/dist/cjs.js!./node_modules/@solana/wallet-adapter-react-ui/styles.css":(module,__webpack_exports__,__webpack_require__)=>{"use strict";__webpack_require__.d(__webpack_exports__,{A:()=>__WEBPACK_DEFAULT_EXPORT__});var _css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/css-loader/dist/runtime/noSourceMaps.js"),_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default=__webpack_require__.n(_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__),_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./node_modules/css-loader/dist/runtime/api.js"),___CSS_LOADER_EXPORT___=__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__)()(_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default());___CSS_LOADER_EXPORT___.push([module.id,"@import url(https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap);"]),___CSS_LOADER_EXPORT___.push([module.id,".wallet-adapter-button {\n background-color: transparent;\n border: none;\n color: #fff;\n cursor: pointer;\n display: flex;\n align-items: center;\n font-family: 'DM Sans', 'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif;\n font-size: 16px;\n font-weight: 600;\n height: 48px;\n line-height: 48px;\n padding: 0 24px;\n border-radius: 4px;\n}\n\n.wallet-adapter-button-trigger {\n background-color: #512da8;\n}\n\n.wallet-adapter-button:not([disabled]):focus-visible {\n outline-color: white;\n}\n\n.wallet-adapter-button:not([disabled]):hover {\n background-color: #1a1f2e;\n}\n\n.wallet-adapter-button[disabled] {\n background: #404144;\n color: #999;\n cursor: not-allowed;\n}\n\n.wallet-adapter-button-end-icon,\n.wallet-adapter-button-start-icon,\n.wallet-adapter-button-end-icon img,\n.wallet-adapter-button-start-icon img {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 24px;\n height: 24px;\n}\n\n.wallet-adapter-button-end-icon {\n margin-left: 12px;\n}\n\n.wallet-adapter-button-start-icon {\n margin-right: 12px;\n}\n\n.wallet-adapter-collapse {\n width: 100%;\n}\n\n.wallet-adapter-dropdown {\n position: relative;\n display: inline-block;\n}\n\n.wallet-adapter-dropdown-list {\n position: absolute;\n z-index: 99;\n display: grid;\n grid-template-rows: 1fr;\n grid-row-gap: 10px;\n padding: 10px;\n top: 100%;\n right: 0;\n margin: 0;\n list-style: none;\n background: #2c2d30;\n border-radius: 10px;\n box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.6);\n opacity: 0;\n visibility: hidden;\n transition: opacity 200ms ease, transform 200ms ease, visibility 200ms;\n font-family: 'DM Sans', 'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif;\n}\n\n.wallet-adapter-dropdown-list-active {\n opacity: 1;\n visibility: visible;\n transform: translateY(10px);\n}\n\n.wallet-adapter-dropdown-list-item {\n display: flex;\n flex-direction: row;\n justify-content: center;\n align-items: center;\n border: none;\n outline: none;\n cursor: pointer;\n white-space: nowrap;\n box-sizing: border-box;\n padding: 0 20px;\n width: 100%;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 600;\n height: 37px;\n color: #fff;\n}\n\n.wallet-adapter-dropdown-list-item:not([disabled]):hover {\n background-color: #1a1f2e;\n}\n\n.wallet-adapter-modal-collapse-button svg {\n align-self: center;\n fill: #999;\n}\n\n.wallet-adapter-modal-collapse-button.wallet-adapter-modal-collapse-button-active svg {\n transform: rotate(180deg);\n transition: transform ease-in 150ms;\n}\n\n.wallet-adapter-modal {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n opacity: 0;\n transition: opacity linear 150ms;\n background: rgba(0, 0, 0, 0.5);\n z-index: 1040;\n overflow-y: auto;\n}\n\n.wallet-adapter-modal.wallet-adapter-modal-fade-in {\n opacity: 1;\n}\n\n.wallet-adapter-modal-button-close {\n display: flex;\n align-items: center;\n justify-content: center;\n position: absolute;\n top: 18px;\n right: 18px;\n padding: 12px;\n cursor: pointer;\n background: #1a1f2e;\n border: none;\n border-radius: 50%;\n}\n\n.wallet-adapter-modal-button-close:focus-visible {\n outline-color: white;\n}\n\n.wallet-adapter-modal-button-close svg {\n fill: #777;\n transition: fill 200ms ease 0s;\n}\n\n.wallet-adapter-modal-button-close:hover svg {\n fill: #fff;\n}\n\n.wallet-adapter-modal-overlay {\n background: rgba(0, 0, 0, 0.5);\n position: fixed;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n}\n\n.wallet-adapter-modal-container {\n display: flex;\n margin: 3rem;\n min-height: calc(100vh - 6rem); /* 100vh - 2 * margin */\n align-items: center;\n justify-content: center;\n}\n\n@media (max-width: 480px) {\n .wallet-adapter-modal-container {\n margin: 1rem;\n min-height: calc(100vh - 2rem); /* 100vh - 2 * margin */\n }\n}\n\n.wallet-adapter-modal-wrapper {\n box-sizing: border-box;\n position: relative;\n display: flex;\n align-items: center;\n flex-direction: column;\n z-index: 1050;\n max-width: 400px;\n border-radius: 10px;\n background: #10141f;\n box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.6);\n font-family: 'DM Sans', 'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif;\n flex: 1;\n}\n\n.wallet-adapter-modal-wrapper .wallet-adapter-button {\n width: 100%;\n}\n\n.wallet-adapter-modal-title {\n font-weight: 500;\n font-size: 24px;\n line-height: 36px;\n margin: 0;\n padding: 64px 48px 48px 48px;\n text-align: center;\n color: #fff;\n}\n\n@media (max-width: 374px) {\n .wallet-adapter-modal-title {\n font-size: 18px;\n }\n}\n\n.wallet-adapter-modal-list {\n margin: 0 0 12px 0;\n padding: 0;\n width: 100%;\n list-style: none;\n}\n\n.wallet-adapter-modal-list .wallet-adapter-button {\n font-weight: 400;\n border-radius: 0;\n font-size: 18px;\n}\n\n.wallet-adapter-modal-list .wallet-adapter-button-end-icon,\n.wallet-adapter-modal-list .wallet-adapter-button-start-icon,\n.wallet-adapter-modal-list .wallet-adapter-button-end-icon img,\n.wallet-adapter-modal-list .wallet-adapter-button-start-icon img {\n width: 28px;\n height: 28px;\n}\n\n.wallet-adapter-modal-list .wallet-adapter-button span {\n margin-left: auto;\n font-size: 14px;\n opacity: .6;\n}\n\n.wallet-adapter-modal-list-more {\n cursor: pointer;\n border: none;\n padding: 12px 24px 24px 12px;\n align-self: flex-end;\n display: flex;\n align-items: center;\n background-color: transparent;\n color: #fff;\n}\n\n.wallet-adapter-modal-list-more svg {\n transition: all 0.1s ease;\n fill: rgba(255, 255, 255, 1);\n margin-left: 0.5rem;\n}\n\n.wallet-adapter-modal-list-more-icon-rotate {\n transform: rotate(180deg);\n}\n\n.wallet-adapter-modal-middle {\n width: 100%;\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: 0 24px 24px 24px;\n box-sizing: border-box;\n}\n\n.wallet-adapter-modal-middle-button {\n display: block;\n cursor: pointer;\n margin-top: 48px;\n width: 100%;\n background-color: #512da8;\n padding: 12px;\n font-size: 18px;\n border: none;\n border-radius: 8px;\n color: #fff;\n}\n",""]);const __WEBPACK_DEFAULT_EXPORT__=___CSS_LOADER_EXPORT___},"./node_modules/css-loader/dist/runtime/api.js":module=>{"use strict";module.exports=function(cssWithMappingToString){var list=[];return list.toString=function toString(){return this.map(function(item){var content="",needLayer=void 0!==item[5];return item[4]&&(content+="@supports (".concat(item[4],") {")),item[2]&&(content+="@media ".concat(item[2]," {")),needLayer&&(content+="@layer".concat(item[5].length>0?" ".concat(item[5]):""," {")),content+=cssWithMappingToString(item),needLayer&&(content+="}"),item[2]&&(content+="}"),item[4]&&(content+="}"),content}).join("")},list.i=function i(modules,media,dedupe,supports,layer){"string"==typeof modules&&(modules=[[null,modules,void 0]]);var alreadyImportedModules={};if(dedupe)for(var k=0;k0?" ".concat(item[5]):""," {").concat(item[1],"}")),item[5]=layer),media&&(item[2]?(item[1]="@media ".concat(item[2]," {").concat(item[1],"}"),item[2]=media):item[2]=media),supports&&(item[4]?(item[1]="@supports (".concat(item[4],") {").concat(item[1],"}"),item[4]=supports):item[4]="".concat(supports)),list.push(item))}},list}},"./node_modules/css-loader/dist/runtime/noSourceMaps.js":module=>{"use strict";module.exports=function(i){return i[1]}},"./node_modules/dijkstrajs/dijkstra.js":module=>{"use strict";var dijkstra={single_source_shortest_paths:function(graph,s,d){var predecessors={},costs={};costs[s]=0;var closest,u,v,cost_of_s_to_u,adjacent_nodes,cost_of_s_to_u_plus_cost_of_e,cost_of_s_to_v,open=dijkstra.PriorityQueue.make();for(open.push(s,0);!open.empty();)for(v in u=(closest=open.pop()).value,cost_of_s_to_u=closest.cost,adjacent_nodes=graph[u]||{})adjacent_nodes.hasOwnProperty(v)&&(cost_of_s_to_u_plus_cost_of_e=cost_of_s_to_u+adjacent_nodes[v],cost_of_s_to_v=costs[v],(void 0===costs[v]||cost_of_s_to_v>cost_of_s_to_u_plus_cost_of_e)&&(costs[v]=cost_of_s_to_u_plus_cost_of_e,open.push(v,cost_of_s_to_u_plus_cost_of_e),predecessors[v]=u));if(void 0!==d&&void 0===costs[d]){var msg=["Could not find a path from ",s," to ",d,"."].join("");throw new Error(msg)}return predecessors},extract_shortest_path_from_predecessor_list:function(predecessors,d){for(var nodes=[],u=d;u;)nodes.push(u),predecessors[u],u=predecessors[u];return nodes.reverse(),nodes},find_path:function(graph,s,d){var predecessors=dijkstra.single_source_shortest_paths(graph,s,d);return dijkstra.extract_shortest_path_from_predecessor_list(predecessors,d)},PriorityQueue:{make:function(opts){var key,T=dijkstra.PriorityQueue,t={};for(key in opts=opts||{},T)T.hasOwnProperty(key)&&(t[key]=T[key]);return t.queue=[],t.sorter=opts.sorter||T.default_sorter,t},default_sorter:function(a,b){return a.cost-b.cost},push:function(value,cost){var item={value,cost};this.queue.push(item),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};module.exports=dijkstra},"./node_modules/eventemitter3/index.js":module=>{"use strict";var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}function EE(fn,context,once){this.fn=fn,this.context=context,this.once=once||!1}function addListener(emitter,event,fn,context,once){if("function"!=typeof fn)throw new TypeError("The listener must be a function");var listener=new EE(fn,context||emitter,once),evt=prefix?prefix+event:event;return emitter._events[evt]?emitter._events[evt].fn?emitter._events[evt]=[emitter._events[evt],listener]:emitter._events[evt].push(listener):(emitter._events[evt]=listener,emitter._eventsCount++),emitter}function clearEvent(emitter,evt){0===--emitter._eventsCount?emitter._events=new Events:delete emitter._events[evt]}function EventEmitter(){this._events=new Events,this._eventsCount=0}Object.create&&(Events.prototype=Object.create(null),(new Events).__proto__||(prefix=!1)),EventEmitter.prototype.eventNames=function eventNames(){var events,name,names=[];if(0===this._eventsCount)return names;for(name in events=this._events)has.call(events,name)&&names.push(prefix?name.slice(1):name);return Object.getOwnPropertySymbols?names.concat(Object.getOwnPropertySymbols(events)):names},EventEmitter.prototype.listeners=function listeners(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i{"use strict";__webpack_require__.d(__webpack_exports__,{A:()=>__WEBPACK_DEFAULT_EXPORT__,b:()=>_index_js__WEBPACK_IMPORTED_MODULE_0__});var _index_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/eventemitter3/index.js");const __WEBPACK_DEFAULT_EXPORT__=_index_js__WEBPACK_IMPORTED_MODULE_0__},"./node_modules/events/events.js":module=>{"use strict";var ReflectOwnKeys,R="object"==typeof Reflect?Reflect:null,ReflectApply=R&&"function"==typeof R.apply?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};ReflectOwnKeys=R&&"function"==typeof R.ownKeys?R.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}:function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)};var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!=value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter,module.exports.once=function once(emitter,name){return new Promise(function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver),reject(err)}function resolver(){"function"==typeof emitter.removeListener&&emitter.removeListener("error",errorListener),resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:!0}),"error"!==name&&function addErrorHandlerIfEventEmitter(emitter,handler,flags){"function"==typeof emitter.on&&eventTargetAgnosticAddListener(emitter,"error",handler,flags)}(emitter,errorListener,{once:!0})})},EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener(listener){if("function"!=typeof listener)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}function _getMaxListeners(that){return void 0===that._maxListeners?EventEmitter.defaultMaxListeners:that._maxListeners}function _addListener(target,type,listener,prepend){var m,events,existing;if(checkListener(listener),void 0===(events=target._events)?(events=target._events=Object.create(null),target._eventsCount=0):(void 0!==events.newListener&&(target.emit("newListener",type,listener.listener?listener.listener:listener),events=target._events),existing=events[type]),void 0===existing)existing=events[type]=listener,++target._eventsCount;else if("function"==typeof existing?existing=events[type]=prepend?[listener,existing]:[existing,listener]:prepend?existing.unshift(listener):existing.push(listener),(m=_getMaxListeners(target))>0&&existing.length>m&&!existing.warned){existing.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners added. Use emitter.setMaxListeners() to increase limit");w.name="MaxListenersExceededWarning",w.emitter=target,w.type=type,w.count=existing.length,function ProcessEmitWarning(warning){console&&console.warn&&console.warn(warning)}(w)}return target}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(target,type,listener){var state={fired:!1,wrapFn:void 0,target,type,listener},wrapped=onceWrapper.bind(state);return wrapped.listener=listener,state.wrapFn=wrapped,wrapped}function _listeners(target,type,unwrap){var events=target._events;if(void 0===events)return[];var evlistener=events[type];return void 0===evlistener?[]:"function"==typeof evlistener?unwrap?[evlistener.listener||evlistener]:[evlistener]:unwrap?function unwrapListeners(arr){for(var ret=new Array(arr.length),i=0;i0&&(er=args[0]),er instanceof Error)throw er;var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));throw err.context=er,err}var handler=events[type];if(void 0===handler)return!1;if("function"==typeof handler)ReflectApply(handler,this,args);else{var len=handler.length,listeners=arrayClone(handler,len);for(i=0;i=0;i--)if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener,position=i;break}if(position<0)return this;0===position?list.shift():function spliceOne(list,index){for(;index+1=0;i--)this.removeListener(type,listeners[i]);return this},EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,!0)},EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,!1)},EventEmitter.listenerCount=function(emitter,type){return"function"==typeof emitter.listenerCount?emitter.listenerCount(type):listenerCount.call(emitter,type)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]}},"./node_modules/ieee754/index.js":(__unused_webpack_module,exports)=>{exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(s?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),(value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias))*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},"./node_modules/jayson/lib/client/browser/index.js":(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";const uuid=__webpack_require__("./node_modules/jayson/node_modules/uuid/dist/esm-browser/index.js").v4,generateRequest=__webpack_require__("./node_modules/jayson/lib/generateRequest.js"),ClientBrowser=function(callServer,options){if(!(this instanceof ClientBrowser))return new ClientBrowser(callServer,options);options||(options={}),this.options={reviver:void 0!==options.reviver?options.reviver:null,replacer:void 0!==options.replacer?options.replacer:null,generator:void 0!==options.generator?options.generator:function(){return uuid()},version:void 0!==options.version?options.version:2,notificationIdNull:"boolean"==typeof options.notificationIdNull&&options.notificationIdNull},this.callServer=callServer};module.exports=ClientBrowser,ClientBrowser.prototype.request=function(method,params,id,callback){const self=this;let request=null;const isBatch=Array.isArray(method)&&"function"==typeof params;if(1===this.options.version&&isBatch)throw new TypeError("JSON-RPC 1.0 does not support batching");if(isBatch||!isBatch&&method&&"object"==typeof method&&"function"==typeof params)callback=params,request=method;else{"function"==typeof id&&(callback=id,id=void 0);const hasCallback="function"==typeof callback;try{request=generateRequest(method,params,id,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(err){if(hasCallback)return callback(err);throw err}if(!hasCallback)return request}let message;try{message=JSON.stringify(request,this.options.replacer)}catch(err){return callback(err)}return this.callServer(message,function(err,response){self._parseResponse(err,response,callback)}),request},ClientBrowser.prototype._parseResponse=function(err,responseText,callback){if(err)return void callback(err);if(!responseText)return callback();let response;try{response=JSON.parse(responseText,this.options.reviver)}catch(err){return callback(err)}if(3===callback.length){if(Array.isArray(response)){const isError=function(res){return void 0!==res.error},isNotError=function(res){return!isError(res)};return callback(null,response.filter(isError),response.filter(isNotError))}return callback(null,response.error,response.result)}callback(null,response)}},"./node_modules/jayson/lib/generateRequest.js":(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";const uuid=__webpack_require__("./node_modules/jayson/node_modules/uuid/dist/esm-browser/index.js").v4;module.exports=function(method,params,id,options){if("string"!=typeof method)throw new TypeError(method+" must be a string");const version="number"==typeof(options=options||{}).version?options.version:2;if(1!==version&&2!==version)throw new TypeError(version+" must be 1 or 2");const request={method};if(2===version&&(request.jsonrpc="2.0"),params){if("object"!=typeof params&&!Array.isArray(params))throw new TypeError(params+" must be an object, array or omitted");request.params=params}if(void 0===id){const generator="function"==typeof options.generator?options.generator:function(){return uuid()};request.id=generator(request,options)}else 2===version&&null===id?options.notificationIdNull&&(request.id=null):request.id=id;return request}},"./node_modules/jayson/node_modules/uuid/dist/esm-browser/index.js":(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{"use strict";var getRandomValues;__webpack_require__.d(__webpack_exports__,{v4:()=>esm_browser_v4});var rnds8=new Uint8Array(16);function rng(){if(!getRandomValues&&!(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}const regex=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;const esm_browser_validate=function validate(uuid){return"string"==typeof uuid&®ex.test(uuid)};for(var byteToHex=[],i=0;i<256;++i)byteToHex.push((i+256).toString(16).substr(1));const esm_browser_stringify=function stringify(arr){var offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,uuid=(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();if(!esm_browser_validate(uuid))throw TypeError("Stringified UUID is invalid");return uuid};const esm_browser_v4=function v4(options,buf,offset){var rnds=(options=options||{}).random||(options.rng||rng)();if(rnds[6]=15&rnds[6]|64,rnds[8]=63&rnds[8]|128,buf){offset=offset||0;for(var i=0;i<16;++i)buf[offset+i]=rnds[i];return buf}return esm_browser_stringify(rnds)}},"./node_modules/react-dom/cjs/react-dom.production.min.js":(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var aa=__webpack_require__("./node_modules/react/index.js"),ca=__webpack_require__("./node_modules/scheduler/index.js");function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c