From b29cdc1b07c39908a083a8f0edc0ff4e9eb8ec24 Mon Sep 17 00:00:00 2001 From: Leeland Clenista Date: Mon, 15 Dec 2025 11:50:11 -0800 Subject: [PATCH] remove nacl and tweetnacl-util package --- .../dist/bundle.78c912c0211a44421f40.js | 3 --- .../dist/bundle.78c912c0211a44421f40.js.map | 1 - .../dist/bundle.df1ee7804c25796915e3.js | 3 --- .../dist/bundle.df1ee7804c25796915e3.js.map | 1 - .../dist/bundle.ecd3017216b8f9e85944.js | 3 +++ ...undle.ecd3017216b8f9e85944.js.LICENSE.txt} | 0 .../dist/bundle.ecd3017216b8f9e85944.js.map | 1 + .../dist/bundle.f14f48a41b2945673e48.js | 3 +++ ...undle.f14f48a41b2945673e48.js.LICENSE.txt} | 0 .../dist/bundle.f14f48a41b2945673e48.js.map | 1 + export-and-sign/dist/index.html | 2 +- export-and-sign/package-lock.json | 26 +------------------ export-and-sign/package.json | 4 +-- export-and-sign/src/event-handlers.js | 17 +++++++++--- 14 files changed, 24 insertions(+), 41 deletions(-) delete mode 100644 export-and-sign/dist/bundle.78c912c0211a44421f40.js delete mode 100644 export-and-sign/dist/bundle.78c912c0211a44421f40.js.map delete mode 100644 export-and-sign/dist/bundle.df1ee7804c25796915e3.js delete mode 100644 export-and-sign/dist/bundle.df1ee7804c25796915e3.js.map create mode 100644 export-and-sign/dist/bundle.ecd3017216b8f9e85944.js rename export-and-sign/dist/{bundle.df1ee7804c25796915e3.js.LICENSE.txt => bundle.ecd3017216b8f9e85944.js.LICENSE.txt} (100%) create mode 100644 export-and-sign/dist/bundle.ecd3017216b8f9e85944.js.map create mode 100644 export-and-sign/dist/bundle.f14f48a41b2945673e48.js rename export-and-sign/dist/{bundle.78c912c0211a44421f40.js.LICENSE.txt => bundle.f14f48a41b2945673e48.js.LICENSE.txt} (100%) create mode 100644 export-and-sign/dist/bundle.f14f48a41b2945673e48.js.map diff --git a/export-and-sign/dist/bundle.78c912c0211a44421f40.js b/export-and-sign/dist/bundle.78c912c0211a44421f40.js deleted file mode 100644 index b8d76fa..0000000 --- a/export-and-sign/dist/bundle.78c912c0211a44421f40.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see bundle.78c912c0211a44421f40.js.LICENSE.txt */ -(()=>{var e,t,r,n,o,a={662:()=>{},758:(e,t,r)=>{"use strict";var n=r(598),o=r(810);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(a(e)+" is not iterable")}function l(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}}function p(e,t,r,n,o){var a=d(e,t,r,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})}function d(e,t,r,n,o){return new y(v().w(e,t,r,n),o||Promise)}function y(e,t){function r(n,o,a,i){try{var u=e[n](o),c=u.value;return c instanceof b?t.resolve(c.v).then(function(e){r("next",e,a,i)},function(e){r("throw",e,a,i)}):t.resolve(c).then(function(e){u.value=e,a(u)},function(e){return r("throw",e,a,i)})}catch(e){i(e)}}var n;this.next||(m(y.prototype),m(y.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),m(this,"_invoke",function(e,o,a){function i(){return new t(function(t,n){r(e,a,t,n)})}return n=n?n.then(i,i):i()},!0)}function v(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var c=n&&n.prototype instanceof u?n:u,s=Object.create(c.prototype);return m(s,"_invoke",function(r,n,o){var a,u,c,s=0,f=o||[],l=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return a=t,u=0,c=e,p.n=r,i}};function d(r,n){for(u=r,c=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(c=a[(u=a[4])?5:(u=3,3)],a[4]=a[5]=e):a[0]<=d&&((o=r<2&&dn||n>y)&&(a[4]=r,a[5]=n,p.n=y,u=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,y),u=f,c=y;(t=u<2?e:c)||!l;){a||(u?u<3?(u>1&&(p.n=-1),d(u,c)):p.n=c:p.v=c);try{if(s=2,a){if(u||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,u<2&&(u=0)}else 1===u&&(t=a.return)&&t.call(a),u<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),u=1);a=e}else if((t=(l=p.n<0)?c:r.call(n,p))!==i)break}catch(t){a=e,u=1,c=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function u(){}function c(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(m(t={},n,function(){return this}),t),l=s.prototype=u.prototype=Object.create(f);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,m(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return c.prototype=s,m(l,"constructor",s),m(s,"constructor",c),c.displayName="GeneratorFunction",m(s,o,"GeneratorFunction"),m(l),m(l,o,"Generator"),m(l,n,function(){return this}),m(l,"toString",function(){return"[object Generator]"}),(v=function(){return{w:a,m:p}})()}function m(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}m=function(e,t,r,n){function a(t,r){m(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},m(e,t,r,n)}function b(e,t){this.v=e,this.k=t}function h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(e){s=!0,o=e}finally{try{if(!c&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw o}}return u}}(e,t)||w(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e){return function(e){if(Array.isArray(e))return x(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||w(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function w(e,t){if(e){if("string"==typeof e)return x(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?x(e,t):void 0}}function x(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function j(e){return I.apply(this,arguments)}function I(){return(I=S(s().mark(function e(t){return s().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,crypto.subtle.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}},e)}))).apply(this,arguments)}function N(){return(N=S(s().mark(function e(){return s().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!_()){e.next=2;break}throw new Error("Doubly iframed");case 2:return e.next=4,D();case 4:if(null!==e.sent){e.next=10;break}return e.next=8,T();case 8:R(e.sent);case 10:case"end":return e.stop()}},e)}))).apply(this,arguments)}function T(){return A.apply(this,arguments)}function A(){return(A=S(s().mark(function e(){var t;return s().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return t=e.sent,e.next=5,crypto.subtle.exportKey("jwk",t.privateKey);case 5:return e.abrupt("return",e.sent);case 6:case"end":return e.stop()}},e)}))).apply(this,arguments)}function D(){var e=M(O);return e?JSON.parse(e):null}function R(e){K(O,JSON.stringify(e),1728e5)}function K(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function M(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return r.hasOwnProperty("expiry")&&r.hasOwnProperty("value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function U(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function G(e){return g(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function C(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(g(n),g(e)))}if(r<0){for(var o=-1*r,a=0,i=0;i0;)r.push(o%58),o=o/58|0}for(var i=0;i0;){var u=r[i];a=(u=void 0===u?a:58*u+a)>>8,r[i]=u%256,i++}}var c=n.concat(r.reverse());return new Uint8Array(c)}function z(){return(z=S(s().mark(function e(t,r,n){var o;return s().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.t0=r,e.next="SOLANA"===e.t0?3:"HEXADECIMAL"===e.t0?13:14;break;case 3:if(n){e.next=5;break}throw new Error("public key must be specified for SOLANA key format");case 5:if(32===t.length){e.next=7;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 7:if(32===n.length){e.next=9;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 9:return(o=new Uint8Array(64)).set(t,0),o.set(n,32),e.abrupt("return",H(o));case 13:return e.abrupt("return","0x"+G(t));case 14:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.abrupt("return","0x"+G(t));case 16:case"end":return e.stop()}},e)}))).apply(this,arguments)}function $(e,t){var r={},n={padding:"^(\\d+(px|em|%|rem) ?){1,4}$",margin:"^(\\d+(px|em|%|rem) ?){1,4}$",borderWidth:"^(\\d+(px|em|rem) ?){1,4}$",borderStyle:"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$",borderColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",borderRadius:"^(\\d+(px|em|%|rem) ?){1,4}$",fontSize:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$",fontWeight:"^(normal|bold|bolder|lighter|\\d{3})$",fontFamily:'^[^";<>]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t=h(e,2),o=t[0],a=t[1],i=o.trim();if(0===i.length)throw new Error("css style property cannot be empty");var u=n[i];if(!u)throw new Error('invalid or unsupported css style property: "'.concat(i,'"'));var c=new RegExp(u),s=a.trim();if(0==s.length)throw new Error('css style for "'.concat(i,'" is empty'));if(!c.test(s))throw new Error('invalid css style value for property "'.concat(i,'"'));r[i]=s}),r}var q={initEmbeddedKey:function(){return N.apply(this,arguments)},generateTargetKey:T,setItemWithExpiry:K,getItemWithExpiry:M,getEmbeddedKey:D,setEmbeddedKey:R,onResetEmbeddedKey:function(){window.localStorage.removeItem(O),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:function(e){return Y.apply(this,arguments)},base58Encode:H,base58Decode:J,encodeKey:function(e,t,r){return z.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),P?P.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),F("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:F,uint8arrayFromHexString:U,uint8arrayToHexString:G,setParentFrameMessageChannelPort:function(e){P=e},normalizePadding:C,fromDerSignature:B,additionalAssociatedData:function(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))},verifyEnclaveSignature:function(e,t,r){return L.apply(this,arguments)},getEd25519PublicKey:function(e){return n.jn.sha512Sync=function(){var e;return o.Zf((e=n.jn).concatBytes.apply(e,arguments))},n.lG(e)},applySettings:function(e){var t={};if(!e)return JSON.stringify(t);var r=JSON.parse(e);if(r.styles){var n=document.getElementById("key-div");if(!n)throw new Error("no key-div HTML element found to apply settings to.");var o=$(r.styles);Object.entries(o).forEach(function(e){var t=h(e,2),r=t[0],o=t[1];n.style[r]=o}),t.styles=o}return JSON.stringify(t)},validateStyles:$,getSettings:function(){var e=window.localStorage.getItem(k);return e?JSON.parse(e):null},setSettings:function(e){window.localStorage.setItem(k,JSON.stringify(e))},parsePrivateKey:function(e){if(Array.isArray(e))return new Uint8Array(e);if("string"==typeof e){if(e.startsWith("0x")&&(e=e.slice(2)),64===e.length&&/^[0-9a-fA-F]+$/.test(e))return U(e);try{return J(e)}catch(e){throw new Error("Invalid private key format. Use hex (64 chars) or base58 format.")}}throw new Error("Private key must be a string (hex/base58) or number array")}},W=r(112),X=r(947),V=r.n(X),Q=r(255);function Z(e){return Z="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Z(e)}function ee(){var e=ie(),t=e.m(ee),r=(Object.getPrototypeOf?Object.getPrototypeOf(t):t.__proto__).constructor;function n(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===r||"GeneratorFunction"===(t.displayName||t.name))}var o={throw:1,return:2,break:3,continue:3};function a(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,o[e],t)},delegateYield:function(e,o,a){return t.resultName=o,r(n.d,te(e),a)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(ee=function(){return{wrap:function(t,r,n,o){return e.w(a(t),r,n,o&&o.reverse())},isGeneratorFunction:n,mark:e.m,awrap:function(e,t){return new ce(e,t)},AsyncIterator:ae,async:function(e,t,r,o,i){return(n(t)?oe:ne)(a(e),t,r,o,i)},keys:re,values:te}})()}function te(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(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(Z(e)+" is not iterable")}function re(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}}function ne(e,t,r,n,o){var a=oe(e,t,r,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})}function oe(e,t,r,n,o){return new ae(ie().w(e,t,r,n),o||Promise)}function ae(e,t){function r(n,o,a,i){try{var u=e[n](o),c=u.value;return c instanceof ce?t.resolve(c.v).then(function(e){r("next",e,a,i)},function(e){r("throw",e,a,i)}):t.resolve(c).then(function(e){u.value=e,a(u)},function(e){return r("throw",e,a,i)})}catch(e){i(e)}}var n;this.next||(ue(ae.prototype),ue(ae.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),ue(this,"_invoke",function(e,o,a){function i(){return new t(function(t,n){r(e,a,t,n)})}return n=n?n.then(i,i):i()},!0)}function ie(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var c=n&&n.prototype instanceof u?n:u,s=Object.create(c.prototype);return ue(s,"_invoke",function(r,n,o){var a,u,c,s=0,f=o||[],l=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return a=t,u=0,c=e,p.n=r,i}};function d(r,n){for(u=r,c=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(c=a[(u=a[4])?5:(u=3,3)],a[4]=a[5]=e):a[0]<=d&&((o=r<2&&dn||n>y)&&(a[4]=r,a[5]=n,p.n=y,u=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,y),u=f,c=y;(t=u<2?e:c)||!l;){a||(u?u<3?(u>1&&(p.n=-1),d(u,c)):p.n=c:p.v=c);try{if(s=2,a){if(u||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,u<2&&(u=0)}else 1===u&&(t=a.return)&&t.call(a),u<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),u=1);a=e}else if((t=(l=p.n<0)?c:r.call(n,p))!==i)break}catch(t){a=e,u=1,c=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function u(){}function c(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ue(t={},n,function(){return this}),t),l=s.prototype=u.prototype=Object.create(f);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ue(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return c.prototype=s,ue(l,"constructor",s),ue(s,"constructor",c),c.displayName="GeneratorFunction",ue(s,o,"GeneratorFunction"),ue(l),ue(l,o,"Generator"),ue(l,n,function(){return this}),ue(l,"toString",function(){return"[object Generator]"}),(ie=function(){return{w:a,m:p}})()}function ue(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}ue=function(e,t,r,n){function a(t,r){ue(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},ue(e,t,r,n)}function ce(e,t){this.v=e,this.k=t}function se(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function fe(e){for(var t=1;t=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(me(e)+" is not iterable")}function Ee(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}}function Se(e,t,r,n,o){var a=Oe(e,t,r,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})}function Oe(e,t,r,n,o){return new ke(Pe().w(e,t,r,n),o||Promise)}function ke(e,t){function r(n,o,a,i){try{var u=e[n](o),c=u.value;return c instanceof je?t.resolve(c.v).then(function(e){r("next",e,a,i)},function(e){r("throw",e,a,i)}):t.resolve(c).then(function(e){u.value=e,a(u)},function(e){return r("throw",e,a,i)})}catch(e){i(e)}}var n;this.next||(_e(ke.prototype),_e(ke.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),_e(this,"_invoke",function(e,o,a){function i(){return new t(function(t,n){r(e,a,t,n)})}return n=n?n.then(i,i):i()},!0)}function Pe(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var c=n&&n.prototype instanceof u?n:u,s=Object.create(c.prototype);return _e(s,"_invoke",function(r,n,o){var a,u,c,s=0,f=o||[],l=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return a=t,u=0,c=e,p.n=r,i}};function d(r,n){for(u=r,c=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(c=a[(u=a[4])?5:(u=3,3)],a[4]=a[5]=e):a[0]<=d&&((o=r<2&&dn||n>y)&&(a[4]=r,a[5]=n,p.n=y,u=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,y),u=f,c=y;(t=u<2?e:c)||!l;){a||(u?u<3?(u>1&&(p.n=-1),d(u,c)):p.n=c:p.v=c);try{if(s=2,a){if(u||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,u<2&&(u=0)}else 1===u&&(t=a.return)&&t.call(a),u<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),u=1);a=e}else if((t=(l=p.n<0)?c:r.call(n,p))!==i)break}catch(t){a=e,u=1,c=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function u(){}function c(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(_e(t={},n,function(){return this}),t),l=s.prototype=u.prototype=Object.create(f);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,_e(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return c.prototype=s,_e(l,"constructor",s),_e(s,"constructor",c),c.displayName="GeneratorFunction",_e(s,o,"GeneratorFunction"),_e(l),_e(l,o,"Generator"),_e(l,n,function(){return this}),_e(l,"toString",function(){return"[object Generator]"}),(Pe=function(){return{w:a,m:p}})()}function _e(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}_e=function(e,t,r,n){function a(t,r){_e(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},_e(e,t,r,n)}function je(e,t){this.v=e,this.k=t}function Ie(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(e){s=!0,o=e}finally{try{if(!c&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw o}}return u}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ne(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ne(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ne(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 22:if(u.organizationId&&u.organizationId===r){e.next=24;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(u.organizationId,"."));case 24:if(u.encappedPublic){e.next=26;break}throw new Error('missing "encappedPublic" in bundle signed data');case 26:if(u.ciphertext){e.next=28;break}throw new Error('missing "ciphertext" in bundle signed data');case 28:return o=q.uint8arrayFromHexString(u.encappedPublic),a=q.uint8arrayFromHexString(u.ciphertext),e.abrupt("break",32);case 31:throw new Error("unsupported version: ".concat(i.version));case 32:return e.next=34,q.getEmbeddedKey();case 34:return c=e.sent,e.next=37,n({ciphertextBuf:a,encappedKeyBuf:o,receiverPrivJwk:c});case 37:return e.abrupt("return",e.sent);case 38:case"end":return e.stop()}},e)})),Ue.apply(this,arguments)}function Ge(e){return Ce.apply(this,arguments)}function Ce(){return(Ce=Ae(we().mark(function e(t){var r,n,o;return we().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=q.getEmbeddedKey()){e.next=4;break}return q.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.abrupt("return");case 4:return e.next=6,q.p256JWKPrivateToPublic(r);case 6:n=e.sent,o=q.uint8arrayToHexString(n),q.sendMessageUp("EMBEDDED_PUBLIC_KEY",o,t);case 9:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Be(e,t,r,n,o,a){return Le.apply(this,arguments)}function Le(){return Le=Ae(we().mark(function e(t,r,n,o,a,i){var u,c,s,f,l,p,d;return we().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Me(n,r,i);case 2:if(u=e.sent,s=new Uint8Array(u),"SOLANA"!==o){e.next=12;break}return f=q.uint8arrayToHexString(s.subarray(0,32)),l=q.getEd25519PublicKey(f),e.next=9,q.encodeKey(s,o,l);case 9:c=e.sent,e.next=15;break;case 12:return e.next=14,q.encodeKey(s,o);case 14:c=e.sent;case 15:if(p=a||"default","SOLANA"!==o){e.next=20;break}d=W.AX.fromSecretKey(q.base58Decode(c)),e.next=24;break;case 20:if("HEXADECIMAL"!==o){e.next=24;break}return e.next=23,Xe(Array.from(q.uint8arrayFromHexString(c)));case 23:d=e.sent;case 24:De=he(he({},De),{},ge({},p,{organizationId:r,privateKey:c,format:o,expiry:(new Date).getTime()+864e5,keypair:d})),q.sendMessageUp("BUNDLE_INJECTED",!0,t);case 26:case"end":return e.stop()}},e)})),Le.apply(this,arguments)}function Fe(e,t){return Ye.apply(this,arguments)}function Ye(){return(Ye=Ae(we().mark(function e(t,r){var n;return we().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=q.applySettings(t),q.setSettings(n),q.sendMessageUp("SETTINGS_APPLIED",!0,r);case 3:case"end":return e.stop()}},e)}))).apply(this,arguments)}function He(e,t,r){return Je.apply(this,arguments)}function Je(){return(Je=Ae(we().mark(function e(t,r,n){var o,a,i,u,c,s,f,l,p;return we().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(Ze(a=De[o=n||"default"],o)){e.next=4;break}return e.abrupt("return");case 4:return e.next=6,et(a);case 6:if(i=e.sent,u=JSON.parse(r),c=u.transaction,"SOLANA"!==u.type){e.next=17;break}f=q.uint8arrayFromHexString(c),(l=W.Kt.deserialize(f)).sign([i]),s=l.serialize(),e.next=18;break;case 17:throw new Error("unsupported transaction type");case 18:p=q.uint8arrayToHexString(s),q.sendMessageUp("TRANSACTION_SIGNED",p,t);case 20:case"end":return e.stop()}},e)}))).apply(this,arguments)}function ze(e,t,r){return $e.apply(this,arguments)}function $e(){return($e=Ae(we().mark(function e(t,r,n){var o,a,i,u,c,s,f,l,p;return we().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(Ze(a=De[o=n||"default"],o)){e.next=4;break}return e.abrupt("return");case 4:return i=JSON.parse(r),u=i.message,c=i.type,s=Re.encode(u),e.next=10,et(a);case 10:if(l=e.sent,"SOLANA"!==c){e.next=16;break}p=V().sign.detached(s,l.secretKey),f=q.uint8arrayToHexString(p),e.next=18;break;case 16:return q.sendMessageUp("ERROR","unsupported message type",t),e.abrupt("return");case 18:q.sendMessageUp("MESSAGE_SIGNED",f,t);case 19:case"end":return e.stop()}},e)}))).apply(this,arguments)}function qe(e,t){return We.apply(this,arguments)}function We(){return(We=Ae(we().mark(function e(t,r){return we().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r){e.next=4;break}return De={},q.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.abrupt("return");case 4:if(De[r]){e.next=7;break}return q.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.abrupt("return");case 7:delete De[r],q.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 9:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Xe(e){return Ve.apply(this,arguments)}function Ve(){return(Ve=Ae(we().mark(function e(t){var r,n;return we().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(32!==(r=q.parsePrivateKey(t)).length){e.next=5;break}n=W.AX.fromSeed(r),e.next=10;break;case 5:if(64!==r.length){e.next=9;break}n=W.AX.fromSecretKey(r),e.next=10;break;case 9:throw new Error("Invalid private key length: ".concat(r.length,". Expected 32 or 64 bytes."));case 10:return e.abrupt("return",n);case 11:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Qe(e){De[e]&&delete De[e]}function Ze(e,t){if(!e)throw new Error("key bytes not found. Please re-inject export bundle for address ".concat(t," into iframe. Note that address is case sensitive.")).toString();if((new Date).getTime()>=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(De);r=i.expiry&&t.push(a)}for(var u=0,c=t;u=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(nt(e)+" is not iterable")}function it(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}}function ut(e,t,r,n,o){var a=ct(e,t,r,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})}function ct(e,t,r,n,o){return new st(ft().w(e,t,r,n),o||Promise)}function st(e,t){function r(n,o,a,i){try{var u=e[n](o),c=u.value;return c instanceof pt?t.resolve(c.v).then(function(e){r("next",e,a,i)},function(e){r("throw",e,a,i)}):t.resolve(c).then(function(e){u.value=e,a(u)},function(e){return r("throw",e,a,i)})}catch(e){i(e)}}var n;this.next||(lt(st.prototype),lt(st.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),lt(this,"_invoke",function(e,o,a){function i(){return new t(function(t,n){r(e,a,t,n)})}return n=n?n.then(i,i):i()},!0)}function ft(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var c=n&&n.prototype instanceof u?n:u,s=Object.create(c.prototype);return lt(s,"_invoke",function(r,n,o){var a,u,c,s=0,f=o||[],l=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return a=t,u=0,c=e,p.n=r,i}};function d(r,n){for(u=r,c=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(c=a[(u=a[4])?5:(u=3,3)],a[4]=a[5]=e):a[0]<=d&&((o=r<2&&dn||n>y)&&(a[4]=r,a[5]=n,p.n=y,u=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,y),u=f,c=y;(t=u<2?e:c)||!l;){a||(u?u<3?(u>1&&(p.n=-1),d(u,c)):p.n=c:p.v=c);try{if(s=2,a){if(u||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,u<2&&(u=0)}else 1===u&&(t=a.return)&&t.call(a),u<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),u=1);a=e}else if((t=(l=p.n<0)?c:r.call(n,p))!==i)break}catch(t){a=e,u=1,c=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function u(){}function c(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(lt(t={},n,function(){return this}),t),l=s.prototype=u.prototype=Object.create(f);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,lt(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return c.prototype=s,lt(l,"constructor",s),lt(s,"constructor",c),c.displayName="GeneratorFunction",lt(s,o,"GeneratorFunction"),lt(l),lt(l,o,"Generator"),lt(l,n,function(){return this}),lt(l,"toString",function(){return"[object Generator]"}),(ft=function(){return{w:a,m:p}})()}function lt(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}lt=function(e,t,r,n){function a(t,r){lt(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},lt(e,t,r,n)}function pt(e,t){this.v=e,this.k=t}function dt(e,t,r,n,o,a,i){try{var u=e[a](i),c=u.value}catch(e){return void r(e)}u.done?t(c):Promise.resolve(c).then(n,o)}function yt(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var a=e.apply(t,r);function i(e){dt(a,n,o,i,u,"next",e)}function u(e){dt(a,n,o,i,u,"throw",e)}i(void 0)})}}window.TKHQ=q,document.addEventListener("DOMContentLoaded",yt(ot().mark(function e(){var t,r,n,o;return ot().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,q.initEmbeddedKey();case 2:return e.next=4,q.getEmbeddedKey();case 4:return t=e.sent,e.next=7,q.p256JWKPrivateToPublic(t);case 7:r=e.sent,n=q.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,rt(ye),(o=q.getSettings())&&q.applySettings(o),q.sendMessageUp("PUBLIC_KEY_READY",n);case 14:case"end":return e.stop()}},e)}))),window.addEventListener("message",function(){var e=yt(ot().mark(function e(t){var r,n,o,a,i;return ot().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.data||"TURNKEY_INIT_MESSAGE_CHANNEL"!=t.data.type||null===(r=t.ports)||void 0===r||!r[0]){e.next=15;break}return(n=t.ports[0]).onmessage=rt(ye).messageEventListener,q.setParentFrameMessageChannelPort(n),e.next=6,q.initEmbeddedKey();case 6:return e.next=8,q.getEmbeddedKey();case 8:return o=e.sent,e.next=11,q.p256JWKPrivateToPublic(o);case 11:a=e.sent,i=q.uint8arrayToHexString(a),document.getElementById("embedded-key").value=i,q.sendMessageUp("PUBLIC_KEY_READY",i);case 15:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}())},790:()=>{}},i={};function u(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return a[e].call(r.exports,r,r.exports,u),r.loaded=!0,r.exports}u.m=a,e=[],u.O=(t,r,n,o)=>{if(!r){var a=1/0;for(f=0;f=o)&&Object.keys(u.O).every(e=>u.O[e](r[c]))?r.splice(c--,1):(i=!1,o0&&e[f-1][2]>o;f--)e[f]=e[f-1];e[f]=[r,n,o]},u.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return u.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,u.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var o=Object.create(null);u.r(o);var a={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>a[t]=()=>e[t]);return a.default=()=>e,u.d(o,a),o},u.d=(e,t)=>{for(var r in t)u.o(t,r)&&!u.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},u.f={},u.e=e=>Promise.all(Object.keys(u.f).reduce((t,r)=>(u.f[r](e,t),t),[])),u.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",u.miniCssF=e=>{},u.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},o="export-and-sign:",u.l=(e,t,r,a)=>{if(n[e])n[e].push(t);else{var i,c;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(d);var o=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),o&&o.forEach(e=>e(r)),t)return t(r)},d=setTimeout(p.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=p.bind(null,i.onerror),i.onload=p.bind(null,i.onload),c&&document.head.appendChild(i)}},u.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},u.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),u.p="/",(()=>{var e={792:0};u.f.j=(t,r)=>{var n=u.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var o=new Promise((r,o)=>n=e[t]=[r,o]);r.push(n[2]=o);var a=u.p+u.u(t),i=new Error;u.l(a,r=>{if(u.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var o=r&&("load"===r.type?"missing":r.type),a=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+o+": "+a+")",i.name="ChunkLoadError",i.type=o,i.request=a,n[1](i)}},"chunk-"+t,t)}},u.O.j=t=>0===e[t];var t=(t,r)=>{var n,o,[a,i,c]=r,s=0;if(a.some(t=>0!==e[t])){for(n in i)u.o(i,n)&&(u.m[n]=i[n]);if(c)var f=c(u)}for(t&&t(r);su(758));c=u.O(c)})(); -//# sourceMappingURL=bundle.78c912c0211a44421f40.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.78c912c0211a44421f40.js.map b/export-and-sign/dist/bundle.78c912c0211a44421f40.js.map deleted file mode 100644 index 25d1a30..0000000 --- a/export-and-sign/dist/bundle.78c912c0211a44421f40.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bundle.78c912c0211a44421f40.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,y2GCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ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AAEpS,EAAKwT,GAA0C,IAA7B8B,EAAgB9B,GAGxD,IAAIqC,EAAuB,CAACC,EAA4BzM,KACvD,IAGIwI,EAAU2B,GAHTnB,EAAU0D,EAAaC,GAAW3M,EAGhB5V,EAAI,EAC3B,GAAG4e,EAAS4D,KAAMhE,GAAgC,IAAxBqD,EAAgBrD,IAAa,CACtD,IAAIJ,KAAYkE,EACZnE,EAAoBre,EAAEwiB,EAAalE,KACrCD,EAAoBrc,EAAEsc,GAAYkE,EAAYlE,IAGhD,GAAGmE,EAAS,IAAInW,EAASmW,EAAQpE,EAClC,CAEA,IADGkE,GAA4BA,EAA2BzM,GACrD5V,EAAI4e,EAAS5d,OAAQhB,IACzB+f,EAAUnB,EAAS5e,GAChBme,EAAoBre,EAAE+hB,EAAiB9B,IAAY8B,EAAgB9B,IACrE8B,EAAgB9B,GAAS,KAE1B8B,EAAgB9B,GAAW,EAE5B,OAAO5B,EAAoBQ,EAAEvS,IAG1BqW,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBpT,QAAQ+S,EAAqBrhB,KAAK,KAAM,IAC3D0hB,EAAmB9f,KAAOyf,EAAqBrhB,KAAK,KAAM0hB,EAAmB9f,KAAK5B,KAAK0hB,G,KClFvF,IAAIE,EAAsBxE,EAAoBQ,OAAEpa,EAAW,CAAC,IAAK,IAAO4Z,EAAoB,MAC5FwE,EAAsBxE,EAAoBQ,EAAEgE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/crypto-utils.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","/**\n * Turnkey Core Module\n * Contains all the core cryptographic and utility functions\n */\n\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n/** constant for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n return await crypto.subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const p256key = await crypto.subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (!item.hasOwnProperty(\"expiry\") || !item.hasOwnProperty(\"value\")) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decoded = BigInt(0);\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await TKHQ.p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = TKHQ.additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport nacl from \"tweetnacl\";\nimport { HpkeDecrypt } from \"./crypto-utils.js\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n let encappedKeyBuf;\n let ciphertextBuf;\n let verified;\n\n // Parse the import bundle\n const bundleObj = JSON.parse(bundle);\n switch (bundleObj.version) {\n case \"v1.0.0\":\n // Validate fields exist\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n // Verify enclave signature\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(`failed to verify enclave signature: ${bundle}`);\n }\n\n // Parse the signed data. The data is produced by JSON encoding followed by hex encoding. We reverse this here.\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n // Validate fields match\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n encappedKeyBuf = TKHQ.uint8arrayFromHexString(signedData.encappedPublic);\n ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n break;\n default:\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Parse the decrypted key bytes\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n // Set in memory\n // If no address provided, use a default key\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair, // Cache the keypair for performance\n },\n };\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Sign the message\n const signature = nacl.sign.detached(messageBytes, keypair.secretKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error( `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectWalletBundle(\n event.data[\"value\"],\n event.data[\"organizationId\"],\n event.data[\"requestId\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n};\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"./crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n\n// Init MessageChannel for communication between iframe <> parent page\nwindow.addEventListener(\"message\", async function (event) {\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage =\n initEventHandlers(HpkeDecrypt).messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n }\n});\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(758)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_slicedToArray","Array","isArray","_arrayWithHoles","next","push","_iterableToArrayLimit","_unsupportedIterableToArray","_nonIterableRest","_toConsumableArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","isDoublyIframed","undefined","window","location","ancestorOrigins","parent","top","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","crypto","subtle","importKey","namedCurve","abrupt","sent","stop","_initEmbeddedKey","_callee2","_context2","Error","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee3","p256key","_context3","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","key","ttl","item","expiry","Date","getTime","localStorage","setItem","itemStr","getItem","hasOwnProperty","removeItem","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","s","rPadded","sPadded","_verifyEnclaveSignature","_callee4","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context4","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","verify","hash","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","_p256JWKPrivateToPublic","_callee5","jwkPrivate","jwkPrivateCopy","publicKey","_context5","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","base58Decode","alphabet","decodedBytes","BigInt","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee6","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_context6","t0","set","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","TKHQ","initEmbeddedKey","onResetEmbeddedKey","p256JWKPrivateToPublic","_x5","encodeKey","_x6","_x7","_x8","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","additionalAssociatedData","senderPubBuf","receiverPubBuf","verifyEnclaveSignature","_x2","_x3","_x4","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","_ref3","_ref4","style","getSettings","setSettings","parsePrivateKey","error","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeDecrypt","_HpkeDecrypt","ciphertextBuf","encappedKeyBuf","receiverPrivJwk","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","inMemoryKeys","textEncoder","textDecoder","TextDecoder","decryptBundle","_decryptBundle","_callee8","bundle","organizationId","bundleObj","embeddedKeyJwk","_context8","version","data","dataSignature","decode","encappedPublic","ciphertext","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee9","targetPubBuf","targetPubHex","_context9","onInjectKeyBundle","_x9","_x10","_onInjectKeyBundle","_callee10","address","keyBytes","keyAddress","cachedKeypair","_context10","subarray","Keypair","fromSecretKey","createSolanaKeypair","format","keypair","onApplySettings","_x11","_x12","_onApplySettings","_callee11","_context11","onSignTransaction","_x13","_x14","_x15","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x16","_x17","_x18","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","nacl","detached","secretKey","onClearEmbeddedPrivateKey","_x19","_x20","_onClearEmbeddedPrivateKey","_callee14","_context14","_x21","_createSolanaKeypair","_callee15","_context15","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x22","_getOrCreateKeypair","_callee16","_context16","initEventHandlers","messageEventListener","_messageEventListener","event","onInjectWalletBundle","t1","t2","t3","t4","t5","t6","_x28","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","preventDefault","_x23","_x24","_x25","_x26","injectWalletBtn","_ref5","_x27","addDOMEventListeners","capture","signal","_ref6","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x29","styleSettings","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","module","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","onScriptComplete","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/bundle.df1ee7804c25796915e3.js b/export-and-sign/dist/bundle.df1ee7804c25796915e3.js deleted file mode 100644 index ebe4ebe..0000000 --- a/export-and-sign/dist/bundle.df1ee7804c25796915e3.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see bundle.df1ee7804c25796915e3.js.LICENSE.txt */ -(self.webpackChunkexport_and_sign=self.webpackChunkexport_and_sign||[]).push([[96],{22:(t,e,r)=>{"use strict";const n=r(341).v4,i=r(289),s=function(t,e){if(!(this instanceof s))return new s(t,e);e||(e={}),this.options={reviver:void 0!==e.reviver?e.reviver:null,replacer:void 0!==e.replacer?e.replacer:null,generator:void 0!==e.generator?e.generator:function(){return n()},version:void 0!==e.version?e.version:2,notificationIdNull:"boolean"==typeof e.notificationIdNull&&e.notificationIdNull},this.callServer=t};t.exports=s,s.prototype.request=function(t,e,r,n){const s=this;let o=null;const a=Array.isArray(t)&&"function"==typeof e;if(1===this.options.version&&a)throw new TypeError("JSON-RPC 1.0 does not support batching");if(a||!a&&t&&"object"==typeof t&&"function"==typeof e)n=e,o=t;else{"function"==typeof r&&(n=r,r=void 0);const s="function"==typeof n;try{o=i(t,e,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(t){if(s)return n(t);throw t}if(!s)return o}let u;try{u=JSON.stringify(o,this.options.replacer)}catch(t){return n(t)}return this.callServer(u,function(t,e){s._parseResponse(t,e,n)}),o},s.prototype._parseResponse=function(t,e,r){if(t)return void r(t);if(!e)return r();let n;try{n=JSON.parse(e,this.options.reviver)}catch(t){return r(t)}if(3===r.length){if(Array.isArray(n)){const t=function(t){return void 0!==t.error},e=function(e){return!t(e)};return r(null,n.filter(t),n.filter(e))}return r(null,n.error,n.result)}r(null,n)}},112:(t,e,r)=>{"use strict";r.d(e,{AX:()=>bs,Kt:()=>li});var n=r(287);const i="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function s(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function o(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function a(t,...e){if(!s(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function u(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");o(t.outputLen),o(t.blockLen)}function h(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function c(...t){for(let e=0;e>>e}const d=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),p=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function y(t){if(a(t),d)return t.toHex();let e="";for(let r=0;r=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function m(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);if(d)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let e=0,i=0;et().update(w(e)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function A(t=32){if(i&&"function"==typeof i.getRandomValues)return i.getRandomValues(new Uint8Array(t));if(i&&"function"==typeof i.randomBytes)return Uint8Array.from(i.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function E(t,e,r){return t&e^~t&r}function B(t,e,r){return t&e^t&r^e&r}class S extends k{constructor(t,e,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(t),this.view=f(this.buffer)}update(t){h(this),a(t=w(t));const{view:e,buffer:r,blockLen:n}=this,i=t.length;for(let s=0;sn-s&&(this.process(r,0),s=0);for(let t=s;t>i&s),a=Number(r&s),u=n?4:0,h=n?0:4;t.setUint32(e+u,o,n),t.setUint32(e+h,a,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const o=f(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=u/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t>U&M)}:{h:0|Number(t>>U&M),l:0|Number(t&M)}}const O=(t,e,r)=>t>>>r,L=(t,e,r)=>t<<32-r|e>>>r,K=(t,e,r)=>t>>>r|e<<32-r,z=(t,e,r)=>t<<32-r|e>>>r,T=(t,e,r)=>t<<64-r|e>>>r-32,R=(t,e,r)=>t>>>r-32|e<<64-r;function C(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:0|i}}const N=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),j=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,D=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),H=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,F=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),W=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,q=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]),$=new Uint32Array(64);class V extends S{constructor(t=32){super(64,t,8,!1),this.A=0|I[0],this.B=0|I[1],this.C=0|I[2],this.D=0|I[3],this.E=0|I[4],this.F=0|I[5],this.G=0|I[6],this.H=0|I[7]}get(){const{A:t,B:e,C:r,D:n,E:i,F:s,G:o,H:a}=this;return[t,e,r,n,i,s,o,a]}set(t,e,r,n,i,s,o,a){this.A=0|t,this.B=0|e,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(t,e){for(let r=0;r<16;r++,e+=4)$[r]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=$[t-15],r=$[t-2],n=l(e,7)^l(e,18)^e>>>3,i=l(r,17)^l(r,19)^r>>>10;$[t]=i+$[t-7]+n+$[t-16]|0}let{A:r,B:n,C:i,D:s,E:o,F:a,G:u,H:h}=this;for(let t=0;t<64;t++){const e=h+(l(o,6)^l(o,11)^l(o,25))+E(o,a,u)+q[t]+$[t]|0,c=(l(r,2)^l(r,13)^l(r,22))+B(r,n,i)|0;h=u,u=a,a=o,o=s+e|0,s=i,i=n,n=r,r=e+c|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(r,n,i,s,o,a,u,h)}roundClean(){c($)}destroy(){this.set(0,0,0,0,0,0,0,0),c(this.buffer)}}const Z=(()=>function(t,e=!1){const r=t.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;sBigInt(t))))(),Y=(()=>Z[0])(),G=(()=>Z[1])(),X=new Uint32Array(80),J=new Uint32Array(80);class Q extends S{constructor(t=64){super(128,t,16,!1),this.Ah=0|_[0],this.Al=0|_[1],this.Bh=0|_[2],this.Bl=0|_[3],this.Ch=0|_[4],this.Cl=0|_[5],this.Dh=0|_[6],this.Dl=0|_[7],this.Eh=0|_[8],this.El=0|_[9],this.Fh=0|_[10],this.Fl=0|_[11],this.Gh=0|_[12],this.Gl=0|_[13],this.Hh=0|_[14],this.Hl=0|_[15]}get(){const{Ah:t,Al:e,Bh:r,Bl:n,Ch:i,Cl:s,Dh:o,Dl:a,Eh:u,El:h,Fh:c,Fl:f,Gh:l,Gl:d,Hh:p,Hl:y}=this;return[t,e,r,n,i,s,o,a,u,h,c,f,l,d,p,y]}set(t,e,r,n,i,s,o,a,u,h,c,f,l,d,p,y){this.Ah=0|t,this.Al=0|e,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|o,this.Dl=0|a,this.Eh=0|u,this.El=0|h,this.Fh=0|c,this.Fl=0|f,this.Gh=0|l,this.Gl=0|d,this.Hh=0|p,this.Hl=0|y}process(t,e){for(let r=0;r<16;r++,e+=4)X[r]=t.getUint32(e),J[r]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|X[t-15],r=0|J[t-15],n=K(e,r,1)^K(e,r,8)^O(e,0,7),i=z(e,r,1)^z(e,r,8)^L(e,r,7),s=0|X[t-2],o=0|J[t-2],a=K(s,o,19)^T(s,o,61)^O(s,0,6),u=z(s,o,19)^R(s,o,61)^L(s,o,6),h=D(i,u,J[t-7],J[t-16]),c=H(h,n,a,X[t-7],X[t-16]);X[t]=0|c,J[t]=0|h}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:o,Cl:a,Dh:u,Dl:h,Eh:c,El:f,Fh:l,Fl:d,Gh:p,Gl:y,Hh:g,Hl:m}=this;for(let t=0;t<80;t++){const e=K(c,f,14)^K(c,f,18)^T(c,f,41),b=z(c,f,14)^z(c,f,18)^R(c,f,41),w=c&l^~c&p,v=F(m,b,f&d^~f&y,G[t],J[t]),k=W(v,g,e,w,Y[t],X[t]),x=0|v,A=K(r,n,28)^T(r,n,34)^T(r,n,39),E=z(r,n,28)^R(r,n,34)^R(r,n,39),B=r&i^r&o^i&o,S=n&s^n&a^s&a;g=0|p,m=0|y,p=0|l,y=0|d,l=0|c,d=0|f,({h:c,l:f}=C(0|u,0|h,0|k,0|x)),u=0|o,h=0|a,o=0|i,a=0|s,i=0|r,s=0|n;const I=N(x,E,S);r=j(I,k,A,B),n=0|I}({h:r,l:n}=C(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=C(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=C(0|this.Ch,0|this.Cl,0|o,0|a)),({h:u,l:h}=C(0|this.Dh,0|this.Dl,0|u,0|h)),({h:c,l:f}=C(0|this.Eh,0|this.El,0|c,0|f)),({h:l,l:d}=C(0|this.Fh,0|this.Fl,0|l,0|d)),({h:p,l:y}=C(0|this.Gh,0|this.Gl,0|p,0|y)),({h:g,l:m}=C(0|this.Hh,0|this.Hl,0|g,0|m)),this.set(r,n,i,s,o,a,u,h,c,f,l,d,p,y,g,m)}roundClean(){c(X,J)}destroy(){c(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const tt=x(()=>new V),et=x(()=>new Q),rt=BigInt(0),nt=BigInt(1);function it(t,e=""){if("boolean"!=typeof t)throw new Error((e&&`"${e}"`)+"expected boolean, got type="+typeof t);return t}function st(t,e,r=""){const n=s(t),i=t?.length,o=void 0!==e;if(!n||o&&i!==e)throw new Error((r&&`"${r}" `)+"expected Uint8Array"+(o?` of length ${e}`:"")+", got "+(n?`length=${i}`:"type="+typeof t));return t}function ot(t){const e=t.toString(16);return 1&e.length?"0"+e:e}function at(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return""===t?rt:BigInt("0x"+t)}function ut(t){return at(y(t))}function ht(t){return a(t),at(y(Uint8Array.from(t).reverse()))}function ct(t,e){return m(t.toString(16).padStart(2*e,"0"))}function ft(t,e){return ct(t,e).reverse()}function lt(t,e,r){let n;if("string"==typeof e)try{n=m(e)}catch(e){throw new Error(t+" must be hex string or Uint8Array, cause: "+e)}else{if(!s(e))throw new Error(t+" must be hex string or Uint8Array");n=Uint8Array.from(e)}const i=n.length;if("number"==typeof r&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function dt(t){return Uint8Array.from(t)}const pt=t=>"bigint"==typeof t&&rt<=t;function yt(t,e,r,n){if(!function(t,e,r){return pt(t)&&pt(e)&&pt(r)&&e<=t&&trt;t>>=nt,e+=1);return e}const mt=t=>(nt<n(t,e,!1)),Object.entries(r).forEach(([t,e])=>n(t,e,!0))}const wt=()=>{throw new Error("not implemented")};function vt(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(void 0!==i)return i;const s=t(r,...n);return e.set(r,s),s}}const kt=BigInt(0),xt=BigInt(1),At=BigInt(2),Et=BigInt(3),Bt=BigInt(4),St=BigInt(5),It=BigInt(7),_t=BigInt(8),Mt=BigInt(9),Ut=BigInt(16);function Pt(t,e){const r=t%e;return r>=kt?r:e+r}function Ot(t,e,r){let n=t;for(;e-- >kt;)n*=n,n%=r;return n}function Lt(t,e){if(t===kt)throw new Error("invert: expected non-zero number");if(e<=kt)throw new Error("invert: expected positive modulus, got "+e);let r=Pt(t,e),n=e,i=kt,s=xt,o=xt,a=kt;for(;r!==kt;){const t=n/r,e=n%r,u=i-o*t,h=s-a*t;n=r,r=e,i=o,s=a,o=u,a=h}if(n!==xt)throw new Error("invert: does not exist");return Pt(i,e)}function Kt(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function zt(t,e){const r=(t.ORDER+xt)/Bt,n=t.pow(e,r);return Kt(t,n,e),n}function Tt(t,e){const r=(t.ORDER-St)/_t,n=t.mul(e,At),i=t.pow(n,r),s=t.mul(e,i),o=t.mul(t.mul(s,At),i),a=t.mul(s,t.sub(o,t.ONE));return Kt(t,a,e),a}function Rt(t){if(t1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return zt;let s=i.pow(n,e);const o=(e+xt)/At;return function(t,n){if(t.is0(n))return n;if(1!==Dt(t,n))throw new Error("Cannot find square root");let i=r,a=t.mul(t.ONE,s),u=t.pow(n,e),h=t.pow(n,o);for(;!t.eql(u,t.ONE);){if(t.is0(u))return t.ZERO;let e=1,r=t.sqr(u);for(;!t.eql(r,t.ONE);)if(e++,r=t.sqr(r),e===i)throw new Error("Cannot find square root");const n=xt<(Pt(t,e)&xt)===xt,Nt=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jt(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((e,r,i)=>t.is0(r)?e:(n[i]=e,t.mul(e,r)),t.ONE),s=t.inv(i);return e.reduceRight((e,r,i)=>t.is0(r)?e:(n[i]=t.mul(e,n[i]),t.mul(e,r)),s),n}function Dt(t,e){const r=(t.ORDER-xt)/At,n=t.pow(e,r),i=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Ht(t,e){void 0!==e&&o(e);const r=void 0!==e?e:t.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function Ft(t,e,r=!1,n={}){if(t<=kt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o,a=!1;if("object"==typeof e&&null!=e){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const t=e;t.BITS&&(i=t.BITS),t.sqrt&&(s=t.sqrt),"boolean"==typeof t.isLE&&(r=t.isLE),"boolean"==typeof t.modFromBytes&&(a=t.modFromBytes),o=t.allowedLengths}else"number"==typeof e&&(i=e),n.sqrt&&(s=n.sqrt);const{nBitLength:u,nByteLength:h}=Ht(t,i);if(h>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const f=Object.freeze({ORDER:t,isLE:r,BITS:u,BYTES:h,MASK:mt(u),ZERO:kt,ONE:xt,allowedLengths:o,create:e=>Pt(e,t),isValid:e=>{if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return kt<=e&&et===kt,isValidNot0:t=>!f.is0(t)&&f.isValid(t),isOdd:t=>(t&xt)===xt,neg:e=>Pt(-e,t),eql:(t,e)=>t===e,sqr:e=>Pt(e*e,t),add:(e,r)=>Pt(e+r,t),sub:(e,r)=>Pt(e-r,t),mul:(e,r)=>Pt(e*r,t),pow:(t,e)=>function(t,e,r){if(rkt;)r&xt&&(n=t.mul(n,i)),i=t.sqr(i),r>>=xt;return n}(f,t,e),div:(e,r)=>Pt(e*Lt(r,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>Lt(e,t),sqrt:s||(e=>{return c||(c=(r=t)%Bt===Et?zt:r%_t===St?Tt:r%Ut===Mt?function(t){const e=Ft(t),r=Rt(t),n=r(e,e.neg(e.ONE)),i=r(e,n),s=r(e,e.neg(n)),o=(t+It)/Ut;return(t,e)=>{let r=t.pow(e,o),a=t.mul(r,n);const u=t.mul(r,i),h=t.mul(r,s),c=t.eql(t.sqr(a),e),f=t.eql(t.sqr(u),e);r=t.cmov(r,a,c),a=t.cmov(h,u,f);const l=t.eql(t.sqr(a),e),d=t.cmov(r,a,l);return Kt(t,d,e),d}}(r):Rt(r)),c(f,e);var r}),toBytes:t=>r?ft(t,h):ct(t,h),fromBytes:(e,n=!0)=>{if(o){if(!o.includes(e.length)||e.length>h)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);const t=new Uint8Array(h);t.set(e,r?0:t.length-e.length),e=t}if(e.length!==h)throw new Error("Field.fromBytes: expected "+h+" bytes, got "+e.length);let i=r?ht(e):ut(e);if(a&&(i=Pt(i,t)),!n&&!f.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:t=>jt(f,t),cmov:(t,e,r)=>r?e:t});return Object.freeze(f)}function Wt(t){if("bigint"!=typeof t)throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function qt(t){const e=Wt(t);return e+Math.ceil(e/2)}const $t=BigInt(0),Vt=BigInt(1);function Zt(t,e){const r=e.negate();return t?r:e}function Yt(t,e){const r=jt(t.Fp,e.map(t=>t.Z));return e.map((e,n)=>t.fromAffine(e.toAffine(r[n])))}function Gt(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Xt(t,e){Gt(t,e);const r=2**t;return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1),mask:mt(t),maxNumber:r,shiftBy:BigInt(t)}}function Jt(t,e,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(t&i),u=t>>o;a>n&&(a-=s,u+=Vt);const h=e*n;return{nextN:u,offset:h+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:e%2!=0,offsetF:h}}const Qt=new WeakMap,te=new WeakMap;function ee(t){return te.get(t)||1}function re(t){if(t!==$t)throw new Error("invalid wNAF")}class ne{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,r=this.ZERO){let n=t;for(;e>$t;)e&Vt&&(r=r.add(n)),n=n.double(),e>>=Vt;return r}precomputeWindow(t,e){const{windows:r,windowSize:n}=Xt(e,this.bits),i=[];let s=t,o=s;for(let t=0;t{if(!(t instanceof e))throw new Error("invalid point at index "+r)})})(r,t),function(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}(n,e);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=gt(BigInt(i));let u=1;a>12?u=a-3:a>4?u=a-2:a>0&&(u=2);const h=mt(u),c=new Array(Number(h)+1).fill(o);let f=o;for(let t=Math.floor((e.BITS-1)/u)*u;t>=0;t-=u){c.fill(o);for(let e=0;e>BigInt(t)&h);c[s]=c[s].add(r[e])}let e=o;for(let t=c.length-1,r=o;t>0;t--)r=r.add(c[t]),e=e.add(r);if(f=f.add(e),0!==t)for(let t=0;t(t[e]="function",t),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(e),e}return Ft(t,{isLE:r})}function oe(t,e,r={},n){if(void 0===n&&(n="edwards"===t),!e||"object"!=typeof e)throw new Error(`expected valid ${t} CURVE object`);for(const t of["p","n","h"]){const r=e[t];if(!("bigint"==typeof r&&r>$t))throw new Error(`CURVE.${t} must be positive bigint`)}const i=se(e.p,r.Fp,n),s=se(e.n,r.Fn,n),o=["Gx","Gy","a","weierstrass"===t?"b":"d"];for(const t of o)if(!i.isValid(e[t]))throw new Error(`CURVE.${t} must be valid field element of CURVE.Fp`);return{CURVE:e=Object.freeze(Object.assign({},e)),Fp:i,Fn:s}}const ae=BigInt(0),ue=BigInt(1),he=BigInt(2),ce=BigInt(8);class fe{constructor(t){this.ep=t}static fromBytes(t){wt()}static fromHex(t){wt()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return y(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}}function le(t){const{CURVE:e,curveOpts:r,hash:n,eddsaOpts:i}=function(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r={Fp:t.Fp,Fn:Ft(e.n,t.nBitLength,!0),uvRatio:t.uvRatio},n={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:r,hash:t.hash,eddsaOpts:n}}(t),o=function(t,e={}){const r=oe("edwards",t,e,e.FpFnLE),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:o}=s;bt(e,{},{uvRatio:"function"});const a=he<n.create(t),h=e.uvRatio||((t,e)=>{try{return{isValid:!0,value:n.sqrt(n.div(t,e))}}catch(t){return{isValid:!1,value:ae}}});if(!function(t,e,r,n){const i=t.sqr(r),s=t.sqr(n),o=t.add(t.mul(e.a,i),s),a=t.add(t.ONE,t.mul(e.d,t.mul(i,s)));return t.eql(o,a)}(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function c(t,e,r=!1){return yt("coordinate "+t,e,r?ue:ae,a),e}function f(t){if(!(t instanceof p))throw new Error("ExtendedPoint expected")}const l=vt((t,e)=>{const{X:r,Y:i,Z:s}=t,o=t.is0();null==e&&(e=o?ce:n.inv(s));const a=u(r*e),h=u(i*e),c=n.mul(s,e);if(o)return{x:ae,y:ue};if(c!==ue)throw new Error("invZ was invalid");return{x:a,y:h}}),d=vt(t=>{const{a:e,d:r}=s;if(t.is0())throw new Error("bad point: ZERO");const{X:n,Y:i,Z:o,T:a}=t,h=u(n*n),c=u(i*i),f=u(o*o),l=u(f*f),d=u(h*e);if(u(f*u(d+c))!==u(l+u(r*u(h*c))))throw new Error("bad point: equation left != right (1)");if(u(n*i)!==u(o*a))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(t,e,r,n){this.X=c("x",t),this.Y=c("y",e),this.Z=c("z",r,!0),this.T=c("t",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){if(t instanceof p)throw new Error("extended point not allowed");const{x:e,y:r}=t||{};return c("x",e),c("y",r),new p(e,r,ue,u(e*r))}static fromBytes(t,e=!1){const r=n.BYTES,{a:i,d:o}=s;t=dt(st(t,r,"point")),it(e,"zip215");const c=dt(t),f=t[r-1];c[r-1]=-129&f;const l=ht(c),d=e?a:n.ORDER;yt("point.y",l,ae,d);const y=u(l*l),g=u(y-ue),m=u(o*y-i);let{isValid:b,value:w}=h(g,m);if(!b)throw new Error("bad point: invalid y coordinate");const v=(w&ue)===ue,k=!!(128&f);if(!e&&w===ae&&k)throw new Error("bad point: x=0 and x_0=1");return k!==v&&(w=u(-w)),p.fromAffine({x:w,y:l})}static fromHex(t,e=!1){return p.fromBytes(lt("point",t),e)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return g.createCache(this,t),e||this.multiply(he),this}assertValidity(){d(this)}equals(t){f(t);const{X:e,Y:r,Z:n}=this,{X:i,Y:s,Z:o}=t,a=u(e*o),h=u(i*n),c=u(r*o),l=u(s*n);return a===h&&c===l}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.X),this.Y,this.Z,u(-this.T))}double(){const{a:t}=s,{X:e,Y:r,Z:n}=this,i=u(e*e),o=u(r*r),a=u(he*u(n*n)),h=u(t*i),c=e+r,f=u(u(c*c)-i-o),l=h+o,d=l-a,y=h-o,g=u(f*d),m=u(l*y),b=u(f*y),w=u(d*l);return new p(g,m,w,b)}add(t){f(t);const{a:e,d:r}=s,{X:n,Y:i,Z:o,T:a}=this,{X:h,Y:c,Z:l,T:d}=t,y=u(n*h),g=u(i*c),m=u(a*r*d),b=u(o*l),w=u((n+i)*(h+c)-y-g),v=b-m,k=b+m,x=u(g-e*y),A=u(w*v),E=u(k*x),B=u(w*x),S=u(v*k);return new p(A,E,S,B)}subtract(t){return this.add(t.negate())}multiply(t){if(!i.isValidNot0(t))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:e,f:r}=g.cached(this,t,t=>Yt(p,t));return Yt(p,[e,r])[0]}multiplyUnsafe(t,e=p.ZERO){if(!i.isValid(t))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return t===ae?p.ZERO:this.is0()||t===ue?this:g.unsafe(this,t,t=>Yt(p,t),e)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(t){return l(this,t)}clearCofactor(){return o===ue?this:this.multiplyUnsafe(o)}toBytes(){const{x:t,y:e}=this.toAffine(),r=n.toBytes(e);return r[r.length-1]|=t&ue?128:0,r}toHex(){return y(this.toBytes())}toString(){return``}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(t){return Yt(p,t)}static msm(t,e){return ie(p,i,t,e)}_setWindowSize(t){this.precompute(t)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,ue,u(s.Gx*s.Gy)),p.ZERO=new p(ae,ue,ue,ae),p.Fp=n,p.Fn=i;const g=new ne(p,i.BITS);return p.BASE.precompute(8),p}(e,r);return function(t,e){const r=e.Point;return Object.assign({},e,{ExtendedPoint:r,CURVE:t,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(t,function(t,e,r={}){if("function"!=typeof e)throw new Error('"hash" function param is required');bt(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:i,Fp:o,Fn:a}=t,u=r.randomBytes||A,h=r.adjustScalarBytes||(t=>t),c=r.domain||((t,e,r)=>{if(it(r,"phflag"),e.length||r)throw new Error("Contexts/pre-hash are not supported");return t});function f(t){return a.create(ht(t))}function l(t){const{head:r,prefix:n,scalar:s}=function(t){const r=m.secretKey;t=lt("private key",t,r);const n=lt("hashed private key",e(t),2*r),i=h(n.slice(0,r));return{head:i,prefix:n.slice(r,2*r),scalar:f(i)}}(t),o=i.multiply(s),a=o.toBytes();return{head:r,prefix:n,scalar:s,point:o,pointBytes:a}}function d(t){return l(t).pointBytes}function p(t=Uint8Array.of(),...r){const i=v(...r);return f(e(c(i,lt("context",t),!!n)))}const y={zip215:!0},g=o.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function b(t=u(m.seed)){return st(t,m.seed,"seed")}const w={getExtendedPublicKey:l,randomSecretKey:b,isValidSecretKey:function(t){return s(t)&&t.length===a.BYTES},isValidPublicKey:function(e,r){try{return!!t.fromBytes(e,r)}catch(t){return!1}},toMontgomery(e){const{y:r}=t.fromBytes(e),n=m.publicKey,i=32===n;if(!i&&57!==n)throw new Error("only defined for 25519 and 448");const s=i?o.div(ue+r,ue-r):o.div(r-ue,r+ue);return o.toBytes(s)},toMontgomerySecret(t){const r=m.secretKey;st(t,r);const n=e(t.subarray(0,r));return h(n).subarray(0,r)},randomPrivateKey:b,precompute:(e=8,r=t.BASE)=>r.precompute(e,!1)};return Object.freeze({keygen:function(t){const e=w.randomSecretKey(t);return{secretKey:e,publicKey:d(e)}},getPublicKey:d,sign:function(t,e,r={}){t=lt("message",t),n&&(t=n(t));const{prefix:s,scalar:o,pointBytes:u}=l(e),h=p(r.context,s,t),c=i.multiply(h).toBytes(),f=p(r.context,c,u,t),d=a.create(h+f*o);if(!a.isValid(d))throw new Error("sign failed: invalid s");return st(v(c,a.toBytes(d)),m.signature,"result")},verify:function(e,r,s,o=y){const{context:a,zip215:u}=o,h=m.signature;e=lt("signature",e,h),r=lt("message",r),s=lt("publicKey",s,m.publicKey),void 0!==u&&it(u,"zip215"),n&&(r=n(r));const c=h/2,f=e.subarray(0,c),l=ht(e.subarray(c,h));let d,g,b;try{d=t.fromBytes(s,u),g=t.fromBytes(f,u),b=i.multiplyUnsafe(l)}catch(t){return!1}if(!u&&d.isSmallOrder())return!1;const w=p(a,g.toBytes(),d.toBytes(),r);return g.add(d.multiplyUnsafe(w)).subtract(b).clearCofactor().is0()},utils:w,Point:t,lengths:m})}(o,n,i))}b("HashToScalar-");const de=BigInt(0),pe=BigInt(1),ye=BigInt(2),ge=(BigInt(3),BigInt(5)),me=BigInt(8),be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),we=(()=>({p:be,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:me,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function ve(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const ke=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function xe(t,e){const r=be,n=Pt(e*e*e,r),i=Pt(n*n*e,r);let s=Pt(t*n*function(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=be,o=t*t%s*t%s,a=Ot(o,ye,s)*o%s,u=Ot(a,pe,s)*t%s,h=Ot(u,ge,s)*u%s,c=Ot(h,e,s)*h%s,f=Ot(c,r,s)*c%s,l=Ot(f,n,s)*f%s,d=Ot(l,i,s)*l%s,p=Ot(d,i,s)*l%s,y=Ot(p,e,s)*h%s;return{pow_p_5_8:Ot(y,ye,s)*t%s,b2:o}}(t*i).pow_p_5_8,r);const o=Pt(e*s*s,r),a=s,u=Pt(s*ke,r),h=o===t,c=o===Pt(-t,r),f=o===Pt(-t*ke,r);return h&&(s=a),(c||f)&&(s=u),Ct(s,r)&&(s=Pt(-s,r)),{isValid:h||c,value:s}}const Ae=(()=>Ft(we.p,{isLE:!0}))(),Ee=(()=>Ft(we.n,{isLE:!0}))(),Be=(()=>({...we,Fp:Ae,hash:et,adjustScalarBytes:ve,uvRatio:xe}))(),Se=(()=>le(Be))(),Ie=ke,_e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Me=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Ue=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Pe=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Oe=t=>xe(pe,t),Le=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ke=t=>Se.Point.Fp.create(ht(t)&Le);function ze(t){const{d:e}=we,r=be,n=t=>Ae.create(t),i=n(Ie*t*t),s=n((i+pe)*Ue);let o=BigInt(-1);const a=n((o-e*i)*n(i+e));let{isValid:u,value:h}=xe(s,a),c=n(h*t);Ct(c,r)||(c=n(-c)),u||(h=c),u||(o=i);const f=n(o*(i-pe)*Pe-a),l=h*h,d=n((h+h)*a),p=n(f*_e),y=n(pe-l),g=n(pe+l);return new Se.Point(n(d*g),n(y*p),n(p*g),n(d*y))}class Te extends fe{constructor(t){super(t)}static fromAffine(t){return new Te(Se.Point.fromAffine(t))}assertSame(t){if(!(t instanceof Te))throw new Error("RistrettoPoint expected")}init(t){return new Te(t)}static hashToCurve(t){return function(t){a(t,64);const e=ze(Ke(t.subarray(0,32))),r=ze(Ke(t.subarray(32,64)));return new Te(e.add(r))}(lt("ristrettoHash",t,64))}static fromBytes(t){a(t,32);const{a:e,d:r}=we,n=be,i=t=>Ae.create(t),s=Ke(t);if(!function(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;nAe.create(t),o=s(s(r+e)*s(r-e)),a=s(t*e),u=s(a*a),{value:h}=Oe(s(o*u)),c=s(h*o),f=s(h*a),l=s(c*f*n);let d;if(Ct(n*l,i)){let r=s(e*Ie),n=s(t*Ie);t=r,e=n,d=s(c*Me)}else d=f;Ct(t*l,i)&&(e=s(-e));let p=s((r-e)*d);return Ct(p,i)&&(p=s(-p)),Ae.toBytes(p)}equals(t){this.assertSame(t);const{X:e,Y:r}=this.ep,{X:n,Y:i}=t.ep,s=t=>Ae.create(t),o=s(e*i)===s(r*n),a=s(r*i)===s(e*n);return o||a}is0(){return this.equals(Te.ZERO)}}Te.BASE=(()=>new Te(Se.Point.BASE))(),Te.ZERO=(()=>new Te(Se.Point.ZERO))(),Te.Fp=(()=>Ae)(),Te.Fn=(()=>Ee)();var Re=r(404),Ce=r.n(Re),Ne=r(763),je=r.n(Ne);function De(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function He(t,...e){if(!((r=t)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Fe(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function We(t,e){He(t);const r=e.outputLen;if(t.length>>e}function Ze(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Ye=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?t=>t:function(t){for(let e=0;et().update(Ge(e)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Qe(t,e,r){return t&e^~t&r}function tr(t,e,r){return t&e^t&r^e&r}class er extends Xe{constructor(t,e,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(t),this.view=$e(this.buffer)}update(t){Fe(this),He(t=Ge(t));const{view:e,buffer:r,blockLen:n}=this,i=t.length;for(let s=0;sn-s&&(this.process(r,0),s=0);for(let t=s;t>i&s),a=Number(r&s),u=n?4:0,h=n?0:4;t.setUint32(e+u,o,n),t.setUint32(e+h,a,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const o=$e(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t>ir&nr)}:{h:0|Number(t>>ir&nr),l:0|Number(t&nr)}}const or=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]),ar=new Uint32Array(64);class ur extends er{constructor(t=32){super(64,t,8,!1),this.A=0|rr[0],this.B=0|rr[1],this.C=0|rr[2],this.D=0|rr[3],this.E=0|rr[4],this.F=0|rr[5],this.G=0|rr[6],this.H=0|rr[7]}get(){const{A:t,B:e,C:r,D:n,E:i,F:s,G:o,H:a}=this;return[t,e,r,n,i,s,o,a]}set(t,e,r,n,i,s,o,a){this.A=0|t,this.B=0|e,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(t,e){for(let r=0;r<16;r++,e+=4)ar[r]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=ar[t-15],r=ar[t-2],n=Ve(e,7)^Ve(e,18)^e>>>3,i=Ve(r,17)^Ve(r,19)^r>>>10;ar[t]=i+ar[t-7]+n+ar[t-16]|0}let{A:r,B:n,C:i,D:s,E:o,F:a,G:u,H:h}=this;for(let t=0;t<64;t++){const e=h+(Ve(o,6)^Ve(o,11)^Ve(o,25))+Qe(o,a,u)+or[t]+ar[t]|0,c=(Ve(r,2)^Ve(r,13)^Ve(r,22))+tr(r,n,i)|0;h=u,u=a,a=o,o=s+e|0,s=i,i=n,n=r,r=e+c|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(r,n,i,s,o,a,u,h)}roundClean(){qe(ar)}destroy(){this.set(0,0,0,0,0,0,0,0),qe(this.buffer)}}const hr=Je(()=>new ur);var cr=r(755),fr=r(601);function lr(t){return Array.isArray(t)?"%5B"+t.map(lr).join("%2C%20")+"%5D":"bigint"==typeof t?`${t}n`:encodeURIComponent(String(null!=t&&null===Object.getPrototypeOf(t)?{...t}:t))}function dr([t,e]){return`${t}=${lr(e)}`}var pr=class extends Error{cause=this.cause;context;constructor(...[t,e]){let r,n;if(e){const{cause:t,...i}=e;t&&(n={cause:t}),Object.keys(i).length>0&&(r=i)}super(function(t,e={}){{let r=`Solana error #${t}; Decode this error by running \`npx @solana/errors decode -- ${t}`;return Object.keys(e).length&&(r+=` '${function(t){const e=Object.entries(t).map(dr).join("&");return btoa(e)}(e)}'`),`${r}\``}}(t,r),n),this.context={__code:t,...r},this.name="SolanaError"}};function yr(t){return"fixedSize"in t&&"number"==typeof t.fixedSize}function gr(t){return 1!==t?.endian}function mr(t){return e={fixedSize:t.size,write(e,r,n){t.range&&function(t,e,r,n){if(nr)throw new pr(8078011,{codecDescription:t,max:r,min:e,value:n})}(t.name,t.range[0],t.range[1],e);const i=new ArrayBuffer(t.size);return t.set(new DataView(i),e,gr(t.config)),r.set(new Uint8Array(i),n),n+t.size}},Object.freeze({...e,encode:t=>{const r=new Uint8Array(function(t,e){return"fixedSize"in e?e.fixedSize:e.getSizeFromValue(t)}(t,e));return e.write(t,r,0),r}});var e}function br(t){return e={fixedSize:t.size,read(e,r=0){!function(t,e,r=0){if(e.length-r<=0)throw new pr(8078e3,{codecDescription:t})}(t.name,e,r),function(t,e,r,n=0){const i=r.length-n;if(ie.read(t,r)[0]});var e}var wr=(t={})=>mr({config:t,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(t,e,r)=>t.setBigUint64(0,BigInt(e),r),size:8}),vr=(t={})=>function(t,e){if(yr(t)!==yr(e))throw new pr(8078004);if(yr(t)&&yr(e)&&t.fixedSize!==e.fixedSize)throw new pr(8078005,{decoderFixedSize:e.fixedSize,encoderFixedSize:t.fixedSize});if(!yr(t)&&!yr(e)&&t.maxSize!==e.maxSize)throw new pr(8078006,{decoderMaxSize:e.maxSize,encoderMaxSize:t.maxSize});return{...e,...t,decode:e.decode,encode:t.encode,read:e.read,write:t.write}}(wr(t),((t={})=>br({config:t,get:(t,e)=>t.getBigUint64(0,e),name:"u64",size:8}))(t));class kr extends TypeError{constructor(t,e){let r;const{message:n,explanation:i,...s}=t,{path:o}=t,a=0===o.length?n:`At path: ${o.join(".")} -- ${n}`;super(i??a),null!=i&&(this.cause=a),Object.assign(this,s),this.name=this.constructor.name,this.failures=()=>r??(r=[t,...e()])}}function xr(t){return"object"==typeof t&&null!=t}function Ar(t){return xr(t)&&!Array.isArray(t)}function Er(t){return"symbol"==typeof t?t.toString():"string"==typeof t?JSON.stringify(t):`${t}`}function Br(t,e,r,n){if(!0===t)return;!1===t?t={}:"string"==typeof t&&(t={message:t});const{path:i,branch:s}=e,{type:o}=r,{refinement:a,message:u=`Expected a value of type \`${o}\`${a?` with refinement \`${a}\``:""}, but received: \`${Er(n)}\``}=t;return{value:n,type:o,refinement:a,key:i[i.length-1],path:i,branch:s,...t,message:u}}function*Sr(t,e,r,n){var i;xr(i=t)&&"function"==typeof i[Symbol.iterator]||(t=[t]);for(const i of t){const t=Br(i,e,r,n);t&&(yield t)}}function*Ir(t,e,r={}){const{path:n=[],branch:i=[t],coerce:s=!1,mask:o=!1}=r,a={path:n,branch:i,mask:o};s&&(t=e.coercer(t,a));let u="valid";for(const n of e.validator(t,a))n.explanation=r.message,u="not_valid",yield[n,void 0];for(let[h,c,f]of e.entries(t,a)){const e=Ir(c,f,{path:void 0===h?n:[...n,h],branch:void 0===h?i:[...i,c],coerce:s,mask:o,message:r.message});for(const r of e)r[0]?(u=null!=r[0].refinement?"not_refined":"not_valid",yield[r[0],void 0]):s&&(c=r[1],void 0===h?t=c:t instanceof Map?t.set(h,c):t instanceof Set?t.add(c):xr(t)&&(void 0!==c||h in t)&&(t[h]=c))}if("not_valid"!==u)for(const n of e.refiner(t,a))n.explanation=r.message,u="not_refined",yield[n,void 0];"valid"===u&&(yield[void 0,t])}class _r{constructor(t){const{type:e,schema:r,validator:n,refiner:i,coercer:s=t=>t,entries:o=function*(){}}=t;this.type=e,this.schema=r,this.entries=o,this.coercer=s,this.validator=n?(t,e)=>Sr(n(t,e),e,this,t):()=>[],this.refiner=i?(t,e)=>Sr(i(t,e),e,this,t):()=>[]}assert(t,e){return function(t,e,r){const n=Pr(t,e,{message:r});if(n[0])throw n[0]}(t,this,e)}create(t,e){return Mr(t,this,e)}is(t){return Ur(t,this)}mask(t,e){return function(t,e,r){const n=Pr(t,e,{coerce:!0,mask:!0,message:r});if(n[0])throw n[0];return n[1]}(t,this,e)}validate(t,e={}){return Pr(t,this,e)}}function Mr(t,e,r){const n=Pr(t,e,{coerce:!0,message:r});if(n[0])throw n[0];return n[1]}function Ur(t,e){return!Pr(t,e)[0]}function Pr(t,e,r={}){const n=Ir(t,e,r),i=function(t){const{done:e,value:r}=t.next();return e?void 0:r}(n);return i[0]?[new kr(i[0],function*(){for(const t of n)t[0]&&(yield t[0])}),void 0]:[void 0,i[1]]}function Or(t,e){return new _r({type:t,schema:null,validator:e})}function Lr(t){return new _r({type:"array",schema:t,*entries(e){if(t&&Array.isArray(e))for(const[r,n]of e.entries())yield[r,n,t]},coercer:t=>Array.isArray(t)?t.slice():t,validator:t=>Array.isArray(t)||`Expected an array value, but received: ${Er(t)}`})}function Kr(){return Or("boolean",t=>"boolean"==typeof t)}function zr(t){return Or("instance",e=>e instanceof t||`Expected a \`${t.name}\` instance, but received: ${Er(e)}`)}function Tr(t){const e=Er(t),r=typeof t;return new _r({type:"literal",schema:"string"===r||"number"===r||"boolean"===r?t:null,validator:r=>r===t||`Expected the literal \`${e}\`, but received: ${Er(r)}`})}function Rr(t){return new _r({...t,validator:(e,r)=>null===e||t.validator(e,r),refiner:(e,r)=>null===e||t.refiner(e,r)})}function Cr(){return Or("number",t=>"number"==typeof t&&!isNaN(t)||`Expected a number, but received: ${Er(t)}`)}function Nr(t){return new _r({...t,validator:(e,r)=>void 0===e||t.validator(e,r),refiner:(e,r)=>void 0===e||t.refiner(e,r)})}function jr(t,e){return new _r({type:"record",schema:null,*entries(r){if(xr(r))for(const n in r){const i=r[n];yield[n,n,t],yield[n,i,e]}},validator:t=>Ar(t)||`Expected an object, but received: ${Er(t)}`,coercer:t=>Ar(t)?{...t}:t})}function Dr(){return Or("string",t=>"string"==typeof t||`Expected a string, but received: ${Er(t)}`)}function Hr(t){const e=Or("never",()=>!1);return new _r({type:"tuple",schema:null,*entries(r){if(Array.isArray(r)){const n=Math.max(t.length,r.length);for(let i=0;iArray.isArray(t)||`Expected an array, but received: ${Er(t)}`,coercer:t=>Array.isArray(t)?t.slice():t})}function Fr(t){const e=Object.keys(t);return new _r({type:"type",schema:t,*entries(r){if(xr(r))for(const n of e)yield[n,r[n],t[n]]},validator:t=>Ar(t)||`Expected an object, but received: ${Er(t)}`,coercer:t=>Ar(t)?{...t}:t})}function Wr(t){const e=t.map(t=>t.type).join(" | ");return new _r({type:"union",schema:null,coercer(e,r){for(const n of t){const[t,i]=n.validate(e,{coerce:!0,mask:r.mask});if(!t)return i}return e},validator(r,n){const i=[];for(const e of t){const[...t]=Ir(r,e,n),[s]=t;if(!s[0])return[];for(const[e]of t)e&&i.push(e)}return[`Expected the value to satisfy a union of \`${e}\`, but received: ${Er(r)}`,...i]}})}function qr(){return Or("unknown",()=>!0)}function $r(t,e,r){return new _r({...t,coercer:(n,i)=>Ur(n,e)?t.coercer(r(n,i),i):t.coercer(n,i)})}r(22),r(678);const Vr=BigInt(0),Zr=BigInt(1),Yr=BigInt(2),Gr=BigInt(7),Xr=BigInt(256),Jr=BigInt(113),Qr=[],tn=[],en=[];for(let t=0,e=Zr,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Qr.push(2*(5*n+r)),tn.push((t+1)*(t+2)/2%64);let i=Vr;for(let t=0;t<7;t++)e=(e<>Gr)*Jr)%Xr,e&Yr&&(i^=Zr<<(Zr<r>32?((t,e,r)=>e<>>64-r)(t,e,r):((t,e,r)=>t<>>32-r)(t,e,r),an=(t,e,r)=>r>32?((t,e,r)=>t<>>64-r)(t,e,r):((t,e,r)=>e<>>32-r)(t,e,r);class un extends Xe{constructor(t,e,r,n=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=e,this.outputLen=r,this.enableXOF=n,this.rounds=i,De(r),!(0=r&&this.keccak();const s=Math.min(r-this.posOut,i-n);t.set(e.subarray(this.posOut,this.posOut+s),n),this.posOut+=s,n+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return De(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(We(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,qe(this.state)}_cloneInto(t){const{blockLen:e,suffix:r,outputLen:n,rounds:i,enableXOF:s}=this;return t||(t=new un(e,r,n,s,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=r,t.outputLen=n,t.enableXOF=s,t.destroyed=this.destroyed,t}}const hn=(()=>{return t=1,e=136,r=32,Je(()=>new un(e,t,r));var t,e,r})();class cn extends k{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,u(t);const r=w(e);if(this.iHash=t.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 n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?t.create().update(r).digest():r);for(let t=0;tnew cn(t,e).update(r).digest();fn.create=(t,e)=>new cn(t,e);const ln=(t,e)=>(t+(t>=0?e:-e)/wn)/e;function dn(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function pn(t,e){const r={};for(let n of Object.keys(e))r[n]=void 0===t[n]?e[n]:t[n];return it(r.lowS,"lowS"),it(r.prehash,"prehash"),void 0!==r.format&&dn(r.format),r}class yn extends Error{constructor(t=""){super(t)}}const gn={Err:yn,_tlv:{encode:(t,e)=>{const{Err:r}=gn;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(1&e.length)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=ot(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?ot(i.length/2|128):"";return ot(t)+s+i+e},decode(t,e){const{Err:r}=gn;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++];let s=0;if(128&i){const t=127&i;if(!t)throw new r("tlv.decode(long): indefinite length not supported");if(t>4)throw new r("tlv.decode(long): byte length is too big");const o=e.subarray(n,n+t);if(o.length!==t)throw new r("tlv.decode: length bytes not complete");if(0===o[0])throw new r("tlv.decode(long): zero leftmost byte");for(const t of o)s=s<<8|t;if(n+=t,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=i;const o=e.subarray(n,n+s);if(o.length!==s)throw new r("tlv.decode: wrong value length");return{v:o,l:e.subarray(n+s)}}},_int:{encode(t){const{Err:e}=gn;if(tfn(e,t,v(...r))),{Fp:o,Fn:a}=t,{ORDER:h,BITS:c}=a,{keygen:f,getPublicKey:l,getSharedSecret:d,utils:p,lengths:g}=function(t,e={}){const{Fn:r}=t,n=e.randomBytes||A,i=Object.assign(En(t.Fp,r),{seed:qt(r.ORDER)});function s(t){try{return!!xn(r,t)}catch(t){return!1}}function o(t=n(i.seed)){return function(t,e,r=!1){const n=t.length,i=Wt(e),s=qt(e);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=Pt(r?ht(t):ut(t),e-xt)+xt;return r?ft(o,i):ct(o,i)}(st(t,i.seed,"seed"),r.ORDER)}function a(e,n=!0){return t.BASE.multiply(xn(r,e)).toBytes(n)}function u(e){if("bigint"==typeof e)return!1;if(e instanceof t)return!0;const{secretKey:n,publicKey:s,publicKeyUncompressed:o}=i;if(r.allowedLengths||n===s)return;const a=lt("key",e).length;return a===s||a===o}const h={isValidSecretKey:s,isValidPublicKey:function(e,r){const{publicKey:n,publicKeyUncompressed:s}=i;try{const i=e.length;return!(!0===r&&i!==n||!1===r&&i!==s||!t.fromBytes(e))}catch(t){return!1}},randomSecretKey:o,isValidPrivateKey:s,randomPrivateKey:o,normPrivateKeyToScalar:t=>xn(r,t),precompute:(e=8,r=t.BASE)=>r.precompute(e,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(e,n,i=!0){if(!0===u(e))throw new Error("first arg must be private key");if(!1===u(n))throw new Error("second arg must be public key");const s=xn(r,e);return t.fromHex(n).multiply(s).toBytes(i)},keygen:function(t){const e=o(t);return{secretKey:e,publicKey:a(e)}},Point:t,utils:h,lengths:i})}(t,r),b={prehash:!1,lowS:"boolean"==typeof r.lowS&&r.lowS,format:void 0,extraEntropy:!1},w="compact";function k(t){return t>h>>bn}function x(t,e){if(!a.isValidNot0(e))throw new Error(`invalid signature ${t}: out of range 1..Point.Fn.ORDER`);return e}class E{constructor(t,e,r){this.r=x("r",t),this.s=x("s",e),null!=r&&(this.recovery=r),Object.freeze(this)}static fromBytes(t,e=w){let r;if(function(t,e){dn(e);const r=g.signature;st(t,"compact"===e?r:"recovered"===e?r+1:void 0,`${e} signature`)}(t,e),"der"===e){const{r:e,s:r}=gn.toSig(st(t));return new E(e,r)}"recovered"===e&&(r=t[0],e="compact",t=t.subarray(1));const n=a.BYTES,i=t.subarray(0,n),s=t.subarray(n,2*n);return new E(a.fromBytes(i),a.fromBytes(s),r)}static fromHex(t,e){return this.fromBytes(m(t),e)}addRecoveryBit(t){return new E(this.r,this.s,t)}recoverPublicKey(e){const r=o.ORDER,{r:n,s:i,recovery:s}=this;if(null==s||![0,1,2,3].includes(s))throw new Error("recovery id invalid");if(h*wn1)throw new Error("recovery id is ambiguous for h>1 curve");const u=2===s||3===s?n+h:n;if(!o.isValid(u))throw new Error("recovery id 2 or 3 invalid");const c=o.toBytes(u),f=t.fromBytes(v(An(!(1&s)),c)),l=a.inv(u),d=S(lt("msgHash",e)),p=a.create(-d*l),y=a.create(i*l),g=t.BASE.multiplyUnsafe(p).add(f.multiplyUnsafe(y));if(g.is0())throw new Error("point at infinify");return g.assertValidity(),g}hasHighS(){return k(this.s)}toBytes(t=w){if(dn(t),"der"===t)return m(gn.hexFromSig(this));const e=a.toBytes(this.r),r=a.toBytes(this.s);if("recovered"===t){if(null==this.recovery)throw new Error("recovery bit must be present");return v(Uint8Array.of(this.recovery),e,r)}return v(e,r)}toHex(t){return y(this.toBytes(t))}assertValidity(){}static fromCompact(t){return E.fromBytes(lt("sig",t),"compact")}static fromDER(t){return E.fromBytes(lt("sig",t),"der")}normalizeS(){return this.hasHighS()?new E(this.r,a.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return y(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return y(this.toBytes("compact"))}}const B=r.bits2int||function(t){if(t.length>8192)throw new Error("input is too large");const e=ut(t),r=8*t.length-c;return r>0?e>>BigInt(r):e},S=r.bits2int_modN||function(t){return a.create(B(t))},I=mt(c);function _(t){return yt("num < 2^"+c,t,mn,I),a.toBytes(t)}function M(t,r){return st(t,void 0,"message"),r?st(e(t),void 0,"prehashed message"):t}return Object.freeze({keygen:f,getPublicKey:l,getSharedSecret:d,utils:p,lengths:g,Point:t,sign:function(r,s,o={}){r=lt("message",r);const{seed:u,k2sig:h}=function(e,r,i){if(["recovered","canonical"].some(t=>t in i))throw new Error("sign() legacy options not supported");const{lowS:s,prehash:o,extraEntropy:u}=pn(i,b);e=M(e,o);const h=S(e),c=xn(a,r),f=[_(c),_(h)];if(null!=u&&!1!==u){const t=!0===u?n(g.secretKey):u;f.push(lt("extraEntropy",t))}const l=v(...f),d=h;return{seed:l,k2sig:function(e){const r=B(e);if(!a.isValidNot0(r))return;const n=a.inv(r),i=t.BASE.multiply(r).toAffine(),o=a.create(i.x);if(o===mn)return;const u=a.create(n*a.create(d+o*c));if(u===mn)return;let h=(i.x===o?0:2)|Number(i.y&bn),f=u;return s&&k(u)&&(f=a.neg(u),h^=1),new E(o,f,h)}}}(r,s,o),c=function(t,e,r){if("number"!=typeof t||t<2)throw new Error("hashLen must be a number");if("number"!=typeof e||e<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");const n=t=>new Uint8Array(t),i=t=>Uint8Array.of(t);let s=n(t),o=n(t),a=0;const u=()=>{s.fill(1),o.fill(0),a=0},h=(...t)=>r(o,s,...t),c=(t=n(0))=>{o=h(i(0),t),s=h(),0!==t.length&&(o=h(i(1),t),s=h())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let t=0;const r=[];for(;t{let r;for(u(),c(t);!(r=e(f()));)c();return u(),r}}(e.outputLen,a.BYTES,i);return c(u,h)},verify:function(e,r,n,i={}){const{lowS:o,prehash:u,format:h}=pn(i,b);if(n=lt("publicKey",n),r=M(lt("message",r),u),"strict"in i)throw new Error("options.strict was renamed to lowS");const c=void 0===h?function(t){let e;const r="string"==typeof t||s(t),n=!r&&null!==t&&"object"==typeof t&&"bigint"==typeof t.r&&"bigint"==typeof t.s;if(!r&&!n)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)e=new E(t.r,t.s);else if(r){try{e=E.fromBytes(lt("sig",t),"der")}catch(t){if(!(t instanceof gn.Err))throw t}if(!e)try{e=E.fromBytes(lt("sig",t),"compact")}catch(t){return!1}}return e||!1}(e):E.fromBytes(lt("sig",e),h);if(!1===c)return!1;try{const e=t.fromBytes(n);if(o&&c.hasHighS())return!1;const{r:i,s}=c,u=S(r),h=a.inv(s),f=a.create(u*h),l=a.create(i*h),d=t.BASE.multiplyUnsafe(f).add(e.multiplyUnsafe(l));return!d.is0()&&a.create(d.x)===i}catch(t){return!1}},recoverPublicKey:function(t,e,r={}){const{prehash:n}=pn(r,b);return e=M(e,n),E.fromBytes(t,"recovered").recoverPublicKey(e).toBytes()},Signature:E,hash:e})}function Sn(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=function(t){const{CURVE:e,curveOpts:r}=function(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(t=>Math.ceil(t/2)))):void 0;return{CURVE:e,curveOpts:{Fp:r,Fn:Ft(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes}}}(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}(t);return function(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Ht(r.Fn.ORDER,r.Fn.BITS))})}(t,Bn(function(t,e={}){const r=oe("weierstrass",t,e),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:o,n:a}=s;bt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:u}=e;if(u&&(!n.is0(s.a)||"bigint"!=typeof u.beta||!Array.isArray(u.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const h=En(n,i);function c(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const f=e.toBytes||function(t,e,r){const{x:i,y:s}=e.toAffine(),o=n.toBytes(i);return it(r,"isCompressed"),r?(c(),v(An(!n.isOdd(s)),o)):v(Uint8Array.of(4),o,n.toBytes(s))},l=e.fromBytes||function(t){st(t,void 0,"Point");const{publicKey:e,publicKeyUncompressed:r}=h,i=t.length,s=t[0],o=t.subarray(1);if(i!==e||2!==s&&3!==s){if(i===r&&4===s){const t=n.BYTES,e=n.fromBytes(o.subarray(0,t)),r=n.fromBytes(o.subarray(t,2*t));if(!p(e,r))throw new Error("bad point: is not on curve");return{x:e,y:r}}throw new Error(`bad point: got length ${i}, expected compressed=${e} or uncompressed=${r}`)}{const t=n.fromBytes(o);if(!n.isValid(t))throw new Error("bad point: is not on curve, wrong x");const e=d(t);let r;try{r=n.sqrt(e)}catch(t){const e=t instanceof Error?": "+t.message:"";throw new Error("bad point: is not on curve, sqrt error"+e)}return c(),!(1&~s)!==n.isOdd(r)&&(r=n.neg(r)),{x:t,y:r}}};function d(t){const e=n.sqr(t),r=n.mul(e,t);return n.add(n.add(r,n.mul(t,s.a)),s.b)}function p(t,e){const r=n.sqr(e),i=d(t);return n.eql(r,i)}if(!p(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const g=n.mul(n.pow(s.a,vn),kn),m=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,m)))throw new Error("bad curve params: a or b");function b(t,e,r=!1){if(!n.isValid(e)||r&&n.is0(e))throw new Error(`bad point coordinate ${t}`);return e}function w(t){if(!(t instanceof B))throw new Error("ProjectivePoint expected")}function k(t){if(!u||!u.basises)throw new Error("no endo");return function(t,e,r){const[[n,i],[s,o]]=e,a=ln(o*t,r),u=ln(-i*t,r);let h=t-a*n-u*s,c=-a*i-u*o;const f=h=d||c=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:h,k2neg:l,k2:c}}(t,u.basises,i.ORDER)}const x=vt((t,e)=>{const{X:r,Y:i,Z:s}=t;if(n.eql(s,n.ONE))return{x:r,y:i};const o=t.is0();null==e&&(e=o?n.ONE:n.inv(s));const a=n.mul(r,e),u=n.mul(i,e),h=n.mul(s,e);if(o)return{x:n.ZERO,y:n.ZERO};if(!n.eql(h,n.ONE))throw new Error("invZ was invalid");return{x:a,y:u}}),A=vt(t=>{if(t.is0()){if(e.allowInfinityPoint&&!n.is0(t.Y))return;throw new Error("bad point: ZERO")}const{x:r,y:i}=t.toAffine();if(!n.isValid(r)||!n.isValid(i))throw new Error("bad point: x or y not field elements");if(!p(r,i))throw new Error("bad point: equation left != right");if(!t.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(t,e,r,i,s){return r=new B(n.mul(r.X,t),r.Y,r.Z),e=Zt(i,e),r=Zt(s,r),e.add(r)}class B{constructor(t,e,r){this.X=b("x",t),this.Y=b("y",e,!0),this.Z=b("z",r),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){const{x:e,y:r}=t||{};if(!t||!n.isValid(e)||!n.isValid(r))throw new Error("invalid affine point");if(t instanceof B)throw new Error("projective point not allowed");return n.is0(e)&&n.is0(r)?B.ZERO:new B(e,r,n.ONE)}static fromBytes(t){const e=B.fromAffine(l(st(t,void 0,"point")));return e.assertValidity(),e}static fromHex(t){return B.fromBytes(lt("pointHex",t))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return I.createCache(this,t),e||this.multiply(vn),this}assertValidity(){A(this)}hasEvenY(){const{y:t}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(t)}equals(t){w(t);const{X:e,Y:r,Z:i}=this,{X:s,Y:o,Z:a}=t,u=n.eql(n.mul(e,a),n.mul(s,i)),h=n.eql(n.mul(r,a),n.mul(o,i));return u&&h}negate(){return new B(this.X,n.neg(this.Y),this.Z)}double(){const{a:t,b:e}=s,r=n.mul(e,vn),{X:i,Y:o,Z:a}=this;let u=n.ZERO,h=n.ZERO,c=n.ZERO,f=n.mul(i,i),l=n.mul(o,o),d=n.mul(a,a),p=n.mul(i,o);return p=n.add(p,p),c=n.mul(i,a),c=n.add(c,c),u=n.mul(t,c),h=n.mul(r,d),h=n.add(u,h),u=n.sub(l,h),h=n.add(l,h),h=n.mul(u,h),u=n.mul(p,u),c=n.mul(r,c),d=n.mul(t,d),p=n.sub(f,d),p=n.mul(t,p),p=n.add(p,c),c=n.add(f,f),f=n.add(c,f),f=n.add(f,d),f=n.mul(f,p),h=n.add(h,f),d=n.mul(o,a),d=n.add(d,d),f=n.mul(d,p),u=n.sub(u,f),c=n.mul(d,l),c=n.add(c,c),c=n.add(c,c),new B(u,h,c)}add(t){w(t);const{X:e,Y:r,Z:i}=this,{X:o,Y:a,Z:u}=t;let h=n.ZERO,c=n.ZERO,f=n.ZERO;const l=s.a,d=n.mul(s.b,vn);let p=n.mul(e,o),y=n.mul(r,a),g=n.mul(i,u),m=n.add(e,r),b=n.add(o,a);m=n.mul(m,b),b=n.add(p,y),m=n.sub(m,b),b=n.add(e,i);let v=n.add(o,u);return b=n.mul(b,v),v=n.add(p,g),b=n.sub(b,v),v=n.add(r,i),h=n.add(a,u),v=n.mul(v,h),h=n.add(y,g),v=n.sub(v,h),f=n.mul(l,b),h=n.mul(d,g),f=n.add(h,f),h=n.sub(y,f),f=n.add(y,f),c=n.mul(h,f),y=n.add(p,p),y=n.add(y,p),g=n.mul(l,g),b=n.mul(d,b),y=n.add(y,g),g=n.sub(p,g),g=n.mul(l,g),b=n.add(b,g),p=n.mul(y,b),c=n.add(c,p),p=n.mul(v,b),h=n.mul(m,h),h=n.sub(h,p),p=n.mul(m,y),f=n.mul(v,f),f=n.add(f,p),new B(h,c,f)}subtract(t){return this.add(t.negate())}is0(){return this.equals(B.ZERO)}multiply(t){const{endo:r}=e;if(!i.isValidNot0(t))throw new Error("invalid scalar: out of range");let n,s;const o=t=>I.cached(this,t,t=>Yt(B,t));if(r){const{k1neg:e,k1:i,k2neg:a,k2:u}=k(t),{p:h,f:c}=o(i),{p:f,f:l}=o(u);s=c.add(l),n=E(r.beta,h,f,e,a)}else{const{p:e,f:r}=o(t);n=e,s=r}return Yt(B,[n,s])[0]}multiplyUnsafe(t){const{endo:r}=e,n=this;if(!i.isValid(t))throw new Error("invalid scalar: out of range");if(t===mn||n.is0())return B.ZERO;if(t===bn)return n;if(I.hasCache(this))return this.multiply(t);if(r){const{k1neg:e,k1:i,k2neg:s,k2:o}=k(t),{p1:a,p2:u}=function(t,e,r,n){let i=e,s=t.ZERO,o=t.ZERO;for(;r>$t||n>$t;)r&Vt&&(s=s.add(i)),n&Vt&&(o=o.add(i)),i=i.double(),r>>=Vt,n>>=Vt;return{p1:s,p2:o}}(B,n,i,o);return E(r.beta,a,u,e,s)}return I.unsafe(n,t)}multiplyAndAddUnsafe(t,e,r){const n=this.multiplyUnsafe(e).add(t.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(t){return x(this,t)}isTorsionFree(){const{isTorsionFree:t}=e;return o===bn||(t?t(B,this):I.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:t}=e;return o===bn?this:t?t(B,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(t=!0){return it(t,"isCompressed"),this.assertValidity(),f(B,this,t)}toHex(t=!0){return y(this.toBytes(t))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(t=!0){return this.toBytes(t)}_setWindowSize(t){this.precompute(t)}static normalizeZ(t){return Yt(B,t)}static msm(t,e){return ie(B,i,t,e)}static fromPrivateKey(t){return B.BASE.multiply(xn(i,t))}}B.BASE=new B(s.Gx,s.Gy,n.ONE),B.ZERO=new B(n.ZERO,n.ONE,n.ZERO),B.Fp=n,B.Fn=i;const S=i.BITS,I=new ne(B,e.endo?Math.ceil(S/2):S);return B.BASE.precompute(8),B}(e,r),n,i))}const In={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},_n={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Mn=BigInt(2),Un=Ft(In.p,{sqrt:function(t){const e=In.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),u=BigInt(88),h=t*t*t%e,c=h*h*t%e,f=Ot(c,r,e)*c%e,l=Ot(f,r,e)*c%e,d=Ot(l,Mn,e)*h%e,p=Ot(d,i,e)*d%e,y=Ot(p,s,e)*p%e,g=Ot(y,a,e)*y%e,m=Ot(g,u,e)*g%e,b=Ot(m,a,e)*y%e,w=Ot(b,r,e)*c%e,v=Ot(w,o,e)*p%e,k=Ot(v,n,e)*h%e,x=Ot(k,Mn,e);if(!Un.eql(Un.sqr(x),t))throw new Error("Cannot find square root");return x}}),Pn=function(t,e){const r=e=>Sn({...t,hash:e});return{...r(e),create:r}}({...In,Fp:Un,lowS:!0,endo:_n},tt);Se.utils.randomPrivateKey;const On=()=>{const t=Se.utils.randomPrivateKey(),e=Ln(t),r=new Uint8Array(64);return r.set(t),r.set(e,32),{publicKey:e,secretKey:r}},Ln=Se.getPublicKey;function Kn(t){try{return Se.ExtendedPoint.fromHex(t),!0}catch{return!1}}const zn=(t,e)=>Se.sign(t,e.slice(0,32)),Tn=Se.verify,Rn=t=>n.Buffer.isBuffer(t)?t:t instanceof Uint8Array?n.Buffer.from(t.buffer,t.byteOffset,t.byteLength):n.Buffer.from(t);class Cn{constructor(t){Object.assign(this,t)}encode(){return n.Buffer.from((0,cr.serialize)(Nn,this))}static decode(t){return(0,cr.deserialize)(Nn,this,t)}static decodeUnchecked(t){return(0,cr.deserializeUnchecked)(Nn,this,t)}}const Nn=new Map;var jn;const Dn=32;let Hn=1;class Fn extends Cn{constructor(t){if(super({}),this._bn=void 0,function(t){return void 0!==t._bn}(t))this._bn=t._bn;else{if("string"==typeof t){const e=je().decode(t);if(e.length!=Dn)throw new Error("Invalid public key input");this._bn=new(Ce())(e)}else this._bn=new(Ce())(t);if(this._bn.byteLength()>Dn)throw new Error("Invalid public key input")}}static unique(){const t=new Fn(Hn);return Hn+=1,new Fn(t.toBuffer())}equals(t){return this._bn.eq(t._bn)}toBase58(){return je().encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const t=this.toBuffer();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}toBuffer(){const t=this._bn.toArrayLike(n.Buffer);if(t.length===Dn)return t;const e=n.Buffer.alloc(32);return t.copy(e,32-t.length),e}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(t,e,r){const i=n.Buffer.concat([t.toBuffer(),n.Buffer.from(e),r.toBuffer()]),s=hr(i);return new Fn(s)}static createProgramAddressSync(t,e){let r=n.Buffer.alloc(0);t.forEach(function(t){if(t.length>32)throw new TypeError("Max seed length exceeded");r=n.Buffer.concat([r,Rn(t)])}),r=n.Buffer.concat([r,e.toBuffer(),n.Buffer.from("ProgramDerivedAddress")]);const i=hr(r);if(Kn(i))throw new Error("Invalid seeds, address must fall off the curve");return new Fn(i)}static async createProgramAddress(t,e){return this.createProgramAddressSync(t,e)}static findProgramAddressSync(t,e){let r,i=255;for(;0!=i;){try{const s=t.concat(n.Buffer.from([i]));r=this.createProgramAddressSync(s,e)}catch(t){if(t instanceof TypeError)throw t;i--;continue}return[r,i]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(t,e){return this.findProgramAddressSync(t,e)}static isOnCurve(t){return Kn(new Fn(t).toBytes())}}jn=Fn,Fn.default=new jn("11111111111111111111111111111111"),Nn.set(Fn,{kind:"struct",fields:[["_bn","u256"]]}),new Fn("BPFLoader1111111111111111111111111111111111");const Wn=1232;class qn extends Error{constructor(t){super(`Signature ${t} has expired: block height exceeded.`),this.signature=void 0,this.signature=t}}Object.defineProperty(qn.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class $n extends Error{constructor(t,e){super(`Transaction was not confirmed in ${e.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${t} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=t}}Object.defineProperty($n.prototype,"name",{value:"TransactionExpiredTimeoutError"});class Vn extends Error{constructor(t){super(`Signature ${t} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=t}}Object.defineProperty(Vn.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class Zn{constructor(t,e){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=t,this.accountKeysFromLookups=e}keySegments(){const t=[this.staticAccountKeys];return this.accountKeysFromLookups&&(t.push(this.accountKeysFromLookups.writable),t.push(this.accountKeysFromLookups.readonly)),t}get(t){for(const e of this.keySegments()){if(t256)throw new Error("Account index overflow encountered during compilation");const e=new Map;this.keySegments().flat().forEach((t,r)=>{e.set(t.toBase58(),r)});const r=t=>{const r=e.get(t.toBase58());if(void 0===r)throw new Error("Encountered an unknown instruction account key during compilation");return r};return t.map(t=>({programIdIndex:r(t.programId),accountKeyIndexes:t.keys.map(t=>r(t.pubkey)),data:t.data}))}}const Yn=(t="publicKey")=>fr.av(32,t),Gn=(t="signature")=>fr.av(64,t),Xn=(t="string")=>{const e=fr.w3([fr.DH("length"),fr.DH("lengthPadding"),fr.av(fr.cY(fr.DH(),-8),"chars")],t),r=e.decode.bind(e),i=e.encode.bind(e),s=e;return s.decode=(t,e)=>r(t,e).chars.toString(),s.encode=(t,e,r)=>{const s={chars:n.Buffer.from(t,"utf8")};return i(s,e,r)},s.alloc=t=>fr.DH().span+fr.DH().span+n.Buffer.from(t,"utf8").length,s};function Jn(t,e){const r=t=>{if(t.span>=0)return t.span;if("function"==typeof t.alloc)return t.alloc(e[t.property]);if("count"in t&&"elementLayout"in t){const n=e[t.property];if(Array.isArray(n))return n.length*r(t.elementLayout)}else if("fields"in t)return Jn({layout:t},e[t.property]);return 0};let n=0;return t.layout.fields.forEach(t=>{n+=r(t)}),n}function Qn(t){let e=0,r=0;for(;;){let n=t.shift();if(e|=(127&n)<<7*r,r+=1,!(128&n))break}return e}function ti(t,e){let r=e;for(;;){let e=127&r;if(r>>=7,0==r){t.push(e);break}e|=128,t.push(e)}}function ei(t,e){if(!t)throw new Error(e||"Assertion failed")}class ri{constructor(t,e){this.payer=void 0,this.keyMetaMap=void 0,this.payer=t,this.keyMetaMap=e}static compile(t,e){const r=new Map,n=t=>{const e=t.toBase58();let n=r.get(e);return void 0===n&&(n={isSigner:!1,isWritable:!1,isInvoked:!1},r.set(e,n)),n},i=n(e);i.isSigner=!0,i.isWritable=!0;for(const e of t){n(e.programId).isInvoked=!0;for(const t of e.keys){const e=n(t.pubkey);e.isSigner||=t.isSigner,e.isWritable||=t.isWritable}}return new ri(e,r)}getMessageComponents(){const t=[...this.keyMetaMap.entries()];ei(t.length<=256,"Max static account keys length exceeded");const e=t.filter(([,t])=>t.isSigner&&t.isWritable),r=t.filter(([,t])=>t.isSigner&&!t.isWritable),n=t.filter(([,t])=>!t.isSigner&&t.isWritable),i=t.filter(([,t])=>!t.isSigner&&!t.isWritable),s={numRequiredSignatures:e.length+r.length,numReadonlySignedAccounts:r.length,numReadonlyUnsignedAccounts:i.length};{ei(e.length>0,"Expected at least one writable signer key");const[t]=e[0];ei(t===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[s,[...e.map(([t])=>new Fn(t)),...r.map(([t])=>new Fn(t)),...n.map(([t])=>new Fn(t)),...i.map(([t])=>new Fn(t))]]}extractTableLookup(t){const[e,r]=this.drainKeysFoundInLookupTable(t.state.addresses,t=>!t.isSigner&&!t.isInvoked&&t.isWritable),[n,i]=this.drainKeysFoundInLookupTable(t.state.addresses,t=>!t.isSigner&&!t.isInvoked&&!t.isWritable);if(0!==e.length||0!==n.length)return[{accountKey:t.key,writableIndexes:e,readonlyIndexes:n},{writable:r,readonly:i}]}drainKeysFoundInLookupTable(t,e){const r=new Array,n=new Array;for(const[i,s]of this.keyMetaMap.entries())if(e(s)){const e=new Fn(i),s=t.findIndex(t=>t.equals(e));s>=0&&(ei(s<256,"Max lookup table index exceeded"),r.push(s),n.push(e),this.keyMetaMap.delete(i))}return[r,n]}}const ni="Reached end of buffer unexpectedly";function ii(t){if(0===t.length)throw new Error(ni);return t.shift()}function si(t,...e){const[r]=e;if(2===e.length?r+(e[1]??0)>t.length:r>=t.length)throw new Error(ni);return t.splice(...e)}class oi{constructor(t){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=t.header,this.accountKeys=t.accountKeys.map(t=>new Fn(t)),this.recentBlockhash=t.recentBlockhash,this.instructions=t.instructions,this.instructions.forEach(t=>this.indexToProgramIds.set(t.programIdIndex,this.accountKeys[t.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(t=>({programIdIndex:t.programIdIndex,accountKeyIndexes:t.accounts,data:je().decode(t.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new Zn(this.staticAccountKeys)}static compile(t){const e=ri.compile(t.instructions,t.payerKey),[r,n]=e.getMessageComponents(),i=new Zn(n).compileInstructions(t.instructions).map(t=>({programIdIndex:t.programIdIndex,accounts:t.accountKeyIndexes,data:je().encode(t.data)}));return new oi({header:r,accountKeys:n,recentBlockhash:t.recentBlockhash,instructions:i})}isAccountSigner(t){return t=this.header.numRequiredSignatures?t-e!this.isProgramId(e))}serialize(){const t=this.accountKeys.length;let e=[];ti(e,t);const r=this.instructions.map(t=>{const{accounts:e,programIdIndex:r}=t,i=Array.from(je().decode(t.data));let s=[];ti(s,e.length);let o=[];return ti(o,i.length),{programIdIndex:r,keyIndicesCount:n.Buffer.from(s),keyIndices:e,dataLength:n.Buffer.from(o),data:i}});let i=[];ti(i,r.length);let s=n.Buffer.alloc(Wn);n.Buffer.from(i).copy(s);let o=i.length;r.forEach(t=>{const e=fr.w3([fr.u8("programIdIndex"),fr.av(t.keyIndicesCount.length,"keyIndicesCount"),fr.O6(fr.u8("keyIndex"),t.keyIndices.length,"keyIndices"),fr.av(t.dataLength.length,"dataLength"),fr.O6(fr.u8("userdatum"),t.data.length,"data")]).encode(t,s,o);o+=e}),s=s.slice(0,o);const a=fr.w3([fr.av(1,"numRequiredSignatures"),fr.av(1,"numReadonlySignedAccounts"),fr.av(1,"numReadonlyUnsignedAccounts"),fr.av(e.length,"keyCount"),fr.O6(Yn("key"),t,"keys"),Yn("recentBlockhash")]),u={numRequiredSignatures:n.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:n.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:n.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:n.Buffer.from(e),keys:this.accountKeys.map(t=>Rn(t.toBytes())),recentBlockhash:je().decode(this.recentBlockhash)};let h=n.Buffer.alloc(2048);const c=a.encode(u,h);return s.copy(h,c),h.slice(0,c+s.length)}static from(t){let e=[...t];const r=ii(e);if(r!==(127&r))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const i=ii(e),s=ii(e),o=Qn(e);let a=[];for(let t=0;t0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new Zn(this.staticAccountKeys,e)}isAccountSigner(t){return t=r?t-rt+e.writableIndexes.length,0):t>=this.header.numRequiredSignatures?t-et.key.equals(r.accountKey));if(!n)throw new Error(`Failed to find address lookup table account for table key ${r.accountKey.toBase58()}`);for(const t of r.writableIndexes){if(!(tt.toBytes()),recentBlockhash:je().decode(this.recentBlockhash),instructionsLength:new Uint8Array(r),serializedInstructions:e,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:n},o);return o.slice(0,a)}serializeInstructions(){let t=0;const e=new Uint8Array(Wn);for(const r of this.compiledInstructions){const n=Array();ti(n,r.accountKeyIndexes.length);const i=Array();ti(i,r.data.length),t+=fr.w3([fr.u8("programIdIndex"),fr.av(n.length,"encodedAccountKeyIndexesLength"),fr.O6(fr.u8(),r.accountKeyIndexes.length,"accountKeyIndexes"),fr.av(i.length,"encodedDataLength"),fr.av(r.data.length,"data")]).encode({programIdIndex:r.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(n),accountKeyIndexes:r.accountKeyIndexes,encodedDataLength:new Uint8Array(i),data:r.data},e,t)}return e.slice(0,t)}serializeAddressTableLookups(){let t=0;const e=new Uint8Array(Wn);for(const r of this.addressTableLookups){const n=Array();ti(n,r.writableIndexes.length);const i=Array();ti(i,r.readonlyIndexes.length),t+=fr.w3([Yn("accountKey"),fr.av(n.length,"encodedWritableIndexesLength"),fr.O6(fr.u8(),r.writableIndexes.length,"writableIndexes"),fr.av(i.length,"encodedReadonlyIndexesLength"),fr.O6(fr.u8(),r.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:r.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(n),writableIndexes:r.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(i),readonlyIndexes:r.readonlyIndexes},e,t)}return e.slice(0,t)}static deserialize(t){let e=[...t];const r=ii(e),n=127&r;ei(r!==n,"Expected versioned message but received legacy message"),ei(0===n,`Expected versioned message with version 0 but found version ${n}`);const i={numRequiredSignatures:ii(e),numReadonlySignedAccounts:ii(e),numReadonlyUnsignedAccounts:ii(e)},s=[],o=Qn(e);for(let t=0;t{const e=ui.deserializeMessageVersion(t);if("legacy"===e)return oi.from(t);if(0===e)return ai.deserialize(t);throw new Error(`Transaction message version ${e} deserialization is not supported`)}},hi=n.Buffer.alloc(64).fill(0);class ci{constructor(t){this.keys=void 0,this.programId=void 0,this.data=n.Buffer.alloc(0),this.programId=t.programId,this.keys=t.keys,t.data&&(this.data=t.data)}toJSON(){return{keys:this.keys.map(({pubkey:t,isSigner:e,isWritable:r})=>({pubkey:t.toJSON(),isSigner:e,isWritable:r})),programId:this.programId.toJSON(),data:[...this.data]}}}class fi{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(t){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,t)if(t.feePayer&&(this.feePayer=t.feePayer),t.signatures&&(this.signatures=t.signatures),Object.prototype.hasOwnProperty.call(t,"nonceInfo")){const{minContextSlot:e,nonceInfo:r}=t;this.minNonceContextSlot=e,this.nonceInfo=r}else if(Object.prototype.hasOwnProperty.call(t,"lastValidBlockHeight")){const{blockhash:e,lastValidBlockHeight:r}=t;this.recentBlockhash=e,this.lastValidBlockHeight=r}else{const{recentBlockhash:e,nonceInfo:r}=t;r&&(this.nonceInfo=r),this.recentBlockhash=e}}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(t=>t.toJSON()),signers:this.signatures.map(({publicKey:t})=>t.toJSON())}}add(...t){if(0===t.length)throw new Error("No instructions");return t.forEach(t=>{"instructions"in t?this.instructions=this.instructions.concat(t.instructions):"data"in t&&"programId"in t&&"keys"in t?this.instructions.push(t):this.instructions.push(new ci(t))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let t,e,r;if(this.nonceInfo?(t=this.nonceInfo.nonce,e=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(t=this.recentBlockhash,e=this.instructions),!t)throw new Error("Transaction recentBlockhash required");if(e.length<1&&console.warn("No instructions provided"),this.feePayer)r=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");r=this.signatures[0].publicKey}for(let t=0;t{t.keys.forEach(t=>{i.push({...t})});const e=t.programId.toString();n.includes(e)||n.push(e)}),n.forEach(t=>{i.push({pubkey:new Fn(t),isSigner:!1,isWritable:!1})});const s=[];i.forEach(t=>{const e=t.pubkey.toString(),r=s.findIndex(t=>t.pubkey.toString()===e);r>-1?(s[r].isWritable=s[r].isWritable||t.isWritable,s[r].isSigner=s[r].isSigner||t.isSigner):s.push(t)}),s.sort(function(t,e){return t.isSigner!==e.isSigner?t.isSigner?-1:1:t.isWritable!==e.isWritable?t.isWritable?-1:1:t.pubkey.toBase58().localeCompare(e.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const o=s.findIndex(t=>t.pubkey.equals(r));if(o>-1){const[t]=s.splice(o,1);t.isSigner=!0,t.isWritable=!0,s.unshift(t)}else s.unshift({pubkey:r,isSigner:!0,isWritable:!0});for(const t of this.signatures){const e=s.findIndex(e=>e.pubkey.equals(t.publicKey));if(!(e>-1))throw new Error(`unknown signer: ${t.publicKey.toString()}`);s[e].isSigner||(s[e].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 a=0,u=0,h=0;const c=[],f=[];s.forEach(({pubkey:t,isSigner:e,isWritable:r})=>{e?(c.push(t.toString()),a+=1,r||(u+=1)):(f.push(t.toString()),r||(h+=1))});const l=c.concat(f),d=e.map(t=>{const{data:e,programId:r}=t;return{programIdIndex:l.indexOf(r.toString()),accounts:t.keys.map(t=>l.indexOf(t.pubkey.toString())),data:je().encode(e)}});return d.forEach(t=>{ei(t.programIdIndex>=0),t.accounts.forEach(t=>ei(t>=0))}),new oi({header:{numRequiredSignatures:a,numReadonlySignedAccounts:u,numReadonlyUnsignedAccounts:h},accountKeys:l,recentBlockhash:t,instructions:d})}_compile(){const t=this.compileMessage(),e=t.accountKeys.slice(0,t.header.numRequiredSignatures);return this.signatures.length===e.length&&this.signatures.every((t,r)=>e[r].equals(t.publicKey))||(this.signatures=e.map(t=>({signature:null,publicKey:t}))),t}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(t){return(await t.getFeeForMessage(this.compileMessage())).value}setSigners(...t){if(0===t.length)throw new Error("No signers");const e=new Set;this.signatures=t.filter(t=>{const r=t.toString();return!e.has(r)&&(e.add(r),!0)}).map(t=>({signature:null,publicKey:t}))}sign(...t){if(0===t.length)throw new Error("No signers");const e=new Set,r=[];for(const n of t){const t=n.publicKey.toString();e.has(t)||(e.add(t),r.push(n))}this.signatures=r.map(t=>({signature:null,publicKey:t.publicKey}));const n=this._compile();this._partialSign(n,...r)}partialSign(...t){if(0===t.length)throw new Error("No signers");const e=new Set,r=[];for(const n of t){const t=n.publicKey.toString();e.has(t)||(e.add(t),r.push(n))}const n=this._compile();this._partialSign(n,...r)}_partialSign(t,...e){const r=t.serialize();e.forEach(t=>{const e=zn(r,t.secretKey);this._addSignature(t.publicKey,Rn(e))})}addSignature(t,e){this._compile(),this._addSignature(t,e)}_addSignature(t,e){ei(64===e.length);const r=this.signatures.findIndex(e=>t.equals(e.publicKey));if(r<0)throw new Error(`unknown signer: ${t.toString()}`);this.signatures[r].signature=n.Buffer.from(e)}verifySignatures(t=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),t)}_getMessageSignednessErrors(t,e){const r={};for(const{signature:n,publicKey:i}of this.signatures)null===n?e&&(r.missing||=[]).push(i):Tn(n,t,i.toBytes())||(r.invalid||=[]).push(i);return r.invalid||r.missing?r:void 0}serialize(t){const{requireAllSignatures:e,verifySignatures:r}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},t),n=this.serializeMessage();if(r){const t=this._getMessageSignednessErrors(n,e);if(t){let e="Signature verification failed.";throw t.invalid&&(e+=`\nInvalid signature for public key${1===t.invalid.length?"":"(s)"} [\`${t.invalid.map(t=>t.toBase58()).join("`, `")}\`].`),t.missing&&(e+=`\nMissing signature for public key${1===t.missing.length?"":"(s)"} [\`${t.missing.map(t=>t.toBase58()).join("`, `")}\`].`),new Error(e)}}return this._serialize(n)}_serialize(t){const{signatures:e}=this,r=[];ti(r,e.length);const i=r.length+64*e.length+t.length,s=n.Buffer.alloc(i);return ei(e.length<256),n.Buffer.from(r).copy(s,0),e.forEach(({signature:t},e)=>{null!==t&&(ei(64===t.length,"signature has invalid length"),n.Buffer.from(t).copy(s,r.length+64*e))}),t.copy(s,r.length+64*e.length),ei(s.length<=Wn,`Transaction too large: ${s.length} > 1232`),s}get keys(){return ei(1===this.instructions.length),this.instructions[0].keys.map(t=>t.pubkey)}get programId(){return ei(1===this.instructions.length),this.instructions[0].programId}get data(){return ei(1===this.instructions.length),this.instructions[0].data}static from(t){let e=[...t];const r=Qn(e);let i=[];for(let t=0;t0&&(r.feePayer=t.accountKeys[0]),e.forEach((e,n)=>{const i={signature:e==je().encode(hi)?null:je().decode(e),publicKey:t.accountKeys[n]};r.signatures.push(i)}),t.instructions.forEach(e=>{const n=e.accounts.map(e=>{const n=t.accountKeys[e];return{pubkey:n,isSigner:r.signatures.some(t=>t.publicKey.toString()===n.toString())||t.isAccountSigner(e),isWritable:t.isAccountWritable(e)}});r.instructions.push(new ci({keys:n,programId:t.accountKeys[e.programIdIndex],data:je().decode(e.data)}))}),r._message=t,r._json=r.toJSON(),r}}class li{get version(){return this.message.version}constructor(t,e){if(this.signatures=void 0,this.message=void 0,void 0!==e)ei(e.length===t.header.numRequiredSignatures,"Expected signatures length to be equal to the number of required signatures"),this.signatures=e;else{const e=[];for(let r=0;rt.equals(n.publicKey));ei(t>=0,`Cannot sign with non signer key ${n.publicKey.toBase58()}`),this.signatures[t]=zn(e,n.secretKey)}}addSignature(t,e){ei(64===e.byteLength,"Signature must be 64 bytes long");const r=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures).findIndex(e=>e.equals(t));ei(r>=0,`Can not add signature; \`${t.toBase58()}\` is not required to sign this transaction`),this.signatures[r]=e}}const di=new Fn("SysvarC1ock11111111111111111111111111111111"),pi=(new Fn("SysvarEpochSchedu1e111111111111111111111111"),new Fn("Sysvar1nstructions1111111111111111111111111"),new Fn("SysvarRecentB1ockHashes11111111111111111111")),yi=new Fn("SysvarRent111111111111111111111111111111111"),gi=(new Fn("SysvarRewards111111111111111111111111111111"),new Fn("SysvarS1otHashes111111111111111111111111111"),new Fn("SysvarS1otHistory11111111111111111111111111"),new Fn("SysvarStakeHistory1111111111111111111111111"));class mi extends Error{constructor({action:t,signature:e,transactionMessage:r,logs:n}){const i=n?`Logs: \n${JSON.stringify(n.slice(-10),null,2)}. `:"",s="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let o;switch(t){case"send":o=`Transaction ${e} resulted in an error. \n${r}. `+i+s;break;case"simulate":o=`Simulation failed. \nMessage: ${r}. \n`+i+s;break;default:o=`Unknown action '${t}'`}super(o),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=e,this.transactionMessage=r,this.transactionLogs=n||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const t=this.transactionLogs;if(null==t||"object"!=typeof t||!("then"in t))return t}async getLogs(t){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((e,r)=>{t.getTransaction(this.signature).then(t=>{if(t&&t.meta&&t.meta.logMessages){const r=t.meta.logMessages;this.transactionLogs=r,e(r)}else r(new Error("Log messages not found"))}).catch(r)})),await this.transactionLogs}}async function bi(t,e,r,n){const i=n&&{skipPreflight:n.skipPreflight,preflightCommitment:n.preflightCommitment||n.commitment,maxRetries:n.maxRetries,minContextSlot:n.minContextSlot},s=await t.sendTransaction(e,r,i);let o;if(null!=e.recentBlockhash&&null!=e.lastValidBlockHeight)o=(await t.confirmTransaction({abortSignal:n?.abortSignal,signature:s,blockhash:e.recentBlockhash,lastValidBlockHeight:e.lastValidBlockHeight},n&&n.commitment)).value;else if(null!=e.minNonceContextSlot&&null!=e.nonceInfo){const{nonceInstruction:r}=e.nonceInfo,i=r.keys[0].pubkey;o=(await t.confirmTransaction({abortSignal:n?.abortSignal,minContextSlot:e.minNonceContextSlot,nonceAccountPubkey:i,nonceValue:e.nonceInfo.nonce,signature:s},n&&n.commitment)).value}else null!=n?.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."),o=(await t.confirmTransaction(s,n&&n.commitment)).value;if(o.err){if(null!=s)throw new mi({action:"send",signature:s,transactionMessage:`Status: (${JSON.stringify(o)})`});throw new Error(`Transaction ${s} failed (${JSON.stringify(o)})`)}return s}function wi(t){return new Promise(e=>setTimeout(e,t))}function vi(t,e){const r=t.layout.span>=0?t.layout.span:Jn(t,e),i=n.Buffer.alloc(r),s=Object.assign({instruction:t.index},e);return t.layout.encode(s,i),i}Error;const ki=fr.I0("lamportsPerSignature"),xi=fr.w3([fr.DH("version"),fr.DH("state"),Yn("authorizedPubkey"),Yn("nonce"),fr.w3([ki],"feeCalculator")]).span;function Ai(t){const e=(0,fr.av)(8,t),r=e.decode.bind(e),n=e.encode.bind(e),i=e,s=vr();return i.decode=(t,e)=>{const n=r(t,e);return s.decode(n)},i.encode=(t,e,r)=>{const i=s.encode(t);return n(i,e,r)},i}const Ei=Object.freeze({Create:{index:0,layout:fr.w3([fr.DH("instruction"),fr.Wg("lamports"),fr.Wg("space"),Yn("programId")])},Assign:{index:1,layout:fr.w3([fr.DH("instruction"),Yn("programId")])},Transfer:{index:2,layout:fr.w3([fr.DH("instruction"),Ai("lamports")])},CreateWithSeed:{index:3,layout:fr.w3([fr.DH("instruction"),Yn("base"),Xn("seed"),fr.Wg("lamports"),fr.Wg("space"),Yn("programId")])},AdvanceNonceAccount:{index:4,layout:fr.w3([fr.DH("instruction")])},WithdrawNonceAccount:{index:5,layout:fr.w3([fr.DH("instruction"),fr.Wg("lamports")])},InitializeNonceAccount:{index:6,layout:fr.w3([fr.DH("instruction"),Yn("authorized")])},AuthorizeNonceAccount:{index:7,layout:fr.w3([fr.DH("instruction"),Yn("authorized")])},Allocate:{index:8,layout:fr.w3([fr.DH("instruction"),fr.Wg("space")])},AllocateWithSeed:{index:9,layout:fr.w3([fr.DH("instruction"),Yn("base"),Xn("seed"),fr.Wg("space"),Yn("programId")])},AssignWithSeed:{index:10,layout:fr.w3([fr.DH("instruction"),Yn("base"),Xn("seed"),Yn("programId")])},TransferWithSeed:{index:11,layout:fr.w3([fr.DH("instruction"),Ai("lamports"),Xn("seed"),Yn("programId")])},UpgradeNonceAccount:{index:12,layout:fr.w3([fr.DH("instruction")])}});class Bi{constructor(){}static createAccount(t){const e=vi(Ei.Create,{lamports:t.lamports,space:t.space,programId:Rn(t.programId.toBuffer())});return new ci({keys:[{pubkey:t.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:t.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:e})}static transfer(t){let e,r;return"basePubkey"in t?(e=vi(Ei.TransferWithSeed,{lamports:BigInt(t.lamports),seed:t.seed,programId:Rn(t.programId.toBuffer())}),r=[{pubkey:t.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:t.basePubkey,isSigner:!0,isWritable:!1},{pubkey:t.toPubkey,isSigner:!1,isWritable:!0}]):(e=vi(Ei.Transfer,{lamports:BigInt(t.lamports)}),r=[{pubkey:t.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:t.toPubkey,isSigner:!1,isWritable:!0}]),new ci({keys:r,programId:this.programId,data:e})}static assign(t){let e,r;return"basePubkey"in t?(e=vi(Ei.AssignWithSeed,{base:Rn(t.basePubkey.toBuffer()),seed:t.seed,programId:Rn(t.programId.toBuffer())}),r=[{pubkey:t.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:t.basePubkey,isSigner:!0,isWritable:!1}]):(e=vi(Ei.Assign,{programId:Rn(t.programId.toBuffer())}),r=[{pubkey:t.accountPubkey,isSigner:!0,isWritable:!0}]),new ci({keys:r,programId:this.programId,data:e})}static createAccountWithSeed(t){const e=vi(Ei.CreateWithSeed,{base:Rn(t.basePubkey.toBuffer()),seed:t.seed,lamports:t.lamports,space:t.space,programId:Rn(t.programId.toBuffer())});let r=[{pubkey:t.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:t.newAccountPubkey,isSigner:!1,isWritable:!0}];return t.basePubkey.equals(t.fromPubkey)||r.push({pubkey:t.basePubkey,isSigner:!0,isWritable:!1}),new ci({keys:r,programId:this.programId,data:e})}static createNonceAccount(t){const e=new fi;"basePubkey"in t&&"seed"in t?e.add(Bi.createAccountWithSeed({fromPubkey:t.fromPubkey,newAccountPubkey:t.noncePubkey,basePubkey:t.basePubkey,seed:t.seed,lamports:t.lamports,space:xi,programId:this.programId})):e.add(Bi.createAccount({fromPubkey:t.fromPubkey,newAccountPubkey:t.noncePubkey,lamports:t.lamports,space:xi,programId:this.programId}));const r={noncePubkey:t.noncePubkey,authorizedPubkey:t.authorizedPubkey};return e.add(this.nonceInitialize(r)),e}static nonceInitialize(t){const e=vi(Ei.InitializeNonceAccount,{authorized:Rn(t.authorizedPubkey.toBuffer())}),r={keys:[{pubkey:t.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:pi,isSigner:!1,isWritable:!1},{pubkey:yi,isSigner:!1,isWritable:!1}],programId:this.programId,data:e};return new ci(r)}static nonceAdvance(t){const e=vi(Ei.AdvanceNonceAccount),r={keys:[{pubkey:t.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:pi,isSigner:!1,isWritable:!1},{pubkey:t.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:e};return new ci(r)}static nonceWithdraw(t){const e=vi(Ei.WithdrawNonceAccount,{lamports:t.lamports});return new ci({keys:[{pubkey:t.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:t.toPubkey,isSigner:!1,isWritable:!0},{pubkey:pi,isSigner:!1,isWritable:!1},{pubkey:yi,isSigner:!1,isWritable:!1},{pubkey:t.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:e})}static nonceAuthorize(t){const e=vi(Ei.AuthorizeNonceAccount,{authorized:Rn(t.newAuthorizedPubkey.toBuffer())});return new ci({keys:[{pubkey:t.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:t.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:e})}static allocate(t){let e,r;return"basePubkey"in t?(e=vi(Ei.AllocateWithSeed,{base:Rn(t.basePubkey.toBuffer()),seed:t.seed,space:t.space,programId:Rn(t.programId.toBuffer())}),r=[{pubkey:t.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:t.basePubkey,isSigner:!0,isWritable:!1}]):(e=vi(Ei.Allocate,{space:t.space}),r=[{pubkey:t.accountPubkey,isSigner:!0,isWritable:!0}]),new ci({keys:r,programId:this.programId,data:e})}}Bi.programId=new Fn("11111111111111111111111111111111");class Si{constructor(){}static getMinNumSignatures(t){return 2*(Math.ceil(t/Si.chunkSize)+1+1)}static async load(t,e,r,i,s){{const n=await t.getMinimumBalanceForRentExemption(s.length),o=await t.getAccountInfo(r.publicKey,"confirmed");let a=null;if(null!==o){if(o.executable)return console.error("Program load failed, account is already executable"),!1;o.data.length!==s.length&&(a=a||new fi,a.add(Bi.allocate({accountPubkey:r.publicKey,space:s.length}))),o.owner.equals(i)||(a=a||new fi,a.add(Bi.assign({accountPubkey:r.publicKey,programId:i}))),o.lamports0?n:1,space:s.length,programId:i}));null!==a&&await bi(t,a,[e,r],{commitment:"confirmed"})}const o=fr.w3([fr.DH("instruction"),fr.DH("offset"),fr.DH("bytesLength"),fr.DH("bytesLengthPadding"),fr.O6(fr.u8("byte"),fr.cY(fr.DH(),-8),"bytes")]),a=Si.chunkSize;let u=0,h=s,c=[];for(;h.length>0;){const s=h.slice(0,a),f=n.Buffer.alloc(a+16);o.encode({instruction:0,offset:u,bytes:s,bytesLength:0,bytesLengthPadding:0},f);const l=(new fi).add({keys:[{pubkey:r.publicKey,isSigner:!0,isWritable:!0}],programId:i,data:f});if(c.push(bi(t,l,[e,r],{commitment:"confirmed"})),t._rpcEndpoint.includes("solana.com")){const t=4;await wi(1e3/t)}u+=a,h=h.slice(a)}await Promise.all(c);{const s=fr.w3([fr.DH("instruction")]),o=n.Buffer.alloc(s.span);s.encode({instruction:1},o);const a=(new fi).add({keys:[{pubkey:r.publicKey,isSigner:!0,isWritable:!0},{pubkey:yi,isSigner:!1,isWritable:!1}],programId:i,data:o}),u="processed",h=await t.sendTransaction(a,[e,r],{preflightCommitment:u}),{context:c,value:f}=await t.confirmTransaction({signature:h,lastValidBlockHeight:a.lastValidBlockHeight,blockhash:a.recentBlockhash},u);if(f.err)throw new Error(`Transaction ${h} failed (${JSON.stringify(f)})`);for(;;){try{if(await t.getSlot({commitment:u})>c.slot)break}catch{}await new Promise(t=>setTimeout(t,Math.round(200)))}}return!0}}Si.chunkSize=932,new Fn("BPFLoader2111111111111111111111111111111111"),globalThis.fetch,fr.w3([fr.DH("typeIndex"),Ai("deactivationSlot"),fr.I0("lastExtendedSlot"),fr.u8("lastExtendedStartIndex"),fr.u8(),fr.O6(Yn(),fr.cY(fr.u8(),-1),"authority")]);const Ii=$r(zr(Fn),Dr(),t=>new Fn(t)),_i=Hr([Dr(),Tr("base64")]),Mi=$r(zr(n.Buffer),_i,t=>n.Buffer.from(t[0],"base64"));function Ui(t){return Wr([Fr({jsonrpc:Tr("2.0"),id:Dr(),result:t}),Fr({jsonrpc:Tr("2.0"),id:Dr(),error:Fr({code:qr(),message:Dr(),data:Nr(Or("any",()=>!0))})})])}const Pi=Ui(qr());function Oi(t){return $r(Ui(t),Pi,e=>"error"in e?e:{...e,result:Mr(e.result,t)})}function Li(t){return Oi(Fr({context:Fr({slot:Cr()}),value:t}))}function Ki(t){return Fr({context:Fr({slot:Cr()}),value:t})}const zi=Fr({foundation:Cr(),foundationTerm:Cr(),initial:Cr(),taper:Cr(),terminal:Cr()}),Ti=(Oi(Lr(Rr(Fr({epoch:Cr(),effectiveSlot:Cr(),amount:Cr(),postBalance:Cr(),commission:Nr(Rr(Cr()))})))),Lr(Fr({slot:Cr(),prioritizationFee:Cr()}))),Ri=Fr({total:Cr(),validator:Cr(),foundation:Cr(),epoch:Cr()}),Ci=Fr({epoch:Cr(),slotIndex:Cr(),slotsInEpoch:Cr(),absoluteSlot:Cr(),blockHeight:Nr(Cr()),transactionCount:Nr(Cr())}),Ni=Fr({slotsPerEpoch:Cr(),leaderScheduleSlotOffset:Cr(),warmup:Kr(),firstNormalEpoch:Cr(),firstNormalSlot:Cr()}),ji=jr(Dr(),Lr(Cr())),Di=Rr(Wr([Fr({}),Dr()])),Hi=Fr({err:Di}),Fi=Tr("receivedSignature"),Wi=(Fr({"solana-core":Dr(),"feature-set":Nr(Cr())}),Fr({program:Dr(),programId:Ii,parsed:qr()})),qi=Fr({programId:Ii,accounts:Lr(Ii),data:Dr()});Li(Fr({err:Rr(Wr([Fr({}),Dr()])),logs:Rr(Lr(Dr())),accounts:Nr(Rr(Lr(Rr(Fr({executable:Kr(),owner:Dr(),lamports:Cr(),data:Lr(Dr()),rentEpoch:Nr(Cr())}))))),unitsConsumed:Nr(Cr()),returnData:Nr(Rr(Fr({programId:Dr(),data:Hr([Dr(),Tr("base64")])}))),innerInstructions:Nr(Rr(Lr(Fr({index:Cr(),instructions:Lr(Wr([Wi,qi]))}))))})),Li(Fr({byIdentity:jr(Dr(),Lr(Cr())),range:Fr({firstSlot:Cr(),lastSlot:Cr()})})),Oi(zi),Oi(Ri),Oi(Ti),Oi(Ci),Oi(Ni),Oi(ji),Oi(Cr()),Li(Fr({total:Cr(),circulating:Cr(),nonCirculating:Cr(),nonCirculatingAccounts:Lr(Ii)}));const $i=Fr({amount:Dr(),uiAmount:Rr(Cr()),decimals:Cr(),uiAmountString:Nr(Dr())}),Vi=(Li(Lr(Fr({address:Ii,amount:Dr(),uiAmount:Rr(Cr()),decimals:Cr(),uiAmountString:Nr(Dr())}))),Li(Lr(Fr({pubkey:Ii,account:Fr({executable:Kr(),owner:Ii,lamports:Cr(),data:Mi,rentEpoch:Cr()})}))),Fr({program:Dr(),parsed:qr(),space:Cr()})),Zi=(Li(Lr(Fr({pubkey:Ii,account:Fr({executable:Kr(),owner:Ii,lamports:Cr(),data:Vi,rentEpoch:Cr()})}))),Li(Lr(Fr({lamports:Cr(),address:Ii}))),Fr({executable:Kr(),owner:Ii,lamports:Cr(),data:Mi,rentEpoch:Cr()})),Yi=(Fr({pubkey:Ii,account:Zi}),$r(Wr([zr(n.Buffer),Vi]),Wr([_i,Vi]),t=>Array.isArray(t)?Mr(t,Mi):t)),Gi=Fr({executable:Kr(),owner:Ii,lamports:Cr(),data:Yi,rentEpoch:Cr()}),Xi=(Fr({pubkey:Ii,account:Gi}),Fr({state:Wr([Tr("active"),Tr("inactive"),Tr("activating"),Tr("deactivating")]),active:Cr(),inactive:Cr()}),Oi(Lr(Fr({signature:Dr(),slot:Cr(),err:Di,memo:Rr(Dr()),blockTime:Nr(Rr(Cr()))}))),Oi(Lr(Fr({signature:Dr(),slot:Cr(),err:Di,memo:Rr(Dr()),blockTime:Nr(Rr(Cr()))}))),Fr({subscription:Cr(),result:Ki(Zi)}),Fr({pubkey:Ii,account:Zi})),Ji=(Fr({subscription:Cr(),result:Ki(Xi)}),Fr({parent:Cr(),slot:Cr(),root:Cr()})),Qi=(Fr({subscription:Cr(),result:Ji}),Wr([Fr({type:Wr([Tr("firstShredReceived"),Tr("completed"),Tr("optimisticConfirmation"),Tr("root")]),slot:Cr(),timestamp:Cr()}),Fr({type:Tr("createdBank"),parent:Cr(),slot:Cr(),timestamp:Cr()}),Fr({type:Tr("frozen"),slot:Cr(),timestamp:Cr(),stats:Fr({numTransactionEntries:Cr(),numSuccessfulTransactions:Cr(),numFailedTransactions:Cr(),maxTransactionsPerEntry:Cr()})}),Fr({type:Tr("dead"),slot:Cr(),timestamp:Cr(),err:Dr()})])),ts=(Fr({subscription:Cr(),result:Qi}),Fr({subscription:Cr(),result:Ki(Wr([Hi,Fi]))}),Fr({subscription:Cr(),result:Cr()}),Fr({pubkey:Dr(),gossip:Rr(Dr()),tpu:Rr(Dr()),rpc:Rr(Dr()),version:Rr(Dr())}),Fr({votePubkey:Dr(),nodePubkey:Dr(),activatedStake:Cr(),epochVoteAccount:Kr(),epochCredits:Lr(Hr([Cr(),Cr(),Cr()])),commission:Cr(),lastVote:Cr(),rootSlot:Rr(Cr())})),es=(Oi(Fr({current:Lr(ts),delinquent:Lr(ts)})),Wr([Tr("processed"),Tr("confirmed"),Tr("finalized")])),rs=Fr({slot:Cr(),confirmations:Rr(Cr()),err:Di,confirmationStatus:Nr(es)}),ns=(Li(Lr(Rr(rs))),Oi(Cr()),Fr({accountKey:Ii,writableIndexes:Lr(Cr()),readonlyIndexes:Lr(Cr())})),is=Fr({signatures:Lr(Dr()),message:Fr({accountKeys:Lr(Dr()),header:Fr({numRequiredSignatures:Cr(),numReadonlySignedAccounts:Cr(),numReadonlyUnsignedAccounts:Cr()}),instructions:Lr(Fr({accounts:Lr(Cr()),data:Dr(),programIdIndex:Cr()})),recentBlockhash:Dr(),addressTableLookups:Nr(Lr(ns))})}),ss=Fr({pubkey:Ii,signer:Kr(),writable:Kr(),source:Nr(Wr([Tr("transaction"),Tr("lookupTable")]))}),os=Fr({accountKeys:Lr(ss),signatures:Lr(Dr())}),as=Fr({parsed:qr(),program:Dr(),programId:Ii}),us=Fr({accounts:Lr(Ii),data:Dr(),programId:Ii}),hs=$r(Wr([us,as]),Wr([Fr({parsed:qr(),program:Dr(),programId:Dr()}),Fr({accounts:Lr(Dr()),data:Dr(),programId:Dr()})]),t=>Mr(t,"accounts"in t?us:as)),cs=Fr({signatures:Lr(Dr()),message:Fr({accountKeys:Lr(ss),instructions:Lr(hs),recentBlockhash:Dr(),addressTableLookups:Nr(Rr(Lr(ns)))})}),fs=Fr({accountIndex:Cr(),mint:Dr(),owner:Nr(Dr()),programId:Nr(Dr()),uiTokenAmount:$i}),ls=Fr({writable:Lr(Ii),readonly:Lr(Ii)}),ds=Fr({err:Di,fee:Cr(),innerInstructions:Nr(Rr(Lr(Fr({index:Cr(),instructions:Lr(Fr({accounts:Lr(Cr()),data:Dr(),programIdIndex:Cr()}))})))),preBalances:Lr(Cr()),postBalances:Lr(Cr()),logMessages:Nr(Rr(Lr(Dr()))),preTokenBalances:Nr(Rr(Lr(fs))),postTokenBalances:Nr(Rr(Lr(fs))),loadedAddresses:Nr(ls),computeUnitsConsumed:Nr(Cr()),costUnits:Nr(Cr())}),ps=Fr({err:Di,fee:Cr(),innerInstructions:Nr(Rr(Lr(Fr({index:Cr(),instructions:Lr(hs)})))),preBalances:Lr(Cr()),postBalances:Lr(Cr()),logMessages:Nr(Rr(Lr(Dr()))),preTokenBalances:Nr(Rr(Lr(fs))),postTokenBalances:Nr(Rr(Lr(fs))),loadedAddresses:Nr(ls),computeUnitsConsumed:Nr(Cr()),costUnits:Nr(Cr())}),ys=Wr([Tr(0),Tr("legacy")]),gs=Fr({pubkey:Dr(),lamports:Cr(),postBalance:Rr(Cr()),rewardType:Rr(Dr()),commission:Nr(Rr(Cr()))}),ms=(Oi(Rr(Fr({blockhash:Dr(),previousBlockhash:Dr(),parentSlot:Cr(),transactions:Lr(Fr({transaction:is,meta:Rr(ds),version:Nr(ys)})),rewards:Nr(Lr(gs)),blockTime:Rr(Cr()),blockHeight:Rr(Cr())}))),Oi(Rr(Fr({blockhash:Dr(),previousBlockhash:Dr(),parentSlot:Cr(),rewards:Nr(Lr(gs)),blockTime:Rr(Cr()),blockHeight:Rr(Cr())}))),Oi(Rr(Fr({blockhash:Dr(),previousBlockhash:Dr(),parentSlot:Cr(),transactions:Lr(Fr({transaction:os,meta:Rr(ds),version:Nr(ys)})),rewards:Nr(Lr(gs)),blockTime:Rr(Cr()),blockHeight:Rr(Cr())}))),Oi(Rr(Fr({blockhash:Dr(),previousBlockhash:Dr(),parentSlot:Cr(),transactions:Lr(Fr({transaction:cs,meta:Rr(ps),version:Nr(ys)})),rewards:Nr(Lr(gs)),blockTime:Rr(Cr()),blockHeight:Rr(Cr())}))),Oi(Rr(Fr({blockhash:Dr(),previousBlockhash:Dr(),parentSlot:Cr(),transactions:Lr(Fr({transaction:os,meta:Rr(ps),version:Nr(ys)})),rewards:Nr(Lr(gs)),blockTime:Rr(Cr()),blockHeight:Rr(Cr())}))),Oi(Rr(Fr({blockhash:Dr(),previousBlockhash:Dr(),parentSlot:Cr(),rewards:Nr(Lr(gs)),blockTime:Rr(Cr()),blockHeight:Rr(Cr())}))),Oi(Rr(Fr({blockhash:Dr(),previousBlockhash:Dr(),parentSlot:Cr(),transactions:Lr(Fr({transaction:is,meta:Rr(ds)})),rewards:Nr(Lr(gs)),blockTime:Rr(Cr())}))),Oi(Rr(Fr({blockhash:Dr(),previousBlockhash:Dr(),parentSlot:Cr(),signatures:Lr(Dr()),blockTime:Rr(Cr())}))),Oi(Rr(Fr({slot:Cr(),meta:Rr(ds),blockTime:Nr(Rr(Cr())),transaction:is,version:Nr(ys)}))),Oi(Rr(Fr({slot:Cr(),transaction:cs,meta:Rr(ps),blockTime:Nr(Rr(Cr())),version:Nr(ys)}))),Li(Fr({blockhash:Dr(),lastValidBlockHeight:Cr()})),Li(Kr()),Oi(Lr(Fr({slot:Cr(),numTransactions:Cr(),numSlots:Cr(),samplePeriodSecs:Cr()}))),Li(Rr(Fr({feeCalculator:Fr({lamportsPerSignature:Cr()})}))),Oi(Dr()),Oi(Dr()),Fr({err:Di,logs:Lr(Dr()),signature:Dr()}));Fr({result:Ki(ms),subscription:Cr()});class bs{constructor(t){this._keypair=void 0,this._keypair=t??On()}static generate(){return new bs(On())}static fromSecretKey(t,e){if(64!==t.byteLength)throw new Error("bad secret key size");const r=t.slice(32,64);if(!e||!e.skipValidation){const e=t.slice(0,32),n=Ln(e);for(let t=0;t<32;t++)if(r[t]!==n[t])throw new Error("provided secretKey is invalid")}return new bs({publicKey:r,secretKey:t})}static fromSeed(t){const e=Ln(t),r=new Uint8Array(64);return r.set(t),r.set(e,32),new bs({publicKey:e,secretKey:r})}get publicKey(){return new Fn(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:fr.w3([fr.DH("instruction"),Ai("recentSlot"),fr.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:fr.w3([fr.DH("instruction")])},ExtendLookupTable:{index:2,layout:fr.w3([fr.DH("instruction"),Ai(),fr.O6(Yn(),fr.cY(fr.DH(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:fr.w3([fr.DH("instruction")])},CloseLookupTable:{index:4,layout:fr.w3([fr.DH("instruction")])}});new Fn("AddressLookupTab1e1111111111111111111111111");Object.freeze({RequestUnits:{index:0,layout:fr.w3([fr.u8("instruction"),fr.DH("units"),fr.DH("additionalFee")])},RequestHeapFrame:{index:1,layout:fr.w3([fr.u8("instruction"),fr.DH("bytes")])},SetComputeUnitLimit:{index:2,layout:fr.w3([fr.u8("instruction"),fr.DH("units")])},SetComputeUnitPrice:{index:3,layout:fr.w3([fr.u8("instruction"),Ai("microLamports")])}});new Fn("ComputeBudget111111111111111111111111111111");const ws=fr.w3([fr.u8("numSignatures"),fr.u8("padding"),fr.NX("signatureOffset"),fr.NX("signatureInstructionIndex"),fr.NX("publicKeyOffset"),fr.NX("publicKeyInstructionIndex"),fr.NX("messageDataOffset"),fr.NX("messageDataSize"),fr.NX("messageInstructionIndex")]);class vs{constructor(){}static createInstructionWithPublicKey(t){const{publicKey:e,message:r,signature:i,instructionIndex:s}=t;ei(32===e.length,`Public Key must be 32 bytes but received ${e.length} bytes`),ei(64===i.length,`Signature must be 64 bytes but received ${i.length} bytes`);const o=ws.span,a=o+e.length,u=a+i.length,h=n.Buffer.alloc(u+r.length),c=null==s?65535:s;return ws.encode({numSignatures:1,padding:0,signatureOffset:a,signatureInstructionIndex:c,publicKeyOffset:o,publicKeyInstructionIndex:c,messageDataOffset:u,messageDataSize:r.length,messageInstructionIndex:c},h),h.fill(e,o),h.fill(i,a),h.fill(r,u),new ci({keys:[],programId:vs.programId,data:h})}static createInstructionWithPrivateKey(t){const{privateKey:e,message:r,instructionIndex:n}=t;ei(64===e.length,`Private key must be 64 bytes but received ${e.length} bytes`);try{const t=bs.fromSecretKey(e),i=t.publicKey.toBytes(),s=zn(r,t.secretKey);return this.createInstructionWithPublicKey({publicKey:i,message:r,signature:s,instructionIndex:n})}catch(t){throw new Error(`Error creating instruction; ${t}`)}}}vs.programId=new Fn("Ed25519SigVerify111111111111111111111111111"),Pn.utils.isValidPrivateKey;const ks=Pn.getPublicKey,xs=fr.w3([fr.u8("numSignatures"),fr.NX("signatureOffset"),fr.u8("signatureInstructionIndex"),fr.NX("ethAddressOffset"),fr.u8("ethAddressInstructionIndex"),fr.NX("messageDataOffset"),fr.NX("messageDataSize"),fr.u8("messageInstructionIndex"),fr.av(20,"ethAddress"),fr.av(64,"signature"),fr.u8("recoveryId")]);class As{constructor(){}static publicKeyToEthAddress(t){ei(64===t.length,`Public key must be 64 bytes but received ${t.length} bytes`);try{return n.Buffer.from(hn(Rn(t))).slice(-20)}catch(t){throw new Error(`Error constructing Ethereum address: ${t}`)}}static createInstructionWithPublicKey(t){const{publicKey:e,message:r,signature:n,recoveryId:i,instructionIndex:s}=t;return As.createInstructionWithEthAddress({ethAddress:As.publicKeyToEthAddress(e),message:r,signature:n,recoveryId:i,instructionIndex:s})}static createInstructionWithEthAddress(t){const{ethAddress:e,message:r,signature:i,recoveryId:s,instructionIndex:o=0}=t;let a;a="string"==typeof e?e.startsWith("0x")?n.Buffer.from(e.substr(2),"hex"):n.Buffer.from(e,"hex"):e,ei(20===a.length,`Address must be 20 bytes but received ${a.length} bytes`);const u=12+a.length,h=u+i.length+1,c=n.Buffer.alloc(xs.span+r.length);return xs.encode({numSignatures:1,signatureOffset:u,signatureInstructionIndex:o,ethAddressOffset:12,ethAddressInstructionIndex:o,messageDataOffset:h,messageDataSize:r.length,messageInstructionIndex:o,signature:Rn(i),ethAddress:Rn(a),recoveryId:s},c),c.fill(Rn(r),xs.span),new ci({keys:[],programId:As.programId,data:c})}static createInstructionWithPrivateKey(t){const{privateKey:e,message:r,instructionIndex:i}=t;ei(32===e.length,`Private key must be 32 bytes but received ${e.length} bytes`);try{const t=Rn(e),s=ks(t,!1).slice(1),o=n.Buffer.from(hn(Rn(r))),[a,u]=((t,e)=>{const r=Pn.sign(t,e);return[r.toCompactRawBytes(),r.recovery]})(o,t);return this.createInstructionWithPublicKey({publicKey:s,message:r,signature:a,recoveryId:u,instructionIndex:i})}catch(t){throw new Error(`Error creating instruction; ${t}`)}}}var Es;As.programId=new Fn("KeccakSecp256k11111111111111111111111111111");const Bs=new Fn("StakeConfig11111111111111111111111111111111");class Ss{constructor(t,e,r){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=t,this.epoch=e,this.custodian=r}}Es=Ss,Ss.default=new Es(0,0,Fn.default);const Is=Object.freeze({Initialize:{index:0,layout:fr.w3([fr.DH("instruction"),((t="authorized")=>fr.w3([Yn("staker"),Yn("withdrawer")],t))(),((t="lockup")=>fr.w3([fr.Wg("unixTimestamp"),fr.Wg("epoch"),Yn("custodian")],t))()])},Authorize:{index:1,layout:fr.w3([fr.DH("instruction"),Yn("newAuthorized"),fr.DH("stakeAuthorizationType")])},Delegate:{index:2,layout:fr.w3([fr.DH("instruction")])},Split:{index:3,layout:fr.w3([fr.DH("instruction"),fr.Wg("lamports")])},Withdraw:{index:4,layout:fr.w3([fr.DH("instruction"),fr.Wg("lamports")])},Deactivate:{index:5,layout:fr.w3([fr.DH("instruction")])},Merge:{index:7,layout:fr.w3([fr.DH("instruction")])},AuthorizeWithSeed:{index:8,layout:fr.w3([fr.DH("instruction"),Yn("newAuthorized"),fr.DH("stakeAuthorizationType"),Xn("authoritySeed"),Yn("authorityOwner")])}});Object.freeze({Staker:{index:0},Withdrawer:{index:1}});class _s{constructor(){}static initialize(t){const{stakePubkey:e,authorized:r,lockup:n}=t,i=n||Ss.default,s=vi(Is.Initialize,{authorized:{staker:Rn(r.staker.toBuffer()),withdrawer:Rn(r.withdrawer.toBuffer())},lockup:{unixTimestamp:i.unixTimestamp,epoch:i.epoch,custodian:Rn(i.custodian.toBuffer())}}),o={keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:yi,isSigner:!1,isWritable:!1}],programId:this.programId,data:s};return new ci(o)}static createAccountWithSeed(t){const e=new fi;e.add(Bi.createAccountWithSeed({fromPubkey:t.fromPubkey,newAccountPubkey:t.stakePubkey,basePubkey:t.basePubkey,seed:t.seed,lamports:t.lamports,space:this.space,programId:this.programId}));const{stakePubkey:r,authorized:n,lockup:i}=t;return e.add(this.initialize({stakePubkey:r,authorized:n,lockup:i}))}static createAccount(t){const e=new fi;e.add(Bi.createAccount({fromPubkey:t.fromPubkey,newAccountPubkey:t.stakePubkey,lamports:t.lamports,space:this.space,programId:this.programId}));const{stakePubkey:r,authorized:n,lockup:i}=t;return e.add(this.initialize({stakePubkey:r,authorized:n,lockup:i}))}static delegate(t){const{stakePubkey:e,authorizedPubkey:r,votePubkey:n}=t,i=vi(Is.Delegate);return(new fi).add({keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:gi,isSigner:!1,isWritable:!1},{pubkey:Bs,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}],programId:this.programId,data:i})}static authorize(t){const{stakePubkey:e,authorizedPubkey:r,newAuthorizedPubkey:n,stakeAuthorizationType:i,custodianPubkey:s}=t,o=vi(Is.Authorize,{newAuthorized:Rn(n.toBuffer()),stakeAuthorizationType:i.index}),a=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1}];return s&&a.push({pubkey:s,isSigner:!0,isWritable:!1}),(new fi).add({keys:a,programId:this.programId,data:o})}static authorizeWithSeed(t){const{stakePubkey:e,authorityBase:r,authoritySeed:n,authorityOwner:i,newAuthorizedPubkey:s,stakeAuthorizationType:o,custodianPubkey:a}=t,u=vi(Is.AuthorizeWithSeed,{newAuthorized:Rn(s.toBuffer()),stakeAuthorizationType:o.index,authoritySeed:n,authorityOwner:Rn(i.toBuffer())}),h=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1},{pubkey:di,isSigner:!1,isWritable:!1}];return a&&h.push({pubkey:a,isSigner:!0,isWritable:!1}),(new fi).add({keys:h,programId:this.programId,data:u})}static splitInstruction(t){const{stakePubkey:e,authorizedPubkey:r,splitStakePubkey:n,lamports:i}=t,s=vi(Is.Split,{lamports:i});return new ci({keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1}],programId:this.programId,data:s})}static split(t,e){const r=new fi;return r.add(Bi.createAccount({fromPubkey:t.authorizedPubkey,newAccountPubkey:t.splitStakePubkey,lamports:e,space:this.space,programId:this.programId})),r.add(this.splitInstruction(t))}static splitWithSeed(t,e){const{stakePubkey:r,authorizedPubkey:n,splitStakePubkey:i,basePubkey:s,seed:o,lamports:a}=t,u=new fi;return u.add(Bi.allocate({accountPubkey:i,basePubkey:s,seed:o,space:this.space,programId:this.programId})),e&&e>0&&u.add(Bi.transfer({fromPubkey:t.authorizedPubkey,toPubkey:i,lamports:e})),u.add(this.splitInstruction({stakePubkey:r,authorizedPubkey:n,splitStakePubkey:i,lamports:a}))}static merge(t){const{stakePubkey:e,sourceStakePubKey:r,authorizedPubkey:n}=t,i=vi(Is.Merge);return(new fi).add({keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:gi,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:i})}static withdraw(t){const{stakePubkey:e,authorizedPubkey:r,toPubkey:n,lamports:i,custodianPubkey:s}=t,o=vi(Is.Withdraw,{lamports:i}),a=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:gi,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}];return s&&a.push({pubkey:s,isSigner:!0,isWritable:!1}),(new fi).add({keys:a,programId:this.programId,data:o})}static deactivate(t){const{stakePubkey:e,authorizedPubkey:r}=t,n=vi(Is.Deactivate);return(new fi).add({keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}],programId:this.programId,data:n})}}_s.programId=new Fn("Stake11111111111111111111111111111111111111"),_s.space=200;const Ms=Object.freeze({InitializeAccount:{index:0,layout:fr.w3([fr.DH("instruction"),((t="voteInit")=>fr.w3([Yn("nodePubkey"),Yn("authorizedVoter"),Yn("authorizedWithdrawer"),fr.u8("commission")],t))()])},Authorize:{index:1,layout:fr.w3([fr.DH("instruction"),Yn("newAuthorized"),fr.DH("voteAuthorizationType")])},Withdraw:{index:3,layout:fr.w3([fr.DH("instruction"),fr.Wg("lamports")])},UpdateValidatorIdentity:{index:4,layout:fr.w3([fr.DH("instruction")])},AuthorizeWithSeed:{index:10,layout:fr.w3([fr.DH("instruction"),((t="voteAuthorizeWithSeedArgs")=>fr.w3([fr.DH("voteAuthorizationType"),Yn("currentAuthorityDerivedKeyOwnerPubkey"),Xn("currentAuthorityDerivedKeySeed"),Yn("newAuthorized")],t))()])}});Object.freeze({Voter:{index:0},Withdrawer:{index:1}});class Us{constructor(){}static initializeAccount(t){const{votePubkey:e,nodePubkey:r,voteInit:n}=t,i=vi(Ms.InitializeAccount,{voteInit:{nodePubkey:Rn(n.nodePubkey.toBuffer()),authorizedVoter:Rn(n.authorizedVoter.toBuffer()),authorizedWithdrawer:Rn(n.authorizedWithdrawer.toBuffer()),commission:n.commission}}),s={keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:yi,isSigner:!1,isWritable:!1},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}],programId:this.programId,data:i};return new ci(s)}static createAccount(t){const e=new fi;return e.add(Bi.createAccount({fromPubkey:t.fromPubkey,newAccountPubkey:t.votePubkey,lamports:t.lamports,space:this.space,programId:this.programId})),e.add(this.initializeAccount({votePubkey:t.votePubkey,nodePubkey:t.voteInit.nodePubkey,voteInit:t.voteInit}))}static authorize(t){const{votePubkey:e,authorizedPubkey:r,newAuthorizedPubkey:n,voteAuthorizationType:i}=t,s=vi(Ms.Authorize,{newAuthorized:Rn(n.toBuffer()),voteAuthorizationType:i.index}),o=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}];return(new fi).add({keys:o,programId:this.programId,data:s})}static authorizeWithSeed(t){const{currentAuthorityDerivedKeyBasePubkey:e,currentAuthorityDerivedKeyOwnerPubkey:r,currentAuthorityDerivedKeySeed:n,newAuthorizedPubkey:i,voteAuthorizationType:s,votePubkey:o}=t,a=vi(Ms.AuthorizeWithSeed,{voteAuthorizeWithSeedArgs:{currentAuthorityDerivedKeyOwnerPubkey:Rn(r.toBuffer()),currentAuthorityDerivedKeySeed:n,newAuthorized:Rn(i.toBuffer()),voteAuthorizationType:s.index}}),u=[{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!0,isWritable:!1}];return(new fi).add({keys:u,programId:this.programId,data:a})}static withdraw(t){const{votePubkey:e,authorizedWithdrawerPubkey:r,lamports:n,toPubkey:i}=t,s=vi(Ms.Withdraw,{lamports:n}),o=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1}];return(new fi).add({keys:o,programId:this.programId,data:s})}static safeWithdraw(t,e,r){if(t.lamports>e-r)throw new Error("Withdraw will leave vote account with insufficient funds.");return Us.withdraw(t)}static updateValidatorIdentity(t){const{votePubkey:e,authorizedWithdrawerPubkey:r,nodePubkey:n}=t,i=vi(Ms.UpdateValidatorIdentity),s=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}];return(new fi).add({keys:s,programId:this.programId,data:i})}}Us.programId=new Fn("Vote111111111111111111111111111111111111111"),Us.space=3762,new Fn("Va1idator1nfo111111111111111111111111111111"),Fr({name:Dr(),website:Nr(Dr()),details:Nr(Dr()),iconUrl:Nr(Dr()),keybaseUsername:Nr(Dr())}),new Fn("Vote111111111111111111111111111111111111111"),fr.w3([Yn("nodePubkey"),Yn("authorizedWithdrawer"),fr.u8("commission"),fr.I0(),fr.O6(fr.w3([fr.I0("slot"),fr.DH("confirmationCount")]),fr.cY(fr.DH(),-8),"votes"),fr.u8("rootSlotValid"),fr.I0("rootSlot"),fr.I0(),fr.O6(fr.w3([fr.I0("epoch"),Yn("authorizedVoter")]),fr.cY(fr.DH(),-8),"authorizedVoters"),fr.w3([fr.O6(fr.w3([Yn("authorizedPubkey"),fr.I0("epochOfLastAuthorizedSwitch"),fr.I0("targetEpoch")]),32,"buf"),fr.I0("idx"),fr.u8("isEmpty")],"priorVoters"),fr.I0(),fr.O6(fr.w3([fr.I0("epoch"),fr.I0("credits"),fr.I0("prevCredits")]),fr.cY(fr.DH(),-8),"epochCredits"),fr.w3([fr.I0("slot"),fr.I0("timestamp")],"lastTimestamp")])},251:(t,e)=>{e.read=function(t,e,r,n,i){var s,o,a=8*i-n-1,u=(1<>1,c=-7,f=r?i-1:0,l=r?-1:1,d=t[e+f];for(f+=l,s=d&(1<<-c)-1,d>>=-c,c+=a;c>0;s=256*s+t[e+f],f+=l,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=n;c>0;o=256*o+t[e+f],f+=l,c-=8);if(0===s)s=1-h;else{if(s===u)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,n),s-=h}return(d?-1:1)*o*Math.pow(2,s-n)},e.write=function(t,e,r,n,i,s){var o,a,u,h=8*s-i-1,c=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:s-1,p=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),(e+=o+f>=1?l/u:l*Math.pow(2,1-f))*u>=2&&(o++,u/=2),o+f>=c?(a=0,o=c):o+f>=1?(a=(e*u-1)*Math.pow(2,i),o+=f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+d]=255&a,d+=p,a/=256,i-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,h-=8);t[r+d-p]|=128*y}},255:(t,e,r)=>{"use strict";r.d(e,{ws:()=>q,GR:()=>yt,RG:()=>gt,v7:()=>mt});class n extends Error{constructor(t){let e;e=t instanceof Error?t.message:"string"==typeof t?t:"",super(e),this.name=this.constructor.name}}class i extends n{}class s extends n{}class o extends n{}class a extends n{}class u extends n{}class h extends n{}class c extends n{}class f extends n{}class l extends n{}class d extends n{}class p extends n{}const y=(g=globalThis,m={},new Proxy(g,{get:(t,e,r)=>e in m?m[e]:g[e],set:(t,e,r)=>(e in m&&delete m[e],g[e]=r,!0),deleteProperty(t,e){let r=!1;return e in m&&(delete m[e],r=!0),e in g&&(delete g[e],r=!0),r},ownKeys(t){const e=Reflect.ownKeys(g),r=Reflect.ownKeys(m),n=new Set(r);return[...e.filter(t=>!n.has(t)),...r]},defineProperty:(t,e,r)=>(e in m&&delete m[e],Reflect.defineProperty(g,e,r),!0),getOwnPropertyDescriptor:(t,e)=>e in m?Reflect.getOwnPropertyDescriptor(m,e):Reflect.getOwnPropertyDescriptor(g,e),has:(t,e)=>e in m||e in g}));var g,m;class b{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){void 0===this._api&&(this._api=await async function(){if(void 0!==y&&void 0!==globalThis.crypto)return globalThis.crypto.subtle;try{const{webcrypto:t}=await r.e(825).then(r.t.bind(r,825,19));return t.subtle}catch(t){throw new p(t)}}())}}const w=8192,v=new Uint8Array(0),k=new Uint8Array([75,69,77,0,0]),x=t=>"object"==typeof t&&null!==t&&"object"==typeof t.privateKey&&"object"==typeof t.publicKey;function A(t,e){if(e<=0)throw new Error("i2Osp: too small size");if(t>=256**e)throw new Error("i2Osp: too large integer");const r=new Uint8Array(e);for(let n=0;n>=8;return r}function E(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t,0),r.set(e,t.length),r}const B=new Uint8Array([101,97,101,95,112,114,107]),S=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);class I{constructor(t,e,r){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_prim",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=t,this._prim=e,this._kdf=r;const n=new Uint8Array(k);n.set(A(this.id,2),3),this._kdf.init(n)}async serializePublicKey(t){return await this._prim.serializePublicKey(t)}async deserializePublicKey(t){return await this._prim.deserializePublicKey(t)}async serializePrivateKey(t){return await this._prim.serializePrivateKey(t)}async deserializePrivateKey(t){return await this._prim.deserializePrivateKey(t)}async importKey(t,e,r=!0){return await this._prim.importKey(t,e,r)}async generateKeyPair(){return await this._prim.generateKeyPair()}async deriveKeyPair(t){if(t.byteLength>w)throw new i("Too long ikm");return await this._prim.deriveKeyPair(t)}async encap(t){let e;e=void 0===t.ekm?await this.generateKeyPair():x(t.ekm)?t.ekm:await this.deriveKeyPair(t.ekm);const r=await this._prim.serializePublicKey(e.publicKey),n=await this._prim.serializePublicKey(t.recipientPublicKey);try{let i,s;if(void 0===t.senderKey)i=new Uint8Array(await this._prim.dh(e.privateKey,t.recipientPublicKey));else{const r=x(t.senderKey)?t.senderKey.privateKey:t.senderKey;i=E(new Uint8Array(await this._prim.dh(e.privateKey,t.recipientPublicKey)),new Uint8Array(await this._prim.dh(r,t.recipientPublicKey)))}if(void 0===t.senderKey)s=E(new Uint8Array(r),new Uint8Array(n));else{const e=x(t.senderKey)?t.senderKey.publicKey:await this._prim.derivePublicKey(t.senderKey),i=await this._prim.serializePublicKey(e);s=function(t,e,r){const n=new Uint8Array(t.length+e.length+r.length);return n.set(t,0),n.set(e,t.length),n.set(r,t.length+e.length),n}(new Uint8Array(r),new Uint8Array(n),new Uint8Array(i))}return{enc:r,sharedSecret:await this._generateSharedSecret(i,s)}}catch(t){throw new a(t)}}async decap(t){const e=await this._prim.deserializePublicKey(t.enc),r=x(t.recipientKey)?t.recipientKey.privateKey:t.recipientKey,n=x(t.recipientKey)?t.recipientKey.publicKey:await this._prim.derivePublicKey(t.recipientKey),i=await this._prim.serializePublicKey(n);try{let n,s;if(void 0===t.senderPublicKey)n=new Uint8Array(await this._prim.dh(r,e));else{n=E(new Uint8Array(await this._prim.dh(r,e)),new Uint8Array(await this._prim.dh(r,t.senderPublicKey)))}if(void 0===t.senderPublicKey)s=E(new Uint8Array(t.enc),new Uint8Array(i));else{const e=await this._prim.serializePublicKey(t.senderPublicKey);s=new Uint8Array(t.enc.byteLength+i.byteLength+e.byteLength),s.set(new Uint8Array(t.enc),0),s.set(new Uint8Array(i),t.enc.byteLength),s.set(new Uint8Array(e),t.enc.byteLength+i.byteLength)}return await this._generateSharedSecret(n,s)}catch(t){throw new u(t)}}async _generateSharedSecret(t,e){const r=this._kdf.buildLabeledIkm(B,t),n=this._kdf.buildLabeledInfo(S,e,this.secretSize);return await this._kdf.extractAndExpand(v.buffer,r.buffer,n.buffer,this.secretSize)}}const _=["deriveBits"],M=new Uint8Array([100,107,112,95,112,114,107]);new Uint8Array([115,107]);class U{constructor(t){Object.defineProperty(this,"_num",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._num=new Uint8Array(t)}val(){return this._num}reset(){this._num.fill(0)}set(t){if(t.length!==this._num.length)throw new Error("Bignum.set: invalid argument");this._num.set(t)}isZero(){for(let t=0;tt[e])return!1}return!1}}const P=new Uint8Array([99,97,110,100,105,100,97,116,101]),O=new Uint8Array([255,255,255,255,0,0,0,0,255,255,255,255,255,255,255,255,188,230,250,173,167,23,158,132,243,185,202,194,252,99,37,81]),L=new Uint8Array([255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,199,99,77,129,244,55,45,223,88,26,13,178,72,176,167,122,236,236,25,106,204,197,41,115]),K=new Uint8Array([1,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,250,81,134,135,131,191,47,150,107,127,204,1,72,247,9,165,208,59,181,201,184,137,156,71,174,187,111,183,30,145,56,100,9]),z=new Uint8Array([48,65,2,1,0,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,4,39,48,37,2,1,1,4,32]),T=new Uint8Array([48,78,2,1,0,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,34,4,55,48,53,2,1,1,4,48]),R=new Uint8Array([48,96,2,1,0,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,35,4,73,48,71,2,1,1,4,66]);class C extends b{constructor(t,e){switch(super(),Object.defineProperty(this,"_hkdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_alg",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nPk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nSk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nDh",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_bitmask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pkcs8AlgId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._hkdf=e,t){case 16:this._alg={name:"ECDH",namedCurve:"P-256"},this._nPk=65,this._nSk=32,this._nDh=32,this._order=O,this._bitmask=255,this._pkcs8AlgId=z;break;case 17:this._alg={name:"ECDH",namedCurve:"P-384"},this._nPk=97,this._nSk=48,this._nDh=48,this._order=L,this._bitmask=255,this._pkcs8AlgId=T;break;default:this._alg={name:"ECDH",namedCurve:"P-521"},this._nPk=133,this._nSk=66,this._nDh=66,this._order=K,this._bitmask=1,this._pkcs8AlgId=R}}async serializePublicKey(t){await this._setup();try{return await this._api.exportKey("raw",t)}catch(t){throw new s(t)}}async deserializePublicKey(t){await this._setup();try{return await this._importRawKey(t,!0)}catch(t){throw new o(t)}}async serializePrivateKey(t){await this._setup();try{const e=await this._api.exportKey("jwk",t);if(!("d"in e))throw new Error("Not private key");return function(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e),n=new Uint8Array(r.length);for(let t=0;t255)throw new Error("Faild to derive a key pair");const n=new Uint8Array(await this._hkdf.labeledExpand(e,P,A(t,1),this._nSk));n[0]=n[0]&this._bitmask,r.set(n)}const n=await this._deserializePkcs8Key(r.val());return r.reset(),{privateKey:n,publicKey:await this.derivePublicKey(n)}}catch(t){throw new d(t)}}async derivePublicKey(t){await this._setup();try{const e=await this._api.exportKey("jwk",t);return delete e.d,delete e.key_ops,await this._api.importKey("jwk",e,this._alg,!0,[])}catch(t){throw new o(t)}}async dh(t,e){try{return await this._setup(),await this._api.deriveBits({name:"ECDH",public:e},t,8*this._nDh)}catch(t){throw new s(t)}}async _importRawKey(t,e){if(e&&t.byteLength!==this._nPk)throw new Error("Invalid public key for the ciphersuite");if(!e&&t.byteLength!==this._nSk)throw new Error("Invalid private key for the ciphersuite");return e?await this._api.importKey("raw",t,this._alg,!0,[]):await this._deserializePkcs8Key(new Uint8Array(t))}async _importJWK(t,e){if(void 0===t.crv||t.crv!==this._alg.namedCurve)throw new Error(`Invalid crv: ${t.crv}`);if(e){if(void 0!==t.d)throw new Error("Invalid key: `d` should not be set");return await this._api.importKey("jwk",t,this._alg,!0,[])}if(void 0===t.d)throw new Error("Invalid key: `d` not found");return await this._api.importKey("jwk",t,this._alg,!0,_)}async _deserializePkcs8Key(t){const e=new Uint8Array(this._pkcs8AlgId.length+t.length);return e.set(this._pkcs8AlgId,0),e.set(t,this._pkcs8AlgId.length),await this._api.importKey("pkcs8",e,this._alg,!0,_)}}const N=new Uint8Array([72,80,75,69,45,118,49]);class j extends b{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:v}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:"HMAC",hash:"SHA-256",length:256}})}init(t){this._suiteId=t}buildLabeledIkm(t,e){this._checkInit();const r=new Uint8Array(7+this._suiteId.byteLength+t.byteLength+e.byteLength);return r.set(N,0),r.set(this._suiteId,7),r.set(t,7+this._suiteId.byteLength),r.set(e,7+this._suiteId.byteLength+t.byteLength),r}buildLabeledInfo(t,e,r){this._checkInit();const n=new Uint8Array(9+this._suiteId.byteLength+t.byteLength+e.byteLength);return n.set(new Uint8Array([0,r]),0),n.set(N,2),n.set(this._suiteId,9),n.set(t,9+this._suiteId.byteLength),n.set(e,9+this._suiteId.byteLength+t.byteLength),n}async extract(t,e){if(await this._setup(),0===t.byteLength&&(t=new ArrayBuffer(this.hashSize)),t.byteLength!==this.hashSize)throw new i("The salt length must be the same as the hashSize");const r=await this._api.importKey("raw",t,this.algHash,!1,["sign"]);return await this._api.sign("HMAC",r,e)}async expand(t,e,r){await this._setup();const n=await this._api.importKey("raw",t,this.algHash,!1,["sign"]),i=new ArrayBuffer(r),s=new Uint8Array(i);let o=v;const a=new Uint8Array(e),u=new Uint8Array(1);if(r>255*this.hashSize)throw new Error("Entropy limit reached");const h=new Uint8Array(this.hashSize+a.length+1);for(let t=1,e=0;e=o.length?(s.set(o,e),e+=o.length):(s.set(o.slice(0,s.length-e),e),e+=s.length-e);return i}async extractAndExpand(t,e,r,n){await this._setup();const i=await this._api.importKey("raw",e,"HKDF",!1,["deriveBits"]);return await this._api.deriveBits({name:"HKDF",hash:this.algHash.hash,salt:t,info:r},i,8*n)}async labeledExtract(t,e,r){return await this.extract(t,this.buildLabeledIkm(e,r).buffer)}async labeledExpand(t,e,r,n){return await this.expand(t,this.buildLabeledInfo(e,r,n).buffer,n)}_checkInit(){if(this._suiteId===v)throw new Error("Not initialized. Call init()")}}class D extends j{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:"HMAC",hash:"SHA-256",length:256}})}}const H=["encrypt","decrypt"];BigInt(0),BigInt(1),BigInt(2);class F extends b{constructor(t){super(),Object.defineProperty(this,"_rawKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._rawKey=t}async seal(t,e,r){await this._setupKey();const n={name:"AES-GCM",iv:t,additionalData:r};return await this._api.encrypt(n,this._key,e)}async open(t,e,r){await this._setupKey();const n={name:"AES-GCM",iv:t,additionalData:r};return await this._api.decrypt(n,this._key,e)}async _setupKey(){if(void 0!==this._key)return;await this._setup();const t=await this._importKey(this._rawKey);new Uint8Array(this._rawKey).fill(0),this._key=t}async _importKey(t){return await this._api.importKey("raw",t,{name:"AES-GCM"},!0,H)}}class W{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"keySize",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"nonceSize",{enumerable:!0,configurable:!0,writable:!0,value:12}),Object.defineProperty(this,"tagSize",{enumerable:!0,configurable:!0,writable:!0,value:16})}createEncryptionContext(t){return new F(t)}}class q extends W{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:2}),Object.defineProperty(this,"keySize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"nonceSize",{enumerable:!0,configurable:!0,writable:!0,value:12}),Object.defineProperty(this,"tagSize",{enumerable:!0,configurable:!0,writable:!0,value:16})}}function $(){return new Promise((t,e)=>{e(new p("Not supported"))})}const V=new Uint8Array([115,101,99]);class Z{constructor(t,e,r){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exporterSecret",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._api=t,this._kdf=e,this.exporterSecret=r}async seal(t,e){return await $()}async open(t,e){return await $()}async export(t,e){if(t.byteLength>w)throw new i("Too long exporter context");try{return await this._kdf.labeledExpand(this.exporterSecret,V,new Uint8Array(t),e)}catch(t){throw new h(t)}}}class Y extends Z{}class G extends Z{constructor(t,e,r,n){super(t,e,r),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.enc=n}}class X extends Z{constructor(t,e,r){if(super(t,e,r.exporterSecret),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nT",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),void 0===r.key||void 0===r.baseNonce||void 0===r.seq)throw new Error("Required parameters are missing");this._aead=r.aead,this._nK=this._aead.keySize,this._nN=this._aead.nonceSize,this._nT=this._aead.tagSize;const n=this._aead.createEncryptionContext(r.key);this._ctx={key:n,baseNonce:r.baseNonce,seq:r.seq}}computeNonce(t){const e=A(t.seq,t.baseNonce.byteLength);return function(t,e){if(t.byteLength!==e.byteLength)throw new Error("xor: different length inputs");const r=new Uint8Array(t.byteLength);for(let n=0;nNumber.MAX_SAFE_INTEGER)throw new l("Message limit reached");t.seq+=1}}var J;class Q{constructor(){J.set(this,Promise.resolve())}async lock(){let t;const e=new Promise(e=>{t=e}),r=function(t,e,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(t):n?n.value:e.get(t)}(this,J,"f");return function(t,e,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===n?i.call(t,r):i?i.value=r:e.set(t,r)}(this,J,e,"f"),await r,t}}J=new WeakMap;var tt,et=function(t,e,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(t):n?n.value:e.get(t)};class rt extends X{constructor(){super(...arguments),tt.set(this,void 0)}async open(t,e=v.buffer){!function(t,e,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===n?i.call(t,r):i?i.value=r:e.set(t,r)}(this,tt,et(this,tt,"f")??new Q,"f");const r=await et(this,tt,"f").lock();let n;try{n=await this._ctx.key.open(this.computeNonce(this._ctx),t,e)}catch(t){throw new f(t)}finally{r()}return this.incrementSeq(this._ctx),n}}tt=new WeakMap;var nt,it=function(t,e,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(t):n?n.value:e.get(t)};class st extends X{constructor(t,e,r,n){super(t,e,r),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),nt.set(this,void 0),this.enc=n}async seal(t,e=v.buffer){!function(t,e,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===n?i.call(t,r):i?i.value=r:e.set(t,r)}(this,nt,it(this,nt,"f")??new Q,"f");const r=await it(this,nt,"f").lock();let n;try{n=await this._ctx.key.seal(this.computeNonce(this._ctx),t,e)}catch(t){throw new c(t)}finally{r()}return this.incrementSeq(this._ctx),n}}nt=new WeakMap;const ot=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),at=new Uint8Array([101,120,112]),ut=new Uint8Array([105,110,102,111,95,104,97,115,104]),ht=new Uint8Array([107,101,121]),ct=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),ft=new Uint8Array([115,101,99,114,101,116]),lt=new Uint8Array([72,80,75,69,0,0,0,0,0,0]);class dt extends b{constructor(t){if(super(),Object.defineProperty(this,"_kem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"number"==typeof t.kem)throw new i("KemId cannot be used");if(this._kem=t.kem,"number"==typeof t.kdf)throw new i("KdfId cannot be used");if(this._kdf=t.kdf,"number"==typeof t.aead)throw new i("AeadId cannot be used");this._aead=t.aead,this._suiteId=new Uint8Array(lt),this._suiteId.set(A(this._kem.id,2),4),this._suiteId.set(A(this._kdf.id,2),6),this._suiteId.set(A(this._aead.id,2),8),this._kdf.init(this._suiteId)}get kem(){return this._kem}get kdf(){return this._kdf}get aead(){return this._aead}async createSenderContext(t){this._validateInputLength(t),await this._setup();const e=await this._kem.encap(t);let r;return r=void 0!==t.psk?void 0!==t.senderKey?3:1:void 0!==t.senderKey?2:0,await this._keyScheduleS(r,e.sharedSecret,e.enc,t)}async createRecipientContext(t){this._validateInputLength(t),await this._setup();const e=await this._kem.decap(t);let r;return r=void 0!==t.psk?void 0!==t.senderPublicKey?3:1:void 0!==t.senderPublicKey?2:0,await this._keyScheduleR(r,e,t)}async seal(t,e,r=v.buffer){const n=await this.createSenderContext(t);return{ct:await n.seal(e,r),enc:n.enc}}async open(t,e,r=v.buffer){const n=await this.createRecipientContext(t);return await n.open(e,r)}async _keySchedule(t,e,r){const n=void 0===r.psk?v:new Uint8Array(r.psk.id),i=await this._kdf.labeledExtract(v.buffer,ct,n),s=void 0===r.info?v:new Uint8Array(r.info),o=await this._kdf.labeledExtract(v.buffer,ut,s),a=new Uint8Array(1+i.byteLength+o.byteLength);a.set(new Uint8Array([t]),0),a.set(new Uint8Array(i),1),a.set(new Uint8Array(o),1+i.byteLength);const u=void 0===r.psk?v:new Uint8Array(r.psk.key),h=this._kdf.buildLabeledIkm(ft,u).buffer,c=this._kdf.buildLabeledInfo(at,a,this._kdf.hashSize).buffer,f=await this._kdf.extractAndExpand(e,h,c,this._kdf.hashSize);if(65535===this._aead.id)return{aead:this._aead,exporterSecret:f};const l=this._kdf.buildLabeledInfo(ht,a,this._aead.keySize).buffer,d=await this._kdf.extractAndExpand(e,h,l,this._aead.keySize),p=this._kdf.buildLabeledInfo(ot,a,this._aead.nonceSize).buffer,y=await this._kdf.extractAndExpand(e,h,p,this._aead.nonceSize);return{aead:this._aead,exporterSecret:f,key:d,baseNonce:new Uint8Array(y),seq:0}}async _keyScheduleS(t,e,r,n){const i=await this._keySchedule(t,e,n);return void 0===i.key?new G(this._api,this._kdf,i.exporterSecret,r):new st(this._api,this._kdf,i,r)}async _keyScheduleR(t,e,r){const n=await this._keySchedule(t,e,r);return void 0===n.key?new Y(this._api,this._kdf,n.exporterSecret):new rt(this._api,this._kdf,n)}_validateInputLength(t){if(void 0!==t.info&&t.info.byteLength>65536)throw new i("Too long info");if(void 0!==t.psk){if(t.psk.key.byteLength<32)throw new i("PSK must have at least 32 bytes");if(t.psk.key.byteLength>w)throw new i("Too long psk.key");if(t.psk.id.byteLength>w)throw new i("Too long psk.id")}}}class pt extends I{constructor(){const t=new D;super(16,new C(16,t),t),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:65}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:65}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:32})}}class yt extends dt{}class gt extends pt{}class mt extends D{}new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),new Uint8Array([48,70,2,1,0,48,5,6,3,43,101,111,4,58,4,56])},281:(t,e)=>{"use strict";function r(t,e,r){return e<=t&&t<=r}function n(t){if(void 0===t)return{};if(t===Object(t))return t;throw TypeError("Could not convert argument to dictionary")}function i(t){this.tokens=[].slice.call(t)}i.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():-1},prepend:function(t){if(Array.isArray(t))for(var e=t;e.length;)this.tokens.unshift(e.pop());else this.tokens.unshift(t)},push:function(t){if(Array.isArray(t))for(var e=t;e.length;)this.tokens.push(e.shift());else this.tokens.push(t)}};var s=-1;function o(t,e){if(t)throw TypeError("Decoder error");return e||65533}var a="utf-8";function u(t,e){if(!(this instanceof u))return new u(t,e);if((t=void 0!==t?String(t).toLowerCase():a)!==a)throw new Error("Encoding not supported. Only utf-8 is supported");e=n(e),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=Boolean(e.fatal),this._ignoreBOM=Boolean(e.ignoreBOM),Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}function h(t,e){if(!(this instanceof h))return new h(t,e);if((t=void 0!==t?String(t).toLowerCase():a)!==a)throw new Error("Encoding not supported. Only utf-8 is supported");e=n(e),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(e.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function c(t){var e=t.fatal,n=0,i=0,a=0,u=128,h=191;this.handler=function(t,c){if(-1===c&&0!==a)return a=0,o(e);if(-1===c)return s;if(0===a){if(r(c,0,127))return c;if(r(c,194,223))a=1,n=c-192;else if(r(c,224,239))224===c&&(u=160),237===c&&(h=159),a=2,n=c-224;else{if(!r(c,240,244))return o(e);240===c&&(u=144),244===c&&(h=143),a=3,n=c-240}return n<<=6*a,null}if(!r(c,u,h))return n=a=i=0,u=128,h=191,t.prepend(c),o(e);if(u=128,h=191,n+=c-128<<6*(a-(i+=1)),i!==a)return null;var f=n;return n=a=i=0,f}}function f(t){t.fatal,this.handler=function(t,e){if(-1===e)return s;if(r(e,0,127))return e;var n,i;r(e,128,2047)?(n=1,i=192):r(e,2048,65535)?(n=2,i=224):r(e,65536,1114111)&&(n=3,i=240);for(var o=[(e>>6*n)+i];n>0;){var a=e>>6*(n-1);o.push(128|63&a),n-=1}return o}}u.prototype={decode:function(t,e){var r;r="object"==typeof t&&t instanceof ArrayBuffer?new Uint8Array(t):"object"==typeof t&&"buffer"in t&&t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(0),e=n(e),this._streaming||(this._decoder=new c({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(e.stream);for(var o,a=new i(r),u=[];!a.endOfStream()&&(o=this._decoder.handler(a,a.read()))!==s;)null!==o&&(Array.isArray(o)?u.push.apply(u,o):u.push(o));if(!this._streaming){do{if((o=this._decoder.handler(a,a.read()))===s)break;null!==o&&(Array.isArray(o)?u.push.apply(u,o):u.push(o))}while(!a.endOfStream());this._decoder=null}return u.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===u[0]?(this._BOMseen=!0,u.shift()):this._BOMseen=!0)),function(t){for(var e="",r=0;r>10),56320+(1023&n)))}return e}(u)}},h.prototype={encode:function(t,e){t=t?String(t):"",e=n(e),this._streaming||(this._encoder=new f(this._options)),this._streaming=Boolean(e.stream);for(var r,o=[],a=new i(function(t){for(var e=String(t),r=e.length,n=0,i=[];n57343)i.push(s);else if(56320<=s&&s<=57343)i.push(65533);else if(55296<=s&&s<=56319)if(n===r-1)i.push(65533);else{var o=t.charCodeAt(n+1);if(56320<=o&&o<=57343){var a=1023&s,u=1023&o;i.push(65536+(a<<10)+u),n+=1}else i.push(65533)}n+=1}return i}(t));!a.endOfStream()&&(r=this._encoder.handler(a,a.read()))!==s;)Array.isArray(r)?o.push.apply(o,r):o.push(r);if(!this._streaming){for(;(r=this._encoder.handler(a,a.read()))!==s;)Array.isArray(r)?o.push.apply(o,r):o.push(r);this._encoder=null}return new Uint8Array(o)}},e.TextEncoder=h,e.TextDecoder=u},287:(t,e,r)=>{"use strict";const n=r(526),i=r(251),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=u,e.SlowBuffer=function(t){return+t!=t&&(t=0),u.alloc(+t)},e.INSPECT_MAX_BYTES=50;const o=2147483647;function a(t){if(t>o)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,u.prototype),e}function u(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return f(t)}return h(t,e,r)}function h(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!u.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|y(t,e);let n=a(r);const i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(Y(t,Uint8Array)){const e=new Uint8Array(t);return d(e.buffer,e.byteOffset,e.byteLength)}return l(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Y(t,ArrayBuffer)||t&&Y(t.buffer,ArrayBuffer))return d(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(Y(t,SharedArrayBuffer)||t&&Y(t.buffer,SharedArrayBuffer)))return d(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return u.from(n,e,r);const i=function(t){if(u.isBuffer(t)){const e=0|p(t.length),r=a(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||G(t.length)?a(0):l(t):"Buffer"===t.type&&Array.isArray(t.data)?l(t.data):void 0}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return u.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function c(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function f(t){return c(t),a(t<0?0:0|p(t))}function l(t){const e=t.length<0?0:0|p(t.length),r=a(e);for(let n=0;n=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|t}function y(t,e){if(u.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Y(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return $(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return V(t).length;default:if(i)return n?-1:$(t).length;e=(""+e).toLowerCase(),i=!0}}function g(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return U(this,e,r);case"utf8":case"utf-8":return S(this,e,r);case"ascii":return _(this,e,r);case"latin1":case"binary":return M(this,e,r);case"base64":return B(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function m(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function b(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),G(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=u.from(e,n)),u.isBuffer(e))return 0===e.length?-1:w(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):w(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function w(t,e,r,n,i){let s,o=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,a/=2,u/=2,r/=2}function h(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){let n=-1;for(s=r;sa&&(r=a-u),s=r;s>=0;s--){let r=!0;for(let n=0;ni&&(n=i):n=i;const s=e.length;let o;for(n>s/2&&(n=s/2),o=0;o>8,i=r%256,s.push(i),s.push(n);return s}(e,t.length-r),t,r,n)}function B(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function S(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+o<=r){let r,n,a,u;switch(o){case 1:e<128&&(s=e);break;case 2:r=t[i+1],128==(192&r)&&(u=(31&e)<<6|63&r,u>127&&(s=u));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(u=(15&e)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:r=t[i+1],n=t[i+2],a=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(u=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&a,u>65535&&u<1114112&&(s=u))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(t){const e=t.length;if(e<=I)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn.length?(u.isBuffer(e)||(e=u.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!u.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},u.byteLength=y,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;er&&(t+=" ... "),""},s&&(u.prototype[s]=u.prototype.inspect),u.prototype.compare=function(t,e,r,n,i){if(Y(t,Uint8Array)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let s=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(e>>>=0);const a=Math.min(s,o),h=this.slice(n,i),c=t.slice(e,r);for(let t=0;t>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return v(this,t,e,r);case"utf8":case"utf-8":return k(this,t,e,r);case"ascii":case"latin1":case"binary":return x(this,t,e,r);case"base64":return A(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const I=4096;function _(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;in)&&(r=n);let i="";for(let n=e;nr)throw new RangeError("Trying to access beyond buffer length")}function L(t,e,r,n,i,s){if(!u.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function K(t,e,r,n,i){H(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,r}function z(t,e,r,n,i){H(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s>>=8,t[r+6]=s,s>>=8,t[r+5]=s,s>>=8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o>>=8,t[r+2]=o,o>>=8,t[r+1]=o,o>>=8,t[r]=o,r+8}function T(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function R(t,e,r,n,s){return e=+e,r>>>=0,s||T(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function C(t,e,r,n,s){return e=+e,r>>>=0,s||T(t,0,r,8),i.write(t,e,r,n,52,8),r+8}u.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||O(t,e,this.length);let n=this[t],i=1,s=0;for(;++s>>=0,e>>>=0,r||O(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},u.prototype.readUint8=u.prototype.readUInt8=function(t,e){return t>>>=0,e||O(t,1,this.length),this[t]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(t,e){return t>>>=0,e||O(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(t,e){return t>>>=0,e||O(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(t,e){return t>>>=0,e||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(t,e){return t>>>=0,e||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readBigUInt64LE=J(function(t){F(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||W(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||W(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<>>=0,e>>>=0,r||O(t,e,this.length);let n=this[t],i=1,s=0;for(;++s=i&&(n-=Math.pow(2,8*e)),n},u.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||O(t,e,this.length);let n=e,i=1,s=this[t+--n];for(;n>0&&(i*=256);)s+=this[t+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*e)),s},u.prototype.readInt8=function(t,e){return t>>>=0,e||O(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u.prototype.readInt16LE=function(t,e){t>>>=0,e||O(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(t,e){t>>>=0,e||O(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(t,e){return t>>>=0,e||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,e){return t>>>=0,e||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readBigInt64LE=J(function(t){F(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||W(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||W(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<>>=0,e||O(t,4,this.length),i.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,e){return t>>>=0,e||O(t,4,this.length),i.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,e){return t>>>=0,e||O(t,8,this.length),i.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,e){return t>>>=0,e||O(t,8,this.length),i.read(this,t,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||L(this,t,e,r,Math.pow(2,8*r)-1,0);let i=1,s=0;for(this[e]=255&t;++s>>=0,r>>>=0,n||L(this,t,e,r,Math.pow(2,8*r)-1,0);let i=r-1,s=1;for(this[e+i]=255&t;--i>=0&&(s*=256);)this[e+i]=t/s&255;return e+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,1,255,0),this[e]=255&t,e+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},u.prototype.writeBigUInt64LE=J(function(t,e=0){return K(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=J(function(t,e=0){return z(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);L(this,t,e,r,n-1,-n)}let i=0,s=1,o=0;for(this[e]=255&t;++i>>=0,!n){const n=Math.pow(2,8*r-1);L(this,t,e,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[e+i]=255&t;--i>=0&&(s*=256);)t<0&&0===o&&0!==this[e+i+1]&&(o=1),this[e+i]=(t/s|0)-o&255;return e+r},u.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},u.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},u.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},u.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},u.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},u.prototype.writeBigInt64LE=J(function(t,e=0){return K(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=J(function(t,e=0){return z(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeFloatLE=function(t,e,r){return R(this,t,e,!0,r)},u.prototype.writeFloatBE=function(t,e,r){return R(this,t,e,!1,r)},u.prototype.writeDoubleLE=function(t,e,r){return C(this,t,e,!0,r)},u.prototype.writeDoubleBE=function(t,e,r){return C(this,t,e,!1,r)},u.prototype.copy=function(t,e,r,n){if(!u.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function H(t,e,r,n,i,s){if(t>r||t3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new N.ERR_OUT_OF_RANGE("value",i,t)}!function(t,e,r){F(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||W(e,t.length-(r+1))}(n,i,s)}function F(t,e){if("number"!=typeof t)throw new N.ERR_INVALID_ARG_TYPE(e,"number",t)}function W(t,e,r){if(Math.floor(t)!==t)throw F(t,r),new N.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new N.ERR_BUFFER_OUT_OF_BOUNDS;throw new N.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}j("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError),j("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=D(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=D(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);const q=/[^+/0-9A-Za-z-_]/g;function $(t,e){let r;e=e||1/0;const n=t.length;let i=null;const s=[];for(let o=0;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function V(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Z(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Y(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function G(t){return t!=t}const X=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function J(t){return"undefined"==typeof BigInt?Q:t}function Q(){throw new Error("BigInt not supported")}},289:(t,e,r)=>{"use strict";const n=r(341).v4;t.exports=function(t,e,r,i){if("string"!=typeof t)throw new TypeError(t+" must be a string");const s="number"==typeof(i=i||{}).version?i.version:2;if(1!==s&&2!==s)throw new TypeError(s+" must be 1 or 2");const o={method:t};if(2===s&&(o.jsonrpc="2.0"),e){if("object"!=typeof e&&!Array.isArray(e))throw new TypeError(e+" must be an object, array or omitted");o.params=e}if(void 0===r){const t="function"==typeof i.generator?i.generator:function(){return n()};o.id=t(o,i)}else 2===s&&null===r?i.notificationIdNull&&(o.id=null):o.id=r;return o}},341:(t,e,r)=>{"use strict";var n;r.d(e,{v4:()=>c});var i=new Uint8Array(16);function s(){if(!n&&!(n="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 n(i)}const o=/^(?:[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;for(var a=[],u=0;u<256;++u)a.push((u+256).toString(16).substr(1));const h=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(a[t[e+0]]+a[t[e+1]]+a[t[e+2]]+a[t[e+3]]+"-"+a[t[e+4]]+a[t[e+5]]+"-"+a[t[e+6]]+a[t[e+7]]+"-"+a[t[e+8]]+a[t[e+9]]+"-"+a[t[e+10]]+a[t[e+11]]+a[t[e+12]]+a[t[e+13]]+a[t[e+14]]+a[t[e+15]]).toLowerCase();if(!function(t){return"string"==typeof t&&o.test(t)}(r))throw TypeError("Stringified UUID is invalid");return r},c=function(t,e,r){var n=(t=t||{}).random||(t.rng||s)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(var i=0;i<16;++i)e[r+i]=n[i];return e}return h(n)}},364:(t,e,r)=>{"use strict";var n=r(861).Buffer;t.exports=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,c=new Uint8Array(o);r255)return;var l=e[f];if(255===l)return;for(var d=0,p=o-1;(0!==l||d>>0,c[p]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");s=d,r++}for(var y=o-s;y!==o&&0===c[y];)y++;var g=n.allocUnsafe(i+(o-y));g.fill(0,0,i);for(var m=i;y!==o;)g[m++]=c[y++];return g}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=n.from(e)),!n.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,i=0,s=0,o=e.length;s!==o&&0===e[s];)s++,r++;for(var h=(o-s)*c+1>>>0,f=new Uint8Array(h);s!==o;){for(var l=e[s],d=0,p=h-1;(0!==l||d>>0,f[p]=l%a>>>0,l=l/a>>>0;if(0!==l)throw new Error("Non-zero carry");i=d,s++}for(var y=h-i;y!==h&&0===f[y];)y++;for(var g=u.repeat(r);y=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+t)}function u(t,e,r){var n=a(t,r);return r-1>=e&&(n|=a(t,r-1)<<4),n}function h(t,e,r,i){for(var s=0,o=0,a=Math.min(t.length,r),u=e;u=49?h-49+10:h>=17?h-17+10:h,n(h>=0&&o0?t:e},s.min=function(t,e){return t.cmp(e)<0?t:e},s.prototype._init=function(t,e,r){if("number"==typeof t)return this._initNumber(t,e,r);if("object"==typeof t)return this._initArray(t,e,r);"hex"===e&&(e=16),n(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)o=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[s]|=o<>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);else if("le"===r)for(i=0,s=0;i>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);return this._strip()},s.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;this._strip()},s.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var s=t.length-r,o=s%n,a=Math.min(s,s-o)+r,u=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=f}catch(t){s.prototype.inspect=f}else s.prototype.inspect=f;function f(){return(this.red?""}var l=["","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"],d=[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],p=[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];function y(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],s=0|e.words[0],o=i*s,a=67108863&o,u=o/67108864|0;r.words[0]=a;for(var h=1;h>>26,f=67108863&u,l=Math.min(h,e.length-1),d=Math.max(0,h-t.length+1);d<=l;d++){var p=h-d|0;c+=(o=(i=0|t.words[p])*(s=0|e.words[d])+f)/67108864|0,f=67108863&o}r.words[h]=0|f,u=0|c}return 0!==u?r.words[h]=0|u:r.length--,r._strip()}s.prototype.toString=function(t,e){var r;if(e=0|e||1,16===(t=t||10)||"hex"===t){r="";for(var i=0,s=0,o=0;o>>24-i&16777215,(i+=2)>=26&&(i-=26,o--),r=0!==s||o!==this.length-1?l[6-u.length]+u+r:u+r}for(0!==s&&(r=s.toString(16)+r);r.length%e!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(t===(0|t)&&t>=2&&t<=36){var h=d[t],c=p[t];r="";var f=this.clone();for(f.negative=0;!f.isZero();){var y=f.modrn(c).toString(t);r=(f=f.idivn(c)).isZero()?y+r:l[h-y.length]+y+r}for(this.isZero()&&(r="0"+r);r.length%e!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(t,e){return this.toArrayLike(o,t,e)}),s.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},s.prototype.toArrayLike=function(t,e,r){this._strip();var i=this.byteLength(),s=r||Math.max(1,i);n(i<=s,"byte array longer than desired length"),n(s>0,"Requested array length <= 0");var o=function(t,e){return t.allocUnsafe?t.allocUnsafe(e):new t(e)}(t,s);return this["_toArrayLike"+("le"===e?"LE":"BE")](o,i),o},s.prototype._toArrayLikeLE=function(t,e){for(var r=0,n=0,i=0,s=0;i>8&255),r>16&255),6===s?(r>24&255),n=0,s=0):(n=o>>>24,s+=2)}if(r=0&&(t[r--]=o>>8&255),r>=0&&(t[r--]=o>>16&255),6===s?(r>=0&&(t[r--]=o>>24&255),n=0,s=0):(n=o>>>24,s+=2)}if(r>=0)for(t[r--]=n;r>=0;)t[r--]=0},Math.clz32?s.prototype._countBits=function(t){return 32-Math.clz32(t)}:s.prototype._countBits=function(t){var e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},s.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 8191&e||(r+=13,e>>>=13),127&e||(r+=7,e>>>=7),15&e||(r+=4,e>>>=4),3&e||(r+=2,e>>>=2),1&e||r++,r},s.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},s.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},s.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},s.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},s.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},s.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},s.prototype.inotn=function(t){n("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),r=t%26;this._expand(e),r>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this._strip()},s.prototype.notn=function(t){return this.clone().inotn(t)},s.prototype.setn=function(t,e){n("number"==typeof t&&t>=0);var r=t/26|0,i=t%26;return this._expand(r+1),this.words[r]=e?this.words[r]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,s=0;s>>26;for(;0!==i&&s>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;st.length?this.clone().iadd(t):t.clone().iadd(this)},s.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var s=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==s&&o>26,this.words[o]=67108863&e;if(0===s&&o>>13,d=0|o[1],p=8191&d,y=d>>>13,g=0|o[2],m=8191&g,b=g>>>13,w=0|o[3],v=8191&w,k=w>>>13,x=0|o[4],A=8191&x,E=x>>>13,B=0|o[5],S=8191&B,I=B>>>13,_=0|o[6],M=8191&_,U=_>>>13,P=0|o[7],O=8191&P,L=P>>>13,K=0|o[8],z=8191&K,T=K>>>13,R=0|o[9],C=8191&R,N=R>>>13,j=0|a[0],D=8191&j,H=j>>>13,F=0|a[1],W=8191&F,q=F>>>13,$=0|a[2],V=8191&$,Z=$>>>13,Y=0|a[3],G=8191&Y,X=Y>>>13,J=0|a[4],Q=8191&J,tt=J>>>13,et=0|a[5],rt=8191&et,nt=et>>>13,it=0|a[6],st=8191&it,ot=it>>>13,at=0|a[7],ut=8191&at,ht=at>>>13,ct=0|a[8],ft=8191&ct,lt=ct>>>13,dt=0|a[9],pt=8191&dt,yt=dt>>>13;r.negative=t.negative^e.negative,r.length=19;var gt=(h+(n=Math.imul(f,D))|0)+((8191&(i=(i=Math.imul(f,H))+Math.imul(l,D)|0))<<13)|0;h=((s=Math.imul(l,H))+(i>>>13)|0)+(gt>>>26)|0,gt&=67108863,n=Math.imul(p,D),i=(i=Math.imul(p,H))+Math.imul(y,D)|0,s=Math.imul(y,H);var mt=(h+(n=n+Math.imul(f,W)|0)|0)+((8191&(i=(i=i+Math.imul(f,q)|0)+Math.imul(l,W)|0))<<13)|0;h=((s=s+Math.imul(l,q)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(m,D),i=(i=Math.imul(m,H))+Math.imul(b,D)|0,s=Math.imul(b,H),n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,q)|0)+Math.imul(y,W)|0,s=s+Math.imul(y,q)|0;var bt=(h+(n=n+Math.imul(f,V)|0)|0)+((8191&(i=(i=i+Math.imul(f,Z)|0)+Math.imul(l,V)|0))<<13)|0;h=((s=s+Math.imul(l,Z)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(v,D),i=(i=Math.imul(v,H))+Math.imul(k,D)|0,s=Math.imul(k,H),n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,q)|0)+Math.imul(b,W)|0,s=s+Math.imul(b,q)|0,n=n+Math.imul(p,V)|0,i=(i=i+Math.imul(p,Z)|0)+Math.imul(y,V)|0,s=s+Math.imul(y,Z)|0;var wt=(h+(n=n+Math.imul(f,G)|0)|0)+((8191&(i=(i=i+Math.imul(f,X)|0)+Math.imul(l,G)|0))<<13)|0;h=((s=s+Math.imul(l,X)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(A,D),i=(i=Math.imul(A,H))+Math.imul(E,D)|0,s=Math.imul(E,H),n=n+Math.imul(v,W)|0,i=(i=i+Math.imul(v,q)|0)+Math.imul(k,W)|0,s=s+Math.imul(k,q)|0,n=n+Math.imul(m,V)|0,i=(i=i+Math.imul(m,Z)|0)+Math.imul(b,V)|0,s=s+Math.imul(b,Z)|0,n=n+Math.imul(p,G)|0,i=(i=i+Math.imul(p,X)|0)+Math.imul(y,G)|0,s=s+Math.imul(y,X)|0;var vt=(h+(n=n+Math.imul(f,Q)|0)|0)+((8191&(i=(i=i+Math.imul(f,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((s=s+Math.imul(l,tt)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(S,D),i=(i=Math.imul(S,H))+Math.imul(I,D)|0,s=Math.imul(I,H),n=n+Math.imul(A,W)|0,i=(i=i+Math.imul(A,q)|0)+Math.imul(E,W)|0,s=s+Math.imul(E,q)|0,n=n+Math.imul(v,V)|0,i=(i=i+Math.imul(v,Z)|0)+Math.imul(k,V)|0,s=s+Math.imul(k,Z)|0,n=n+Math.imul(m,G)|0,i=(i=i+Math.imul(m,X)|0)+Math.imul(b,G)|0,s=s+Math.imul(b,X)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,tt)|0)+Math.imul(y,Q)|0,s=s+Math.imul(y,tt)|0;var kt=(h+(n=n+Math.imul(f,rt)|0)|0)+((8191&(i=(i=i+Math.imul(f,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((s=s+Math.imul(l,nt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(M,D),i=(i=Math.imul(M,H))+Math.imul(U,D)|0,s=Math.imul(U,H),n=n+Math.imul(S,W)|0,i=(i=i+Math.imul(S,q)|0)+Math.imul(I,W)|0,s=s+Math.imul(I,q)|0,n=n+Math.imul(A,V)|0,i=(i=i+Math.imul(A,Z)|0)+Math.imul(E,V)|0,s=s+Math.imul(E,Z)|0,n=n+Math.imul(v,G)|0,i=(i=i+Math.imul(v,X)|0)+Math.imul(k,G)|0,s=s+Math.imul(k,X)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,tt)|0)+Math.imul(b,Q)|0,s=s+Math.imul(b,tt)|0,n=n+Math.imul(p,rt)|0,i=(i=i+Math.imul(p,nt)|0)+Math.imul(y,rt)|0,s=s+Math.imul(y,nt)|0;var xt=(h+(n=n+Math.imul(f,st)|0)|0)+((8191&(i=(i=i+Math.imul(f,ot)|0)+Math.imul(l,st)|0))<<13)|0;h=((s=s+Math.imul(l,ot)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(O,D),i=(i=Math.imul(O,H))+Math.imul(L,D)|0,s=Math.imul(L,H),n=n+Math.imul(M,W)|0,i=(i=i+Math.imul(M,q)|0)+Math.imul(U,W)|0,s=s+Math.imul(U,q)|0,n=n+Math.imul(S,V)|0,i=(i=i+Math.imul(S,Z)|0)+Math.imul(I,V)|0,s=s+Math.imul(I,Z)|0,n=n+Math.imul(A,G)|0,i=(i=i+Math.imul(A,X)|0)+Math.imul(E,G)|0,s=s+Math.imul(E,X)|0,n=n+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(k,Q)|0,s=s+Math.imul(k,tt)|0,n=n+Math.imul(m,rt)|0,i=(i=i+Math.imul(m,nt)|0)+Math.imul(b,rt)|0,s=s+Math.imul(b,nt)|0,n=n+Math.imul(p,st)|0,i=(i=i+Math.imul(p,ot)|0)+Math.imul(y,st)|0,s=s+Math.imul(y,ot)|0;var At=(h+(n=n+Math.imul(f,ut)|0)|0)+((8191&(i=(i=i+Math.imul(f,ht)|0)+Math.imul(l,ut)|0))<<13)|0;h=((s=s+Math.imul(l,ht)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(z,D),i=(i=Math.imul(z,H))+Math.imul(T,D)|0,s=Math.imul(T,H),n=n+Math.imul(O,W)|0,i=(i=i+Math.imul(O,q)|0)+Math.imul(L,W)|0,s=s+Math.imul(L,q)|0,n=n+Math.imul(M,V)|0,i=(i=i+Math.imul(M,Z)|0)+Math.imul(U,V)|0,s=s+Math.imul(U,Z)|0,n=n+Math.imul(S,G)|0,i=(i=i+Math.imul(S,X)|0)+Math.imul(I,G)|0,s=s+Math.imul(I,X)|0,n=n+Math.imul(A,Q)|0,i=(i=i+Math.imul(A,tt)|0)+Math.imul(E,Q)|0,s=s+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(k,rt)|0,s=s+Math.imul(k,nt)|0,n=n+Math.imul(m,st)|0,i=(i=i+Math.imul(m,ot)|0)+Math.imul(b,st)|0,s=s+Math.imul(b,ot)|0,n=n+Math.imul(p,ut)|0,i=(i=i+Math.imul(p,ht)|0)+Math.imul(y,ut)|0,s=s+Math.imul(y,ht)|0;var Et=(h+(n=n+Math.imul(f,ft)|0)|0)+((8191&(i=(i=i+Math.imul(f,lt)|0)+Math.imul(l,ft)|0))<<13)|0;h=((s=s+Math.imul(l,lt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(C,D),i=(i=Math.imul(C,H))+Math.imul(N,D)|0,s=Math.imul(N,H),n=n+Math.imul(z,W)|0,i=(i=i+Math.imul(z,q)|0)+Math.imul(T,W)|0,s=s+Math.imul(T,q)|0,n=n+Math.imul(O,V)|0,i=(i=i+Math.imul(O,Z)|0)+Math.imul(L,V)|0,s=s+Math.imul(L,Z)|0,n=n+Math.imul(M,G)|0,i=(i=i+Math.imul(M,X)|0)+Math.imul(U,G)|0,s=s+Math.imul(U,X)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,s=s+Math.imul(I,tt)|0,n=n+Math.imul(A,rt)|0,i=(i=i+Math.imul(A,nt)|0)+Math.imul(E,rt)|0,s=s+Math.imul(E,nt)|0,n=n+Math.imul(v,st)|0,i=(i=i+Math.imul(v,ot)|0)+Math.imul(k,st)|0,s=s+Math.imul(k,ot)|0,n=n+Math.imul(m,ut)|0,i=(i=i+Math.imul(m,ht)|0)+Math.imul(b,ut)|0,s=s+Math.imul(b,ht)|0,n=n+Math.imul(p,ft)|0,i=(i=i+Math.imul(p,lt)|0)+Math.imul(y,ft)|0,s=s+Math.imul(y,lt)|0;var Bt=(h+(n=n+Math.imul(f,pt)|0)|0)+((8191&(i=(i=i+Math.imul(f,yt)|0)+Math.imul(l,pt)|0))<<13)|0;h=((s=s+Math.imul(l,yt)|0)+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,n=Math.imul(C,W),i=(i=Math.imul(C,q))+Math.imul(N,W)|0,s=Math.imul(N,q),n=n+Math.imul(z,V)|0,i=(i=i+Math.imul(z,Z)|0)+Math.imul(T,V)|0,s=s+Math.imul(T,Z)|0,n=n+Math.imul(O,G)|0,i=(i=i+Math.imul(O,X)|0)+Math.imul(L,G)|0,s=s+Math.imul(L,X)|0,n=n+Math.imul(M,Q)|0,i=(i=i+Math.imul(M,tt)|0)+Math.imul(U,Q)|0,s=s+Math.imul(U,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,s=s+Math.imul(I,nt)|0,n=n+Math.imul(A,st)|0,i=(i=i+Math.imul(A,ot)|0)+Math.imul(E,st)|0,s=s+Math.imul(E,ot)|0,n=n+Math.imul(v,ut)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(k,ut)|0,s=s+Math.imul(k,ht)|0,n=n+Math.imul(m,ft)|0,i=(i=i+Math.imul(m,lt)|0)+Math.imul(b,ft)|0,s=s+Math.imul(b,lt)|0;var St=(h+(n=n+Math.imul(p,pt)|0)|0)+((8191&(i=(i=i+Math.imul(p,yt)|0)+Math.imul(y,pt)|0))<<13)|0;h=((s=s+Math.imul(y,yt)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(C,V),i=(i=Math.imul(C,Z))+Math.imul(N,V)|0,s=Math.imul(N,Z),n=n+Math.imul(z,G)|0,i=(i=i+Math.imul(z,X)|0)+Math.imul(T,G)|0,s=s+Math.imul(T,X)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(L,Q)|0,s=s+Math.imul(L,tt)|0,n=n+Math.imul(M,rt)|0,i=(i=i+Math.imul(M,nt)|0)+Math.imul(U,rt)|0,s=s+Math.imul(U,nt)|0,n=n+Math.imul(S,st)|0,i=(i=i+Math.imul(S,ot)|0)+Math.imul(I,st)|0,s=s+Math.imul(I,ot)|0,n=n+Math.imul(A,ut)|0,i=(i=i+Math.imul(A,ht)|0)+Math.imul(E,ut)|0,s=s+Math.imul(E,ht)|0,n=n+Math.imul(v,ft)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(k,ft)|0,s=s+Math.imul(k,lt)|0;var It=(h+(n=n+Math.imul(m,pt)|0)|0)+((8191&(i=(i=i+Math.imul(m,yt)|0)+Math.imul(b,pt)|0))<<13)|0;h=((s=s+Math.imul(b,yt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(C,G),i=(i=Math.imul(C,X))+Math.imul(N,G)|0,s=Math.imul(N,X),n=n+Math.imul(z,Q)|0,i=(i=i+Math.imul(z,tt)|0)+Math.imul(T,Q)|0,s=s+Math.imul(T,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(L,rt)|0,s=s+Math.imul(L,nt)|0,n=n+Math.imul(M,st)|0,i=(i=i+Math.imul(M,ot)|0)+Math.imul(U,st)|0,s=s+Math.imul(U,ot)|0,n=n+Math.imul(S,ut)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,ut)|0,s=s+Math.imul(I,ht)|0,n=n+Math.imul(A,ft)|0,i=(i=i+Math.imul(A,lt)|0)+Math.imul(E,ft)|0,s=s+Math.imul(E,lt)|0;var _t=(h+(n=n+Math.imul(v,pt)|0)|0)+((8191&(i=(i=i+Math.imul(v,yt)|0)+Math.imul(k,pt)|0))<<13)|0;h=((s=s+Math.imul(k,yt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(C,Q),i=(i=Math.imul(C,tt))+Math.imul(N,Q)|0,s=Math.imul(N,tt),n=n+Math.imul(z,rt)|0,i=(i=i+Math.imul(z,nt)|0)+Math.imul(T,rt)|0,s=s+Math.imul(T,nt)|0,n=n+Math.imul(O,st)|0,i=(i=i+Math.imul(O,ot)|0)+Math.imul(L,st)|0,s=s+Math.imul(L,ot)|0,n=n+Math.imul(M,ut)|0,i=(i=i+Math.imul(M,ht)|0)+Math.imul(U,ut)|0,s=s+Math.imul(U,ht)|0,n=n+Math.imul(S,ft)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ft)|0,s=s+Math.imul(I,lt)|0;var Mt=(h+(n=n+Math.imul(A,pt)|0)|0)+((8191&(i=(i=i+Math.imul(A,yt)|0)+Math.imul(E,pt)|0))<<13)|0;h=((s=s+Math.imul(E,yt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(C,rt),i=(i=Math.imul(C,nt))+Math.imul(N,rt)|0,s=Math.imul(N,nt),n=n+Math.imul(z,st)|0,i=(i=i+Math.imul(z,ot)|0)+Math.imul(T,st)|0,s=s+Math.imul(T,ot)|0,n=n+Math.imul(O,ut)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(L,ut)|0,s=s+Math.imul(L,ht)|0,n=n+Math.imul(M,ft)|0,i=(i=i+Math.imul(M,lt)|0)+Math.imul(U,ft)|0,s=s+Math.imul(U,lt)|0;var Ut=(h+(n=n+Math.imul(S,pt)|0)|0)+((8191&(i=(i=i+Math.imul(S,yt)|0)+Math.imul(I,pt)|0))<<13)|0;h=((s=s+Math.imul(I,yt)|0)+(i>>>13)|0)+(Ut>>>26)|0,Ut&=67108863,n=Math.imul(C,st),i=(i=Math.imul(C,ot))+Math.imul(N,st)|0,s=Math.imul(N,ot),n=n+Math.imul(z,ut)|0,i=(i=i+Math.imul(z,ht)|0)+Math.imul(T,ut)|0,s=s+Math.imul(T,ht)|0,n=n+Math.imul(O,ft)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(L,ft)|0,s=s+Math.imul(L,lt)|0;var Pt=(h+(n=n+Math.imul(M,pt)|0)|0)+((8191&(i=(i=i+Math.imul(M,yt)|0)+Math.imul(U,pt)|0))<<13)|0;h=((s=s+Math.imul(U,yt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(C,ut),i=(i=Math.imul(C,ht))+Math.imul(N,ut)|0,s=Math.imul(N,ht),n=n+Math.imul(z,ft)|0,i=(i=i+Math.imul(z,lt)|0)+Math.imul(T,ft)|0,s=s+Math.imul(T,lt)|0;var Ot=(h+(n=n+Math.imul(O,pt)|0)|0)+((8191&(i=(i=i+Math.imul(O,yt)|0)+Math.imul(L,pt)|0))<<13)|0;h=((s=s+Math.imul(L,yt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(C,ft),i=(i=Math.imul(C,lt))+Math.imul(N,ft)|0,s=Math.imul(N,lt);var Lt=(h+(n=n+Math.imul(z,pt)|0)|0)+((8191&(i=(i=i+Math.imul(z,yt)|0)+Math.imul(T,pt)|0))<<13)|0;h=((s=s+Math.imul(T,yt)|0)+(i>>>13)|0)+(Lt>>>26)|0,Lt&=67108863;var Kt=(h+(n=Math.imul(C,pt))|0)+((8191&(i=(i=Math.imul(C,yt))+Math.imul(N,pt)|0))<<13)|0;return h=((s=Math.imul(N,yt))+(i>>>13)|0)+(Kt>>>26)|0,Kt&=67108863,u[0]=gt,u[1]=mt,u[2]=bt,u[3]=wt,u[4]=vt,u[5]=kt,u[6]=xt,u[7]=At,u[8]=Et,u[9]=Bt,u[10]=St,u[11]=It,u[12]=_t,u[13]=Mt,u[14]=Ut,u[15]=Pt,u[16]=Ot,u[17]=Lt,u[18]=Kt,0!==h&&(u[19]=h,r.length++),r};function m(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,s=0;s>>26)|0)>>>26,o&=67108863}r.words[s]=a,n=o,o=i}return 0!==n?r.words[s]=n:r.length--,r._strip()}function b(t,e,r){return m(t,e,r)}function w(t,e){this.x=t,this.y=e}Math.imul||(g=y),s.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?g(this,t,e):r<63?y(this,t,e):r<1024?m(this,t,e):b(this,t,e)},w.prototype.makeRBT=function(t){for(var e=new Array(t),r=s.prototype._countBits(t)-1,n=0;n>=1;return n},w.prototype.permute=function(t,e,r,n,i,s){for(var o=0;o>>=1)i++;return 1<>>=13,r[2*o+1]=8191&s,s>>>=13;for(o=2*e;o>=26,r+=s/67108864|0,r+=o>>>26,this.words[i]=67108863&o}return 0!==r&&(this.words[i]=r,this.length++),this.length=0===t?1:this.length,e?this.ineg():this},s.prototype.muln=function(t){return this.clone().imuln(t)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i&1}return e}(t);if(0===e.length)return new s(1);for(var r=this,n=0;n=0);var e,r=t%26,i=(t-r)/26,s=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(e=0;e>>26-r}o&&(this.words[e]=o,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var s=t%26,o=Math.min((t-s)/26,this.length),a=67108863^67108863>>>s<o)for(this.length-=o,h=0;h=0&&(0!==c||h>=i);h--){var f=0|this.words[h];this.words[h]=c<<26-s|f>>>s,c=f&a}return u&&0!==c&&(u.words[u.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(t,e,r){return n(0===this.negative),this.iushrn(t,e,r)},s.prototype.shln=function(t){return this.clone().ishln(t)},s.prototype.ushln=function(t){return this.clone().iushln(t)},s.prototype.shrn=function(t){return this.clone().ishrn(t)},s.prototype.ushrn=function(t){return this.clone().iushrn(t)},s.prototype.testn=function(t){n("number"==typeof t&&t>=0);var e=t%26,r=(t-e)/26,i=1<=0);var e=t%26,r=(t-e)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==e&&r++,this.length=Math.min(r,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},s.prototype.isubn=function(t){if(n("number"==typeof t),n(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(u/67108864|0),this.words[i+r]=67108863&s}for(;i>26,this.words[i+r]=67108863&s;if(0===a)return this._strip();for(n(-1===a),a=0,i=0;i>26,this.words[i]=67108863&s;return this.negative=1,this._strip()},s.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),i=t,o=0|i.words[i.length-1];0!=(r=26-this._countBits(o))&&(i=i.ushln(r),n.iushln(r),o=0|i.words[i.length-1]);var a,u=n.length-i.length;if("mod"!==e){(a=new s(null)).length=u+1,a.words=new Array(a.length);for(var h=0;h=0;f--){var l=67108864*(0|n.words[i.length+f])+(0|n.words[i.length+f-1]);for(l=Math.min(l/o|0,67108863),n._ishlnsubmul(i,l,f);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,f),n.isZero()||(n.negative^=1);a&&(a.words[f]=l)}return a&&a._strip(),n._strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:a||null,mod:n}},s.prototype.divmod=function(t,e,r){return n(!t.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===t.negative?(a=this.neg().divmod(t,e),"mod"!==e&&(i=a.div.neg()),"div"!==e&&(o=a.mod.neg(),r&&0!==o.negative&&o.iadd(t)),{div:i,mod:o}):0===this.negative&&0!==t.negative?(a=this.divmod(t.neg(),e),"mod"!==e&&(i=a.div.neg()),{div:i,mod:a.mod}):0!==(this.negative&t.negative)?(a=this.neg().divmod(t.neg(),e),"div"!==e&&(o=a.mod.neg(),r&&0!==o.negative&&o.isub(t)),{div:a.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new s(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new s(this.modrn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new s(this.modrn(t.words[0]))}:this._wordDiv(t,e);var i,o,a},s.prototype.div=function(t){return this.divmod(t,"div",!1).div},s.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},s.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},s.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),s=r.cmp(n);return s<0||1===i&&0===s?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},s.prototype.modrn=function(t){var e=t<0;e&&(t=-t),n(t<=67108863);for(var r=(1<<26)%t,i=0,s=this.length-1;s>=0;s--)i=(r*i+(0|this.words[s]))%t;return e?-i:i},s.prototype.modn=function(t){return this.modrn(t)},s.prototype.idivn=function(t){var e=t<0;e&&(t=-t),n(t<=67108863);for(var r=0,i=this.length-1;i>=0;i--){var s=(0|this.words[i])+67108864*r;this.words[i]=s/t|0,r=s%t}return this._strip(),e?this.ineg():this},s.prototype.divn=function(t){return this.clone().idivn(t)},s.prototype.egcd=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i=new s(1),o=new s(0),a=new s(0),u=new s(1),h=0;e.isEven()&&r.isEven();)e.iushrn(1),r.iushrn(1),++h;for(var c=r.clone(),f=e.clone();!e.isZero();){for(var l=0,d=1;0===(e.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(c),o.isub(f)),i.iushrn(1),o.iushrn(1);for(var p=0,y=1;0===(r.words[0]&y)&&p<26;++p,y<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||u.isOdd())&&(a.iadd(c),u.isub(f)),a.iushrn(1),u.iushrn(1);e.cmp(r)>=0?(e.isub(r),i.isub(a),o.isub(u)):(r.isub(e),a.isub(i),u.isub(o))}return{a,b:u,gcd:r.iushln(h)}},s.prototype._invmp=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i,o=new s(1),a=new s(0),u=r.clone();e.cmpn(1)>0&&r.cmpn(1)>0;){for(var h=0,c=1;0===(e.words[0]&c)&&h<26;++h,c<<=1);if(h>0)for(e.iushrn(h);h-- >0;)o.isOdd()&&o.iadd(u),o.iushrn(1);for(var f=0,l=1;0===(r.words[0]&l)&&f<26;++f,l<<=1);if(f>0)for(r.iushrn(f);f-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);e.cmp(r)>=0?(e.isub(r),o.isub(a)):(r.isub(e),a.isub(o))}return(i=0===e.cmpn(1)?o:a).cmpn(0)<0&&i.iadd(t),i},s.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var s=e;e=r,r=s}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},s.prototype.invm=function(t){return this.egcd(t).a.umod(t)},s.prototype.isEven=function(){return!(1&this.words[0])},s.prototype.isOdd=function(){return!(1&~this.words[0])},s.prototype.andln=function(t){return this.words[0]&t},s.prototype.bincn=function(t){n("number"==typeof t);var e=t%26,r=(t-e)/26,i=1<>>26,a&=67108863,this.words[o]=a}return 0!==s&&(this.words[o]=s,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(t){var e,r=t<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)e=1;else{r&&(t=-t),n(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},s.prototype.gtn=function(t){return 1===this.cmpn(t)},s.prototype.gt=function(t){return 1===this.cmp(t)},s.prototype.gten=function(t){return this.cmpn(t)>=0},s.prototype.gte=function(t){return this.cmp(t)>=0},s.prototype.ltn=function(t){return-1===this.cmpn(t)},s.prototype.lt=function(t){return-1===this.cmp(t)},s.prototype.lten=function(t){return this.cmpn(t)<=0},s.prototype.lte=function(t){return this.cmp(t)<=0},s.prototype.eqn=function(t){return 0===this.cmpn(t)},s.prototype.eq=function(t){return 0===this.cmp(t)},s.red=function(t){return new S(t)},s.prototype.toRed=function(t){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(t){return this.red=t,this},s.prototype.forceRed=function(t){return n(!this.red,"Already a number in reduction context"),this._forceRed(t)},s.prototype.redAdd=function(t){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},s.prototype.redIAdd=function(t){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},s.prototype.redSub=function(t){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},s.prototype.redISub=function(t){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},s.prototype.redShl=function(t){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},s.prototype.redMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},s.prototype.redIMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(t){return n(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var v={k256:null,p224:null,p192:null,p25519:null};function k(t,e){this.name=t,this.p=new s(e,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function x(){k.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function A(){k.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function E(){k.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function B(){k.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function S(t){if("string"==typeof t){var e=s._prime(t);this.m=e.p,this.prime=e}else n(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function I(t){S.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(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)}k.prototype._tmp=function(){var t=new s(null);return t.words=new Array(Math.ceil(this.n/13)),t},k.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},k.prototype.split=function(t,e){t.iushrn(this.n,0,e)},k.prototype.imulK=function(t){return t.imul(this.k)},i(x,k),x.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,s=o}s>>>=22,t.words[i-10]=s,0===s&&t.length>10?t.length-=10:t.length-=9},x.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},s._prime=function(t){if(v[t])return v[t];var e;if("k256"===t)e=new x;else if("p224"===t)e=new A;else if("p192"===t)e=new E;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new B}return v[t]=e,e},S.prototype._verify1=function(t){n(0===t.negative,"red works only with positives"),n(t.red,"red works only with red numbers")},S.prototype._verify2=function(t,e){n(0===(t.negative|e.negative),"red works only with positives"),n(t.red&&t.red===e.red,"red works only with red numbers")},S.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):(c(t,t.umod(this.m)._forceRed(this)),t)},S.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},S.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},S.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},S.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},S.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},S.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},S.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},S.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},S.prototype.isqr=function(t){return this.imul(t,t.clone())},S.prototype.sqr=function(t){return this.mul(t,t)},S.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(n(e%2==1),3===e){var r=this.m.add(new s(1)).iushrn(2);return this.pow(t,r)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);n(!i.isZero());var a=new s(1).toRed(this),u=a.redNeg(),h=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new s(2*c*c).toRed(this);0!==this.pow(c,h).cmp(u);)c.redIAdd(u);for(var f=this.pow(c,i),l=this.pow(t,i.addn(1).iushrn(1)),d=this.pow(t,i),p=o;0!==d.cmp(a);){for(var y=d,g=0;0!==y.cmp(a);g++)y=y.redSqr();n(g=0;n--){for(var h=e.words[n],c=u-1;c>=0;c--){var f=h>>c&1;i!==r[0]&&(i=this.sqr(i)),0!==f||0!==o?(o<<=1,o|=f,(4===++a||0===n&&0===c)&&(i=this.mul(i,r[o]),a=0,o=0)):a=0}u=26}return i},S.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},S.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},s.mont=function(t){return new I(t)},i(I,S),I.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},I.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},I.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},I.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new s(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},I.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t=r.nmd(t),this)},526:(t,e)=>{"use strict";e.byteLength=function(t){var e=a(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,s=a(t),o=s[0],u=s[1],h=new i(function(t,e,r){return 3*(e+r)/4-r}(0,o,u)),c=0,f=u>0?o-4:o;for(r=0;r>16&255,h[c++]=e>>8&255,h[c++]=255&e;return 2===u&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,h[c++]=255&e),1===u&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,h[c++]=e>>8&255,h[c++]=255&e),h},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,s=[],o=16383,a=0,u=n-i;au?u:a+o));return 1===i?(e=t[n-1],s.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],s.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"=")),s.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)r[o]=s[o],n[s.charCodeAt(o)]=o;function a(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function u(t){return r[t>>18&63]+r[t>>12&63]+r[t>>6&63]+r[63&t]}function h(t,e,r){for(var n,i=[],s=e;s{"use strict";r.d(e,{jn:()=>K,lG:()=>O});const n=2n**255n-19n,i=2n**252n+27742317777372353535851937790883648493n,s=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,o=0x6666666666666666666666666666666666666666666666666666666666666658n,a={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:n,n:i,h:8,Gx:s,Gy:o},u=(t="")=>{throw new Error(t)},h=t=>"string"==typeof t,c=(t,e)=>!(t instanceof Uint8Array)||"number"==typeof e&&e>0&&t.length!==e?u("Uint8Array expected"):t,f=t=>new Uint8Array(t),l=(t,e)=>c(h(t)?k(t):f(t),e),d=(t,e=n)=>{let r=t%e;return r>=0n?r:e+r},p=t=>t instanceof g?t:u("Point expected");let y;class g{constructor(t,e,r,n){this.ex=t,this.ey=e,this.ez=r,this.et=n}static fromAffine(t){return new g(t.x,t.y,1n,d(t.x*t.y))}static fromHex(t,e=!0){const{d:r}=a,i=(t=l(t,32)).slice();i[31]=-129&t[31];const s=A(i);0n===s||(!e||0n0n;i=i.double(),t>>=1n)1n&t?r=r.add(i):e&&(n=n.add(i));return r}multiply(t){return this.mul(t)}clearCofactor(){return this.mul(BigInt(a.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.mul(i/2n,!1).double();return t=t.add(this),t.is0()}toAffine(){const{ex:t,ey:e,ez:r}=this;if(this.is0())return{x:0n,y:0n};const n=B(r);return 1n!==d(r*n)&&u("invalid inverse"),{x:d(t*n),y:d(e*n)}}toRawBytes(){const{x:t,y:e}=this.toAffine(),r=x(e);return r[31]|=1n&t?128:0,r}toHex(){return v(this.toRawBytes())}}g.BASE=new g(s,o,1n,d(s*o)),g.ZERO=new g(0n,1n,1n,0n);const{BASE:m,ZERO:b}=g,w=(t,e)=>t.toString(16).padStart(e,"0"),v=t=>Array.from(t).map(t=>w(t,2)).join(""),k=t=>{const e=t.length;(!h(t)||e%2)&&u("hex invalid 1");const r=f(e/2);for(let e=0;ek(w(t,64)).reverse(),A=t=>BigInt("0x"+v(f(c(t)).reverse())),E=(...t)=>{const e=f(t.reduce((t,e)=>t+c(e).length,0));let r=0;return t.forEach(t=>{e.set(t,r),r+=t.length}),e},B=(t,e=n)=>{(0n===t||e<=0n)&&u("no inverse n="+t+" mod="+e);let r=d(t,e),i=e,s=0n,o=1n,a=1n,h=0n;for(;0n!==r;){const t=i/r,e=i%r,n=s-a*t,u=o-h*t;i=r,r=e,s=a,o=h,a=n,h=u}return 1n===i?d(s,e):u("no inverse")},S=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=n;return r},I=19681161376707505956807079304988542015446066515923890162744021073123829784752n,_=(t,e)=>{const r=d(e*e*e),i=(t=>{const e=t*t%n*t%n,r=S(e,2n)*e%n,i=S(r,1n)*t%n,s=S(i,5n)*i%n,o=S(s,10n)*s%n,a=S(o,20n)*o%n,u=S(a,40n)*a%n,h=S(u,80n)*u%n,c=S(h,80n)*u%n,f=S(c,10n)*s%n;return{pow_p_5_8:S(f,2n)*t%n,b2:e}})(t*d(r*r*e)).pow_p_5_8;let s=d(t*r*i);const o=d(e*s*s),a=s,u=d(s*I),h=o===t,c=o===d(-t),f=o===d(-t*I);return h&&(s=a),(c||f)&&(s=u),1n==(1n&d(s))&&(s=d(-s)),{isValid:h||c,value:s}};let M;const U=t=>{const e=t.slice(0,32);e[0]&=248,e[31]&=127,e[31]|=64;const r=t.slice(32,64),n=d(A(e),i),s=m.mul(n),o=s.toRawBytes();return{head:e,prefix:r,scalar:n,point:s,pointBytes:o}},P=t=>U(((...t)=>"function"==typeof M?M(...t):u("etc.sha512Sync not set"))(l(t,32))),O=t=>P(t).pointBytes,L=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,K={bytesToHex:v,hexToBytes:k,concatBytes:E,mod:d,invert:B,randomBytes:t=>{const e=L();return e||u("crypto.getRandomValues must be defined"),e.getRandomValues(f(t))},sha512Async:async(...t)=>{const e=L();e||u("crypto.subtle or etc.sha512Async must be defined");const r=E(...t);return f(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(K,{sha512Sync:{configurable:!1,get:()=>M,set(t){M||(M=t)}}});const z=t=>{const e=y||(y=(()=>{const t=[];let e=m,r=e;for(let n=0;n<33;n++){r=e,t.push(r);for(let n=1;n<128;n++)r=r.add(e),t.push(r);e=r.double()}return t})()),r=(t,e)=>{let r=e.negate();return t?r:e};let n=b,i=m;const s=BigInt(255),o=BigInt(8);for(let a=0;a<33;a++){const u=128*a;let h=Number(t&s);t>>=o,h>128&&(h-=256,t+=1n);const c=u,f=u+Math.abs(h)-1,l=a%2!=0,d=h<0;0===h?i=i.add(r(l,e[c])):n=n.add(r(d,e[f]))}return{p:n,f:i}}},601:(t,e,r)=>{"use strict";e.I0=e.DH=e.NX=e.u8=e.cY=void 0,e.av=e.O6=e.w3=e.Wg=void 0;const n=r(287);function i(t){if(!(t instanceof Uint8Array))throw new TypeError("b must be a Uint8Array")}function s(t){return i(t),n.Buffer.from(t.buffer,t.byteOffset,t.length)}class o{constructor(t,e){if(!Number.isInteger(t))throw new TypeError("span must be an integer");this.span=t,this.property=e}makeDestinationObject(){return{}}getSpan(t,e){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(t){const e=Object.create(this.constructor.prototype);return Object.assign(e,this),e.property=t,e}fromArray(t){}}function a(t,e){return e.property?t+"["+e.property+"]":t}class u extends o{isCount(){throw new Error("ExternalLayout is abstract")}}class h extends u{constructor(t,e=0,r){if(!(t instanceof o))throw new TypeError("layout must be a Layout");if(!Number.isInteger(e))throw new TypeError("offset must be integer or undefined");super(t.span,r||t.property),this.layout=t,this.offset=e}isCount(){return this.layout instanceof c||this.layout instanceof f}decode(t,e=0){return this.layout.decode(t,e+this.offset)}encode(t,e,r=0){return this.layout.encode(t,e,r+this.offset)}}class c extends o{constructor(t,e){if(super(t,e),6t+n.encode(i,e,r+t),0);return this.count instanceof u&&this.count.encode(t.length,e,r),i}}class b extends o{constructor(t,e,r){if(!Array.isArray(t)||!t.reduce((t,e)=>t&&e instanceof o,!0))throw new TypeError("fields must be array of Layout instances");"boolean"==typeof e&&void 0===r&&(r=e,e=void 0);for(const e of t)if(0>e.span&&void 0===e.property)throw new Error("fields cannot contain unnamed variable-length layout");let n=-1;try{n=t.reduce((t,e)=>t+e.getSpan(),0)}catch(t){}super(n,e),this.fields=t,this.decodePrefixes=!!r}getSpan(t,e=0){if(0<=this.span)return this.span;let r=0;try{r=this.fields.reduce((r,n)=>{const i=n.getSpan(t,e);return e+=i,r+i},0)}catch(t){throw new RangeError("indeterminate span")}return r}decode(t,e=0){i(t);const r=this.makeDestinationObject();for(const n of this.fields)if(void 0!==n.property&&(r[n.property]=n.decode(t,e)),e+=n.getSpan(t,e),this.decodePrefixes&&t.length===e)break;return r}encode(t,e,r=0){const n=r;let i=0,s=0;for(const n of this.fields){let o=n.span;if(s=0o&&(o=n.getSpan(e,r)))}i=r,r+=o}return i+s-n}fromArray(t){const e=this.makeDestinationObject();for(const r of this.fields)void 0!==r.property&&0r.span?e=-1:0<=e&&(e+=r.span)}}}class w extends o{constructor(t,e){if(!(t instanceof u&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let r=-1;t instanceof u||(r=t),super(r,e),this.length=t}getSpan(t,e){let r=this.span;return 0>r&&(r=this.length.decode(t,e)),r}decode(t,e=0){let r=this.span;return 0>r&&(r=this.length.decode(t,e)),s(t).slice(e,e+r)}encode(t,e,r){let n=this.length;if(this.length instanceof u&&(n=t.length),!(t instanceof Uint8Array&&n===t.length))throw new TypeError(a("Blob.encode",this)+" requires (length "+n+") Uint8Array as src");if(r+n>e.length)throw new RangeError("encoding overruns Uint8Array");const i=s(t);return s(e).write(i.toString("hex"),r,n,"hex"),this.length instanceof u&&this.length.encode(n,e,r),n}}e.cY=(t,e,r)=>new h(t,e,r),e.u8=t=>new c(1,t),e.NX=t=>new c(2,t),e.DH=t=>new c(4,t),e.I0=t=>new y(t),e.Wg=t=>new g(t),e.w3=(t,e,r)=>new b(t,e,r),e.O6=(t,e,r)=>new m(t,e,r),e.av=(t,e)=>new w(t,e)},678:t=>{"use strict";var e=Object.prototype.hasOwnProperty,r="~";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function s(t,e,n,s,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new i(n,s||t,o),u=r?r+e:e;return t._events[u]?t._events[u].fn?t._events[u]=[t._events[u],a]:t._events[u].push(a):(t._events[u]=a,t._eventsCount++),t}function o(t,e){0===--t._eventsCount?t._events=new n:delete t._events[e]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var t,n,i=[];if(0===this._eventsCount)return i;for(n in t=this._events)e.call(t,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(t)):i},a.prototype.listeners=function(t){var e=r?r+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i=0;a--)(i=t[a])&&(o=(s<3?i(o):s>3?i(e,r,o):i(e,r))||o);return s>3&&o&&Object.defineProperty(e,r,o),o},o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)"default"!==r&&Object.hasOwnProperty.call(t,r)&&n(e,t,r);return i(e,t),e},a=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.deserializeUnchecked=e.deserialize=e.serialize=e.BinaryReader=e.BinaryWriter=e.BorshError=e.baseDecode=e.baseEncode=void 0;const u=a(r(404)),h=a(r(763)),c=o(r(281)),f=new("function"!=typeof TextDecoder?c.TextDecoder:TextDecoder)("utf-8",{fatal:!0});e.baseEncode=function(t){return"string"==typeof t&&(t=Buffer.from(t,"utf8")),h.default.encode(Buffer.from(t))},e.baseDecode=function(t){return Buffer.from(h.default.decode(t))};const l=1024;class d extends Error{constructor(t){super(t),this.fieldPath=[],this.originalMessage=t}addToFieldPath(t){this.fieldPath.splice(0,0,t),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}e.BorshError=d;class p{constructor(){this.buf=Buffer.alloc(l),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(l)]))}writeU8(t){this.maybeResize(),this.buf.writeUInt8(t,this.length),this.length+=1}writeU16(t){this.maybeResize(),this.buf.writeUInt16LE(t,this.length),this.length+=2}writeU32(t){this.maybeResize(),this.buf.writeUInt32LE(t,this.length),this.length+=4}writeU64(t){this.maybeResize(),this.writeBuffer(Buffer.from(new u.default(t).toArray("le",8)))}writeU128(t){this.maybeResize(),this.writeBuffer(Buffer.from(new u.default(t).toArray("le",16)))}writeU256(t){this.maybeResize(),this.writeBuffer(Buffer.from(new u.default(t).toArray("le",32)))}writeU512(t){this.maybeResize(),this.writeBuffer(Buffer.from(new u.default(t).toArray("le",64)))}writeBuffer(t){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),t,Buffer.alloc(l)]),this.length+=t.length}writeString(t){this.maybeResize();const e=Buffer.from(t,"utf8");this.writeU32(e.length),this.writeBuffer(e)}writeFixedArray(t){this.writeBuffer(Buffer.from(t))}writeArray(t,e){this.maybeResize(),this.writeU32(t.length);for(const r of t)this.maybeResize(),e(r)}toArray(){return this.buf.subarray(0,this.length)}}function y(t,e,r){const n=r.value;r.value=function(...t){try{return n.apply(this,t)}catch(t){if(t instanceof RangeError){const e=t.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(e)>=0)throw new d("Reached the end of buffer when deserializing")}throw t}}}e.BinaryWriter=p;class g{constructor(t){this.buf=t,this.offset=0}readU8(){const t=this.buf.readUInt8(this.offset);return this.offset+=1,t}readU16(){const t=this.buf.readUInt16LE(this.offset);return this.offset+=2,t}readU32(){const t=this.buf.readUInt32LE(this.offset);return this.offset+=4,t}readU64(){const t=this.readBuffer(8);return new u.default(t,"le")}readU128(){const t=this.readBuffer(16);return new u.default(t,"le")}readU256(){const t=this.readBuffer(32);return new u.default(t,"le")}readU512(){const t=this.readBuffer(64);return new u.default(t,"le")}readBuffer(t){if(this.offset+t>this.buf.length)throw new d(`Expected buffer length ${t} isn't within bounds`);const e=this.buf.slice(this.offset,this.offset+t);return this.offset+=t,e}readString(){const t=this.readU32(),e=this.readBuffer(t);try{return f.decode(e)}catch(t){throw new d(`Error decoding UTF-8 string: ${t}`)}}readFixedArray(t){return new Uint8Array(this.readBuffer(t))}readArray(t){const e=this.readU32(),r=Array();for(let n=0;n{b(t,e,r,n[0],i)});else if(void 0!==n.kind)switch(n.kind){case"option":null==r?i.writeU8(0):(i.writeU8(1),b(t,e,r,n.type,i));break;case"map":i.writeU32(r.size),r.forEach((r,s)=>{b(t,e,s,n.key,i),b(t,e,r,n.value,i)});break;default:throw new d(`FieldType ${n} unrecognized`)}else w(t,r,i)}catch(t){throw t instanceof d&&t.addToFieldPath(e),t}}function w(t,e,r){if("function"==typeof e.borshSerialize)return void e.borshSerialize(r);const n=t.get(e.constructor);if(!n)throw new d(`Class ${e.constructor.name} is missing in schema`);if("struct"===n.kind)n.fields.map(([n,i])=>{b(t,n,e[n],i,r)});else{if("enum"!==n.kind)throw new d(`Unexpected schema kind: ${n.kind} for ${e.constructor.name}`);{const i=e[n.field];for(let s=0;sv(t,e,r[0],n))}if("option"===r.kind)return n.readU8()?v(t,e,r.type,n):void 0;if("map"===r.kind){let i=new Map;const s=n.readU32();for(let o=0;o=n.values.length)throw new d(`Enum index: ${i} is out of range`);const[s,o]=n.values[i],a=v(t,s,o,r);return new e({[s]:a})}throw new d(`Unexpected schema kind: ${n.kind} for ${e.constructor.name}`)}s([y],g.prototype,"readU8",null),s([y],g.prototype,"readU16",null),s([y],g.prototype,"readU32",null),s([y],g.prototype,"readU64",null),s([y],g.prototype,"readU128",null),s([y],g.prototype,"readU256",null),s([y],g.prototype,"readU512",null),s([y],g.prototype,"readString",null),s([y],g.prototype,"readFixedArray",null),s([y],g.prototype,"readArray",null),e.BinaryReader=g,e.serialize=function(t,e,r=p){const n=new r;return w(t,e,n),n.toArray()},e.deserialize=function(t,e,r,n=g){const i=new n(r),s=k(t,e,i);if(i.offset{var n=r(364);t.exports=n("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},810:(t,e,r)=>{"use strict";function n(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function i(t,e){!function(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}(t);const r=e.outputLen;if(t.lengthO});const s=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function o(t){if("string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))}(t)),!(t instanceof Uint8Array))throw new Error("expected Uint8Array, got "+typeof t);return t}class a{clone(){return this._cloneInto()}}function u(t){const e=e=>t().update(o(e)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}class h extends a{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=s(this.buffer)}update(t){n(this);const{view:e,buffer:r,blockLen:i}=this,a=(t=o(t)).length;for(let n=0;no-u&&(this.process(r,0),u=0);for(let t=u;t>i&s),a=Number(r&s),u=n?4:0,h=n?0:4;t.setUint32(e+u,o,n),t.setUint32(e+h,a,n)}(r,o-8,BigInt(8*this.length),a),this.process(r,0);const h=s(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=c/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t>f&c)}:{h:0|Number(t>>f&c),l:0|Number(t&c)}}const d=function(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;it>>>r,y=(t,e,r)=>t<<32-r|e>>>r,g=(t,e,r)=>t>>>r|e<<32-r,m=(t,e,r)=>t<<32-r|e>>>r,b=(t,e,r)=>t<<64-r|e>>>r-32,w=(t,e,r)=>t>>>r-32|e<<64-r,v=function(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:0|i}},k=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),x=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,A=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),E=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,B=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,S=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),[I,_]=(()=>d(["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(t=>BigInt(t))))(),M=new Uint32Array(80),U=new Uint32Array(80);class P extends h{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:e,Bh:r,Bl:n,Ch:i,Cl:s,Dh:o,Dl:a,Eh:u,El:h,Fh:c,Fl:f,Gh:l,Gl:d,Hh:p,Hl:y}=this;return[t,e,r,n,i,s,o,a,u,h,c,f,l,d,p,y]}set(t,e,r,n,i,s,o,a,u,h,c,f,l,d,p,y){this.Ah=0|t,this.Al=0|e,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|o,this.Dl=0|a,this.Eh=0|u,this.El=0|h,this.Fh=0|c,this.Fl=0|f,this.Gh=0|l,this.Gl=0|d,this.Hh=0|p,this.Hl=0|y}process(t,e){for(let r=0;r<16;r++,e+=4)M[r]=t.getUint32(e),U[r]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|M[t-15],r=0|U[t-15],n=g(e,r,1)^g(e,r,8)^p(e,r,7),i=m(e,r,1)^m(e,r,8)^y(e,r,7),s=0|M[t-2],o=0|U[t-2],a=g(s,o,19)^b(s,o,61)^p(s,o,6),u=m(s,o,19)^w(s,o,61)^y(s,o,6),h=A(i,u,U[t-7],U[t-16]),c=E(h,n,a,M[t-7],M[t-16]);M[t]=0|c,U[t]=0|h}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:o,Cl:a,Dh:u,Dl:h,Eh:c,El:f,Fh:l,Fl:d,Gh:P,Gl:O,Hh:L,Hl:K}=this;for(let t=0;t<80;t++){const e=g(c,f,14)^g(c,f,18)^b(c,f,41),p=m(c,f,14)^m(c,f,18)^w(c,f,41),y=c&l^~c&P,A=S(K,p,f&d^~f&O,_[t],U[t]),E=B(A,L,e,y,I[t],M[t]),z=0|A,T=g(r,n,28)^b(r,n,34)^b(r,n,39),R=m(r,n,28)^w(r,n,34)^w(r,n,39),C=r&i^r&o^i&o,N=n&s^n&a^s&a;L=0|P,K=0|O,P=0|l,O=0|d,l=0|c,d=0|f,({h:c,l:f}=v(0|u,0|h,0|E,0|z)),u=0|o,h=0|a,o=0|i,a=0|s,i=0|r,s=0|n;const j=k(z,R,N);r=x(j,E,T,C),n=0|j}({h:r,l:n}=v(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=v(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=v(0|this.Ch,0|this.Cl,0|o,0|a)),({h:u,l:h}=v(0|this.Dh,0|this.Dl,0|u,0|h)),({h:c,l:f}=v(0|this.Eh,0|this.El,0|c,0|f)),({h:l,l:d}=v(0|this.Fh,0|this.Fl,0|l,0|d)),({h:P,l:O}=v(0|this.Gh,0|this.Gl,0|P,0|O)),({h:L,l:K}=v(0|this.Hh,0|this.Hl,0|L,0|K)),this.set(r,n,i,s,o,a,u,h,c,f,l,d,P,O,L,K)}roundClean(){M.fill(0),U.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const O=u(()=>new P)},861:(t,e,r)=>{var n=r(287),i=n.Buffer;function s(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return i(t,e,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(s(n,e),e.Buffer=o),s(i,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return i(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var n=i(t);return void 0!==e?"string"==typeof r?n.fill(e,r):n.fill(e):n.fill(0),n},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return i(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n.SlowBuffer(t)}},947:(t,e,r)=>{!function(t){"use strict";var e=function(t){var e,r=new Float64Array(16);if(t)for(e=0;e>24&255,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r,t[e+4]=n>>24&255,t[e+5]=n>>16&255,t[e+6]=n>>8&255,t[e+7]=255&n}function y(t,e,r,n,i){var s,o=0;for(s=0;s>>8)-1}function g(t,e,r,n){return y(t,e,r,n,16)}function m(t,e,r,n){return y(t,e,r,n,32)}function b(t,e,r,n){!function(t,e,r,n){for(var i,s=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,o=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,a=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,h=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,c=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,l=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,d=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,p=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,g=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,m=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,b=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,w=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,v=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,k=s,x=o,A=a,E=u,B=h,S=c,I=f,_=l,M=d,U=p,P=y,O=g,L=m,K=b,z=w,T=v,R=0;R<20;R+=2)k^=(i=(L^=(i=(M^=(i=(B^=(i=k+L|0)<<7|i>>>25)+k|0)<<9|i>>>23)+B|0)<<13|i>>>19)+M|0)<<18|i>>>14,S^=(i=(x^=(i=(K^=(i=(U^=(i=S+x|0)<<7|i>>>25)+S|0)<<9|i>>>23)+U|0)<<13|i>>>19)+K|0)<<18|i>>>14,P^=(i=(I^=(i=(A^=(i=(z^=(i=P+I|0)<<7|i>>>25)+P|0)<<9|i>>>23)+z|0)<<13|i>>>19)+A|0)<<18|i>>>14,T^=(i=(O^=(i=(_^=(i=(E^=(i=T+O|0)<<7|i>>>25)+T|0)<<9|i>>>23)+E|0)<<13|i>>>19)+_|0)<<18|i>>>14,k^=(i=(E^=(i=(A^=(i=(x^=(i=k+E|0)<<7|i>>>25)+k|0)<<9|i>>>23)+x|0)<<13|i>>>19)+A|0)<<18|i>>>14,S^=(i=(B^=(i=(_^=(i=(I^=(i=S+B|0)<<7|i>>>25)+S|0)<<9|i>>>23)+I|0)<<13|i>>>19)+_|0)<<18|i>>>14,P^=(i=(U^=(i=(M^=(i=(O^=(i=P+U|0)<<7|i>>>25)+P|0)<<9|i>>>23)+O|0)<<13|i>>>19)+M|0)<<18|i>>>14,T^=(i=(z^=(i=(K^=(i=(L^=(i=T+z|0)<<7|i>>>25)+T|0)<<9|i>>>23)+L|0)<<13|i>>>19)+K|0)<<18|i>>>14;k=k+s|0,x=x+o|0,A=A+a|0,E=E+u|0,B=B+h|0,S=S+c|0,I=I+f|0,_=_+l|0,M=M+d|0,U=U+p|0,P=P+y|0,O=O+g|0,L=L+m|0,K=K+b|0,z=z+w|0,T=T+v|0,t[0]=k>>>0&255,t[1]=k>>>8&255,t[2]=k>>>16&255,t[3]=k>>>24&255,t[4]=x>>>0&255,t[5]=x>>>8&255,t[6]=x>>>16&255,t[7]=x>>>24&255,t[8]=A>>>0&255,t[9]=A>>>8&255,t[10]=A>>>16&255,t[11]=A>>>24&255,t[12]=E>>>0&255,t[13]=E>>>8&255,t[14]=E>>>16&255,t[15]=E>>>24&255,t[16]=B>>>0&255,t[17]=B>>>8&255,t[18]=B>>>16&255,t[19]=B>>>24&255,t[20]=S>>>0&255,t[21]=S>>>8&255,t[22]=S>>>16&255,t[23]=S>>>24&255,t[24]=I>>>0&255,t[25]=I>>>8&255,t[26]=I>>>16&255,t[27]=I>>>24&255,t[28]=_>>>0&255,t[29]=_>>>8&255,t[30]=_>>>16&255,t[31]=_>>>24&255,t[32]=M>>>0&255,t[33]=M>>>8&255,t[34]=M>>>16&255,t[35]=M>>>24&255,t[36]=U>>>0&255,t[37]=U>>>8&255,t[38]=U>>>16&255,t[39]=U>>>24&255,t[40]=P>>>0&255,t[41]=P>>>8&255,t[42]=P>>>16&255,t[43]=P>>>24&255,t[44]=O>>>0&255,t[45]=O>>>8&255,t[46]=O>>>16&255,t[47]=O>>>24&255,t[48]=L>>>0&255,t[49]=L>>>8&255,t[50]=L>>>16&255,t[51]=L>>>24&255,t[52]=K>>>0&255,t[53]=K>>>8&255,t[54]=K>>>16&255,t[55]=K>>>24&255,t[56]=z>>>0&255,t[57]=z>>>8&255,t[58]=z>>>16&255,t[59]=z>>>24&255,t[60]=T>>>0&255,t[61]=T>>>8&255,t[62]=T>>>16&255,t[63]=T>>>24&255}(t,e,r,n)}function w(t,e,r,n){!function(t,e,r,n){for(var i,s=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,o=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,a=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,h=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,c=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,l=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,d=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,p=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,g=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,m=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,b=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,w=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,v=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,k=0;k<20;k+=2)s^=(i=(m^=(i=(d^=(i=(h^=(i=s+m|0)<<7|i>>>25)+s|0)<<9|i>>>23)+h|0)<<13|i>>>19)+d|0)<<18|i>>>14,c^=(i=(o^=(i=(b^=(i=(p^=(i=c+o|0)<<7|i>>>25)+c|0)<<9|i>>>23)+p|0)<<13|i>>>19)+b|0)<<18|i>>>14,y^=(i=(f^=(i=(a^=(i=(w^=(i=y+f|0)<<7|i>>>25)+y|0)<<9|i>>>23)+w|0)<<13|i>>>19)+a|0)<<18|i>>>14,v^=(i=(g^=(i=(l^=(i=(u^=(i=v+g|0)<<7|i>>>25)+v|0)<<9|i>>>23)+u|0)<<13|i>>>19)+l|0)<<18|i>>>14,s^=(i=(u^=(i=(a^=(i=(o^=(i=s+u|0)<<7|i>>>25)+s|0)<<9|i>>>23)+o|0)<<13|i>>>19)+a|0)<<18|i>>>14,c^=(i=(h^=(i=(l^=(i=(f^=(i=c+h|0)<<7|i>>>25)+c|0)<<9|i>>>23)+f|0)<<13|i>>>19)+l|0)<<18|i>>>14,y^=(i=(p^=(i=(d^=(i=(g^=(i=y+p|0)<<7|i>>>25)+y|0)<<9|i>>>23)+g|0)<<13|i>>>19)+d|0)<<18|i>>>14,v^=(i=(w^=(i=(b^=(i=(m^=(i=v+w|0)<<7|i>>>25)+v|0)<<9|i>>>23)+m|0)<<13|i>>>19)+b|0)<<18|i>>>14;t[0]=s>>>0&255,t[1]=s>>>8&255,t[2]=s>>>16&255,t[3]=s>>>24&255,t[4]=c>>>0&255,t[5]=c>>>8&255,t[6]=c>>>16&255,t[7]=c>>>24&255,t[8]=y>>>0&255,t[9]=y>>>8&255,t[10]=y>>>16&255,t[11]=y>>>24&255,t[12]=v>>>0&255,t[13]=v>>>8&255,t[14]=v>>>16&255,t[15]=v>>>24&255,t[16]=f>>>0&255,t[17]=f>>>8&255,t[18]=f>>>16&255,t[19]=f>>>24&255,t[20]=l>>>0&255,t[21]=l>>>8&255,t[22]=l>>>16&255,t[23]=l>>>24&255,t[24]=d>>>0&255,t[25]=d>>>8&255,t[26]=d>>>16&255,t[27]=d>>>24&255,t[28]=p>>>0&255,t[29]=p>>>8&255,t[30]=p>>>16&255,t[31]=p>>>24&255}(t,e,r,n)}var v=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function k(t,e,r,n,i,s,o){var a,u,h=new Uint8Array(16),c=new Uint8Array(64);for(u=0;u<16;u++)h[u]=0;for(u=0;u<8;u++)h[u]=s[u];for(;i>=64;){for(b(c,h,o,v),u=0;u<64;u++)t[e+u]=r[n+u]^c[u];for(a=1,u=8;u<16;u++)a=a+(255&h[u])|0,h[u]=255&a,a>>>=8;i-=64,e+=64,n+=64}if(i>0)for(b(c,h,o,v),u=0;u=64;){for(b(u,a,i,v),o=0;o<64;o++)t[e+o]=u[o];for(s=1,o=8;o<16;o++)s=s+(255&a[o])|0,a[o]=255&s,s>>>=8;r-=64,e+=64}if(r>0)for(b(u,a,i,v),o=0;o>>13|r<<3),n=255&t[4]|(255&t[5])<<8,this.r[2]=7939&(r>>>10|n<<6),i=255&t[6]|(255&t[7])<<8,this.r[3]=8191&(n>>>7|i<<9),s=255&t[8]|(255&t[9])<<8,this.r[4]=255&(i>>>4|s<<12),this.r[5]=s>>>1&8190,o=255&t[10]|(255&t[11])<<8,this.r[6]=8191&(s>>>14|o<<2),a=255&t[12]|(255&t[13])<<8,this.r[7]=8065&(o>>>11|a<<5),u=255&t[14]|(255&t[15])<<8,this.r[8]=8191&(a>>>8|u<<8),this.r[9]=u>>>5&127,this.pad[0]=255&t[16]|(255&t[17])<<8,this.pad[1]=255&t[18]|(255&t[19])<<8,this.pad[2]=255&t[20]|(255&t[21])<<8,this.pad[3]=255&t[22]|(255&t[23])<<8,this.pad[4]=255&t[24]|(255&t[25])<<8,this.pad[5]=255&t[26]|(255&t[27])<<8,this.pad[6]=255&t[28]|(255&t[29])<<8,this.pad[7]=255&t[30]|(255&t[31])<<8};function S(t,e,r,n,i,s){var o=new B(s);return o.update(r,n,i),o.finish(t,e),0}function I(t,e,r,n,i,s){var o=new Uint8Array(16);return S(o,0,r,n,i,s),g(t,e,o,0)}function _(t,e,r,n,i){var s;if(r<32)return-1;for(E(t,0,e,0,r,n,i),S(t,16,t,32,r-32,t),s=0;s<16;s++)t[s]=0;return 0}function M(t,e,r,n,i){var s,o=new Uint8Array(32);if(r<32)return-1;if(A(o,0,32,n,i),0!==I(e,16,e,32,r-32,o))return-1;for(E(t,0,e,0,r,n,i),s=0;s<32;s++)t[s]=0;return 0}function U(t,e){var r;for(r=0;r<16;r++)t[r]=0|e[r]}function P(t){var e,r,n=1;for(e=0;e<16;e++)r=t[e]+n+65535,n=Math.floor(r/65536),t[e]=r-65536*n;t[0]+=n-1+37*(n-1)}function O(t,e,r){for(var n,i=~(r-1),s=0;s<16;s++)n=i&(t[s]^e[s]),t[s]^=n,e[s]^=n}function L(t,r){var n,i,s,o=e(),a=e();for(n=0;n<16;n++)a[n]=r[n];for(P(a),P(a),P(a),i=0;i<2;i++){for(o[0]=a[0]-65517,n=1;n<15;n++)o[n]=a[n]-65535-(o[n-1]>>16&1),o[n-1]&=65535;o[15]=a[15]-32767-(o[14]>>16&1),s=o[15]>>16&1,o[14]&=65535,O(a,o,1-s)}for(n=0;n<16;n++)t[2*n]=255&a[n],t[2*n+1]=a[n]>>8}function K(t,e){var r=new Uint8Array(32),n=new Uint8Array(32);return L(r,t),L(n,e),m(r,0,n,0)}function z(t){var e=new Uint8Array(32);return L(e,t),1&e[0]}function T(t,e){var r;for(r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function R(t,e,r){for(var n=0;n<16;n++)t[n]=e[n]+r[n]}function C(t,e,r){for(var n=0;n<16;n++)t[n]=e[n]-r[n]}function N(t,e,r){var n,i,s=0,o=0,a=0,u=0,h=0,c=0,f=0,l=0,d=0,p=0,y=0,g=0,m=0,b=0,w=0,v=0,k=0,x=0,A=0,E=0,B=0,S=0,I=0,_=0,M=0,U=0,P=0,O=0,L=0,K=0,z=0,T=r[0],R=r[1],C=r[2],N=r[3],j=r[4],D=r[5],H=r[6],F=r[7],W=r[8],q=r[9],$=r[10],V=r[11],Z=r[12],Y=r[13],G=r[14],X=r[15];s+=(n=e[0])*T,o+=n*R,a+=n*C,u+=n*N,h+=n*j,c+=n*D,f+=n*H,l+=n*F,d+=n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i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),v=(n=v+i+65535)-65536*(i=Math.floor(n/65536)),s=(n=(s+=i-1+37*(i-1))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),v=(n=v+i+65535)-65536*(i=Math.floor(n/65536)),s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=a,t[3]=u,t[4]=h,t[5]=c,t[6]=f,t[7]=l,t[8]=d,t[9]=p,t[10]=y,t[11]=g,t[12]=m,t[13]=b,t[14]=w,t[15]=v}function j(t,e){N(t,e,e)}function D(t,r){var n,i=e();for(n=0;n<16;n++)i[n]=r[n];for(n=253;n>=0;n--)j(i,i),2!==n&&4!==n&&N(i,i,r);for(n=0;n<16;n++)t[n]=i[n]}function H(t,r){var n,i=e();for(n=0;n<16;n++)i[n]=r[n];for(n=250;n>=0;n--)j(i,i),1!==n&&N(i,i,r);for(n=0;n<16;n++)t[n]=i[n]}function F(t,r,n){var i,s,o=new Uint8Array(32),a=new Float64Array(80),h=e(),c=e(),f=e(),l=e(),d=e(),p=e();for(s=0;s<31;s++)o[s]=r[s];for(o[31]=127&r[31]|64,o[0]&=248,T(a,n),s=0;s<16;s++)c[s]=a[s],l[s]=h[s]=f[s]=0;for(h[0]=l[0]=1,s=254;s>=0;--s)O(h,c,i=o[s>>>3]>>>(7&s)&1),O(f,l,i),R(d,h,f),C(h,h,f),R(f,c,l),C(c,c,l),j(l,d),j(p,h),N(h,f,h),N(f,c,d),R(d,h,f),C(h,h,f),j(c,h),C(f,l,p),N(h,f,u),R(h,h,l),N(f,f,h),N(h,l,p),N(l,c,a),j(c,d),O(h,c,i),O(f,l,i);for(s=0;s<16;s++)a[s+16]=h[s],a[s+32]=f[s],a[s+48]=c[s],a[s+64]=l[s];var y=a.subarray(32),g=a.subarray(16);return D(y,y),N(g,g,y),L(t,g),0}function W(t,e){return F(t,e,s)}function q(t,e){return n(e,32),W(t,e)}function $(t,e,r){var n=new Uint8Array(32);return F(n,r,e),w(t,i,n,v)}B.prototype.blocks=function(t,e,r){for(var n,i,s,o,a,u,h,c,f,l,d,p,y,g,m,b,w,v,k,x=this.fin?0:2048,A=this.h[0],E=this.h[1],B=this.h[2],S=this.h[3],I=this.h[4],_=this.h[5],M=this.h[6],U=this.h[7],P=this.h[8],O=this.h[9],L=this.r[0],K=this.r[1],z=this.r[2],T=this.r[3],R=this.r[4],C=this.r[5],N=this.r[6],j=this.r[7],D=this.r[8],H=this.r[9];r>=16;)l=f=0,l+=(A+=8191&(n=255&t[e+0]|(255&t[e+1])<<8))*L,l+=(E+=8191&(n>>>13|(i=255&t[e+2]|(255&t[e+3])<<8)<<3))*(5*H),l+=(B+=8191&(i>>>10|(s=255&t[e+4]|(255&t[e+5])<<8)<<6))*(5*D),l+=(S+=8191&(s>>>7|(o=255&t[e+6]|(255&t[e+7])<<8)<<9))*(5*j),f=(l+=(I+=8191&(o>>>4|(a=255&t[e+8]|(255&t[e+9])<<8)<<12))*(5*N))>>>13,l&=8191,l+=(_+=a>>>1&8191)*(5*C),l+=(M+=8191&(a>>>14|(u=255&t[e+10]|(255&t[e+11])<<8)<<2))*(5*R),l+=(U+=8191&(u>>>11|(h=255&t[e+12]|(255&t[e+13])<<8)<<5))*(5*T),l+=(P+=8191&(h>>>8|(c=255&t[e+14]|(255&t[e+15])<<8)<<8))*(5*z),d=f+=(l+=(O+=c>>>5|x)*(5*K))>>>13,d+=A*K,d+=E*L,d+=B*(5*H),d+=S*(5*D),f=(d+=I*(5*j))>>>13,d&=8191,d+=_*(5*N),d+=M*(5*C),d+=U*(5*R),d+=P*(5*T),f+=(d+=O*(5*z))>>>13,d&=8191,p=f,p+=A*z,p+=E*K,p+=B*L,p+=S*(5*H),f=(p+=I*(5*D))>>>13,p&=8191,p+=_*(5*j),p+=M*(5*N),p+=U*(5*C),p+=P*(5*R),y=f+=(p+=O*(5*T))>>>13,y+=A*T,y+=E*z,y+=B*K,y+=S*L,f=(y+=I*(5*H))>>>13,y&=8191,y+=_*(5*D),y+=M*(5*j),y+=U*(5*N),y+=P*(5*C),g=f+=(y+=O*(5*R))>>>13,g+=A*R,g+=E*T,g+=B*z,g+=S*K,f=(g+=I*L)>>>13,g&=8191,g+=_*(5*H),g+=M*(5*D),g+=U*(5*j),g+=P*(5*N),m=f+=(g+=O*(5*C))>>>13,m+=A*C,m+=E*R,m+=B*T,m+=S*z,f=(m+=I*K)>>>13,m&=8191,m+=_*L,m+=M*(5*H),m+=U*(5*D),m+=P*(5*j),b=f+=(m+=O*(5*N))>>>13,b+=A*N,b+=E*C,b+=B*R,b+=S*T,f=(b+=I*z)>>>13,b&=8191,b+=_*K,b+=M*L,b+=U*(5*H),b+=P*(5*D),w=f+=(b+=O*(5*j))>>>13,w+=A*j,w+=E*N,w+=B*C,w+=S*R,f=(w+=I*T)>>>13,w&=8191,w+=_*z,w+=M*K,w+=U*L,w+=P*(5*H),v=f+=(w+=O*(5*D))>>>13,v+=A*D,v+=E*j,v+=B*N,v+=S*C,f=(v+=I*R)>>>13,v&=8191,v+=_*T,v+=M*z,v+=U*K,v+=P*L,k=f+=(v+=O*(5*H))>>>13,k+=A*H,k+=E*D,k+=B*j,k+=S*N,f=(k+=I*C)>>>13,k&=8191,k+=_*R,k+=M*T,k+=U*z,k+=P*K,A=l=8191&(f=(f=((f+=(k+=O*L)>>>13)<<2)+f|0)+(l&=8191)|0),E=d+=f>>>=13,B=p&=8191,S=y&=8191,I=g&=8191,_=m&=8191,M=b&=8191,U=w&=8191,P=v&=8191,O=k&=8191,e+=16,r-=16;this.h[0]=A,this.h[1]=E,this.h[2]=B,this.h[3]=S,this.h[4]=I,this.h[5]=_,this.h[6]=M,this.h[7]=U,this.h[8]=P,this.h[9]=O},B.prototype.finish=function(t,e){var r,n,i,s,o=new Uint16Array(10);if(this.leftover){for(s=this.leftover,this.buffer[s++]=1;s<16;s++)this.buffer[s]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,s=2;s<10;s++)this.h[s]+=r,r=this.h[s]>>>13,this.h[s]&=8191;for(this.h[0]+=5*r,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,o[0]=this.h[0]+5,r=o[0]>>>13,o[0]&=8191,s=1;s<10;s++)o[s]=this.h[s]+r,r=o[s]>>>13,o[s]&=8191;for(o[9]-=8192,n=(1^r)-1,s=0;s<10;s++)o[s]&=n;for(n=~n,s=0;s<10;s++)this.h[s]=this.h[s]&n|o[s];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),i=this.h[0]+this.pad[0],this.h[0]=65535&i,s=1;s<8;s++)i=(this.h[s]+this.pad[s]|0)+(i>>>16)|0,this.h[s]=65535&i;t[e+0]=this.h[0]>>>0&255,t[e+1]=this.h[0]>>>8&255,t[e+2]=this.h[1]>>>0&255,t[e+3]=this.h[1]>>>8&255,t[e+4]=this.h[2]>>>0&255,t[e+5]=this.h[2]>>>8&255,t[e+6]=this.h[3]>>>0&255,t[e+7]=this.h[3]>>>8&255,t[e+8]=this.h[4]>>>0&255,t[e+9]=this.h[4]>>>8&255,t[e+10]=this.h[5]>>>0&255,t[e+11]=this.h[5]>>>8&255,t[e+12]=this.h[6]>>>0&255,t[e+13]=this.h[6]>>>8&255,t[e+14]=this.h[7]>>>0&255,t[e+15]=this.h[7]>>>8&255},B.prototype.update=function(t,e,r){var n,i;if(this.leftover){for((i=16-this.leftover)>r&&(i=r),n=0;n=16&&(i=r-r%16,this.blocks(t,e,i),e+=i,r-=i),r){for(n=0;n=128;){for(x=0;x<16;x++)A=8*x+Z,U[x]=r[A+0]<<24|r[A+1]<<16|r[A+2]<<8|r[A+3],P[x]=r[A+4]<<24|r[A+5]<<16|r[A+6]<<8|r[A+7];for(x=0;x<80;x++)if(i=O,s=L,o=K,a=z,u=T,h=R,c=C,l=j,d=D,p=H,y=F,g=W,m=q,b=$,S=65535&(B=V),I=B>>>16,_=65535&(E=N),M=E>>>16,S+=65535&(B=(W>>>14|T<<18)^(W>>>18|T<<14)^(T>>>9|W<<23)),I+=B>>>16,_+=65535&(E=(T>>>14|W<<18)^(T>>>18|W<<14)^(W>>>9|T<<23)),M+=E>>>16,S+=65535&(B=W&q^~W&$),I+=B>>>16,_+=65535&(E=T&R^~T&C),M+=E>>>16,S+=65535&(B=Y[2*x+1]),I+=B>>>16,_+=65535&(E=Y[2*x]),M+=E>>>16,E=U[x%16],I+=(B=P[x%16])>>>16,_+=65535&E,M+=E>>>16,_+=(I+=(S+=65535&B)>>>16)>>>16,S=65535&(B=k=65535&S|I<<16),I=B>>>16,_=65535&(E=v=65535&_|(M+=_>>>16)<<16),M=E>>>16,S+=65535&(B=(j>>>28|O<<4)^(O>>>2|j<<30)^(O>>>7|j<<25)),I+=B>>>16,_+=65535&(E=(O>>>28|j<<4)^(j>>>2|O<<30)^(j>>>7|O<<25)),M+=E>>>16,I+=(B=j&D^j&H^D&H)>>>16,_+=65535&(E=O&L^O&K^L&K),M+=E>>>16,f=65535&(_+=(I+=(S+=65535&B)>>>16)>>>16)|(M+=_>>>16)<<16,w=65535&S|I<<16,S=65535&(B=y),I=B>>>16,_=65535&(E=a),M=E>>>16,I+=(B=k)>>>16,_+=65535&(E=v),M+=E>>>16,L=i,K=s,z=o,T=a=65535&(_+=(I+=(S+=65535&B)>>>16)>>>16)|(M+=_>>>16)<<16,R=u,C=h,N=c,O=f,D=l,H=d,F=p,W=y=65535&S|I<<16,q=g,$=m,V=b,j=w,x%16==15)for(A=0;A<16;A++)E=U[A],S=65535&(B=P[A]),I=B>>>16,_=65535&E,M=E>>>16,E=U[(A+9)%16],S+=65535&(B=P[(A+9)%16]),I+=B>>>16,_+=65535&E,M+=E>>>16,v=U[(A+1)%16],S+=65535&(B=((k=P[(A+1)%16])>>>1|v<<31)^(k>>>8|v<<24)^(k>>>7|v<<25)),I+=B>>>16,_+=65535&(E=(v>>>1|k<<31)^(v>>>8|k<<24)^v>>>7),M+=E>>>16,v=U[(A+14)%16],I+=(B=((k=P[(A+14)%16])>>>19|v<<13)^(v>>>29|k<<3)^(k>>>6|v<<26))>>>16,_+=65535&(E=(v>>>19|k<<13)^(k>>>29|v<<3)^v>>>6),M+=E>>>16,M+=(_+=(I+=(S+=65535&B)>>>16)>>>16)>>>16,U[A]=65535&_|M<<16,P[A]=65535&S|I<<16;S=65535&(B=j),I=B>>>16,_=65535&(E=O),M=E>>>16,E=t[0],I+=(B=e[0])>>>16,_+=65535&E,M+=E>>>16,M+=(_+=(I+=(S+=65535&B)>>>16)>>>16)>>>16,t[0]=O=65535&_|M<<16,e[0]=j=65535&S|I<<16,S=65535&(B=D),I=B>>>16,_=65535&(E=L),M=E>>>16,E=t[1],I+=(B=e[1])>>>16,_+=65535&E,M+=E>>>16,M+=(_+=(I+=(S+=65535&B)>>>16)>>>16)>>>16,t[1]=L=65535&_|M<<16,e[1]=D=65535&S|I<<16,S=65535&(B=H),I=B>>>16,_=65535&(E=K),M=E>>>16,E=t[2],I+=(B=e[2])>>>16,_+=65535&E,M+=E>>>16,M+=(_+=(I+=(S+=65535&B)>>>16)>>>16)>>>16,t[2]=K=65535&_|M<<16,e[2]=H=65535&S|I<<16,S=65535&(B=F),I=B>>>16,_=65535&(E=z),M=E>>>16,E=t[3],I+=(B=e[3])>>>16,_+=65535&E,M+=E>>>16,M+=(_+=(I+=(S+=65535&B)>>>16)>>>16)>>>16,t[3]=z=65535&_|M<<16,e[3]=F=65535&S|I<<16,S=65535&(B=W),I=B>>>16,_=65535&(E=T),M=E>>>16,E=t[4],I+=(B=e[4])>>>16,_+=65535&E,M+=E>>>16,M+=(_+=(I+=(S+=65535&B)>>>16)>>>16)>>>16,t[4]=T=65535&_|M<<16,e[4]=W=65535&S|I<<16,S=65535&(B=q),I=B>>>16,_=65535&(E=R),M=E>>>16,E=t[5],I+=(B=e[5])>>>16,_+=65535&E,M+=E>>>16,M+=(_+=(I+=(S+=65535&B)>>>16)>>>16)>>>16,t[5]=R=65535&_|M<<16,e[5]=q=65535&S|I<<16,S=65535&(B=$),I=B>>>16,_=65535&(E=C),M=E>>>16,E=t[6],I+=(B=e[6])>>>16,_+=65535&E,M+=E>>>16,M+=(_+=(I+=(S+=65535&B)>>>16)>>>16)>>>16,t[6]=C=65535&_|M<<16,e[6]=$=65535&S|I<<16,S=65535&(B=V),I=B>>>16,_=65535&(E=N),M=E>>>16,E=t[7],I+=(B=e[7])>>>16,_+=65535&E,M+=E>>>16,M+=(_+=(I+=(S+=65535&B)>>>16)>>>16)>>>16,t[7]=N=65535&_|M<<16,e[7]=V=65535&S|I<<16,Z+=128,n-=128}return n}function X(t,e,r){var n,i=new Int32Array(8),s=new Int32Array(8),o=new Uint8Array(256),a=r;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,s[0]=4089235720,s[1]=2227873595,s[2]=4271175723,s[3]=1595750129,s[4]=2917565137,s[5]=725511199,s[6]=4215389547,s[7]=327033209,G(i,s,e,r),r%=128,n=0;n=0;--i)Q(t,e,n=r[i/8|0]>>(7&i)&1),J(e,t),J(t,t),Q(t,e,n)}function rt(t,r){var n=[e(),e(),e(),e()];U(n[0],f),U(n[1],l),U(n[2],a),N(n[3],f,l),et(t,n,r)}function nt(t,r,i){var s,o=new Uint8Array(64),a=[e(),e(),e(),e()];for(i||n(r,32),X(o,r,32),o[0]&=248,o[31]&=127,o[31]|=64,rt(a,o),tt(t,a),s=0;s<32;s++)r[s+32]=t[s];return 0}var it=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function st(t,e){var r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*it[i],r=e[i]>>8,e[i]&=255;for(i=0;i<32;i++)e[i]-=r*it[i];for(n=0;n<32;n++)e[n+1]+=e[n]>>8,t[n]=255&e[n]}function ot(t){var e,r=new Float64Array(64);for(e=0;e<64;e++)r[e]=t[e];for(e=0;e<64;e++)t[e]=0;st(t,r)}function at(t,r,n,i){var s,o,a=new Uint8Array(64),u=new Uint8Array(64),h=new Uint8Array(64),c=new Float64Array(64),f=[e(),e(),e(),e()];X(a,i,32),a[0]&=248,a[31]&=127,a[31]|=64;var l=n+64;for(s=0;s>7&&C(t[0],o,t[0]),N(t[3],t[0],t[1]),0)}(l,i))return-1;for(s=0;s=0},t.sign.keyPair=function(){var t=new Uint8Array(ct),e=new Uint8Array(ft);return nt(t,e),{publicKey:t,secretKey:e}},t.sign.keyPair.fromSecretKey=function(t){if(dt(t),t.length!==ft)throw new Error("bad secret key size");for(var e=new Uint8Array(ct),r=0;r 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';\nexport { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(title + ' boolean expected, got ' + value);\n}\n// tmp name until v2\nexport function _abool2(value, title = '') {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value, length, title = '') {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n }\n catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n }\n else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_1n << BigInt(n)) - _1n;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error('invalid validator function');\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\nexport function isHash(val) {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(object, fields, optFields = {}) {\n if (!object || typeof object !== 'object')\n throw new Error('expected valid options object');\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n return FpPow(Field(modulo), num, power);\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction assertIsSquare(Fp, root, n) {\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\nfunction sqrt5mod8(Fp, n) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (Fp, n) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n if (Fp.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t))\n return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp, num, power) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return Fp.ONE;\n if (power === _1n)\n return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n// TODO: remove\nexport function FpDiv(Fp, lhs, rhs) {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre(Fp, n) {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?\nisLE = false, opts = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength = undefined;\n let _sqrt = undefined;\n let modFromBytes = false;\n let allowedLengths = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE)\n throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS)\n _nbitLength = _opts.BITS;\n if (_opts.sqrt)\n _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean')\n isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean')\n modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n }\n else {\n if (typeof bitLenOrOpts === 'number')\n _nbitLength = bitLenOrOpts;\n if (opts.sqrt)\n _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP; // cached sqrtP\n const f = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: _sqrt ||\n ((n) => {\n if (!sqrtP)\n sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n });\n return Object.freeze(f);\n}\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from \"../utils.js\";\nimport { Field, FpInvertBatch, nLength, validateField } from \"./modular.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nexport function negateCt(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ(c, points) {\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\nfunction assert0(n) {\n if (n !== _0n)\n throw new Error('invalid wNAF');\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n // Parametrized with a given Point class (not individual point)\n constructor(Point, bits) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n // non-const time multiplication ladder\n _unsafeLadder(elm, n, p = this.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(point, W) {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points = [];\n let p = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n))\n throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n }\n else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n)\n break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n }\n else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n getPrecomputes(W, point, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W);\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function')\n comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n cached(point, scalar, transform) {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n unsafe(point, scalar, transform, prev) {\n const W = getW(point);\n if (W === 1)\n return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P, W) {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n hasCache(elm) {\n return getW(elm) !== 1;\n }\n}\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe(Point, point, k1, k2) {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n p1 = p1.add(acc);\n if (k2 & _1n)\n p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger(c, fieldN, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, fieldN, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n// TODO: remove\n/** @deprecated */\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\nfunction createField(order, field, isLE) {\n if (field) {\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n//# sourceMappingURL=curve.js.map","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, ensureBytes, isBytes, memoized, notImplemented, randomBytes as randomBytesWeb, } from \"../utils.js\";\nimport { _createCurveFields, normalizeZ, pippenger, wNAF, } from \"./curve.js\";\nimport { Field } from \"./modular.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\nfunction isEdValidXY(Fp, CURVE, x, y) {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\nexport function edwards(params, extraOpts = {}) {\n const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor } = CURVE;\n _validateObject(extraOpts, {}, { uvRatio: 'function' });\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n) => Fp.create(n); // Function overrides\n // sqrt(u/v)\n const uvRatio = extraOpts.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title, n, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n function aextpoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(X, Y, Z, T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes, zip215 = false) {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(bytes, zip215 = false) {\n return Point.fromBytes(ensureBytes('point', bytes), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_2n); // random number\n return this;\n }\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n aextpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n aextpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n // Constant-time multiplication.\n multiply(scalar) {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar))\n throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar, acc = Point.ZERO) {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar))\n throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n)\n return Point.ZERO;\n if (this.is0() || scalar === _1n)\n return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ) {\n return toAffineMemo(this, invertedZ);\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n toBytes() {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return ``;\n }\n // TODO: remove\n get ex() {\n return this.X;\n }\n get ey() {\n return this.Y;\n }\n get ez() {\n return this.Z;\n }\n get et() {\n return this.T;\n }\n static normalizeZ(points) {\n return normalizeZ(Point, points);\n }\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n _setWindowSize(windowSize) {\n this.precompute(windowSize);\n }\n toRawBytes() {\n return this.toBytes();\n }\n }\n // base / generator point\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n Point.Fp = Fp;\n // scalar field\n Point.Fn = Fn;\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport class PrimeEdwardsPoint {\n constructor(ep) {\n this.ep = ep;\n }\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes) {\n notImplemented();\n }\n static fromHex(_hex) {\n notImplemented();\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n // Common implementations\n clearCofactor() {\n // no-op for prime-order groups\n return this;\n }\n assertValidity() {\n this.ep.assertValidity();\n }\n toAffine(invertedZ) {\n return this.ep.toAffine(invertedZ);\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return this.toHex();\n }\n isTorsionFree() {\n return true;\n }\n isSmallOrder() {\n return false;\n }\n add(other) {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n subtract(other) {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return this.init(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return this.init(this.ep.double());\n }\n negate() {\n return this.init(this.ep.negate());\n }\n precompute(windowSize, isLazy) {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n /** @deprecated use `toBytes` */\n toRawBytes() {\n return this.toBytes();\n }\n}\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point, cHash, eddsaOpts = {}) {\n if (typeof cHash !== 'function')\n throw new Error('\"hash\" function param is required');\n _validateObject(eddsaOpts, {}, {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n });\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n const randomBytes = eddsaOpts.randomBytes || randomBytesWeb;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);\n const domain = eddsaOpts.domain ||\n ((data, ctx, phflag) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key) {\n const len = lengths.secretKey;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey) {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, secretKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s))\n throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts = { zip215: true };\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = ensureBytes('signature', sig, len);\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);\n if (zip215 !== undefined)\n abool(zip215, 'zip215');\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false; // zip215 allows public keys of small order\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)) {\n return abytes(seed, lengths.seed, 'seed');\n }\n function keygen(seed) {\n const secretKey = utils.randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n function isValidSecretKey(key) {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n function isValidPublicKey(key, zip215) {\n try {\n return !!Point.fromBytes(key, zip215);\n }\n catch (error) {\n return false;\n }\n }\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey) {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57)\n throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n toMontgomerySecret(secretKey) {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n /** @deprecated */\n randomPrivateKey: randomSecretKey,\n /** @deprecated */\n precompute(windowSize = 8, point = Point.BASE) {\n return point.precompute(windowSize, false);\n },\n };\n return Object.freeze({\n keygen,\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\nfunction _eddsa_legacy_opts_to_new(c) {\n const CURVE = {\n a: c.a,\n d: c.d,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n const Fn = Field(CURVE.n, c.nBitLength, true);\n const curveOpts = { Fp, Fn, uvRatio: c.uvRatio };\n const eddsaOpts = {\n randomBytes: c.randomBytes,\n adjustScalarBytes: c.adjustScalarBytes,\n domain: c.domain,\n prehash: c.prehash,\n mapToCurve: c.mapToCurve,\n };\n return { CURVE, curveOpts, hash: c.hash, eddsaOpts };\n}\nfunction _eddsa_new_output_to_legacy(c, eddsa) {\n const Point = eddsa.Point;\n const legacy = Object.assign({}, eddsa, {\n ExtendedPoint: Point,\n CURVE: c,\n nBitLength: Point.Fn.BITS,\n nByteLength: Point.Fn.BYTES,\n });\n return legacy;\n}\n// TODO: remove. Use eddsa\nexport function twistedEdwards(c) {\n const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);\n const Point = edwards(CURVE, curveOpts);\n const EDDSA = eddsa(Point, hash, eddsaOpts);\n return _eddsa_new_output_to_legacy(c, EDDSA);\n}\n//# sourceMappingURL=edwards.js.map","import { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from \"../utils.js\";\nimport { FpInvertBatch, mod } from \"./modular.js\";\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value, length) {\n anum(value);\n anum(length);\n if (value < 0 || value >= 1 << (8 * length))\n throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0);\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\nfunction strxor(a, b) {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\nfunction anum(item) {\n if (!Number.isSafeInteger(item))\n throw new Error('number expected');\n}\nfunction normDST(DST) {\n if (!isBytes(DST) && typeof DST !== 'string')\n throw new Error('DST must be Uint8Array or string');\n return typeof DST === 'string' ? utf8ToBytes(DST) : DST;\n}\n/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\nexport function expand_message_xmd(msg, DST, lenInBytes, H) {\n abytes(msg);\n anum(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255)\n DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255)\n throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\nexport function expand_message_xof(msg, DST, lenInBytes, k, H) {\n abytes(msg);\n anum(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest());\n}\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg, count, options) {\n _validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n if (!isHash(options.hash))\n throw new Error('expected valid hash');\n abytes(msg);\n anum(count);\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n }\n else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n }\n else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n }\n else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\nexport function isogenyMap(field, map) {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x, y) => {\n const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\nexport const _DST_scalar = utf8ToBytes('HashToScalar-');\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */\nexport function createHasher(Point, mapToCurve, defaults) {\n if (typeof mapToCurve !== 'function')\n throw new Error('mapToCurve() must be defined');\n function map(num) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO))\n return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n return {\n defaults,\n hashToCurve(msg, options) {\n const opts = Object.assign({}, defaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\n },\n encodeToCurve(msg, options) {\n const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};\n const opts = Object.assign({}, defaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars) {\n if (!Array.isArray(scalars))\n throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint')\n throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08\n hashToScalar(msg, options) {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\n };\n}\n//# sourceMappingURL=hash-to-curve.js.map","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';\nimport { pippenger } from \"./abstract/curve.js\";\nimport { PrimeEdwardsPoint, twistedEdwards, } from \"./abstract/edwards.js\";\nimport { _DST_scalar, createHasher, expand_message_xmd, } from \"./abstract/hash-to-curve.js\";\nimport { Field, FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { bytesToNumberLE, ensureBytes, equalBytes } from \"./utils.js\";\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n// P = 2n**255n-19n\nconst ed25519_CURVE_p = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nconst Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();\nconst Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n ...ed25519_CURVE,\n Fp,\n hash: sha512,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n}))();\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const { secretKey, publicKey } = ed25519.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\n/** Context of ed25519. Uses context for domain separation. */\nexport const ed25519ctx = /* @__PURE__ */ (() => twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n}))();\n/** Prehashed version of ed25519. Accepts already-hashed messages in sign() and verify(). */\nexport const ed25519ph = /* @__PURE__ */ (() => twistedEdwards(Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n})))();\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomSecretKey());\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = Fp.ORDER;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x) => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519.Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\nfunction ristretto255_map(bytes) {\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n}\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint {\n constructor(ep) {\n super(ep);\n }\n static fromAffine(ap) {\n return new _RistrettoPoint(ed25519.Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _RistrettoPoint))\n throw new Error('RistrettoPoint expected');\n }\n init(ep) {\n return new _RistrettoPoint(ep);\n }\n /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\n static hashToCurve(hex) {\n return ristretto255_map(ensureBytes('ristrettoHash', hex, 64));\n }\n static fromBytes(bytes) {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519.Point(x, y, _1n, t));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n return _RistrettoPoint.fromBytes(ensureBytes('ristrettoHex', hex, 32));\n }\n static msm(points, scalars) {\n return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes() {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P))\n Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P))\n s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n// Do NOT change syntax: the following gymnastics is done,\n// because typescript strips comments, which makes bundlers disable tree-shaking.\n// prettier-ignore\n_RistrettoPoint.BASE = \n/* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();\n// prettier-ignore\n_RistrettoPoint.ZERO = \n/* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();\n// prettier-ignore\n_RistrettoPoint.Fp = \n/* @__PURE__ */ (() => Fp)();\n// prettier-ignore\n_RistrettoPoint.Fn = \n/* @__PURE__ */ (() => Fn)();\nexport const ristretto255 = { Point: _RistrettoPoint };\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher = {\n hashToCurve(msg, options) {\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return ristretto255_map(xmd);\n },\n hashToScalar(msg, options = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n};\n// export const ristretto255_oprf: OPRF = createORPF({\n// name: 'ristretto255-SHA512',\n// Point: RistrettoPoint,\n// hash: sha512,\n// hashToGroup: ristretto255_hasher.hashToCurve,\n// hashToScalar: ristretto255_hasher.hashToScalar,\n// });\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n return ed25519.utils.toMontgomery(ensureBytes('pub', edwardsPub));\n}\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport const edwardsToMontgomery = edwardsToMontgomeryPub;\n/** @deprecated use `ed25519.utils.toMontgomerySecret` */\nexport function edwardsToMontgomeryPriv(edwardsPriv) {\n return ed25519.utils.toMontgomerySecret(ensureBytes('pub', edwardsPriv));\n}\n/** @deprecated use `ristretto255.Point` */\nexport const RistrettoPoint = _RistrettoPoint;\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToCurve = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const encodeToCurve = /* @__PURE__ */ (() => ed25519_hasher.encodeToCurve)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToRistretto255 = /* @__PURE__ */ (() => ristretto255_hasher.hashToCurve)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hash_to_ristretto255 = /* @__PURE__ */ (() => ristretto255_hasher.hashToCurve)();\n//# sourceMappingURL=ed25519.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map","// src/codes.ts\nvar SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;\nvar SOLANA_ERROR__INVALID_NONCE = 2;\nvar SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;\nvar SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;\nvar SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;\nvar SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;\nvar SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;\nvar SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;\nvar SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;\nvar SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;\nvar SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;\nvar SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;\nvar SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;\nvar SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;\nvar SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;\nvar SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;\nvar SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 28e5;\nvar SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;\nvar SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;\nvar SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;\nvar SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;\nvar SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;\nvar SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;\nvar SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;\nvar SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;\nvar SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;\nvar SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;\nvar SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;\nvar SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 323e4;\nvar SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;\nvar SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;\nvar SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;\nvar SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 361e4;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;\nvar SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611e3;\nvar SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704e3;\nvar SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;\nvar SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;\nvar SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;\nvar SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;\nvar SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128e3;\nvar SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;\nvar SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615e3;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;\nvar SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508e3;\nvar SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;\nvar SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;\nvar SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;\nvar SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;\nvar SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;\nvar SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;\nvar SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;\nvar SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;\nvar SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;\nvar SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;\nvar SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;\nvar SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663e3;\nvar SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;\nvar SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;\nvar SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;\nvar SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;\nvar SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;\nvar SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;\nvar SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;\nvar SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;\nvar SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;\nvar SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;\nvar SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;\nvar SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;\nvar SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;\nvar SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;\nvar SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;\nvar SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 705e4;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;\nvar SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;\nvar SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;\nvar SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;\nvar SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;\nvar SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;\nvar SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;\nvar SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;\nvar SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;\nvar SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;\nvar SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;\nvar SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;\nvar SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;\nvar SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;\nvar SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;\nvar SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078e3;\nvar SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;\nvar SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;\nvar SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;\nvar SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;\nvar SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;\nvar SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;\nvar SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;\nvar SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;\nvar SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;\nvar SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;\nvar SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;\nvar SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;\nvar SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;\nvar SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;\nvar SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;\nvar SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;\nvar SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;\nvar SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;\nvar SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;\nvar SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;\nvar SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;\nvar SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;\nvar SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 81e5;\nvar SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;\nvar SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;\nvar SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 819e4;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 99e5;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;\n\n// src/context.ts\nfunction encodeValue(value) {\n if (Array.isArray(value)) {\n const commaSeparatedValues = value.map(encodeValue).join(\n \"%2C%20\"\n /* \", \" */\n );\n return \"%5B\" + commaSeparatedValues + /* \"]\" */\n \"%5D\";\n } else if (typeof value === \"bigint\") {\n return `${value}n`;\n } else {\n return encodeURIComponent(\n String(\n value != null && Object.getPrototypeOf(value) === null ? (\n // Plain objects with no prototype don't have a `toString` method.\n // Convert them before stringifying them.\n { ...value }\n ) : value\n )\n );\n }\n}\nfunction encodeObjectContextEntry([key, value]) {\n return `${key}=${encodeValue(value)}`;\n}\nfunction encodeContextObject(context) {\n const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join(\"&\");\n return btoa(searchParamsString);\n}\n\n// src/messages.ts\nvar SolanaErrorMessages = {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: \"Account not found at address: $address\",\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: \"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.\",\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: \"Expected decoded account at address: $address\",\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: \"Failed to decode account data at address: $address\",\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: \"Accounts not found at addresses: $addresses\",\n [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]: \"Unable to find a viable program address bump seed.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: \"$putativeAddress is not a base58-encoded address.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: \"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: \"The `CryptoKey` must be an `Ed25519` public key.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]: \"$putativeOffCurveAddress is not a base58-encoded off-curve address.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: \"Invalid seeds; point must fall off the Ed25519 curve.\",\n [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]: \"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].\",\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: \"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.\",\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: \"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.\",\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: \"Expected program derived address bump to be in the range [0, 255], got: $bump.\",\n [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: \"Program address cannot end with PDA marker.\",\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: \"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.\",\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: \"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.\",\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: \"The network has progressed past the last block for which this transaction could have been committed.\",\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: \"Codec [$codecDescription] cannot decode empty byte arrays.\",\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: \"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.\",\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: \"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].\",\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: \"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].\",\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: \"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].\",\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]: \"Encoder and decoder must either both be fixed-size or variable-size.\",\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: \"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.\",\n [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: \"Expected a fixed-size codec, got a variable-size one.\",\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: \"Codec [$codecDescription] expected a positive byte length, got $bytesLength.\",\n [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: \"Expected a variable-size codec, got a fixed-size one.\",\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: \"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].\",\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: \"Codec [$codecDescription] expected $expected bytes, got $bytesLength.\",\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: \"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].\",\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: \"Invalid discriminated union variant. Expected one of [$variants], got $value.\",\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: \"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.\",\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: \"Invalid literal union variant. Expected one of [$variants], got $value.\",\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: \"Expected [$codecDescription] to have $expected items, got $actual.\",\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: \"Invalid value $value for base $base with alphabet $alphabet.\",\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: \"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.\",\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: \"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.\",\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: \"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.\",\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: \"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].\",\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: \"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.\",\n [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: \"No random values implementation could be found.\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: \"instruction requires an uninitialized account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]: \"instruction tries to borrow reference for an account which is already borrowed\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: \"instruction left account with an outstanding borrowed reference\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]: \"program other than the account's owner changed the size of the account data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: \"account data too small for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: \"instruction expected an executable account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]: \"An account does not have enough lamports to be rent-exempt\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: \"Program arithmetic overflowed\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: \"Failed to serialize or deserialize account data: $encodedData\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]: \"Builtin programs must consume compute units\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: \"Cross-program invocation call depth too deep\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: \"Computational budget exceeded\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: \"custom program error: #$code\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: \"instruction contains duplicate accounts\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]: \"instruction modifications of multiply-passed account differ\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: \"executable accounts must be rent exempt\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: \"instruction changed executable accounts data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]: \"instruction changed the balance of an executable account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: \"instruction changed executable bit of an account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]: \"instruction modified data of an account it does not own\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]: \"instruction spent from the balance of an account it does not own\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: \"generic instruction error\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: \"Provided owner is not allowed\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: \"Account is immutable\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: \"Incorrect authority provided\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: \"incorrect program id for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: \"insufficient funds for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: \"invalid account data for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: \"Invalid account owner\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: \"invalid program argument\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: \"program returned invalid error code\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: \"invalid instruction data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: \"Failed to reallocate account data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: \"Provided seeds do not result in a valid address\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]: \"Accounts data allocations exceeded the maximum allowed per transaction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: \"Max accounts exceeded\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: \"Max instruction trace length exceeded\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]: \"Length of the seed is too long for address generation\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: \"An account required by the instruction is missing\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: \"missing required signature for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]: \"instruction illegally modified the program id of an account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: \"insufficient account keys for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]: \"Cross-program invocation with unauthorized signer or writable account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]: \"Failed to create program execution environment\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: \"Program failed to compile\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: \"Program failed to complete\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: \"instruction modified data of a read-only account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]: \"instruction changed the balance of a read-only account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]: \"Cross-program invocation reentrancy not allowed for this instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: \"instruction modified rent epoch of an account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]: \"sum of account balances before and after instruction do not match\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: \"instruction requires an initialized account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: \"\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: \"Unsupported program id\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: \"Unsupported sysvar\",\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: \"The instruction does not have any accounts.\",\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: \"The instruction does not have any data.\",\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: \"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.\",\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: \"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.\",\n [SOLANA_ERROR__INVALID_NONCE]: \"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: \"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: \"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]: \"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]: \"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: \"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant\",\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: \"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: \"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: \"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: \"JSON-RPC error: The method does not exist / is not available ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: \"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: \"Minimum context slot has not been reached\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: \"Node is unhealthy; behind by $numSlotsBehind slots\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: \"No snapshot\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: \"Transaction simulation failed\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]: \"Transaction history is not available from this node\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: \"Transaction signature length mismatch\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]: \"Transaction signature verification failure\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: \"$__serverMessage\",\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: \"Key pair bytes must be of length 64, got $byteLength.\",\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: \"Expected private key bytes with length 32. Actual length: $actualLength.\",\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: \"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.\",\n [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]: \"The provided private key does not match the provided public key.\",\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: \"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.\",\n [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: \"Lamports value must be in the range [0, 2e64-1]\",\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: \"`$value` cannot be parsed as a `BigInt`\",\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: \"$message\",\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: \"`$value` cannot be parsed as a `Number`\",\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: \"No nonce account could be found at address `$nonceAccountAddress`\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: \"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]: \"WebSocket was closed before payload could be added to the send buffer\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: \"WebSocket connection closed\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: \"WebSocket failed to connect\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]: \"Failed to obtain a subscription id from the server\",\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: \"Could not find an API plan for RPC method: `$method`\",\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: \"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.\",\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: \"HTTP error ($statusCode): $message\",\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: \"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.\",\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: \"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.\",\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: \"The provided value does not implement the `KeyPairSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: \"The provided value does not implement the `MessageModifyingSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: \"The provided value does not implement the `MessagePartialSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: \"The provided value does not implement any of the `MessageSigner` interfaces\",\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: \"The provided value does not implement the `TransactionModifyingSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: \"The provided value does not implement the `TransactionPartialSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: \"The provided value does not implement the `TransactionSendingSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: \"The provided value does not implement any of the `TransactionSigner` interfaces\",\n [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]: \"More than one `TransactionSendingSigner` was identified.\",\n [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]: \"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.\",\n [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]: \"Wallet account signers do not support signing multiple messages/transactions in a single operation\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: \"Cannot export a non-extractable key.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: \"No digest implementation could be found.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]: \"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]: \"This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\\n\\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]: \"No signature verification implementation could be found.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: \"No key generation implementation could be found.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: \"No signing implementation could be found.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: \"No key export implementation could be found.\",\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: \"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: \"Transaction processing left an account with an outstanding borrowed reference\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: \"Account in use\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: \"Account loaded twice\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]: \"Attempt to debit an account but found no record of a prior credit.\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]: \"Transaction loads an address table account that doesn't exist\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: \"This transaction has already been processed\",\n [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: \"Blockhash not found\",\n [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: \"Loader call chain is too deep\",\n [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]: \"Transactions are currently disabled due to cluster maintenance\",\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: \"Transaction contains a duplicate instruction ($index) that is not allowed\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: \"Insufficient funds for fee\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: \"Transaction results in an account ($accountIndex) with insufficient funds for rent\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: \"This account may not be used to pay transaction fees\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: \"Transaction contains an invalid account reference\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]: \"Transaction loads an address table account with invalid data\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]: \"Transaction address table lookup uses an invalid index\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]: \"Transaction loads an address table account with an invalid owner\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]: \"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]: \"This program may not be used for executing instructions\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]: \"Transaction leaves an account with a lower balance than rent-exempt minimum\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]: \"Transaction loads a writable account that cannot be written\",\n [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]: \"Transaction exceeded max loaded accounts data size cap\",\n [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]: \"Transaction requires a fee but has no signature present\",\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: \"Attempt to load a program that does not exist\",\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: \"Execution of the program referenced by account at index $accountIndex is temporarily restricted.\",\n [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: \"ResanitizationNeeded\",\n [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: \"Transaction failed to sanitize accounts offsets correctly\",\n [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: \"Transaction did not pass signature verification\",\n [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: \"Transaction locked too many accounts\",\n [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]: \"Sum of account balances before and after transaction do not match\",\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: \"The transaction failed with the error `$errorName`\",\n [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: \"Transaction version is unsupported\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]: \"Transaction would exceed account data limit within the block\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]: \"Transaction would exceed total account data limit\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]: \"Transaction would exceed max account limit within the block\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]: \"Transaction would exceed max Block Cost Limit\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: \"Transaction would exceed max Vote Cost Limit\",\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: \"Attempted to sign a transaction with an address that is not a signer for it\",\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: \"Transaction is missing an address at index: $index.\",\n [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]: \"Transaction has no expected signers therefore it cannot be encoded\",\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: \"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes\",\n [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: \"Transaction does not have a blockhash lifetime\",\n [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: \"Transaction is not a durable nonce transaction\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: \"Contents of these address lookup tables unknown: $lookupTableAddresses\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: \"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: \"No fee payer set in CompiledTransaction\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: \"Could not find program address at index $index\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]: \"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more\",\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: \"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more\",\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: \"Transaction is missing a fee payer.\",\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]: \"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.\",\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]: \"Transaction first instruction is not advance nonce account instruction.\",\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]: \"Transaction with no instructions cannot be durable nonce transaction.\",\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: \"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees\",\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: \"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable\",\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: \"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.\",\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: \"Transaction is missing signatures for addresses: $addresses.\",\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: \"Transaction version must be in the range [0, 127]. `$actualVersion` given\"\n};\n\n// src/message-formatter.ts\nvar START_INDEX = \"i\";\nvar TYPE = \"t\";\nfunction getHumanReadableErrorMessage(code, context = {}) {\n const messageFormatString = SolanaErrorMessages[code];\n if (messageFormatString.length === 0) {\n return \"\";\n }\n let state;\n function commitStateUpTo(endIndex) {\n if (state[TYPE] === 2 /* Variable */) {\n const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);\n fragments.push(\n variableName in context ? (\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${context[variableName]}`\n ) : `$${variableName}`\n );\n } else if (state[TYPE] === 1 /* Text */) {\n fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));\n }\n }\n const fragments = [];\n messageFormatString.split(\"\").forEach((char, ii) => {\n if (ii === 0) {\n state = {\n [START_INDEX]: 0,\n [TYPE]: messageFormatString[0] === \"\\\\\" ? 0 /* EscapeSequence */ : messageFormatString[0] === \"$\" ? 2 /* Variable */ : 1 /* Text */\n };\n return;\n }\n let nextState;\n switch (state[TYPE]) {\n case 0 /* EscapeSequence */:\n nextState = { [START_INDEX]: ii, [TYPE]: 1 /* Text */ };\n break;\n case 1 /* Text */:\n if (char === \"\\\\\") {\n nextState = { [START_INDEX]: ii, [TYPE]: 0 /* EscapeSequence */ };\n } else if (char === \"$\") {\n nextState = { [START_INDEX]: ii, [TYPE]: 2 /* Variable */ };\n }\n break;\n case 2 /* Variable */:\n if (char === \"\\\\\") {\n nextState = { [START_INDEX]: ii, [TYPE]: 0 /* EscapeSequence */ };\n } else if (char === \"$\") {\n nextState = { [START_INDEX]: ii, [TYPE]: 2 /* Variable */ };\n } else if (!char.match(/\\w/)) {\n nextState = { [START_INDEX]: ii, [TYPE]: 1 /* Text */ };\n }\n break;\n }\n if (nextState) {\n if (state !== nextState) {\n commitStateUpTo(ii);\n }\n state = nextState;\n }\n });\n commitStateUpTo();\n return fragments.join(\"\");\n}\nfunction getErrorMessage(code, context = {}) {\n if (process.env.NODE_ENV !== \"production\") {\n return getHumanReadableErrorMessage(code, context);\n } else {\n let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \\`npx @solana/errors decode -- ${code}`;\n if (Object.keys(context).length) {\n decodingAdviceMessage += ` '${encodeContextObject(context)}'`;\n }\n return `${decodingAdviceMessage}\\``;\n }\n}\n\n// src/error.ts\nfunction isSolanaError(e, code) {\n const isSolanaError2 = e instanceof Error && e.name === \"SolanaError\";\n if (isSolanaError2) {\n if (code !== void 0) {\n return e.context.__code === code;\n }\n return true;\n }\n return false;\n}\nvar SolanaError = class extends Error {\n /**\n * Indicates the root cause of this {@link SolanaError}, if any.\n *\n * For example, a transaction error might have an instruction error as its root cause. In this\n * case, you will be able to access the instruction error on the transaction error as `cause`.\n */\n cause = this.cause;\n /**\n * Contains context that can assist in understanding or recovering from a {@link SolanaError}.\n */\n context;\n constructor(...[code, contextAndErrorOptions]) {\n let context;\n let errorOptions;\n if (contextAndErrorOptions) {\n const { cause, ...contextRest } = contextAndErrorOptions;\n if (cause) {\n errorOptions = { cause };\n }\n if (Object.keys(contextRest).length > 0) {\n context = contextRest;\n }\n }\n const message = getErrorMessage(code, context);\n super(message, errorOptions);\n this.context = {\n __code: code,\n ...context\n };\n this.name = \"SolanaError\";\n }\n};\n\n// src/stack-trace.ts\nfunction safeCaptureStackTrace(...args) {\n if (\"captureStackTrace\" in Error && typeof Error.captureStackTrace === \"function\") {\n Error.captureStackTrace(...args);\n }\n}\n\n// src/rpc-enum-errors.ts\nfunction getSolanaErrorFromRpcError({ errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }, constructorOpt) {\n let rpcErrorName;\n let rpcErrorContext;\n if (typeof rpcEnumError === \"string\") {\n rpcErrorName = rpcEnumError;\n } else {\n rpcErrorName = Object.keys(rpcEnumError)[0];\n rpcErrorContext = rpcEnumError[rpcErrorName];\n }\n const codeOffset = orderedErrorNames.indexOf(rpcErrorName);\n const errorCode = errorCodeBaseOffset + codeOffset;\n const errorContext = getErrorContext(errorCode, rpcErrorName, rpcErrorContext);\n const err = new SolanaError(errorCode, errorContext);\n safeCaptureStackTrace(err, constructorOpt);\n return err;\n}\n\n// src/instruction-error.ts\nvar ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/program/src/instruction.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n \"GenericError\",\n \"InvalidArgument\",\n \"InvalidInstructionData\",\n \"InvalidAccountData\",\n \"AccountDataTooSmall\",\n \"InsufficientFunds\",\n \"IncorrectProgramId\",\n \"MissingRequiredSignature\",\n \"AccountAlreadyInitialized\",\n \"UninitializedAccount\",\n \"UnbalancedInstruction\",\n \"ModifiedProgramId\",\n \"ExternalAccountLamportSpend\",\n \"ExternalAccountDataModified\",\n \"ReadonlyLamportChange\",\n \"ReadonlyDataModified\",\n \"DuplicateAccountIndex\",\n \"ExecutableModified\",\n \"RentEpochModified\",\n \"NotEnoughAccountKeys\",\n \"AccountDataSizeChanged\",\n \"AccountNotExecutable\",\n \"AccountBorrowFailed\",\n \"AccountBorrowOutstanding\",\n \"DuplicateAccountOutOfSync\",\n \"Custom\",\n \"InvalidError\",\n \"ExecutableDataModified\",\n \"ExecutableLamportChange\",\n \"ExecutableAccountNotRentExempt\",\n \"UnsupportedProgramId\",\n \"CallDepth\",\n \"MissingAccount\",\n \"ReentrancyNotAllowed\",\n \"MaxSeedLengthExceeded\",\n \"InvalidSeeds\",\n \"InvalidRealloc\",\n \"ComputationalBudgetExceeded\",\n \"PrivilegeEscalation\",\n \"ProgramEnvironmentSetupFailure\",\n \"ProgramFailedToComplete\",\n \"ProgramFailedToCompile\",\n \"Immutable\",\n \"IncorrectAuthority\",\n \"BorshIoError\",\n \"AccountNotRentExempt\",\n \"InvalidAccountOwner\",\n \"ArithmeticOverflow\",\n \"UnsupportedSysvar\",\n \"IllegalOwner\",\n \"MaxAccountsDataAllocationsExceeded\",\n \"MaxAccountsExceeded\",\n \"MaxInstructionTraceLengthExceeded\",\n \"BuiltinProgramsMustConsumeComputeUnits\"\n];\nfunction getSolanaErrorFromInstructionError(index, instructionError) {\n const numberIndex = Number(index);\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 4615001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n index: numberIndex,\n ...rpcErrorContext !== void 0 ? { instructionErrorContext: rpcErrorContext } : null\n };\n } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) {\n return {\n code: Number(rpcErrorContext),\n index: numberIndex\n };\n } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR) {\n return {\n encodedData: rpcErrorContext,\n index: numberIndex\n };\n }\n return { index: numberIndex };\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: instructionError\n },\n getSolanaErrorFromInstructionError\n );\n}\n\n// src/transaction-error.ts\nvar ORDERED_ERROR_NAMES2 = [\n // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/src/transaction/error.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n \"AccountInUse\",\n \"AccountLoadedTwice\",\n \"AccountNotFound\",\n \"ProgramAccountNotFound\",\n \"InsufficientFundsForFee\",\n \"InvalidAccountForFee\",\n \"AlreadyProcessed\",\n \"BlockhashNotFound\",\n // `InstructionError` intentionally omitted; delegated to `getSolanaErrorFromInstructionError`\n \"CallChainTooDeep\",\n \"MissingSignatureForFee\",\n \"InvalidAccountIndex\",\n \"SignatureFailure\",\n \"InvalidProgramForExecution\",\n \"SanitizeFailure\",\n \"ClusterMaintenance\",\n \"AccountBorrowOutstanding\",\n \"WouldExceedMaxBlockCostLimit\",\n \"UnsupportedVersion\",\n \"InvalidWritableAccount\",\n \"WouldExceedMaxAccountCostLimit\",\n \"WouldExceedAccountDataBlockLimit\",\n \"TooManyAccountLocks\",\n \"AddressLookupTableNotFound\",\n \"InvalidAddressLookupTableOwner\",\n \"InvalidAddressLookupTableData\",\n \"InvalidAddressLookupTableIndex\",\n \"InvalidRentPayingAccount\",\n \"WouldExceedMaxVoteCostLimit\",\n \"WouldExceedAccountDataTotalLimit\",\n \"DuplicateInstruction\",\n \"InsufficientFundsForRent\",\n \"MaxLoadedAccountsDataSizeExceeded\",\n \"InvalidLoadedAccountsDataSizeLimit\",\n \"ResanitizationNeeded\",\n \"ProgramExecutionTemporarilyRestricted\",\n \"UnbalancedTransaction\"\n];\nfunction getSolanaErrorFromTransactionError(transactionError) {\n if (typeof transactionError === \"object\" && \"InstructionError\" in transactionError) {\n return getSolanaErrorFromInstructionError(\n ...transactionError.InstructionError\n );\n }\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 7050001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n ...rpcErrorContext !== void 0 ? { transactionErrorContext: rpcErrorContext } : null\n };\n } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) {\n return {\n index: Number(rpcErrorContext)\n };\n } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT || errorCode === SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED) {\n return {\n accountIndex: Number(rpcErrorContext.account_index)\n };\n }\n },\n orderedErrorNames: ORDERED_ERROR_NAMES2,\n rpcEnumError: transactionError\n },\n getSolanaErrorFromTransactionError\n );\n}\n\n// src/json-rpc-error.ts\nfunction getSolanaErrorFromJsonRpcError(putativeErrorResponse) {\n let out;\n if (isRpcErrorResponse(putativeErrorResponse)) {\n const { code: rawCode, data, message } = putativeErrorResponse;\n const code = Number(rawCode);\n if (code === SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) {\n const { err, ...preflightErrorContext } = data;\n const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null;\n out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, {\n ...preflightErrorContext,\n ...causeObject\n });\n } else {\n let errorContext;\n switch (code) {\n case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:\n case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:\n case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:\n case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:\n case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:\n case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:\n errorContext = { __serverMessage: message };\n break;\n default:\n if (typeof data === \"object\" && !Array.isArray(data)) {\n errorContext = data;\n }\n }\n out = new SolanaError(code, errorContext);\n }\n } else {\n const message = typeof putativeErrorResponse === \"object\" && putativeErrorResponse !== null && \"message\" in putativeErrorResponse && typeof putativeErrorResponse.message === \"string\" ? putativeErrorResponse.message : \"Malformed JSON-RPC error with no message attribute\";\n out = new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, { error: putativeErrorResponse, message });\n }\n safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError);\n return out;\n}\nfunction isRpcErrorResponse(value) {\n return typeof value === \"object\" && value !== null && \"code\" in value && \"message\" in value && (typeof value.code === \"number\" || typeof value.code === \"bigint\") && typeof value.message === \"string\";\n}\n\nexport { SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED, SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT, SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT, SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND, SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED, SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE, SOLANA_ERROR__ADDRESSES__MALFORMED_PDA, SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH, SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE, SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE, SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, SOLANA_ERROR__CODECS__INVALID_CONSTANT, SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT, SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT, SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE, SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT, SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW, SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR, SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS, SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH, SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX, SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND, SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR, SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER, SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE, SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY, SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID, SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT, SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE, SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID, SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS, SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION, SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE, SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE, SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE, SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE, SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED, SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION, SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT, SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN, SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID, SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR, SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS, SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA, SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH, SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING, SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING, SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR, SOLANA_ERROR__JSON_RPC__INVALID_PARAMS, SOLANA_ERROR__JSON_RPC__INVALID_REQUEST, SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND, SOLANA_ERROR__JSON_RPC__PARSE_ERROR, SOLANA_ERROR__JSON_RPC__SCAN_ERROR, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION, SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH, SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY, SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE, SOLANA_ERROR__MALFORMED_BIGINT_STRING, SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, SOLANA_ERROR__MALFORMED_NUMBER_STRING, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID, SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS, SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING, SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT, SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED, SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP, SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE, SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT, SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED, SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE, SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED, SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED, SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE, SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE, SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS, SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION, SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN, SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT, SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING, SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME, SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT, SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT, SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING, SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE, SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING, SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, SolanaError, getSolanaErrorFromInstructionError, getSolanaErrorFromJsonRpcError, getSolanaErrorFromTransactionError, isSolanaError, safeCaptureStackTrace };\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map","import { SolanaError, SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH, SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL } from '@solana/errors';\n\n// src/add-codec-sentinel.ts\n\n// src/bytes.ts\nvar mergeBytes = (byteArrays) => {\n const nonEmptyByteArrays = byteArrays.filter((arr) => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach((arr) => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\nvar padBytes = (bytes, length) => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\nvar fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\nfunction containsBytes(data, bytes, offset) {\n const slice = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length);\n if (slice.length !== bytes.length) return false;\n return bytes.every((b, i) => b === slice[i]);\n}\nfunction getEncodedSize(value, encoder) {\n return \"fixedSize\" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\nfunction createEncoder(encoder) {\n return Object.freeze({\n ...encoder,\n encode: (value) => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n }\n });\n}\nfunction createDecoder(decoder) {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]\n });\n}\nfunction createCodec(codec) {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: (value) => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n }\n });\n}\nfunction isFixedSize(codec) {\n return \"fixedSize\" in codec && typeof codec.fixedSize === \"number\";\n}\nfunction assertIsFixedSize(codec) {\n if (!isFixedSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);\n }\n}\nfunction isVariableSize(codec) {\n return !isFixedSize(codec);\n}\nfunction assertIsVariableSize(codec) {\n if (!isVariableSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);\n }\n}\nfunction combineCodec(encoder, decoder) {\n if (isFixedSize(encoder) !== isFixedSize(decoder)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH);\n }\n if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, {\n decoderFixedSize: decoder.fixedSize,\n encoderFixedSize: encoder.fixedSize\n });\n }\n if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, {\n decoderMaxSize: decoder.maxSize,\n encoderMaxSize: encoder.maxSize\n });\n }\n return {\n ...decoder,\n ...encoder,\n decode: decoder.decode,\n encode: encoder.encode,\n read: decoder.read,\n write: encoder.write\n };\n}\n\n// src/add-codec-sentinel.ts\nfunction addEncoderSentinel(encoder, sentinel) {\n const write = (value, bytes, offset) => {\n const encoderBytes = encoder.encode(value);\n if (findSentinelIndex(encoderBytes, sentinel) >= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, {\n encodedBytes: encoderBytes,\n hexEncodedBytes: hexBytes(encoderBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel\n });\n }\n bytes.set(encoderBytes, offset);\n offset += encoderBytes.length;\n bytes.set(sentinel, offset);\n offset += sentinel.length;\n return offset;\n };\n if (isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: encoder.fixedSize + sentinel.length, write });\n }\n return createEncoder({\n ...encoder,\n ...encoder.maxSize != null ? { maxSize: encoder.maxSize + sentinel.length } : {},\n getSizeFromValue: (value) => encoder.getSizeFromValue(value) + sentinel.length,\n write\n });\n}\nfunction addDecoderSentinel(decoder, sentinel) {\n const read = (bytes, offset) => {\n const candidateBytes = offset === 0 ? bytes : bytes.slice(offset);\n const sentinelIndex = findSentinelIndex(candidateBytes, sentinel);\n if (sentinelIndex === -1) {\n throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, {\n decodedBytes: candidateBytes,\n hexDecodedBytes: hexBytes(candidateBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel\n });\n }\n const preSentinelBytes = candidateBytes.slice(0, sentinelIndex);\n return [decoder.decode(preSentinelBytes), offset + preSentinelBytes.length + sentinel.length];\n };\n if (isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: decoder.fixedSize + sentinel.length, read });\n }\n return createDecoder({\n ...decoder,\n ...decoder.maxSize != null ? { maxSize: decoder.maxSize + sentinel.length } : {},\n read\n });\n}\nfunction addCodecSentinel(codec, sentinel) {\n return combineCodec(addEncoderSentinel(codec, sentinel), addDecoderSentinel(codec, sentinel));\n}\nfunction findSentinelIndex(bytes, sentinel) {\n return bytes.findIndex((byte, index, arr) => {\n if (sentinel.length === 1) return byte === sentinel[0];\n return containsBytes(arr, sentinel, index);\n });\n}\nfunction hexBytes(bytes) {\n return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, \"0\"), \"\");\n}\nfunction assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {\n if (bytes.length - offset <= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, {\n codecDescription\n });\n }\n}\nfunction assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {\n bytesLength,\n codecDescription,\n expected\n });\n }\n}\nfunction assertByteArrayOffsetIsNotOutOfRange(codecDescription, offset, bytesLength) {\n if (offset < 0 || offset > bytesLength) {\n throw new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, {\n bytesLength,\n codecDescription,\n offset\n });\n }\n}\n\n// src/add-codec-size-prefix.ts\nfunction addEncoderSizePrefix(encoder, prefix) {\n const write = (value, bytes, offset) => {\n const encoderBytes = encoder.encode(value);\n offset = prefix.write(encoderBytes.length, bytes, offset);\n bytes.set(encoderBytes, offset);\n return offset + encoderBytes.length;\n };\n if (isFixedSize(prefix) && isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });\n }\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;\n const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : encoder.maxSize ?? null;\n const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;\n return createEncoder({\n ...encoder,\n ...maxSize !== null ? { maxSize } : {},\n getSizeFromValue: (value) => {\n const encoderSize = getEncodedSize(value, encoder);\n return getEncodedSize(encoderSize, prefix) + encoderSize;\n },\n write\n });\n}\nfunction addDecoderSizePrefix(decoder, prefix) {\n const read = (bytes, offset) => {\n const [bigintSize, decoderOffset] = prefix.read(bytes, offset);\n const size = Number(bigintSize);\n offset = decoderOffset;\n if (offset > 0 || bytes.length > size) {\n bytes = bytes.slice(offset, offset + size);\n }\n assertByteArrayHasEnoughBytesForCodec(\"addDecoderSizePrefix\", size, bytes);\n return [decoder.decode(bytes), offset + size];\n };\n if (isFixedSize(prefix) && isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });\n }\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;\n const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : decoder.maxSize ?? null;\n const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;\n return createDecoder({ ...decoder, ...maxSize !== null ? { maxSize } : {}, read });\n}\nfunction addCodecSizePrefix(codec, prefix) {\n return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));\n}\n\n// src/fix-codec-size.ts\nfunction fixEncoderSize(encoder, fixedBytes) {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value, bytes, offset) => {\n const variableByteArray = encoder.encode(value);\n const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n }\n });\n}\nfunction fixDecoderSize(decoder, fixedBytes) {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes, offset) => {\n assertByteArrayHasEnoughBytesForCodec(\"fixCodecSize\", fixedBytes, bytes, offset);\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n }\n });\n}\nfunction fixCodecSize(codec, fixedBytes) {\n return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(codec, fixedBytes));\n}\n\n// src/offset-codec.ts\nfunction offsetEncoder(encoder, config) {\n return createEncoder({\n ...encoder,\n write: (value, bytes, preOffset) => {\n const wrapBytes = (offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange(\"offsetEncoder\", newPreOffset, bytes.length);\n const postOffset = encoder.write(value, bytes, newPreOffset);\n const newPostOffset = config.postOffset ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes }) : postOffset;\n assertByteArrayOffsetIsNotOutOfRange(\"offsetEncoder\", newPostOffset, bytes.length);\n return newPostOffset;\n }\n });\n}\nfunction offsetDecoder(decoder, config) {\n return createDecoder({\n ...decoder,\n read: (bytes, preOffset) => {\n const wrapBytes = (offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange(\"offsetDecoder\", newPreOffset, bytes.length);\n const [value, postOffset] = decoder.read(bytes, newPreOffset);\n const newPostOffset = config.postOffset ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes }) : postOffset;\n assertByteArrayOffsetIsNotOutOfRange(\"offsetDecoder\", newPostOffset, bytes.length);\n return [value, newPostOffset];\n }\n });\n}\nfunction offsetCodec(codec, config) {\n return combineCodec(offsetEncoder(codec, config), offsetDecoder(codec, config));\n}\nfunction modulo(dividend, divisor) {\n if (divisor === 0) return 0;\n return (dividend % divisor + divisor) % divisor;\n}\nfunction resizeEncoder(encoder, resize) {\n if (isFixedSize(encoder)) {\n const fixedSize = resize(encoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: \"resizeEncoder\"\n });\n }\n return createEncoder({ ...encoder, fixedSize });\n }\n return createEncoder({\n ...encoder,\n getSizeFromValue: (value) => {\n const newSize = resize(encoder.getSizeFromValue(value));\n if (newSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: newSize,\n codecDescription: \"resizeEncoder\"\n });\n }\n return newSize;\n }\n });\n}\nfunction resizeDecoder(decoder, resize) {\n if (isFixedSize(decoder)) {\n const fixedSize = resize(decoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: \"resizeDecoder\"\n });\n }\n return createDecoder({ ...decoder, fixedSize });\n }\n return decoder;\n}\nfunction resizeCodec(codec, resize) {\n return combineCodec(resizeEncoder(codec, resize), resizeDecoder(codec, resize));\n}\n\n// src/pad-codec.ts\nfunction padLeftEncoder(encoder, offset) {\n return offsetEncoder(\n resizeEncoder(encoder, (size) => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset }\n );\n}\nfunction padRightEncoder(encoder, offset) {\n return offsetEncoder(\n resizeEncoder(encoder, (size) => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset }\n );\n}\nfunction padLeftDecoder(decoder, offset) {\n return offsetDecoder(\n resizeDecoder(decoder, (size) => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset }\n );\n}\nfunction padRightDecoder(decoder, offset) {\n return offsetDecoder(\n resizeDecoder(decoder, (size) => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset }\n );\n}\nfunction padLeftCodec(codec, offset) {\n return combineCodec(padLeftEncoder(codec, offset), padLeftDecoder(codec, offset));\n}\nfunction padRightCodec(codec, offset) {\n return combineCodec(padRightEncoder(codec, offset), padRightDecoder(codec, offset));\n}\n\n// src/reverse-codec.ts\nfunction copySourceToTargetInReverse(source, target_WILL_MUTATE, sourceOffset, sourceLength, targetOffset = 0) {\n while (sourceOffset < --sourceLength) {\n const leftValue = source[sourceOffset];\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceLength];\n target_WILL_MUTATE[sourceLength + targetOffset] = leftValue;\n sourceOffset++;\n }\n if (sourceOffset === sourceLength) {\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceOffset];\n }\n}\nfunction reverseEncoder(encoder) {\n assertIsFixedSize(encoder);\n return createEncoder({\n ...encoder,\n write: (value, bytes, offset) => {\n const newOffset = encoder.write(value, bytes, offset);\n copySourceToTargetInReverse(\n bytes,\n bytes,\n offset,\n offset + encoder.fixedSize\n );\n return newOffset;\n }\n });\n}\nfunction reverseDecoder(decoder) {\n assertIsFixedSize(decoder);\n return createDecoder({\n ...decoder,\n read: (bytes, offset) => {\n const reversedBytes = bytes.slice();\n copySourceToTargetInReverse(\n bytes,\n reversedBytes,\n offset,\n offset + decoder.fixedSize\n );\n return decoder.read(reversedBytes, offset);\n }\n });\n}\nfunction reverseCodec(codec) {\n return combineCodec(reverseEncoder(codec), reverseDecoder(codec));\n}\n\n// src/transform-codec.ts\nfunction transformEncoder(encoder, unmap) {\n return createEncoder({\n ...isVariableSize(encoder) ? { ...encoder, getSizeFromValue: (value) => encoder.getSizeFromValue(unmap(value)) } : encoder,\n write: (value, bytes, offset) => encoder.write(unmap(value), bytes, offset)\n });\n}\nfunction transformDecoder(decoder, map) {\n return createDecoder({\n ...decoder,\n read: (bytes, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n }\n });\n}\nfunction transformCodec(codec, unmap, map) {\n return createCodec({\n ...transformEncoder(codec, unmap),\n read: map ? transformDecoder(codec, map).read : codec.read\n });\n}\n\nexport { addCodecSentinel, addCodecSizePrefix, addDecoderSentinel, addDecoderSizePrefix, addEncoderSentinel, addEncoderSizePrefix, assertByteArrayHasEnoughBytesForCodec, assertByteArrayIsNotEmptyForCodec, assertByteArrayOffsetIsNotOutOfRange, assertIsFixedSize, assertIsVariableSize, combineCodec, containsBytes, createCodec, createDecoder, createEncoder, fixBytes, fixCodecSize, fixDecoderSize, fixEncoderSize, getEncodedSize, isFixedSize, isVariableSize, mergeBytes, offsetCodec, offsetDecoder, offsetEncoder, padBytes, padLeftCodec, padLeftDecoder, padLeftEncoder, padRightCodec, padRightDecoder, padRightEncoder, resizeCodec, resizeDecoder, resizeEncoder, reverseCodec, reverseDecoder, reverseEncoder, transformCodec, transformDecoder, transformEncoder };\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map","import { SolanaError, SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE } from '@solana/errors';\nimport { combineCodec, createDecoder, createEncoder, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';\n\n// src/assertions.ts\nfunction assertNumberIsBetweenForCodec(codecDescription, min, max, value) {\n if (value < min || value > max) {\n throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {\n codecDescription,\n max,\n min,\n value\n });\n }\n}\n\n// src/common.ts\nvar Endian = /* @__PURE__ */ ((Endian2) => {\n Endian2[Endian2[\"Little\"] = 0] = \"Little\";\n Endian2[Endian2[\"Big\"] = 1] = \"Big\";\n return Endian2;\n})(Endian || {});\nfunction isLittleEndian(config) {\n return config?.endian === 1 /* Big */ ? false : true;\n}\nfunction numberEncoderFactory(input) {\n return createEncoder({\n fixedSize: input.size,\n write(value, bytes, offset) {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n }\n });\n}\nfunction numberDecoderFactory(input) {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0) {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n }\n });\n}\nfunction toArrayBuffer(bytes, offset, length) {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n\n// src/f32.ts\nvar getF32Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"f32\",\n set: (view, value, le) => view.setFloat32(0, Number(value), le),\n size: 4\n});\nvar getF32Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: \"f32\",\n size: 4\n});\nvar getF32Codec = (config = {}) => combineCodec(getF32Encoder(config), getF32Decoder(config));\nvar getF64Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"f64\",\n set: (view, value, le) => view.setFloat64(0, Number(value), le),\n size: 8\n});\nvar getF64Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat64(0, le),\n name: \"f64\",\n size: 8\n});\nvar getF64Codec = (config = {}) => combineCodec(getF64Encoder(config), getF64Decoder(config));\nvar getI128Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i128\",\n range: [-BigInt(\"0x7fffffffffffffffffffffffffffffff\") - 1n, BigInt(\"0x7fffffffffffffffffffffffffffffff\")],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16\n});\nvar getI128Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigInt64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: \"i128\",\n size: 16\n});\nvar getI128Codec = (config = {}) => combineCodec(getI128Encoder(config), getI128Decoder(config));\nvar getI16Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i16\",\n range: [-Number(\"0x7fff\") - 1, Number(\"0x7fff\")],\n set: (view, value, le) => view.setInt16(0, Number(value), le),\n size: 2\n});\nvar getI16Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getInt16(0, le),\n name: \"i16\",\n size: 2\n});\nvar getI16Codec = (config = {}) => combineCodec(getI16Encoder(config), getI16Decoder(config));\nvar getI32Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i32\",\n range: [-Number(\"0x7fffffff\") - 1, Number(\"0x7fffffff\")],\n set: (view, value, le) => view.setInt32(0, Number(value), le),\n size: 4\n});\nvar getI32Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getInt32(0, le),\n name: \"i32\",\n size: 4\n});\nvar getI32Codec = (config = {}) => combineCodec(getI32Encoder(config), getI32Decoder(config));\nvar getI64Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i64\",\n range: [-BigInt(\"0x7fffffffffffffff\") - 1n, BigInt(\"0x7fffffffffffffff\")],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8\n});\nvar getI64Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: \"i64\",\n size: 8\n});\nvar getI64Codec = (config = {}) => combineCodec(getI64Encoder(config), getI64Decoder(config));\nvar getI8Encoder = () => numberEncoderFactory({\n name: \"i8\",\n range: [-Number(\"0x7f\") - 1, Number(\"0x7f\")],\n set: (view, value) => view.setInt8(0, Number(value)),\n size: 1\n});\nvar getI8Decoder = () => numberDecoderFactory({\n get: (view) => view.getInt8(0),\n name: \"i8\",\n size: 1\n});\nvar getI8Codec = () => combineCodec(getI8Encoder(), getI8Decoder());\nvar getShortU16Encoder = () => createEncoder({\n getSizeFromValue: (value) => {\n if (value <= 127) return 1;\n if (value <= 16383) return 2;\n return 3;\n },\n maxSize: 3,\n write: (value, bytes, offset) => {\n assertNumberIsBetweenForCodec(\"shortU16\", 0, 65535, value);\n const shortU16Bytes = [0];\n for (let ii = 0; ; ii += 1) {\n const alignedValue = Number(value) >> ii * 7;\n if (alignedValue === 0) {\n break;\n }\n const nextSevenBits = 127 & alignedValue;\n shortU16Bytes[ii] = nextSevenBits;\n if (ii > 0) {\n shortU16Bytes[ii - 1] |= 128;\n }\n }\n bytes.set(shortU16Bytes, offset);\n return offset + shortU16Bytes.length;\n }\n});\nvar getShortU16Decoder = () => createDecoder({\n maxSize: 3,\n read: (bytes, offset) => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 127 & currentByte;\n value |= nextSevenBits << byteIndex * 7;\n if ((currentByte & 128) === 0) {\n break;\n }\n }\n return [value, offset + byteCount];\n }\n});\nvar getShortU16Codec = () => combineCodec(getShortU16Encoder(), getShortU16Decoder());\nvar getU128Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u128\",\n range: [0n, BigInt(\"0xffffffffffffffffffffffffffffffff\")],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16\n});\nvar getU128Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: \"u128\",\n size: 16\n});\nvar getU128Codec = (config = {}) => combineCodec(getU128Encoder(config), getU128Decoder(config));\nvar getU16Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u16\",\n range: [0, Number(\"0xffff\")],\n set: (view, value, le) => view.setUint16(0, Number(value), le),\n size: 2\n});\nvar getU16Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: \"u16\",\n size: 2\n});\nvar getU16Codec = (config = {}) => combineCodec(getU16Encoder(config), getU16Decoder(config));\nvar getU32Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u32\",\n range: [0, Number(\"0xffffffff\")],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n size: 4\n});\nvar getU32Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getUint32(0, le),\n name: \"u32\",\n size: 4\n});\nvar getU32Codec = (config = {}) => combineCodec(getU32Encoder(config), getU32Decoder(config));\nvar getU64Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u64\",\n range: [0n, BigInt(\"0xffffffffffffffff\")],\n set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),\n size: 8\n});\nvar getU64Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getBigUint64(0, le),\n name: \"u64\",\n size: 8\n});\nvar getU64Codec = (config = {}) => combineCodec(getU64Encoder(config), getU64Decoder(config));\nvar getU8Encoder = () => numberEncoderFactory({\n name: \"u8\",\n range: [0, Number(\"0xff\")],\n set: (view, value) => view.setUint8(0, Number(value)),\n size: 1\n});\nvar getU8Decoder = () => numberDecoderFactory({\n get: (view) => view.getUint8(0),\n name: \"u8\",\n size: 1\n});\nvar getU8Codec = () => combineCodec(getU8Encoder(), getU8Decoder());\n\nexport { Endian, assertNumberIsBetweenForCodec, getF32Codec, getF32Decoder, getF32Encoder, getF64Codec, getF64Decoder, getF64Encoder, getI128Codec, getI128Decoder, getI128Encoder, getI16Codec, getI16Decoder, getI16Encoder, getI32Codec, getI32Decoder, getI32Encoder, getI64Codec, getI64Decoder, getI64Encoder, getI8Codec, getI8Decoder, getI8Encoder, getShortU16Codec, getShortU16Decoder, getShortU16Encoder, getU128Codec, getU128Decoder, getU128Encoder, getU16Codec, getU16Decoder, getU16Encoder, getU32Codec, getU32Decoder, getU32Encoder, getU64Codec, getU64Decoder, getU64Encoder, getU8Codec, getU8Decoder, getU8Encoder };\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map","/**\n * A `StructFailure` represents a single specific failure in validation.\n */\n/**\n * `StructError` objects are thrown (or returned) when validation fails.\n *\n * Validation logic is design to exit early for maximum performance. The error\n * represents the first error encountered during validation. For more detail,\n * the `error.failures` property is a generator function that can be run to\n * continue validation and receive all the failures in the data.\n */\nclass StructError extends TypeError {\n constructor(failure, failures) {\n let cached;\n const { message, explanation, ...rest } = failure;\n const { path } = failure;\n const msg = path.length === 0 ? message : `At path: ${path.join('.')} -- ${message}`;\n super(explanation ?? msg);\n if (explanation != null)\n this.cause = msg;\n Object.assign(this, rest);\n this.name = this.constructor.name;\n this.failures = () => {\n return (cached ?? (cached = [failure, ...failures()]));\n };\n }\n}\n\n/**\n * Check if a value is an iterator.\n */\nfunction isIterable(x) {\n return isObject(x) && typeof x[Symbol.iterator] === 'function';\n}\n/**\n * Check if a value is a plain object.\n */\nfunction isObject(x) {\n return typeof x === 'object' && x != null;\n}\n/**\n * Check if a value is a non-array object.\n */\nfunction isNonArrayObject(x) {\n return isObject(x) && !Array.isArray(x);\n}\n/**\n * Check if a value is a plain object.\n */\nfunction isPlainObject(x) {\n if (Object.prototype.toString.call(x) !== '[object Object]') {\n return false;\n }\n const prototype = Object.getPrototypeOf(x);\n return prototype === null || prototype === Object.prototype;\n}\n/**\n * Return a value as a printable string.\n */\nfunction print(value) {\n if (typeof value === 'symbol') {\n return value.toString();\n }\n return typeof value === 'string' ? JSON.stringify(value) : `${value}`;\n}\n/**\n * Shifts (removes and returns) the first value from the `input` iterator.\n * Like `Array.prototype.shift()` but for an `Iterator`.\n */\nfunction shiftIterator(input) {\n const { done, value } = input.next();\n return done ? undefined : value;\n}\n/**\n * Convert a single validation result to a failure.\n */\nfunction toFailure(result, context, struct, value) {\n if (result === true) {\n return;\n }\n else if (result === false) {\n result = {};\n }\n else if (typeof result === 'string') {\n result = { message: result };\n }\n const { path, branch } = context;\n const { type } = struct;\n const { refinement, message = `Expected a value of type \\`${type}\\`${refinement ? ` with refinement \\`${refinement}\\`` : ''}, but received: \\`${print(value)}\\``, } = result;\n return {\n value,\n type,\n refinement,\n key: path[path.length - 1],\n path,\n branch,\n ...result,\n message,\n };\n}\n/**\n * Convert a validation result to an iterable of failures.\n */\nfunction* toFailures(result, context, struct, value) {\n if (!isIterable(result)) {\n result = [result];\n }\n for (const r of result) {\n const failure = toFailure(r, context, struct, value);\n if (failure) {\n yield failure;\n }\n }\n}\n/**\n * Check a value against a struct, traversing deeply into nested values, and\n * returning an iterator of failures or success.\n */\nfunction* run(value, struct, options = {}) {\n const { path = [], branch = [value], coerce = false, mask = false } = options;\n const ctx = { path, branch, mask };\n if (coerce) {\n value = struct.coercer(value, ctx);\n }\n let status = 'valid';\n for (const failure of struct.validator(value, ctx)) {\n failure.explanation = options.message;\n status = 'not_valid';\n yield [failure, undefined];\n }\n for (let [k, v, s] of struct.entries(value, ctx)) {\n const ts = run(v, s, {\n path: k === undefined ? path : [...path, k],\n branch: k === undefined ? branch : [...branch, v],\n coerce,\n mask,\n message: options.message,\n });\n for (const t of ts) {\n if (t[0]) {\n status = t[0].refinement != null ? 'not_refined' : 'not_valid';\n yield [t[0], undefined];\n }\n else if (coerce) {\n v = t[1];\n if (k === undefined) {\n value = v;\n }\n else if (value instanceof Map) {\n value.set(k, v);\n }\n else if (value instanceof Set) {\n value.add(v);\n }\n else if (isObject(value)) {\n if (v !== undefined || k in value)\n value[k] = v;\n }\n }\n }\n }\n if (status !== 'not_valid') {\n for (const failure of struct.refiner(value, ctx)) {\n failure.explanation = options.message;\n status = 'not_refined';\n yield [failure, undefined];\n }\n }\n if (status === 'valid') {\n yield [undefined, value];\n }\n}\n\n/**\n * `Struct` objects encapsulate the validation logic for a specific type of\n * values. Once constructed, you use the `assert`, `is` or `validate` helpers to\n * validate unknown input data against the struct.\n */\nclass Struct {\n constructor(props) {\n const { type, schema, validator, refiner, coercer = (value) => value, entries = function* () { }, } = props;\n this.type = type;\n this.schema = schema;\n this.entries = entries;\n this.coercer = coercer;\n if (validator) {\n this.validator = (value, context) => {\n const result = validator(value, context);\n return toFailures(result, context, this, value);\n };\n }\n else {\n this.validator = () => [];\n }\n if (refiner) {\n this.refiner = (value, context) => {\n const result = refiner(value, context);\n return toFailures(result, context, this, value);\n };\n }\n else {\n this.refiner = () => [];\n }\n }\n /**\n * Assert that a value passes the struct's validation, throwing if it doesn't.\n */\n assert(value, message) {\n return assert(value, this, message);\n }\n /**\n * Create a value with the struct's coercion logic, then validate it.\n */\n create(value, message) {\n return create(value, this, message);\n }\n /**\n * Check if a value passes the struct's validation.\n */\n is(value) {\n return is(value, this);\n }\n /**\n * Mask a value, coercing and validating it, but returning only the subset of\n * properties defined by the struct's schema. Masking applies recursively to\n * props of `object` structs only.\n */\n mask(value, message) {\n return mask(value, this, message);\n }\n /**\n * Validate a value with the struct's validation logic, returning a tuple\n * representing the result.\n *\n * You may optionally pass `true` for the `coerce` argument to coerce\n * the value before attempting to validate it. If you do, the result will\n * contain the coerced result when successful. Also, `mask` will turn on\n * masking of the unknown `object` props recursively if passed.\n */\n validate(value, options = {}) {\n return validate(value, this, options);\n }\n}\n/**\n * Assert that a value passes a struct, throwing if it doesn't.\n */\nfunction assert(value, struct, message) {\n const result = validate(value, struct, { message });\n if (result[0]) {\n throw result[0];\n }\n}\n/**\n * Create a value with the coercion logic of struct and validate it.\n */\nfunction create(value, struct, message) {\n const result = validate(value, struct, { coerce: true, message });\n if (result[0]) {\n throw result[0];\n }\n else {\n return result[1];\n }\n}\n/**\n * Mask a value, returning only the subset of properties defined by a struct.\n */\nfunction mask(value, struct, message) {\n const result = validate(value, struct, { coerce: true, mask: true, message });\n if (result[0]) {\n throw result[0];\n }\n else {\n return result[1];\n }\n}\n/**\n * Check if a value passes a struct.\n */\nfunction is(value, struct) {\n const result = validate(value, struct);\n return !result[0];\n}\n/**\n * Validate a value against a struct, returning an error if invalid, or the\n * value (with potential coercion) if valid.\n */\nfunction validate(value, struct, options = {}) {\n const tuples = run(value, struct, options);\n const tuple = shiftIterator(tuples);\n if (tuple[0]) {\n const error = new StructError(tuple[0], function* () {\n for (const t of tuples) {\n if (t[0]) {\n yield t[0];\n }\n }\n });\n return [error, undefined];\n }\n else {\n const v = tuple[1];\n return [undefined, v];\n }\n}\n\nfunction assign(...Structs) {\n const isType = Structs[0].type === 'type';\n const schemas = Structs.map((s) => s.schema);\n const schema = Object.assign({}, ...schemas);\n return isType ? type(schema) : object(schema);\n}\n/**\n * Define a new struct type with a custom validation function.\n */\nfunction define(name, validator) {\n return new Struct({ type: name, schema: null, validator });\n}\n/**\n * Create a new struct based on an existing struct, but the value is allowed to\n * be `undefined`. `log` will be called if the value is not `undefined`.\n */\nfunction deprecated(struct, log) {\n return new Struct({\n ...struct,\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx),\n validator(value, ctx) {\n if (value === undefined) {\n return true;\n }\n else {\n log(value, ctx);\n return struct.validator(value, ctx);\n }\n },\n });\n}\n/**\n * Create a struct with dynamic validation logic.\n *\n * The callback will receive the value currently being validated, and must\n * return a struct object to validate it with. This can be useful to model\n * validation logic that changes based on its input.\n */\nfunction dynamic(fn) {\n return new Struct({\n type: 'dynamic',\n schema: null,\n *entries(value, ctx) {\n const struct = fn(value, ctx);\n yield* struct.entries(value, ctx);\n },\n validator(value, ctx) {\n const struct = fn(value, ctx);\n return struct.validator(value, ctx);\n },\n coercer(value, ctx) {\n const struct = fn(value, ctx);\n return struct.coercer(value, ctx);\n },\n refiner(value, ctx) {\n const struct = fn(value, ctx);\n return struct.refiner(value, ctx);\n },\n });\n}\n/**\n * Create a struct with lazily evaluated validation logic.\n *\n * The first time validation is run with the struct, the callback will be called\n * and must return a struct object to use. This is useful for cases where you\n * want to have self-referential structs for nested data structures to avoid a\n * circular definition problem.\n */\nfunction lazy(fn) {\n let struct;\n return new Struct({\n type: 'lazy',\n schema: null,\n *entries(value, ctx) {\n struct ?? (struct = fn());\n yield* struct.entries(value, ctx);\n },\n validator(value, ctx) {\n struct ?? (struct = fn());\n return struct.validator(value, ctx);\n },\n coercer(value, ctx) {\n struct ?? (struct = fn());\n return struct.coercer(value, ctx);\n },\n refiner(value, ctx) {\n struct ?? (struct = fn());\n return struct.refiner(value, ctx);\n },\n });\n}\n/**\n * Create a new struct based on an existing object struct, but excluding\n * specific properties.\n *\n * Like TypeScript's `Omit` utility.\n */\nfunction omit(struct, keys) {\n const { schema } = struct;\n const subschema = { ...schema };\n for (const key of keys) {\n delete subschema[key];\n }\n switch (struct.type) {\n case 'type':\n return type(subschema);\n default:\n return object(subschema);\n }\n}\n/**\n * Create a new struct based on an existing object struct, but with all of its\n * properties allowed to be `undefined`.\n *\n * Like TypeScript's `Partial` utility.\n */\nfunction partial(struct) {\n const isStruct = struct instanceof Struct;\n const schema = isStruct ? { ...struct.schema } : { ...struct };\n for (const key in schema) {\n schema[key] = optional(schema[key]);\n }\n if (isStruct && struct.type === 'type') {\n return type(schema);\n }\n return object(schema);\n}\n/**\n * Create a new struct based on an existing object struct, but only including\n * specific properties.\n *\n * Like TypeScript's `Pick` utility.\n */\nfunction pick(struct, keys) {\n const { schema } = struct;\n const subschema = {};\n for (const key of keys) {\n subschema[key] = schema[key];\n }\n switch (struct.type) {\n case 'type':\n return type(subschema);\n default:\n return object(subschema);\n }\n}\n/**\n * Define a new struct type with a custom validation function.\n *\n * @deprecated This function has been renamed to `define`.\n */\nfunction struct(name, validator) {\n console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.');\n return define(name, validator);\n}\n\n/**\n * Ensure that any value passes validation.\n */\nfunction any() {\n return define('any', () => true);\n}\nfunction array(Element) {\n return new Struct({\n type: 'array',\n schema: Element,\n *entries(value) {\n if (Element && Array.isArray(value)) {\n for (const [i, v] of value.entries()) {\n yield [i, v, Element];\n }\n }\n },\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n validator(value) {\n return (Array.isArray(value) ||\n `Expected an array value, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a bigint.\n */\nfunction bigint() {\n return define('bigint', (value) => {\n return typeof value === 'bigint';\n });\n}\n/**\n * Ensure that a value is a boolean.\n */\nfunction boolean() {\n return define('boolean', (value) => {\n return typeof value === 'boolean';\n });\n}\n/**\n * Ensure that a value is a valid `Date`.\n *\n * Note: this also ensures that the value is *not* an invalid `Date` object,\n * which can occur when parsing a date fails but still returns a `Date`.\n */\nfunction date() {\n return define('date', (value) => {\n return ((value instanceof Date && !isNaN(value.getTime())) ||\n `Expected a valid \\`Date\\` object, but received: ${print(value)}`);\n });\n}\nfunction enums(values) {\n const schema = {};\n const description = values.map((v) => print(v)).join();\n for (const key of values) {\n schema[key] = key;\n }\n return new Struct({\n type: 'enums',\n schema,\n validator(value) {\n return (values.includes(value) ||\n `Expected one of \\`${description}\\`, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a function.\n */\nfunction func() {\n return define('func', (value) => {\n return (typeof value === 'function' ||\n `Expected a function, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is an instance of a specific class.\n */\nfunction instance(Class) {\n return define('instance', (value) => {\n return (value instanceof Class ||\n `Expected a \\`${Class.name}\\` instance, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is an integer.\n */\nfunction integer() {\n return define('integer', (value) => {\n return ((typeof value === 'number' && !isNaN(value) && Number.isInteger(value)) ||\n `Expected an integer, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value matches all of a set of types.\n */\nfunction intersection(Structs) {\n return new Struct({\n type: 'intersection',\n schema: null,\n *entries(value, ctx) {\n for (const S of Structs) {\n yield* S.entries(value, ctx);\n }\n },\n *validator(value, ctx) {\n for (const S of Structs) {\n yield* S.validator(value, ctx);\n }\n },\n *refiner(value, ctx) {\n for (const S of Structs) {\n yield* S.refiner(value, ctx);\n }\n },\n });\n}\nfunction literal(constant) {\n const description = print(constant);\n const t = typeof constant;\n return new Struct({\n type: 'literal',\n schema: t === 'string' || t === 'number' || t === 'boolean' ? constant : null,\n validator(value) {\n return (value === constant ||\n `Expected the literal \\`${description}\\`, but received: ${print(value)}`);\n },\n });\n}\nfunction map(Key, Value) {\n return new Struct({\n type: 'map',\n schema: null,\n *entries(value) {\n if (Key && Value && value instanceof Map) {\n for (const [k, v] of value.entries()) {\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n coercer(value) {\n return value instanceof Map ? new Map(value) : value;\n },\n validator(value) {\n return (value instanceof Map ||\n `Expected a \\`Map\\` object, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that no value ever passes validation.\n */\nfunction never() {\n return define('never', () => false);\n}\n/**\n * Augment an existing struct to allow `null` values.\n */\nfunction nullable(struct) {\n return new Struct({\n ...struct,\n validator: (value, ctx) => value === null || struct.validator(value, ctx),\n refiner: (value, ctx) => value === null || struct.refiner(value, ctx),\n });\n}\n/**\n * Ensure that a value is a number.\n */\nfunction number() {\n return define('number', (value) => {\n return ((typeof value === 'number' && !isNaN(value)) ||\n `Expected a number, but received: ${print(value)}`);\n });\n}\nfunction object(schema) {\n const knowns = schema ? Object.keys(schema) : [];\n const Never = never();\n return new Struct({\n type: 'object',\n schema: schema ? schema : null,\n *entries(value) {\n if (schema && isObject(value)) {\n const unknowns = new Set(Object.keys(value));\n for (const key of knowns) {\n unknowns.delete(key);\n yield [key, value[key], schema[key]];\n }\n for (const key of unknowns) {\n yield [key, value[key], Never];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value, ctx) {\n if (!isNonArrayObject(value)) {\n return value;\n }\n const coerced = { ...value };\n // The `object` struct has special behaviour enabled by the mask flag.\n // When masking, properties that are not in the schema are deleted from\n // the coerced object instead of eventually failing validaiton.\n if (ctx.mask && schema) {\n for (const key in coerced) {\n if (schema[key] === undefined) {\n delete coerced[key];\n }\n }\n }\n return coerced;\n },\n });\n}\n/**\n * Augment a struct to allow `undefined` values.\n */\nfunction optional(struct) {\n return new Struct({\n ...struct,\n validator: (value, ctx) => value === undefined || struct.validator(value, ctx),\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx),\n });\n}\n/**\n * Ensure that a value is an object with keys and values of specific types, but\n * without ensuring any specific shape of properties.\n *\n * Like TypeScript's `Record` utility.\n */\nfunction record(Key, Value) {\n return new Struct({\n type: 'record',\n schema: null,\n *entries(value) {\n if (isObject(value)) {\n for (const k in value) {\n const v = value[k];\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value) {\n return isNonArrayObject(value) ? { ...value } : value;\n },\n });\n}\n/**\n * Ensure that a value is a `RegExp`.\n *\n * Note: this does not test the value against the regular expression! For that\n * you need to use the `pattern()` refinement.\n */\nfunction regexp() {\n return define('regexp', (value) => {\n return value instanceof RegExp;\n });\n}\nfunction set(Element) {\n return new Struct({\n type: 'set',\n schema: null,\n *entries(value) {\n if (Element && value instanceof Set) {\n for (const v of value) {\n yield [v, v, Element];\n }\n }\n },\n coercer(value) {\n return value instanceof Set ? new Set(value) : value;\n },\n validator(value) {\n return (value instanceof Set ||\n `Expected a \\`Set\\` object, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a string.\n */\nfunction string() {\n return define('string', (value) => {\n return (typeof value === 'string' ||\n `Expected a string, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is a tuple of a specific length, and that each of its\n * elements is of a specific type.\n */\nfunction tuple(Structs) {\n const Never = never();\n return new Struct({\n type: 'tuple',\n schema: null,\n *entries(value) {\n if (Array.isArray(value)) {\n const length = Math.max(Structs.length, value.length);\n for (let i = 0; i < length; i++) {\n yield [i, value[i], Structs[i] || Never];\n }\n }\n },\n validator(value) {\n return (Array.isArray(value) ||\n `Expected an array, but received: ${print(value)}`);\n },\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n });\n}\n/**\n * Ensure that a value has a set of known properties of specific types.\n *\n * Note: Unrecognized properties are allowed and untouched. This is similar to\n * how TypeScript's structural typing works.\n */\nfunction type(schema) {\n const keys = Object.keys(schema);\n return new Struct({\n type: 'type',\n schema,\n *entries(value) {\n if (isObject(value)) {\n for (const k of keys) {\n yield [k, value[k], schema[k]];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value) {\n return isNonArrayObject(value) ? { ...value } : value;\n },\n });\n}\n/**\n * Ensure that a value matches one of a set of types.\n */\nfunction union(Structs) {\n const description = Structs.map((s) => s.type).join(' | ');\n return new Struct({\n type: 'union',\n schema: null,\n coercer(value, ctx) {\n for (const S of Structs) {\n const [error, coerced] = S.validate(value, {\n coerce: true,\n mask: ctx.mask,\n });\n if (!error) {\n return coerced;\n }\n }\n return value;\n },\n validator(value, ctx) {\n const failures = [];\n for (const S of Structs) {\n const [...tuples] = run(value, S, ctx);\n const [first] = tuples;\n if (!first[0]) {\n return [];\n }\n else {\n for (const [failure] of tuples) {\n if (failure) {\n failures.push(failure);\n }\n }\n }\n }\n return [\n `Expected the value to satisfy a union of \\`${description}\\`, but received: ${print(value)}`,\n ...failures,\n ];\n },\n });\n}\n/**\n * Ensure that any value passes validation, without widening its type to `any`.\n */\nfunction unknown() {\n return define('unknown', () => true);\n}\n\n/**\n * Augment a `Struct` to add an additional coercion step to its input.\n *\n * This allows you to transform input data before validating it, to increase the\n * likelihood that it passes validation—for example for default values, parsing\n * different formats, etc.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction coerce(struct, condition, coercer) {\n return new Struct({\n ...struct,\n coercer: (value, ctx) => {\n return is(value, condition)\n ? struct.coercer(coercer(value, ctx), ctx)\n : struct.coercer(value, ctx);\n },\n });\n}\n/**\n * Augment a struct to replace `undefined` values with a default.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction defaulted(struct, fallback, options = {}) {\n return coerce(struct, unknown(), (x) => {\n const f = typeof fallback === 'function' ? fallback() : fallback;\n if (x === undefined) {\n return f;\n }\n if (!options.strict && isPlainObject(x) && isPlainObject(f)) {\n const ret = { ...x };\n let changed = false;\n for (const key in f) {\n if (ret[key] === undefined) {\n ret[key] = f[key];\n changed = true;\n }\n }\n if (changed) {\n return ret;\n }\n }\n return x;\n });\n}\n/**\n * Augment a struct to trim string inputs.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction trimmed(struct) {\n return coerce(struct, string(), (x) => x.trim());\n}\n\n/**\n * Ensure that a string, array, map, or set is empty.\n */\nfunction empty(struct) {\n return refine(struct, 'empty', (value) => {\n const size = getSize(value);\n return (size === 0 ||\n `Expected an empty ${struct.type} but received one with a size of \\`${size}\\``);\n });\n}\nfunction getSize(value) {\n if (value instanceof Map || value instanceof Set) {\n return value.size;\n }\n else {\n return value.length;\n }\n}\n/**\n * Ensure that a number or date is below a threshold.\n */\nfunction max(struct, threshold, options = {}) {\n const { exclusive } = options;\n return refine(struct, 'max', (value) => {\n return exclusive\n ? value < threshold\n : value <= threshold ||\n `Expected a ${struct.type} less than ${exclusive ? '' : 'or equal to '}${threshold} but received \\`${value}\\``;\n });\n}\n/**\n * Ensure that a number or date is above a threshold.\n */\nfunction min(struct, threshold, options = {}) {\n const { exclusive } = options;\n return refine(struct, 'min', (value) => {\n return exclusive\n ? value > threshold\n : value >= threshold ||\n `Expected a ${struct.type} greater than ${exclusive ? '' : 'or equal to '}${threshold} but received \\`${value}\\``;\n });\n}\n/**\n * Ensure that a string, array, map or set is not empty.\n */\nfunction nonempty(struct) {\n return refine(struct, 'nonempty', (value) => {\n const size = getSize(value);\n return (size > 0 || `Expected a nonempty ${struct.type} but received an empty one`);\n });\n}\n/**\n * Ensure that a string matches a regular expression.\n */\nfunction pattern(struct, regexp) {\n return refine(struct, 'pattern', (value) => {\n return (regexp.test(value) ||\n `Expected a ${struct.type} matching \\`/${regexp.source}/\\` but received \"${value}\"`);\n });\n}\n/**\n * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`.\n */\nfunction size(struct, min, max = min) {\n const expected = `Expected a ${struct.type}`;\n const of = min === max ? `of \\`${min}\\`` : `between \\`${min}\\` and \\`${max}\\``;\n return refine(struct, 'size', (value) => {\n if (typeof value === 'number' || value instanceof Date) {\n return ((min <= value && value <= max) ||\n `${expected} ${of} but received \\`${value}\\``);\n }\n else if (value instanceof Map || value instanceof Set) {\n const { size } = value;\n return ((min <= size && size <= max) ||\n `${expected} with a size ${of} but received one with a size of \\`${size}\\``);\n }\n else {\n const { length } = value;\n return ((min <= length && length <= max) ||\n `${expected} with a length ${of} but received one with a length of \\`${length}\\``);\n }\n });\n}\n/**\n * Augment a `Struct` to add an additional refinement to the validation.\n *\n * The refiner function is guaranteed to receive a value of the struct's type,\n * because the struct's existing validation will already have passed. This\n * allows you to layer additional validation on top of existing structs.\n */\nfunction refine(struct, name, refiner) {\n return new Struct({\n ...struct,\n *refiner(value, ctx) {\n yield* struct.refiner(value, ctx);\n const result = refiner(value, ctx);\n const failures = toFailures(result, ctx, struct, value);\n for (const failure of failures) {\n yield { ...failure, refinement: name };\n }\n },\n });\n}\n\nexport { Struct, StructError, any, array, assert, assign, bigint, boolean, coerce, create, date, defaulted, define, deprecated, dynamic, empty, enums, func, instance, integer, intersection, is, lazy, literal, map, mask, max, min, never, nonempty, nullable, number, object, omit, optional, partial, pattern, pick, record, refine, regexp, set, size, string, struct, trimmed, tuple, type, union, unknown, validate };\n//# sourceMappingURL=index.mjs.map\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createHasher, createXOFer, Hash, swap32IfBE, toBytes, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/** Keccak sponge function. */\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n this.enableXOF = false;\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));\n/** SHA3-224 hash function. */\nexport const sha3_224 = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\nconst genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n//# sourceMappingURL=sha3.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes } from \"./utils.js\";\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils';\nimport { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from \"../utils.js\";\nimport { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from \"./curve.js\";\nimport { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from \"./modular.js\";\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k, basis, n) {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n const optsn = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS, 'lowS');\n abool(optsn.prehash, 'prehash');\n if (optsn.format !== undefined)\n validateSigFormat(optsn.format);\n return optsn;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function _normFnElement(Fn, key) {\n const { BYTES: expected } = Fn;\n let num;\n if (typeof key === 'bigint') {\n num = key;\n }\n else {\n let bytes = ensureBytes('private key', key);\n try {\n num = Fn.fromBytes(bytes);\n }\n catch (error) {\n throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);\n }\n }\n if (!Fn.isValidNot0(num))\n throw new Error('invalid private key: out of range [1..N-1]');\n return num;\n}\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * @example\n```js\nconst opts = {\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n};\nconst p256_Point = weierstrass(opts);\n```\n */\nexport function weierstrassN(params, extraOpts = {}) {\n const validated = _createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n _validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n wrapPrivateKey: 'boolean',\n });\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd(y);\n return concatBytes(pprefix(hasEvenY), bx);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;\n const isHeadOdd = (head & 1) === 1; // ECDSA-specific\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n const toAffineMemo = memoized((p, iz) => {\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(ensureBytes('pointHex', hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo } = extraOpts;\n if (!Fn.isValidNot0(scalar))\n throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point, fake; // Fake point is used to const-time mult\n const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n }\n else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n const { endo } = extraOpts;\n const p = this;\n if (!Fn.isValid(sc))\n throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p; // fast-path\n if (wnaf.hasCache(this))\n return this.multiply(sc);\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n }\n else {\n return wnaf.unsafe(p, sc);\n }\n }\n multiplyAndAddUnsafe(Q, a, b) {\n const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));\n return sum.is0() ? undefined : sum;\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n return toAffineMemo(this, invertedZ);\n }\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree() {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(cofactor);\n }\n isSmallOrder() {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n toBytes(isCompressed = true) {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return ``;\n }\n // TODO: remove\n get px() {\n return this.X;\n }\n get py() {\n return this.X;\n }\n get pz() {\n return this.Z;\n }\n toRawBytes(isCompressed = true) {\n return this.toBytes(isCompressed);\n }\n _setWindowSize(windowSize) {\n this.precompute(windowSize);\n }\n static normalizeZ(points) {\n return normalizeZ(Point, points);\n }\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(_normFnElement(Fn, privateKey));\n }\n }\n // base / generator point\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n Point.Fp = Fp;\n // scalar field\n Point.Fn = Fn;\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\nfunction getWLengths(Fp, Fn) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n function isValidSecretKey(secretKey) {\n try {\n return !!_normFnElement(Fn, secretKey);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n return !!Point.fromBytes(publicKey);\n }\n catch (error) {\n return false;\n }\n }\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)) {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey, isCompressed = true) {\n return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);\n }\n function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n if (typeof item === 'bigint')\n return false;\n if (item instanceof Point)\n return true;\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (Fn.allowedLengths || secretKey === publicKey)\n return undefined;\n const l = ensureBytes('key', item).length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n throw new Error('second arg must be public key');\n const s = _normFnElement(Fn, secretKeyA);\n const b = Point.fromHex(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n // TODO: remove\n isValidPrivateKey: isValidSecretKey,\n randomPrivateKey: randomSecretKey,\n normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),\n precompute(windowSize = 8, point = Point.BASE) {\n return point.precompute(windowSize, false);\n },\n };\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n * We need `hash` for 2 features:\n * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`\n * 2. k generation in `sign`, using HMAC-drbg(hash)\n *\n * ECDSAOpts are only rarely needed.\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n ahash(hash);\n _validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;\n const hmac = ecdsaOpts.hmac ||\n ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts = {\n prehash: false,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,\n format: undefined, //'compact' as ECDSASigFormat,\n extraEntropy: false,\n };\n const defaultSigOpts_format = 'compact';\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function validateSigLength(bytes, format) {\n validateSigFormat(format);\n const size = lengths.signature;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer, `${format} signature`);\n }\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null)\n this.recovery = recovery;\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts_format) {\n validateSigLength(bytes, format);\n let recid;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = Fn.BYTES;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(messageHash) {\n const FIELD_ORDER = Fp.ORDER;\n const { r, s, recovery: rec } = this;\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;\n if (hasCofactor && rec > 1)\n throw new Error('recovery id is ambiguous for h>1 curve');\n const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj))\n throw new Error('recovery id 2 or 3 invalid');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0())\n throw new Error('point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts_format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\n const r = Fn.toBytes(this.r);\n const s = Fn.toBytes(this.s);\n if (format === 'recovered') {\n if (this.recovery == null)\n throw new Error('recovery bit must be present');\n return concatBytes(Uint8Array.of(this.recovery), r, s);\n }\n return concatBytes(r, s);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n // TODO: remove\n assertValidity() { }\n static fromCompact(hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'compact');\n }\n static fromDER(hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'der');\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;\n }\n toDERRawBytes() {\n return this.toBytes('der');\n }\n toDERHex() {\n return bytesToHex(this.toBytes('der'));\n }\n toCompactRawBytes() {\n return this.toBytes('compact');\n }\n toCompactHex() {\n return bytesToHex(this.toBytes('compact'));\n }\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = ecdsaOpts.bits2int ||\n function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num) {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message, privateKey, opts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // mod n, not mod p\n if (!Fn.isValidNot0(k))\n return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n message = ensureBytes('message', message);\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig;\n }\n function tryParsingSig(sg) {\n // Try to deduce format\n let sig = undefined;\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj = !isHex &&\n sg !== null &&\n typeof sg === 'object' &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n if (isObj) {\n sig = new Signature(sg.r, sg.s);\n }\n else if (isHex) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n }\n if (!sig) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');\n }\n catch (error) {\n return false;\n }\n }\n }\n if (!sig)\n return false;\n return sig;\n }\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = ensureBytes('publicKey', publicKey);\n message = validateMsgAndHash(ensureBytes('message', message), prehash);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const sig = format === undefined\n ? tryParsingSig(signature)\n : Signature.fromBytes(ensureBytes('sig', signature), format);\n if (sig === false)\n return false;\n try {\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS())\n return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0())\n return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n });\n}\n/** @deprecated use `weierstrass` in newer releases */\nexport function weierstrassPoints(c) {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n return _weierstrass_new_output_to_legacy(c, Point);\n}\nfunction _weierstrass_legacy_opts_to_new(c) {\n const CURVE = {\n a: c.a,\n b: c.b,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n let allowedLengths = c.allowedPrivateKeyLengths\n ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))\n : undefined;\n const Fn = Field(CURVE.n, {\n BITS: c.nBitLength,\n allowedLengths: allowedLengths,\n modFromBytes: c.wrapPrivateKey,\n });\n const curveOpts = {\n Fp,\n Fn,\n allowInfinityPoint: c.allowInfinityPoint,\n endo: c.endo,\n isTorsionFree: c.isTorsionFree,\n clearCofactor: c.clearCofactor,\n fromBytes: c.fromBytes,\n toBytes: c.toBytes,\n };\n return { CURVE, curveOpts };\n}\nfunction _ecdsa_legacy_opts_to_new(c) {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const ecdsaOpts = {\n hmac: c.hmac,\n randomBytes: c.randomBytes,\n lowS: c.lowS,\n bits2int: c.bits2int,\n bits2int_modN: c.bits2int_modN,\n };\n return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };\n}\nexport function _legacyHelperEquat(Fp, a, b) {\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².\n * @returns y²\n */\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n return weierstrassEquation;\n}\nfunction _weierstrass_new_output_to_legacy(c, Point) {\n const { Fp, Fn } = Point;\n function isWithinCurveOrder(num) {\n return inRange(num, _1n, Fn.ORDER);\n }\n const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);\n return Object.assign({}, {\n CURVE: c,\n Point: Point,\n ProjectivePoint: Point,\n normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),\n weierstrassEquation,\n isWithinCurveOrder,\n });\n}\nfunction _ecdsa_new_output_to_legacy(c, _ecdsa) {\n const Point = _ecdsa.Point;\n return Object.assign({}, _ecdsa, {\n ProjectivePoint: Point,\n CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),\n });\n}\n// _ecdsa_legacy\nexport function weierstrass(c) {\n const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n const signs = ecdsa(Point, hash, ecdsaOpts);\n return _ecdsa_new_output_to_legacy(c, signs);\n}\n//# sourceMappingURL=weierstrass.js.map","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createCurve } from \"./_shortw_utils.js\";\nimport { createHasher, isogenyMap, } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, mod, pow2 } from \"./abstract/modular.js\";\nimport { _normFnElement, mapToCurveSimpleSWU, } from \"./abstract/weierstrass.js\";\nimport { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey) === true;\n * ```\n */\nexport const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(utf8ToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();\nconst hasEven = (y) => y % _2n === _0n;\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = _normFnElement(Fn, priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x))\n throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y))\n y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey) {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n const { Fn } = Pointk1;\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const { Fn, BASE } = Pointk1;\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1_CURVE.p))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1_CURVE.n))\n return false;\n // int(challenge(bytes(r)||bytes(P)||m))%n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r)\n return false;\n return true;\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)) => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n // TODO: remove\n secp256k1.utils.randomSecretKey;\n function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };\n }\n return {\n keygen,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey: randomSecretKey,\n randomPrivateKey: randomSecretKey,\n taggedHash,\n // TODO: remove\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n mod,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\n };\n})();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n}))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { weierstrass } from \"./abstract/weierstrass.js\";\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash) {\n return { hash };\n}\n/** @deprecated use new `weierstrass()` and `ecdsa()` methods */\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, hash: hash });\n return { ...create(defHash), create };\n}\n//# sourceMappingURL=_shortw_utils.js.map","import { Buffer } from 'buffer';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport BN from 'bn.js';\nimport bs58 from 'bs58';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { serialize, deserialize, deserializeUnchecked } from 'borsh';\nimport * as BufferLayout from '@solana/buffer-layout';\nimport { blob } from '@solana/buffer-layout';\nimport { getU64Codec, getU64Encoder } from '@solana/codecs-numbers';\nimport { coerce, instance, string, tuple, literal, unknown, type, number, array, nullable, optional, boolean, record, union, create, any, assert as assert$1 } from 'superstruct';\nimport RpcClient from 'jayson/lib/client/browser';\nimport { CommonClient, WebSocket } from 'rpc-websockets';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { secp256k1 } from '@noble/curves/secp256k1';\n\n/**\n * A 64 byte secret key, the first 32 bytes of which is the\n * private scalar and the last 32 bytes is the public key.\n * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/\n */\n\n/**\n * Ed25519 Keypair\n */\n\nconst generatePrivateKey = ed25519.utils.randomPrivateKey;\nconst generateKeypair = () => {\n const privateScalar = ed25519.utils.randomPrivateKey();\n const publicKey = getPublicKey(privateScalar);\n const secretKey = new Uint8Array(64);\n secretKey.set(privateScalar);\n secretKey.set(publicKey, 32);\n return {\n publicKey,\n secretKey\n };\n};\nconst getPublicKey = ed25519.getPublicKey;\nfunction isOnCurve(publicKey) {\n try {\n ed25519.ExtendedPoint.fromHex(publicKey);\n return true;\n } catch {\n return false;\n }\n}\nconst sign = (message, secretKey) => ed25519.sign(message, secretKey.slice(0, 32));\nconst verify = ed25519.verify;\n\nconst toBuffer = arr => {\n if (Buffer.isBuffer(arr)) {\n return arr;\n } else if (arr instanceof Uint8Array) {\n return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);\n } else {\n return Buffer.from(arr);\n }\n};\n\n// Class wrapping a plain object\nclass Struct {\n constructor(properties) {\n Object.assign(this, properties);\n }\n encode() {\n return Buffer.from(serialize(SOLANA_SCHEMA, this));\n }\n static decode(data) {\n return deserialize(SOLANA_SCHEMA, this, data);\n }\n static decodeUnchecked(data) {\n return deserializeUnchecked(SOLANA_SCHEMA, this, data);\n }\n}\n\n// Class representing a Rust-compatible enum, since enums are only strings or\n// numbers in pure JS\nclass Enum extends Struct {\n constructor(properties) {\n super(properties);\n this.enum = '';\n if (Object.keys(properties).length !== 1) {\n throw new Error('Enum can only take single value');\n }\n Object.keys(properties).map(key => {\n this.enum = key;\n });\n }\n}\nconst SOLANA_SCHEMA = new Map();\n\nvar _PublicKey;\n\n/**\n * Maximum length of derived pubkey seed\n */\nconst MAX_SEED_LENGTH = 32;\n\n/**\n * Size of public key in bytes\n */\nconst PUBLIC_KEY_LENGTH = 32;\n\n/**\n * Value to be converted into public key\n */\n\n/**\n * JSON object representation of PublicKey class\n */\n\nfunction isPublicKeyData(value) {\n return value._bn !== undefined;\n}\n\n// local counter used by PublicKey.unique()\nlet uniquePublicKeyCounter = 1;\n\n/**\n * A public key\n */\nclass PublicKey extends Struct {\n /**\n * Create a new PublicKey object\n * @param value ed25519 public key as buffer or base-58 encoded string\n */\n constructor(value) {\n super({});\n /** @internal */\n this._bn = void 0;\n if (isPublicKeyData(value)) {\n this._bn = value._bn;\n } else {\n if (typeof value === 'string') {\n // assume base 58 encoding by default\n const decoded = bs58.decode(value);\n if (decoded.length != PUBLIC_KEY_LENGTH) {\n throw new Error(`Invalid public key input`);\n }\n this._bn = new BN(decoded);\n } else {\n this._bn = new BN(value);\n }\n if (this._bn.byteLength() > PUBLIC_KEY_LENGTH) {\n throw new Error(`Invalid public key input`);\n }\n }\n }\n\n /**\n * Returns a unique PublicKey for tests and benchmarks using a counter\n */\n static unique() {\n const key = new PublicKey(uniquePublicKeyCounter);\n uniquePublicKeyCounter += 1;\n return new PublicKey(key.toBuffer());\n }\n\n /**\n * Default public key value. The base58-encoded string representation is all ones (as seen below)\n * The underlying BN number is 32 bytes that are all zeros\n */\n\n /**\n * Checks if two publicKeys are equal\n */\n equals(publicKey) {\n return this._bn.eq(publicKey._bn);\n }\n\n /**\n * Return the base-58 representation of the public key\n */\n toBase58() {\n return bs58.encode(this.toBytes());\n }\n toJSON() {\n return this.toBase58();\n }\n\n /**\n * Return the byte array representation of the public key in big endian\n */\n toBytes() {\n const buf = this.toBuffer();\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n }\n\n /**\n * Return the Buffer representation of the public key in big endian\n */\n toBuffer() {\n const b = this._bn.toArrayLike(Buffer);\n if (b.length === PUBLIC_KEY_LENGTH) {\n return b;\n }\n const zeroPad = Buffer.alloc(32);\n b.copy(zeroPad, 32 - b.length);\n return zeroPad;\n }\n get [Symbol.toStringTag]() {\n return `PublicKey(${this.toString()})`;\n }\n\n /**\n * Return the base-58 representation of the public key\n */\n toString() {\n return this.toBase58();\n }\n\n /**\n * Derive a public key from another key, a seed, and a program ID.\n * The program ID will also serve as the owner of the public key, giving\n * it permission to write data to the account.\n */\n /* eslint-disable require-await */\n static async createWithSeed(fromPublicKey, seed, programId) {\n const buffer = Buffer.concat([fromPublicKey.toBuffer(), Buffer.from(seed), programId.toBuffer()]);\n const publicKeyBytes = sha256(buffer);\n return new PublicKey(publicKeyBytes);\n }\n\n /**\n * Derive a program address from seeds and a program ID.\n */\n /* eslint-disable require-await */\n static createProgramAddressSync(seeds, programId) {\n let buffer = Buffer.alloc(0);\n seeds.forEach(function (seed) {\n if (seed.length > MAX_SEED_LENGTH) {\n throw new TypeError(`Max seed length exceeded`);\n }\n buffer = Buffer.concat([buffer, toBuffer(seed)]);\n });\n buffer = Buffer.concat([buffer, programId.toBuffer(), Buffer.from('ProgramDerivedAddress')]);\n const publicKeyBytes = sha256(buffer);\n if (isOnCurve(publicKeyBytes)) {\n throw new Error(`Invalid seeds, address must fall off the curve`);\n }\n return new PublicKey(publicKeyBytes);\n }\n\n /**\n * Async version of createProgramAddressSync\n * For backwards compatibility\n *\n * @deprecated Use {@link createProgramAddressSync} instead\n */\n /* eslint-disable require-await */\n static async createProgramAddress(seeds, programId) {\n return this.createProgramAddressSync(seeds, programId);\n }\n\n /**\n * Find a valid program address\n *\n * Valid program addresses must fall off the ed25519 curve. This function\n * iterates a nonce until it finds one that when combined with the seeds\n * results in a valid program address.\n */\n static findProgramAddressSync(seeds, programId) {\n let nonce = 255;\n let address;\n while (nonce != 0) {\n try {\n const seedsWithNonce = seeds.concat(Buffer.from([nonce]));\n address = this.createProgramAddressSync(seedsWithNonce, programId);\n } catch (err) {\n if (err instanceof TypeError) {\n throw err;\n }\n nonce--;\n continue;\n }\n return [address, nonce];\n }\n throw new Error(`Unable to find a viable program address nonce`);\n }\n\n /**\n * Async version of findProgramAddressSync\n * For backwards compatibility\n *\n * @deprecated Use {@link findProgramAddressSync} instead\n */\n static async findProgramAddress(seeds, programId) {\n return this.findProgramAddressSync(seeds, programId);\n }\n\n /**\n * Check that a pubkey is on the ed25519 curve.\n */\n static isOnCurve(pubkeyData) {\n const pubkey = new PublicKey(pubkeyData);\n return isOnCurve(pubkey.toBytes());\n }\n}\n_PublicKey = PublicKey;\nPublicKey.default = new _PublicKey('11111111111111111111111111111111');\nSOLANA_SCHEMA.set(PublicKey, {\n kind: 'struct',\n fields: [['_bn', 'u256']]\n});\n\n/**\n * An account key pair (public and secret keys).\n *\n * @deprecated since v1.10.0, please use {@link Keypair} instead.\n */\nclass Account {\n /**\n * Create a new Account object\n *\n * If the secretKey parameter is not provided a new key pair is randomly\n * created for the account\n *\n * @param secretKey Secret key for the account\n */\n constructor(secretKey) {\n /** @internal */\n this._publicKey = void 0;\n /** @internal */\n this._secretKey = void 0;\n if (secretKey) {\n const secretKeyBuffer = toBuffer(secretKey);\n if (secretKey.length !== 64) {\n throw new Error('bad secret key size');\n }\n this._publicKey = secretKeyBuffer.slice(32, 64);\n this._secretKey = secretKeyBuffer.slice(0, 32);\n } else {\n this._secretKey = toBuffer(generatePrivateKey());\n this._publicKey = toBuffer(getPublicKey(this._secretKey));\n }\n }\n\n /**\n * The public key for this account\n */\n get publicKey() {\n return new PublicKey(this._publicKey);\n }\n\n /**\n * The **unencrypted** secret key for this account. The first 32 bytes\n * is the private scalar and the last 32 bytes is the public key.\n * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/\n */\n get secretKey() {\n return Buffer.concat([this._secretKey, this._publicKey], 64);\n }\n}\n\nconst BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey('BPFLoader1111111111111111111111111111111111');\n\n/**\n * Maximum over-the-wire size of a Transaction\n *\n * 1280 is IPv6 minimum MTU\n * 40 bytes is the size of the IPv6 header\n * 8 bytes is the size of the fragment header\n */\nconst PACKET_DATA_SIZE = 1280 - 40 - 8;\nconst VERSION_PREFIX_MASK = 0x7f;\nconst SIGNATURE_LENGTH_IN_BYTES = 64;\n\nclass TransactionExpiredBlockheightExceededError extends Error {\n constructor(signature) {\n super(`Signature ${signature} has expired: block height exceeded.`);\n this.signature = void 0;\n this.signature = signature;\n }\n}\nObject.defineProperty(TransactionExpiredBlockheightExceededError.prototype, 'name', {\n value: 'TransactionExpiredBlockheightExceededError'\n});\nclass TransactionExpiredTimeoutError extends Error {\n constructor(signature, timeoutSeconds) {\n 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.`);\n this.signature = void 0;\n this.signature = signature;\n }\n}\nObject.defineProperty(TransactionExpiredTimeoutError.prototype, 'name', {\n value: 'TransactionExpiredTimeoutError'\n});\nclass TransactionExpiredNonceInvalidError extends Error {\n constructor(signature) {\n super(`Signature ${signature} has expired: the nonce is no longer valid.`);\n this.signature = void 0;\n this.signature = signature;\n }\n}\nObject.defineProperty(TransactionExpiredNonceInvalidError.prototype, 'name', {\n value: 'TransactionExpiredNonceInvalidError'\n});\n\nclass MessageAccountKeys {\n constructor(staticAccountKeys, accountKeysFromLookups) {\n this.staticAccountKeys = void 0;\n this.accountKeysFromLookups = void 0;\n this.staticAccountKeys = staticAccountKeys;\n this.accountKeysFromLookups = accountKeysFromLookups;\n }\n keySegments() {\n const keySegments = [this.staticAccountKeys];\n if (this.accountKeysFromLookups) {\n keySegments.push(this.accountKeysFromLookups.writable);\n keySegments.push(this.accountKeysFromLookups.readonly);\n }\n return keySegments;\n }\n get(index) {\n for (const keySegment of this.keySegments()) {\n if (index < keySegment.length) {\n return keySegment[index];\n } else {\n index -= keySegment.length;\n }\n }\n return;\n }\n get length() {\n return this.keySegments().flat().length;\n }\n compileInstructions(instructions) {\n // Bail early if any account indexes would overflow a u8\n const U8_MAX = 255;\n if (this.length > U8_MAX + 1) {\n throw new Error('Account index overflow encountered during compilation');\n }\n const keyIndexMap = new Map();\n this.keySegments().flat().forEach((key, index) => {\n keyIndexMap.set(key.toBase58(), index);\n });\n const findKeyIndex = key => {\n const keyIndex = keyIndexMap.get(key.toBase58());\n if (keyIndex === undefined) throw new Error('Encountered an unknown instruction account key during compilation');\n return keyIndex;\n };\n return instructions.map(instruction => {\n return {\n programIdIndex: findKeyIndex(instruction.programId),\n accountKeyIndexes: instruction.keys.map(meta => findKeyIndex(meta.pubkey)),\n data: instruction.data\n };\n });\n }\n}\n\n/**\n * Layout for a public key\n */\nconst publicKey = (property = 'publicKey') => {\n return BufferLayout.blob(32, property);\n};\n\n/**\n * Layout for a signature\n */\nconst signature = (property = 'signature') => {\n return BufferLayout.blob(64, property);\n};\n/**\n * Layout for a Rust String type\n */\nconst rustString = (property = 'string') => {\n const rsl = BufferLayout.struct([BufferLayout.u32('length'), BufferLayout.u32('lengthPadding'), BufferLayout.blob(BufferLayout.offset(BufferLayout.u32(), -8), 'chars')], property);\n const _decode = rsl.decode.bind(rsl);\n const _encode = rsl.encode.bind(rsl);\n const rslShim = rsl;\n rslShim.decode = (b, offset) => {\n const data = _decode(b, offset);\n return data['chars'].toString();\n };\n rslShim.encode = (str, b, offset) => {\n const data = {\n chars: Buffer.from(str, 'utf8')\n };\n return _encode(data, b, offset);\n };\n rslShim.alloc = str => {\n return BufferLayout.u32().span + BufferLayout.u32().span + Buffer.from(str, 'utf8').length;\n };\n return rslShim;\n};\n\n/**\n * Layout for an Authorized object\n */\nconst authorized = (property = 'authorized') => {\n return BufferLayout.struct([publicKey('staker'), publicKey('withdrawer')], property);\n};\n\n/**\n * Layout for a Lockup object\n */\nconst lockup = (property = 'lockup') => {\n return BufferLayout.struct([BufferLayout.ns64('unixTimestamp'), BufferLayout.ns64('epoch'), publicKey('custodian')], property);\n};\n\n/**\n * Layout for a VoteInit object\n */\nconst voteInit = (property = 'voteInit') => {\n return BufferLayout.struct([publicKey('nodePubkey'), publicKey('authorizedVoter'), publicKey('authorizedWithdrawer'), BufferLayout.u8('commission')], property);\n};\n\n/**\n * Layout for a VoteAuthorizeWithSeedArgs object\n */\nconst voteAuthorizeWithSeedArgs = (property = 'voteAuthorizeWithSeedArgs') => {\n return BufferLayout.struct([BufferLayout.u32('voteAuthorizationType'), publicKey('currentAuthorityDerivedKeyOwnerPubkey'), rustString('currentAuthorityDerivedKeySeed'), publicKey('newAuthorized')], property);\n};\nfunction getAlloc(type, fields) {\n const getItemAlloc = item => {\n if (item.span >= 0) {\n return item.span;\n } else if (typeof item.alloc === 'function') {\n return item.alloc(fields[item.property]);\n } else if ('count' in item && 'elementLayout' in item) {\n const field = fields[item.property];\n if (Array.isArray(field)) {\n return field.length * getItemAlloc(item.elementLayout);\n }\n } else if ('fields' in item) {\n // This is a `Structure` whose size needs to be recursively measured.\n return getAlloc({\n layout: item\n }, fields[item.property]);\n }\n // Couldn't determine allocated size of layout\n return 0;\n };\n let alloc = 0;\n type.layout.fields.forEach(item => {\n alloc += getItemAlloc(item);\n });\n return alloc;\n}\n\nfunction decodeLength(bytes) {\n let len = 0;\n let size = 0;\n for (;;) {\n let elem = bytes.shift();\n len |= (elem & 0x7f) << size * 7;\n size += 1;\n if ((elem & 0x80) === 0) {\n break;\n }\n }\n return len;\n}\nfunction encodeLength(bytes, len) {\n let rem_len = len;\n for (;;) {\n let elem = rem_len & 0x7f;\n rem_len >>= 7;\n if (rem_len == 0) {\n bytes.push(elem);\n break;\n } else {\n elem |= 0x80;\n bytes.push(elem);\n }\n }\n}\n\nfunction assert (condition, message) {\n if (!condition) {\n throw new Error(message || 'Assertion failed');\n }\n}\n\nclass CompiledKeys {\n constructor(payer, keyMetaMap) {\n this.payer = void 0;\n this.keyMetaMap = void 0;\n this.payer = payer;\n this.keyMetaMap = keyMetaMap;\n }\n static compile(instructions, payer) {\n const keyMetaMap = new Map();\n const getOrInsertDefault = pubkey => {\n const address = pubkey.toBase58();\n let keyMeta = keyMetaMap.get(address);\n if (keyMeta === undefined) {\n keyMeta = {\n isSigner: false,\n isWritable: false,\n isInvoked: false\n };\n keyMetaMap.set(address, keyMeta);\n }\n return keyMeta;\n };\n const payerKeyMeta = getOrInsertDefault(payer);\n payerKeyMeta.isSigner = true;\n payerKeyMeta.isWritable = true;\n for (const ix of instructions) {\n getOrInsertDefault(ix.programId).isInvoked = true;\n for (const accountMeta of ix.keys) {\n const keyMeta = getOrInsertDefault(accountMeta.pubkey);\n keyMeta.isSigner ||= accountMeta.isSigner;\n keyMeta.isWritable ||= accountMeta.isWritable;\n }\n }\n return new CompiledKeys(payer, keyMetaMap);\n }\n getMessageComponents() {\n const mapEntries = [...this.keyMetaMap.entries()];\n assert(mapEntries.length <= 256, 'Max static account keys length exceeded');\n const writableSigners = mapEntries.filter(([, meta]) => meta.isSigner && meta.isWritable);\n const readonlySigners = mapEntries.filter(([, meta]) => meta.isSigner && !meta.isWritable);\n const writableNonSigners = mapEntries.filter(([, meta]) => !meta.isSigner && meta.isWritable);\n const readonlyNonSigners = mapEntries.filter(([, meta]) => !meta.isSigner && !meta.isWritable);\n const header = {\n numRequiredSignatures: writableSigners.length + readonlySigners.length,\n numReadonlySignedAccounts: readonlySigners.length,\n numReadonlyUnsignedAccounts: readonlyNonSigners.length\n };\n\n // sanity checks\n {\n assert(writableSigners.length > 0, 'Expected at least one writable signer key');\n const [payerAddress] = writableSigners[0];\n assert(payerAddress === this.payer.toBase58(), 'Expected first writable signer key to be the fee payer');\n }\n const staticAccountKeys = [...writableSigners.map(([address]) => new PublicKey(address)), ...readonlySigners.map(([address]) => new PublicKey(address)), ...writableNonSigners.map(([address]) => new PublicKey(address)), ...readonlyNonSigners.map(([address]) => new PublicKey(address))];\n return [header, staticAccountKeys];\n }\n extractTableLookup(lookupTable) {\n const [writableIndexes, drainedWritableKeys] = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, keyMeta => !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable);\n const [readonlyIndexes, drainedReadonlyKeys] = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, keyMeta => !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable);\n\n // Don't extract lookup if no keys were found\n if (writableIndexes.length === 0 && readonlyIndexes.length === 0) {\n return;\n }\n return [{\n accountKey: lookupTable.key,\n writableIndexes,\n readonlyIndexes\n }, {\n writable: drainedWritableKeys,\n readonly: drainedReadonlyKeys\n }];\n }\n\n /** @internal */\n drainKeysFoundInLookupTable(lookupTableEntries, keyMetaFilter) {\n const lookupTableIndexes = new Array();\n const drainedKeys = new Array();\n for (const [address, keyMeta] of this.keyMetaMap.entries()) {\n if (keyMetaFilter(keyMeta)) {\n const key = new PublicKey(address);\n const lookupTableIndex = lookupTableEntries.findIndex(entry => entry.equals(key));\n if (lookupTableIndex >= 0) {\n assert(lookupTableIndex < 256, 'Max lookup table index exceeded');\n lookupTableIndexes.push(lookupTableIndex);\n drainedKeys.push(key);\n this.keyMetaMap.delete(address);\n }\n }\n }\n return [lookupTableIndexes, drainedKeys];\n }\n}\n\nconst END_OF_BUFFER_ERROR_MESSAGE = 'Reached end of buffer unexpectedly';\n\n/**\n * Delegates to `Array#shift`, but throws if the array is zero-length.\n */\nfunction guardedShift(byteArray) {\n if (byteArray.length === 0) {\n throw new Error(END_OF_BUFFER_ERROR_MESSAGE);\n }\n return byteArray.shift();\n}\n\n/**\n * Delegates to `Array#splice`, but throws if the section being spliced out extends past the end of\n * the array.\n */\nfunction guardedSplice(byteArray, ...args) {\n const [start] = args;\n if (args.length === 2 // Implies that `deleteCount` was supplied\n ? start + (args[1] ?? 0) > byteArray.length : start >= byteArray.length) {\n throw new Error(END_OF_BUFFER_ERROR_MESSAGE);\n }\n return byteArray.splice(...args);\n}\n\n/**\n * An instruction to execute by a program\n *\n * @property {number} programIdIndex\n * @property {number[]} accounts\n * @property {string} data\n */\n\n/**\n * Message constructor arguments\n */\n\n/**\n * List of instructions to be processed atomically\n */\nclass Message {\n constructor(args) {\n this.header = void 0;\n this.accountKeys = void 0;\n this.recentBlockhash = void 0;\n this.instructions = void 0;\n this.indexToProgramIds = new Map();\n this.header = args.header;\n this.accountKeys = args.accountKeys.map(account => new PublicKey(account));\n this.recentBlockhash = args.recentBlockhash;\n this.instructions = args.instructions;\n this.instructions.forEach(ix => this.indexToProgramIds.set(ix.programIdIndex, this.accountKeys[ix.programIdIndex]));\n }\n get version() {\n return 'legacy';\n }\n get staticAccountKeys() {\n return this.accountKeys;\n }\n get compiledInstructions() {\n return this.instructions.map(ix => ({\n programIdIndex: ix.programIdIndex,\n accountKeyIndexes: ix.accounts,\n data: bs58.decode(ix.data)\n }));\n }\n get addressTableLookups() {\n return [];\n }\n getAccountKeys() {\n return new MessageAccountKeys(this.staticAccountKeys);\n }\n static compile(args) {\n const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);\n const [header, staticAccountKeys] = compiledKeys.getMessageComponents();\n const accountKeys = new MessageAccountKeys(staticAccountKeys);\n const instructions = accountKeys.compileInstructions(args.instructions).map(ix => ({\n programIdIndex: ix.programIdIndex,\n accounts: ix.accountKeyIndexes,\n data: bs58.encode(ix.data)\n }));\n return new Message({\n header,\n accountKeys: staticAccountKeys,\n recentBlockhash: args.recentBlockhash,\n instructions\n });\n }\n isAccountSigner(index) {\n return index < this.header.numRequiredSignatures;\n }\n isAccountWritable(index) {\n const numSignedAccounts = this.header.numRequiredSignatures;\n if (index >= this.header.numRequiredSignatures) {\n const unsignedAccountIndex = index - numSignedAccounts;\n const numUnsignedAccounts = this.accountKeys.length - numSignedAccounts;\n const numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts;\n return unsignedAccountIndex < numWritableUnsignedAccounts;\n } else {\n const numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts;\n return index < numWritableSignedAccounts;\n }\n }\n isProgramId(index) {\n return this.indexToProgramIds.has(index);\n }\n programIds() {\n return [...this.indexToProgramIds.values()];\n }\n nonProgramIds() {\n return this.accountKeys.filter((_, index) => !this.isProgramId(index));\n }\n serialize() {\n const numKeys = this.accountKeys.length;\n let keyCount = [];\n encodeLength(keyCount, numKeys);\n const instructions = this.instructions.map(instruction => {\n const {\n accounts,\n programIdIndex\n } = instruction;\n const data = Array.from(bs58.decode(instruction.data));\n let keyIndicesCount = [];\n encodeLength(keyIndicesCount, accounts.length);\n let dataCount = [];\n encodeLength(dataCount, data.length);\n return {\n programIdIndex,\n keyIndicesCount: Buffer.from(keyIndicesCount),\n keyIndices: accounts,\n dataLength: Buffer.from(dataCount),\n data\n };\n });\n let instructionCount = [];\n encodeLength(instructionCount, instructions.length);\n let instructionBuffer = Buffer.alloc(PACKET_DATA_SIZE);\n Buffer.from(instructionCount).copy(instructionBuffer);\n let instructionBufferLength = instructionCount.length;\n instructions.forEach(instruction => {\n const instructionLayout = BufferLayout.struct([BufferLayout.u8('programIdIndex'), BufferLayout.blob(instruction.keyIndicesCount.length, 'keyIndicesCount'), BufferLayout.seq(BufferLayout.u8('keyIndex'), instruction.keyIndices.length, 'keyIndices'), BufferLayout.blob(instruction.dataLength.length, 'dataLength'), BufferLayout.seq(BufferLayout.u8('userdatum'), instruction.data.length, 'data')]);\n const length = instructionLayout.encode(instruction, instructionBuffer, instructionBufferLength);\n instructionBufferLength += length;\n });\n instructionBuffer = instructionBuffer.slice(0, instructionBufferLength);\n const signDataLayout = BufferLayout.struct([BufferLayout.blob(1, 'numRequiredSignatures'), BufferLayout.blob(1, 'numReadonlySignedAccounts'), BufferLayout.blob(1, 'numReadonlyUnsignedAccounts'), BufferLayout.blob(keyCount.length, 'keyCount'), BufferLayout.seq(publicKey('key'), numKeys, 'keys'), publicKey('recentBlockhash')]);\n const transaction = {\n numRequiredSignatures: Buffer.from([this.header.numRequiredSignatures]),\n numReadonlySignedAccounts: Buffer.from([this.header.numReadonlySignedAccounts]),\n numReadonlyUnsignedAccounts: Buffer.from([this.header.numReadonlyUnsignedAccounts]),\n keyCount: Buffer.from(keyCount),\n keys: this.accountKeys.map(key => toBuffer(key.toBytes())),\n recentBlockhash: bs58.decode(this.recentBlockhash)\n };\n let signData = Buffer.alloc(2048);\n const length = signDataLayout.encode(transaction, signData);\n instructionBuffer.copy(signData, length);\n return signData.slice(0, length + instructionBuffer.length);\n }\n\n /**\n * Decode a compiled message into a Message object.\n */\n static from(buffer) {\n // Slice up wire data\n let byteArray = [...buffer];\n const numRequiredSignatures = guardedShift(byteArray);\n if (numRequiredSignatures !== (numRequiredSignatures & VERSION_PREFIX_MASK)) {\n throw new Error('Versioned messages must be deserialized with VersionedMessage.deserialize()');\n }\n const numReadonlySignedAccounts = guardedShift(byteArray);\n const numReadonlyUnsignedAccounts = guardedShift(byteArray);\n const accountCount = decodeLength(byteArray);\n let accountKeys = [];\n for (let i = 0; i < accountCount; i++) {\n const account = guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH);\n accountKeys.push(new PublicKey(Buffer.from(account)));\n }\n const recentBlockhash = guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH);\n const instructionCount = decodeLength(byteArray);\n let instructions = [];\n for (let i = 0; i < instructionCount; i++) {\n const programIdIndex = guardedShift(byteArray);\n const accountCount = decodeLength(byteArray);\n const accounts = guardedSplice(byteArray, 0, accountCount);\n const dataLength = decodeLength(byteArray);\n const dataSlice = guardedSplice(byteArray, 0, dataLength);\n const data = bs58.encode(Buffer.from(dataSlice));\n instructions.push({\n programIdIndex,\n accounts,\n data\n });\n }\n const messageArgs = {\n header: {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts\n },\n recentBlockhash: bs58.encode(Buffer.from(recentBlockhash)),\n accountKeys,\n instructions\n };\n return new Message(messageArgs);\n }\n}\n\n/**\n * Message constructor arguments\n */\n\nclass MessageV0 {\n constructor(args) {\n this.header = void 0;\n this.staticAccountKeys = void 0;\n this.recentBlockhash = void 0;\n this.compiledInstructions = void 0;\n this.addressTableLookups = void 0;\n this.header = args.header;\n this.staticAccountKeys = args.staticAccountKeys;\n this.recentBlockhash = args.recentBlockhash;\n this.compiledInstructions = args.compiledInstructions;\n this.addressTableLookups = args.addressTableLookups;\n }\n get version() {\n return 0;\n }\n get numAccountKeysFromLookups() {\n let count = 0;\n for (const lookup of this.addressTableLookups) {\n count += lookup.readonlyIndexes.length + lookup.writableIndexes.length;\n }\n return count;\n }\n getAccountKeys(args) {\n let accountKeysFromLookups;\n if (args && 'accountKeysFromLookups' in args && args.accountKeysFromLookups) {\n if (this.numAccountKeysFromLookups != args.accountKeysFromLookups.writable.length + args.accountKeysFromLookups.readonly.length) {\n throw new Error('Failed to get account keys because of a mismatch in the number of account keys from lookups');\n }\n accountKeysFromLookups = args.accountKeysFromLookups;\n } else if (args && 'addressLookupTableAccounts' in args && args.addressLookupTableAccounts) {\n accountKeysFromLookups = this.resolveAddressTableLookups(args.addressLookupTableAccounts);\n } else if (this.addressTableLookups.length > 0) {\n throw new Error('Failed to get account keys because address table lookups were not resolved');\n }\n return new MessageAccountKeys(this.staticAccountKeys, accountKeysFromLookups);\n }\n isAccountSigner(index) {\n return index < this.header.numRequiredSignatures;\n }\n isAccountWritable(index) {\n const numSignedAccounts = this.header.numRequiredSignatures;\n const numStaticAccountKeys = this.staticAccountKeys.length;\n if (index >= numStaticAccountKeys) {\n const lookupAccountKeysIndex = index - numStaticAccountKeys;\n const numWritableLookupAccountKeys = this.addressTableLookups.reduce((count, lookup) => count + lookup.writableIndexes.length, 0);\n return lookupAccountKeysIndex < numWritableLookupAccountKeys;\n } else if (index >= this.header.numRequiredSignatures) {\n const unsignedAccountIndex = index - numSignedAccounts;\n const numUnsignedAccounts = numStaticAccountKeys - numSignedAccounts;\n const numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts;\n return unsignedAccountIndex < numWritableUnsignedAccounts;\n } else {\n const numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts;\n return index < numWritableSignedAccounts;\n }\n }\n resolveAddressTableLookups(addressLookupTableAccounts) {\n const accountKeysFromLookups = {\n writable: [],\n readonly: []\n };\n for (const tableLookup of this.addressTableLookups) {\n const tableAccount = addressLookupTableAccounts.find(account => account.key.equals(tableLookup.accountKey));\n if (!tableAccount) {\n throw new Error(`Failed to find address lookup table account for table key ${tableLookup.accountKey.toBase58()}`);\n }\n for (const index of tableLookup.writableIndexes) {\n if (index < tableAccount.state.addresses.length) {\n accountKeysFromLookups.writable.push(tableAccount.state.addresses[index]);\n } else {\n throw new Error(`Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`);\n }\n }\n for (const index of tableLookup.readonlyIndexes) {\n if (index < tableAccount.state.addresses.length) {\n accountKeysFromLookups.readonly.push(tableAccount.state.addresses[index]);\n } else {\n throw new Error(`Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`);\n }\n }\n }\n return accountKeysFromLookups;\n }\n static compile(args) {\n const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);\n const addressTableLookups = new Array();\n const accountKeysFromLookups = {\n writable: new Array(),\n readonly: new Array()\n };\n const lookupTableAccounts = args.addressLookupTableAccounts || [];\n for (const lookupTable of lookupTableAccounts) {\n const extractResult = compiledKeys.extractTableLookup(lookupTable);\n if (extractResult !== undefined) {\n const [addressTableLookup, {\n writable,\n readonly\n }] = extractResult;\n addressTableLookups.push(addressTableLookup);\n accountKeysFromLookups.writable.push(...writable);\n accountKeysFromLookups.readonly.push(...readonly);\n }\n }\n const [header, staticAccountKeys] = compiledKeys.getMessageComponents();\n const accountKeys = new MessageAccountKeys(staticAccountKeys, accountKeysFromLookups);\n const compiledInstructions = accountKeys.compileInstructions(args.instructions);\n return new MessageV0({\n header,\n staticAccountKeys,\n recentBlockhash: args.recentBlockhash,\n compiledInstructions,\n addressTableLookups\n });\n }\n serialize() {\n const encodedStaticAccountKeysLength = Array();\n encodeLength(encodedStaticAccountKeysLength, this.staticAccountKeys.length);\n const serializedInstructions = this.serializeInstructions();\n const encodedInstructionsLength = Array();\n encodeLength(encodedInstructionsLength, this.compiledInstructions.length);\n const serializedAddressTableLookups = this.serializeAddressTableLookups();\n const encodedAddressTableLookupsLength = Array();\n encodeLength(encodedAddressTableLookupsLength, this.addressTableLookups.length);\n const messageLayout = BufferLayout.struct([BufferLayout.u8('prefix'), BufferLayout.struct([BufferLayout.u8('numRequiredSignatures'), BufferLayout.u8('numReadonlySignedAccounts'), BufferLayout.u8('numReadonlyUnsignedAccounts')], 'header'), BufferLayout.blob(encodedStaticAccountKeysLength.length, 'staticAccountKeysLength'), BufferLayout.seq(publicKey(), this.staticAccountKeys.length, 'staticAccountKeys'), publicKey('recentBlockhash'), BufferLayout.blob(encodedInstructionsLength.length, 'instructionsLength'), BufferLayout.blob(serializedInstructions.length, 'serializedInstructions'), BufferLayout.blob(encodedAddressTableLookupsLength.length, 'addressTableLookupsLength'), BufferLayout.blob(serializedAddressTableLookups.length, 'serializedAddressTableLookups')]);\n const serializedMessage = new Uint8Array(PACKET_DATA_SIZE);\n const MESSAGE_VERSION_0_PREFIX = 1 << 7;\n const serializedMessageLength = messageLayout.encode({\n prefix: MESSAGE_VERSION_0_PREFIX,\n header: this.header,\n staticAccountKeysLength: new Uint8Array(encodedStaticAccountKeysLength),\n staticAccountKeys: this.staticAccountKeys.map(key => key.toBytes()),\n recentBlockhash: bs58.decode(this.recentBlockhash),\n instructionsLength: new Uint8Array(encodedInstructionsLength),\n serializedInstructions,\n addressTableLookupsLength: new Uint8Array(encodedAddressTableLookupsLength),\n serializedAddressTableLookups\n }, serializedMessage);\n return serializedMessage.slice(0, serializedMessageLength);\n }\n serializeInstructions() {\n let serializedLength = 0;\n const serializedInstructions = new Uint8Array(PACKET_DATA_SIZE);\n for (const instruction of this.compiledInstructions) {\n const encodedAccountKeyIndexesLength = Array();\n encodeLength(encodedAccountKeyIndexesLength, instruction.accountKeyIndexes.length);\n const encodedDataLength = Array();\n encodeLength(encodedDataLength, instruction.data.length);\n const instructionLayout = BufferLayout.struct([BufferLayout.u8('programIdIndex'), BufferLayout.blob(encodedAccountKeyIndexesLength.length, 'encodedAccountKeyIndexesLength'), BufferLayout.seq(BufferLayout.u8(), instruction.accountKeyIndexes.length, 'accountKeyIndexes'), BufferLayout.blob(encodedDataLength.length, 'encodedDataLength'), BufferLayout.blob(instruction.data.length, 'data')]);\n serializedLength += instructionLayout.encode({\n programIdIndex: instruction.programIdIndex,\n encodedAccountKeyIndexesLength: new Uint8Array(encodedAccountKeyIndexesLength),\n accountKeyIndexes: instruction.accountKeyIndexes,\n encodedDataLength: new Uint8Array(encodedDataLength),\n data: instruction.data\n }, serializedInstructions, serializedLength);\n }\n return serializedInstructions.slice(0, serializedLength);\n }\n serializeAddressTableLookups() {\n let serializedLength = 0;\n const serializedAddressTableLookups = new Uint8Array(PACKET_DATA_SIZE);\n for (const lookup of this.addressTableLookups) {\n const encodedWritableIndexesLength = Array();\n encodeLength(encodedWritableIndexesLength, lookup.writableIndexes.length);\n const encodedReadonlyIndexesLength = Array();\n encodeLength(encodedReadonlyIndexesLength, lookup.readonlyIndexes.length);\n const addressTableLookupLayout = BufferLayout.struct([publicKey('accountKey'), BufferLayout.blob(encodedWritableIndexesLength.length, 'encodedWritableIndexesLength'), BufferLayout.seq(BufferLayout.u8(), lookup.writableIndexes.length, 'writableIndexes'), BufferLayout.blob(encodedReadonlyIndexesLength.length, 'encodedReadonlyIndexesLength'), BufferLayout.seq(BufferLayout.u8(), lookup.readonlyIndexes.length, 'readonlyIndexes')]);\n serializedLength += addressTableLookupLayout.encode({\n accountKey: lookup.accountKey.toBytes(),\n encodedWritableIndexesLength: new Uint8Array(encodedWritableIndexesLength),\n writableIndexes: lookup.writableIndexes,\n encodedReadonlyIndexesLength: new Uint8Array(encodedReadonlyIndexesLength),\n readonlyIndexes: lookup.readonlyIndexes\n }, serializedAddressTableLookups, serializedLength);\n }\n return serializedAddressTableLookups.slice(0, serializedLength);\n }\n static deserialize(serializedMessage) {\n let byteArray = [...serializedMessage];\n const prefix = guardedShift(byteArray);\n const maskedPrefix = prefix & VERSION_PREFIX_MASK;\n assert(prefix !== maskedPrefix, `Expected versioned message but received legacy message`);\n const version = maskedPrefix;\n assert(version === 0, `Expected versioned message with version 0 but found version ${version}`);\n const header = {\n numRequiredSignatures: guardedShift(byteArray),\n numReadonlySignedAccounts: guardedShift(byteArray),\n numReadonlyUnsignedAccounts: guardedShift(byteArray)\n };\n const staticAccountKeys = [];\n const staticAccountKeysLength = decodeLength(byteArray);\n for (let i = 0; i < staticAccountKeysLength; i++) {\n staticAccountKeys.push(new PublicKey(guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH)));\n }\n const recentBlockhash = bs58.encode(guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH));\n const instructionCount = decodeLength(byteArray);\n const compiledInstructions = [];\n for (let i = 0; i < instructionCount; i++) {\n const programIdIndex = guardedShift(byteArray);\n const accountKeyIndexesLength = decodeLength(byteArray);\n const accountKeyIndexes = guardedSplice(byteArray, 0, accountKeyIndexesLength);\n const dataLength = decodeLength(byteArray);\n const data = new Uint8Array(guardedSplice(byteArray, 0, dataLength));\n compiledInstructions.push({\n programIdIndex,\n accountKeyIndexes,\n data\n });\n }\n const addressTableLookupsCount = decodeLength(byteArray);\n const addressTableLookups = [];\n for (let i = 0; i < addressTableLookupsCount; i++) {\n const accountKey = new PublicKey(guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH));\n const writableIndexesLength = decodeLength(byteArray);\n const writableIndexes = guardedSplice(byteArray, 0, writableIndexesLength);\n const readonlyIndexesLength = decodeLength(byteArray);\n const readonlyIndexes = guardedSplice(byteArray, 0, readonlyIndexesLength);\n addressTableLookups.push({\n accountKey,\n writableIndexes,\n readonlyIndexes\n });\n }\n return new MessageV0({\n header,\n staticAccountKeys,\n recentBlockhash,\n compiledInstructions,\n addressTableLookups\n });\n }\n}\n\n// eslint-disable-next-line no-redeclare\nconst VersionedMessage = {\n deserializeMessageVersion(serializedMessage) {\n const prefix = serializedMessage[0];\n const maskedPrefix = prefix & VERSION_PREFIX_MASK;\n\n // if the highest bit of the prefix is not set, the message is not versioned\n if (maskedPrefix === prefix) {\n return 'legacy';\n }\n\n // the lower 7 bits of the prefix indicate the message version\n return maskedPrefix;\n },\n deserialize: serializedMessage => {\n const version = VersionedMessage.deserializeMessageVersion(serializedMessage);\n if (version === 'legacy') {\n return Message.from(serializedMessage);\n }\n if (version === 0) {\n return MessageV0.deserialize(serializedMessage);\n } else {\n throw new Error(`Transaction message version ${version} deserialization is not supported`);\n }\n }\n};\n\n/** @internal */\n\n/**\n * Transaction signature as base-58 encoded string\n */\n\nlet TransactionStatus = /*#__PURE__*/function (TransactionStatus) {\n TransactionStatus[TransactionStatus[\"BLOCKHEIGHT_EXCEEDED\"] = 0] = \"BLOCKHEIGHT_EXCEEDED\";\n TransactionStatus[TransactionStatus[\"PROCESSED\"] = 1] = \"PROCESSED\";\n TransactionStatus[TransactionStatus[\"TIMED_OUT\"] = 2] = \"TIMED_OUT\";\n TransactionStatus[TransactionStatus[\"NONCE_INVALID\"] = 3] = \"NONCE_INVALID\";\n return TransactionStatus;\n}({});\n\n/**\n * Default (empty) signature\n */\nconst DEFAULT_SIGNATURE = Buffer.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0);\n\n/**\n * Account metadata used to define instructions\n */\n\n/**\n * List of TransactionInstruction object fields that may be initialized at construction\n */\n\n/**\n * Configuration object for Transaction.serialize()\n */\n\n/**\n * @internal\n */\n\n/**\n * Transaction Instruction class\n */\nclass TransactionInstruction {\n constructor(opts) {\n /**\n * Public keys to include in this transaction\n * Boolean represents whether this pubkey needs to sign the transaction\n */\n this.keys = void 0;\n /**\n * Program Id to execute\n */\n this.programId = void 0;\n /**\n * Program input\n */\n this.data = Buffer.alloc(0);\n this.programId = opts.programId;\n this.keys = opts.keys;\n if (opts.data) {\n this.data = opts.data;\n }\n }\n\n /**\n * @internal\n */\n toJSON() {\n return {\n keys: this.keys.map(({\n pubkey,\n isSigner,\n isWritable\n }) => ({\n pubkey: pubkey.toJSON(),\n isSigner,\n isWritable\n })),\n programId: this.programId.toJSON(),\n data: [...this.data]\n };\n }\n}\n\n/**\n * Pair of signature and corresponding public key\n */\n\n/**\n * List of Transaction object fields that may be initialized at construction\n */\n\n// For backward compatibility; an unfortunate consequence of being\n// forced to over-export types by the documentation generator.\n// See https://github.com/solana-labs/solana/pull/25820\n\n/**\n * Blockhash-based transactions have a lifetime that are defined by\n * the blockhash they include. Any transaction whose blockhash is\n * too old will be rejected.\n */\n\n/**\n * Use these options to construct a durable nonce transaction.\n */\n\n/**\n * Nonce information to be used to build an offline Transaction.\n */\n\n/**\n * @internal\n */\n\n/**\n * Transaction class\n */\nclass Transaction {\n /**\n * The first (payer) Transaction signature\n *\n * @returns {Buffer | null} Buffer of payer's signature\n */\n get signature() {\n if (this.signatures.length > 0) {\n return this.signatures[0].signature;\n }\n return null;\n }\n\n /**\n * The transaction fee payer\n */\n\n // Construct a transaction with a blockhash and lastValidBlockHeight\n\n // Construct a transaction using a durable nonce\n\n /**\n * @deprecated `TransactionCtorFields` has been deprecated and will be removed in a future version.\n * Please supply a `TransactionBlockhashCtor` instead.\n */\n\n /**\n * Construct an empty Transaction\n */\n constructor(opts) {\n /**\n * Signatures for the transaction. Typically created by invoking the\n * `sign()` method\n */\n this.signatures = [];\n this.feePayer = void 0;\n /**\n * The instructions to atomically execute\n */\n this.instructions = [];\n /**\n * A recent transaction id. Must be populated by the caller\n */\n this.recentBlockhash = void 0;\n /**\n * the last block chain can advance to before tx is declared expired\n * */\n this.lastValidBlockHeight = void 0;\n /**\n * Optional Nonce information. If populated, transaction will use a durable\n * Nonce hash instead of a recentBlockhash. Must be populated by the caller\n */\n this.nonceInfo = void 0;\n /**\n * If this is a nonce transaction this represents the minimum slot from which\n * to evaluate if the nonce has advanced when attempting to confirm the\n * transaction. This protects against a case where the transaction confirmation\n * logic loads the nonce account from an old slot and assumes the mismatch in\n * nonce value implies that the nonce has been advanced.\n */\n this.minNonceContextSlot = void 0;\n /**\n * @internal\n */\n this._message = void 0;\n /**\n * @internal\n */\n this._json = void 0;\n if (!opts) {\n return;\n }\n if (opts.feePayer) {\n this.feePayer = opts.feePayer;\n }\n if (opts.signatures) {\n this.signatures = opts.signatures;\n }\n if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) {\n const {\n minContextSlot,\n nonceInfo\n } = opts;\n this.minNonceContextSlot = minContextSlot;\n this.nonceInfo = nonceInfo;\n } else if (Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')) {\n const {\n blockhash,\n lastValidBlockHeight\n } = opts;\n this.recentBlockhash = blockhash;\n this.lastValidBlockHeight = lastValidBlockHeight;\n } else {\n const {\n recentBlockhash,\n nonceInfo\n } = opts;\n if (nonceInfo) {\n this.nonceInfo = nonceInfo;\n }\n this.recentBlockhash = recentBlockhash;\n }\n }\n\n /**\n * @internal\n */\n toJSON() {\n return {\n recentBlockhash: this.recentBlockhash || null,\n feePayer: this.feePayer ? this.feePayer.toJSON() : null,\n nonceInfo: this.nonceInfo ? {\n nonce: this.nonceInfo.nonce,\n nonceInstruction: this.nonceInfo.nonceInstruction.toJSON()\n } : null,\n instructions: this.instructions.map(instruction => instruction.toJSON()),\n signers: this.signatures.map(({\n publicKey\n }) => {\n return publicKey.toJSON();\n })\n };\n }\n\n /**\n * Add one or more instructions to this Transaction\n *\n * @param {Array< Transaction | TransactionInstruction | TransactionInstructionCtorFields >} items - Instructions to add to the Transaction\n */\n add(...items) {\n if (items.length === 0) {\n throw new Error('No instructions');\n }\n items.forEach(item => {\n if ('instructions' in item) {\n this.instructions = this.instructions.concat(item.instructions);\n } else if ('data' in item && 'programId' in item && 'keys' in item) {\n this.instructions.push(item);\n } else {\n this.instructions.push(new TransactionInstruction(item));\n }\n });\n return this;\n }\n\n /**\n * Compile transaction data\n */\n compileMessage() {\n if (this._message && JSON.stringify(this.toJSON()) === JSON.stringify(this._json)) {\n return this._message;\n }\n let recentBlockhash;\n let instructions;\n if (this.nonceInfo) {\n recentBlockhash = this.nonceInfo.nonce;\n if (this.instructions[0] != this.nonceInfo.nonceInstruction) {\n instructions = [this.nonceInfo.nonceInstruction, ...this.instructions];\n } else {\n instructions = this.instructions;\n }\n } else {\n recentBlockhash = this.recentBlockhash;\n instructions = this.instructions;\n }\n if (!recentBlockhash) {\n throw new Error('Transaction recentBlockhash required');\n }\n if (instructions.length < 1) {\n console.warn('No instructions provided');\n }\n let feePayer;\n if (this.feePayer) {\n feePayer = this.feePayer;\n } else if (this.signatures.length > 0 && this.signatures[0].publicKey) {\n // Use implicit fee payer\n feePayer = this.signatures[0].publicKey;\n } else {\n throw new Error('Transaction fee payer required');\n }\n for (let i = 0; i < instructions.length; i++) {\n if (instructions[i].programId === undefined) {\n throw new Error(`Transaction instruction index ${i} has undefined program id`);\n }\n }\n const programIds = [];\n const accountMetas = [];\n instructions.forEach(instruction => {\n instruction.keys.forEach(accountMeta => {\n accountMetas.push({\n ...accountMeta\n });\n });\n const programId = instruction.programId.toString();\n if (!programIds.includes(programId)) {\n programIds.push(programId);\n }\n });\n\n // Append programID account metas\n programIds.forEach(programId => {\n accountMetas.push({\n pubkey: new PublicKey(programId),\n isSigner: false,\n isWritable: false\n });\n });\n\n // Cull duplicate account metas\n const uniqueMetas = [];\n accountMetas.forEach(accountMeta => {\n const pubkeyString = accountMeta.pubkey.toString();\n const uniqueIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.toString() === pubkeyString;\n });\n if (uniqueIndex > -1) {\n uniqueMetas[uniqueIndex].isWritable = uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable;\n uniqueMetas[uniqueIndex].isSigner = uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner;\n } else {\n uniqueMetas.push(accountMeta);\n }\n });\n\n // Sort. Prioritizing first by signer, then by writable\n uniqueMetas.sort(function (x, y) {\n if (x.isSigner !== y.isSigner) {\n // Signers always come before non-signers\n return x.isSigner ? -1 : 1;\n }\n if (x.isWritable !== y.isWritable) {\n // Writable accounts always come before read-only accounts\n return x.isWritable ? -1 : 1;\n }\n // Otherwise, sort by pubkey, stringwise.\n const options = {\n localeMatcher: 'best fit',\n usage: 'sort',\n sensitivity: 'variant',\n ignorePunctuation: false,\n numeric: false,\n caseFirst: 'lower'\n };\n return x.pubkey.toBase58().localeCompare(y.pubkey.toBase58(), 'en', options);\n });\n\n // Move fee payer to the front\n const feePayerIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.equals(feePayer);\n });\n if (feePayerIndex > -1) {\n const [payerMeta] = uniqueMetas.splice(feePayerIndex, 1);\n payerMeta.isSigner = true;\n payerMeta.isWritable = true;\n uniqueMetas.unshift(payerMeta);\n } else {\n uniqueMetas.unshift({\n pubkey: feePayer,\n isSigner: true,\n isWritable: true\n });\n }\n\n // Disallow unknown signers\n for (const signature of this.signatures) {\n const uniqueIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.equals(signature.publicKey);\n });\n if (uniqueIndex > -1) {\n if (!uniqueMetas[uniqueIndex].isSigner) {\n uniqueMetas[uniqueIndex].isSigner = true;\n 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.');\n }\n } else {\n throw new Error(`unknown signer: ${signature.publicKey.toString()}`);\n }\n }\n let numRequiredSignatures = 0;\n let numReadonlySignedAccounts = 0;\n let numReadonlyUnsignedAccounts = 0;\n\n // Split out signing from non-signing keys and count header values\n const signedKeys = [];\n const unsignedKeys = [];\n uniqueMetas.forEach(({\n pubkey,\n isSigner,\n isWritable\n }) => {\n if (isSigner) {\n signedKeys.push(pubkey.toString());\n numRequiredSignatures += 1;\n if (!isWritable) {\n numReadonlySignedAccounts += 1;\n }\n } else {\n unsignedKeys.push(pubkey.toString());\n if (!isWritable) {\n numReadonlyUnsignedAccounts += 1;\n }\n }\n });\n const accountKeys = signedKeys.concat(unsignedKeys);\n const compiledInstructions = instructions.map(instruction => {\n const {\n data,\n programId\n } = instruction;\n return {\n programIdIndex: accountKeys.indexOf(programId.toString()),\n accounts: instruction.keys.map(meta => accountKeys.indexOf(meta.pubkey.toString())),\n data: bs58.encode(data)\n };\n });\n compiledInstructions.forEach(instruction => {\n assert(instruction.programIdIndex >= 0);\n instruction.accounts.forEach(keyIndex => assert(keyIndex >= 0));\n });\n return new Message({\n header: {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts\n },\n accountKeys,\n recentBlockhash,\n instructions: compiledInstructions\n });\n }\n\n /**\n * @internal\n */\n _compile() {\n const message = this.compileMessage();\n const signedKeys = message.accountKeys.slice(0, message.header.numRequiredSignatures);\n if (this.signatures.length === signedKeys.length) {\n const valid = this.signatures.every((pair, index) => {\n return signedKeys[index].equals(pair.publicKey);\n });\n if (valid) return message;\n }\n this.signatures = signedKeys.map(publicKey => ({\n signature: null,\n publicKey\n }));\n return message;\n }\n\n /**\n * Get a buffer of the Transaction data that need to be covered by signatures\n */\n serializeMessage() {\n return this._compile().serialize();\n }\n\n /**\n * Get the estimated fee associated with a transaction\n *\n * @param {Connection} connection Connection to RPC Endpoint.\n *\n * @returns {Promise} The estimated fee for the transaction\n */\n async getEstimatedFee(connection) {\n return (await connection.getFeeForMessage(this.compileMessage())).value;\n }\n\n /**\n * Specify the public keys which will be used to sign the Transaction.\n * The first signer will be used as the transaction fee payer account.\n *\n * Signatures can be added with either `partialSign` or `addSignature`\n *\n * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be\n * specified and it can be set in the Transaction constructor or with the\n * `feePayer` property.\n */\n setSigners(...signers) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n const seen = new Set();\n this.signatures = signers.filter(publicKey => {\n const key = publicKey.toString();\n if (seen.has(key)) {\n return false;\n } else {\n seen.add(key);\n return true;\n }\n }).map(publicKey => ({\n signature: null,\n publicKey\n }));\n }\n\n /**\n * Sign the Transaction with the specified signers. Multiple signatures may\n * be applied to a Transaction. The first signature is considered \"primary\"\n * and is used identify and confirm transactions.\n *\n * If the Transaction `feePayer` is not set, the first signer will be used\n * as the transaction fee payer account.\n *\n * Transaction fields should not be modified after the first call to `sign`,\n * as doing so may invalidate the signature and cause the Transaction to be\n * rejected.\n *\n * The Transaction must be assigned a valid `recentBlockhash` before invoking this method\n *\n * @param {Array} signers Array of signers that will sign the transaction\n */\n sign(...signers) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n // Dedupe signers\n const seen = new Set();\n const uniqueSigners = [];\n for (const signer of signers) {\n const key = signer.publicKey.toString();\n if (seen.has(key)) {\n continue;\n } else {\n seen.add(key);\n uniqueSigners.push(signer);\n }\n }\n this.signatures = uniqueSigners.map(signer => ({\n signature: null,\n publicKey: signer.publicKey\n }));\n const message = this._compile();\n this._partialSign(message, ...uniqueSigners);\n }\n\n /**\n * Partially sign a transaction with the specified accounts. All accounts must\n * correspond to either the fee payer or a signer account in the transaction\n * instructions.\n *\n * All the caveats from the `sign` method apply to `partialSign`\n *\n * @param {Array} signers Array of signers that will sign the transaction\n */\n partialSign(...signers) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n // Dedupe signers\n const seen = new Set();\n const uniqueSigners = [];\n for (const signer of signers) {\n const key = signer.publicKey.toString();\n if (seen.has(key)) {\n continue;\n } else {\n seen.add(key);\n uniqueSigners.push(signer);\n }\n }\n const message = this._compile();\n this._partialSign(message, ...uniqueSigners);\n }\n\n /**\n * @internal\n */\n _partialSign(message, ...signers) {\n const signData = message.serialize();\n signers.forEach(signer => {\n const signature = sign(signData, signer.secretKey);\n this._addSignature(signer.publicKey, toBuffer(signature));\n });\n }\n\n /**\n * Add an externally created signature to a transaction. The public key\n * must correspond to either the fee payer or a signer account in the transaction\n * instructions.\n *\n * @param {PublicKey} pubkey Public key that will be added to the transaction.\n * @param {Buffer} signature An externally created signature to add to the transaction.\n */\n addSignature(pubkey, signature) {\n this._compile(); // Ensure signatures array is populated\n this._addSignature(pubkey, signature);\n }\n\n /**\n * @internal\n */\n _addSignature(pubkey, signature) {\n assert(signature.length === 64);\n const index = this.signatures.findIndex(sigpair => pubkey.equals(sigpair.publicKey));\n if (index < 0) {\n throw new Error(`unknown signer: ${pubkey.toString()}`);\n }\n this.signatures[index].signature = Buffer.from(signature);\n }\n\n /**\n * Verify signatures of a Transaction\n * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one.\n * If no boolean is provided, we expect a fully signed Transaction by default.\n *\n * @param {boolean} [requireAllSignatures=true] Require a fully signed Transaction\n */\n verifySignatures(requireAllSignatures = true) {\n const signatureErrors = this._getMessageSignednessErrors(this.serializeMessage(), requireAllSignatures);\n return !signatureErrors;\n }\n\n /**\n * @internal\n */\n _getMessageSignednessErrors(message, requireAllSignatures) {\n const errors = {};\n for (const {\n signature,\n publicKey\n } of this.signatures) {\n if (signature === null) {\n if (requireAllSignatures) {\n (errors.missing ||= []).push(publicKey);\n }\n } else {\n if (!verify(signature, message, publicKey.toBytes())) {\n (errors.invalid ||= []).push(publicKey);\n }\n }\n }\n return errors.invalid || errors.missing ? errors : undefined;\n }\n\n /**\n * Serialize the Transaction in the wire format.\n *\n * @param {Buffer} [config] Config of transaction.\n *\n * @returns {Buffer} Signature of transaction in wire format.\n */\n serialize(config) {\n const {\n requireAllSignatures,\n verifySignatures\n } = Object.assign({\n requireAllSignatures: true,\n verifySignatures: true\n }, config);\n const signData = this.serializeMessage();\n if (verifySignatures) {\n const sigErrors = this._getMessageSignednessErrors(signData, requireAllSignatures);\n if (sigErrors) {\n let errorMessage = 'Signature verification failed.';\n if (sigErrors.invalid) {\n errorMessage += `\\nInvalid signature for public key${sigErrors.invalid.length === 1 ? '' : '(s)'} [\\`${sigErrors.invalid.map(p => p.toBase58()).join('`, `')}\\`].`;\n }\n if (sigErrors.missing) {\n errorMessage += `\\nMissing signature for public key${sigErrors.missing.length === 1 ? '' : '(s)'} [\\`${sigErrors.missing.map(p => p.toBase58()).join('`, `')}\\`].`;\n }\n throw new Error(errorMessage);\n }\n }\n return this._serialize(signData);\n }\n\n /**\n * @internal\n */\n _serialize(signData) {\n const {\n signatures\n } = this;\n const signatureCount = [];\n encodeLength(signatureCount, signatures.length);\n const transactionLength = signatureCount.length + signatures.length * 64 + signData.length;\n const wireTransaction = Buffer.alloc(transactionLength);\n assert(signatures.length < 256);\n Buffer.from(signatureCount).copy(wireTransaction, 0);\n signatures.forEach(({\n signature\n }, index) => {\n if (signature !== null) {\n assert(signature.length === 64, `signature has invalid length`);\n Buffer.from(signature).copy(wireTransaction, signatureCount.length + index * 64);\n }\n });\n signData.copy(wireTransaction, signatureCount.length + signatures.length * 64);\n assert(wireTransaction.length <= PACKET_DATA_SIZE, `Transaction too large: ${wireTransaction.length} > ${PACKET_DATA_SIZE}`);\n return wireTransaction;\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get keys() {\n assert(this.instructions.length === 1);\n return this.instructions[0].keys.map(keyObj => keyObj.pubkey);\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get programId() {\n assert(this.instructions.length === 1);\n return this.instructions[0].programId;\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get data() {\n assert(this.instructions.length === 1);\n return this.instructions[0].data;\n }\n\n /**\n * Parse a wire transaction into a Transaction object.\n *\n * @param {Buffer | Uint8Array | Array} buffer Signature of wire Transaction\n *\n * @returns {Transaction} Transaction associated with the signature\n */\n static from(buffer) {\n // Slice up wire data\n let byteArray = [...buffer];\n const signatureCount = decodeLength(byteArray);\n let signatures = [];\n for (let i = 0; i < signatureCount; i++) {\n const signature = guardedSplice(byteArray, 0, SIGNATURE_LENGTH_IN_BYTES);\n signatures.push(bs58.encode(Buffer.from(signature)));\n }\n return Transaction.populate(Message.from(byteArray), signatures);\n }\n\n /**\n * Populate Transaction object from message and signatures\n *\n * @param {Message} message Message of transaction\n * @param {Array} signatures List of signatures to assign to the transaction\n *\n * @returns {Transaction} The populated Transaction\n */\n static populate(message, signatures = []) {\n const transaction = new Transaction();\n transaction.recentBlockhash = message.recentBlockhash;\n if (message.header.numRequiredSignatures > 0) {\n transaction.feePayer = message.accountKeys[0];\n }\n signatures.forEach((signature, index) => {\n const sigPubkeyPair = {\n signature: signature == bs58.encode(DEFAULT_SIGNATURE) ? null : bs58.decode(signature),\n publicKey: message.accountKeys[index]\n };\n transaction.signatures.push(sigPubkeyPair);\n });\n message.instructions.forEach(instruction => {\n const keys = instruction.accounts.map(account => {\n const pubkey = message.accountKeys[account];\n return {\n pubkey,\n isSigner: transaction.signatures.some(keyObj => keyObj.publicKey.toString() === pubkey.toString()) || message.isAccountSigner(account),\n isWritable: message.isAccountWritable(account)\n };\n });\n transaction.instructions.push(new TransactionInstruction({\n keys,\n programId: message.accountKeys[instruction.programIdIndex],\n data: bs58.decode(instruction.data)\n }));\n });\n transaction._message = message;\n transaction._json = transaction.toJSON();\n return transaction;\n }\n}\n\nclass TransactionMessage {\n constructor(args) {\n this.payerKey = void 0;\n this.instructions = void 0;\n this.recentBlockhash = void 0;\n this.payerKey = args.payerKey;\n this.instructions = args.instructions;\n this.recentBlockhash = args.recentBlockhash;\n }\n static decompile(message, args) {\n const {\n header,\n compiledInstructions,\n recentBlockhash\n } = message;\n const {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts\n } = header;\n const numWritableSignedAccounts = numRequiredSignatures - numReadonlySignedAccounts;\n assert(numWritableSignedAccounts > 0, 'Message header is invalid');\n const numWritableUnsignedAccounts = message.staticAccountKeys.length - numRequiredSignatures - numReadonlyUnsignedAccounts;\n assert(numWritableUnsignedAccounts >= 0, 'Message header is invalid');\n const accountKeys = message.getAccountKeys(args);\n const payerKey = accountKeys.get(0);\n if (payerKey === undefined) {\n throw new Error('Failed to decompile message because no account keys were found');\n }\n const instructions = [];\n for (const compiledIx of compiledInstructions) {\n const keys = [];\n for (const keyIndex of compiledIx.accountKeyIndexes) {\n const pubkey = accountKeys.get(keyIndex);\n if (pubkey === undefined) {\n throw new Error(`Failed to find key for account key index ${keyIndex}`);\n }\n const isSigner = keyIndex < numRequiredSignatures;\n let isWritable;\n if (isSigner) {\n isWritable = keyIndex < numWritableSignedAccounts;\n } else if (keyIndex < accountKeys.staticAccountKeys.length) {\n isWritable = keyIndex - numRequiredSignatures < numWritableUnsignedAccounts;\n } else {\n isWritable = keyIndex - accountKeys.staticAccountKeys.length <\n // accountKeysFromLookups cannot be undefined because we already found a pubkey for this index above\n accountKeys.accountKeysFromLookups.writable.length;\n }\n keys.push({\n pubkey,\n isSigner: keyIndex < header.numRequiredSignatures,\n isWritable\n });\n }\n const programId = accountKeys.get(compiledIx.programIdIndex);\n if (programId === undefined) {\n throw new Error(`Failed to find program id for program id index ${compiledIx.programIdIndex}`);\n }\n instructions.push(new TransactionInstruction({\n programId,\n data: toBuffer(compiledIx.data),\n keys\n }));\n }\n return new TransactionMessage({\n payerKey,\n instructions,\n recentBlockhash\n });\n }\n compileToLegacyMessage() {\n return Message.compile({\n payerKey: this.payerKey,\n recentBlockhash: this.recentBlockhash,\n instructions: this.instructions\n });\n }\n compileToV0Message(addressLookupTableAccounts) {\n return MessageV0.compile({\n payerKey: this.payerKey,\n recentBlockhash: this.recentBlockhash,\n instructions: this.instructions,\n addressLookupTableAccounts\n });\n }\n}\n\n/**\n * Versioned transaction class\n */\nclass VersionedTransaction {\n get version() {\n return this.message.version;\n }\n constructor(message, signatures) {\n this.signatures = void 0;\n this.message = void 0;\n if (signatures !== undefined) {\n assert(signatures.length === message.header.numRequiredSignatures, 'Expected signatures length to be equal to the number of required signatures');\n this.signatures = signatures;\n } else {\n const defaultSignatures = [];\n for (let i = 0; i < message.header.numRequiredSignatures; i++) {\n defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES));\n }\n this.signatures = defaultSignatures;\n }\n this.message = message;\n }\n serialize() {\n const serializedMessage = this.message.serialize();\n const encodedSignaturesLength = Array();\n encodeLength(encodedSignaturesLength, this.signatures.length);\n const transactionLayout = BufferLayout.struct([BufferLayout.blob(encodedSignaturesLength.length, 'encodedSignaturesLength'), BufferLayout.seq(signature(), this.signatures.length, 'signatures'), BufferLayout.blob(serializedMessage.length, 'serializedMessage')]);\n const serializedTransaction = new Uint8Array(2048);\n const serializedTransactionLength = transactionLayout.encode({\n encodedSignaturesLength: new Uint8Array(encodedSignaturesLength),\n signatures: this.signatures,\n serializedMessage\n }, serializedTransaction);\n return serializedTransaction.slice(0, serializedTransactionLength);\n }\n static deserialize(serializedTransaction) {\n let byteArray = [...serializedTransaction];\n const signatures = [];\n const signaturesLength = decodeLength(byteArray);\n for (let i = 0; i < signaturesLength; i++) {\n signatures.push(new Uint8Array(guardedSplice(byteArray, 0, SIGNATURE_LENGTH_IN_BYTES)));\n }\n const message = VersionedMessage.deserialize(new Uint8Array(byteArray));\n return new VersionedTransaction(message, signatures);\n }\n sign(signers) {\n const messageData = this.message.serialize();\n const signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures);\n for (const signer of signers) {\n const signerIndex = signerPubkeys.findIndex(pubkey => pubkey.equals(signer.publicKey));\n assert(signerIndex >= 0, `Cannot sign with non signer key ${signer.publicKey.toBase58()}`);\n this.signatures[signerIndex] = sign(messageData, signer.secretKey);\n }\n }\n addSignature(publicKey, signature) {\n assert(signature.byteLength === 64, 'Signature must be 64 bytes long');\n const signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures);\n const signerIndex = signerPubkeys.findIndex(pubkey => pubkey.equals(publicKey));\n assert(signerIndex >= 0, `Can not add signature; \\`${publicKey.toBase58()}\\` is not required to sign this transaction`);\n this.signatures[signerIndex] = signature;\n }\n}\n\n// TODO: These constants should be removed in favor of reading them out of a\n// Syscall account\n\n/**\n * @internal\n */\nconst NUM_TICKS_PER_SECOND = 160;\n\n/**\n * @internal\n */\nconst DEFAULT_TICKS_PER_SLOT = 64;\n\n/**\n * @internal\n */\nconst NUM_SLOTS_PER_SECOND = NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT;\n\n/**\n * @internal\n */\nconst MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND;\n\nconst SYSVAR_CLOCK_PUBKEY = new PublicKey('SysvarC1ock11111111111111111111111111111111');\nconst SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey('SysvarEpochSchedu1e111111111111111111111111');\nconst SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey('Sysvar1nstructions1111111111111111111111111');\nconst SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey('SysvarRecentB1ockHashes11111111111111111111');\nconst SYSVAR_RENT_PUBKEY = new PublicKey('SysvarRent111111111111111111111111111111111');\nconst SYSVAR_REWARDS_PUBKEY = new PublicKey('SysvarRewards111111111111111111111111111111');\nconst SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey('SysvarS1otHashes111111111111111111111111111');\nconst SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey('SysvarS1otHistory11111111111111111111111111');\nconst SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey('SysvarStakeHistory1111111111111111111111111');\n\nclass SendTransactionError extends Error {\n constructor({\n action,\n signature,\n transactionMessage,\n logs\n }) {\n const maybeLogsOutput = logs ? `Logs: \\n${JSON.stringify(logs.slice(-10), null, 2)}. ` : '';\n const guideText = '\\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.';\n let message;\n switch (action) {\n case 'send':\n message = `Transaction ${signature} resulted in an error. \\n` + `${transactionMessage}. ` + maybeLogsOutput + guideText;\n break;\n case 'simulate':\n message = `Simulation failed. \\nMessage: ${transactionMessage}. \\n` + maybeLogsOutput + guideText;\n break;\n default:\n {\n message = `Unknown action '${(a => a)(action)}'`;\n }\n }\n super(message);\n this.signature = void 0;\n this.transactionMessage = void 0;\n this.transactionLogs = void 0;\n this.signature = signature;\n this.transactionMessage = transactionMessage;\n this.transactionLogs = logs ? logs : undefined;\n }\n get transactionError() {\n return {\n message: this.transactionMessage,\n logs: Array.isArray(this.transactionLogs) ? this.transactionLogs : undefined\n };\n }\n\n /* @deprecated Use `await getLogs()` instead */\n get logs() {\n const cachedLogs = this.transactionLogs;\n if (cachedLogs != null && typeof cachedLogs === 'object' && 'then' in cachedLogs) {\n return undefined;\n }\n return cachedLogs;\n }\n async getLogs(connection) {\n if (!Array.isArray(this.transactionLogs)) {\n this.transactionLogs = new Promise((resolve, reject) => {\n connection.getTransaction(this.signature).then(tx => {\n if (tx && tx.meta && tx.meta.logMessages) {\n const logs = tx.meta.logMessages;\n this.transactionLogs = logs;\n resolve(logs);\n } else {\n reject(new Error('Log messages not found'));\n }\n }).catch(reject);\n });\n }\n return await this.transactionLogs;\n }\n}\n\n// Keep in sync with client/src/rpc_custom_errors.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nconst SolanaJSONRPCErrorCode = {\n JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n JSON_RPC_SCAN_ERROR: -32012,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016\n};\nclass SolanaJSONRPCError extends Error {\n constructor({\n code,\n message,\n data\n }, customMessage) {\n super(customMessage != null ? `${customMessage}: ${message}` : message);\n this.code = void 0;\n this.data = void 0;\n this.code = code;\n this.data = data;\n this.name = 'SolanaJSONRPCError';\n }\n}\n\n/**\n * Sign, send and confirm a transaction.\n *\n * If `commitment` option is not specified, defaults to 'max' commitment.\n *\n * @param {Connection} connection\n * @param {Transaction} transaction\n * @param {Array} signers\n * @param {ConfirmOptions} [options]\n * @returns {Promise}\n */\nasync function sendAndConfirmTransaction(connection, transaction, signers, options) {\n const sendOptions = options && {\n skipPreflight: options.skipPreflight,\n preflightCommitment: options.preflightCommitment || options.commitment,\n maxRetries: options.maxRetries,\n minContextSlot: options.minContextSlot\n };\n const signature = await connection.sendTransaction(transaction, signers, sendOptions);\n let status;\n if (transaction.recentBlockhash != null && transaction.lastValidBlockHeight != null) {\n status = (await connection.confirmTransaction({\n abortSignal: options?.abortSignal,\n signature: signature,\n blockhash: transaction.recentBlockhash,\n lastValidBlockHeight: transaction.lastValidBlockHeight\n }, options && options.commitment)).value;\n } else if (transaction.minNonceContextSlot != null && transaction.nonceInfo != null) {\n const {\n nonceInstruction\n } = transaction.nonceInfo;\n const nonceAccountPubkey = nonceInstruction.keys[0].pubkey;\n status = (await connection.confirmTransaction({\n abortSignal: options?.abortSignal,\n minContextSlot: transaction.minNonceContextSlot,\n nonceAccountPubkey,\n nonceValue: transaction.nonceInfo.nonce,\n signature\n }, options && options.commitment)).value;\n } else {\n if (options?.abortSignal != null) {\n 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.');\n }\n status = (await connection.confirmTransaction(signature, options && options.commitment)).value;\n }\n if (status.err) {\n if (signature != null) {\n throw new SendTransactionError({\n action: 'send',\n signature: signature,\n transactionMessage: `Status: (${JSON.stringify(status)})`\n });\n }\n throw new Error(`Transaction ${signature} failed (${JSON.stringify(status)})`);\n }\n return signature;\n}\n\n// zzz\nfunction sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * @internal\n */\n\n/**\n * Populate a buffer of instruction data using an InstructionType\n * @internal\n */\nfunction encodeData(type, fields) {\n const allocLength = type.layout.span >= 0 ? type.layout.span : getAlloc(type, fields);\n const data = Buffer.alloc(allocLength);\n const layoutFields = Object.assign({\n instruction: type.index\n }, fields);\n type.layout.encode(layoutFields, data);\n return data;\n}\n\n/**\n * Decode instruction data buffer using an InstructionType\n * @internal\n */\nfunction decodeData$1(type, buffer) {\n let data;\n try {\n data = type.layout.decode(buffer);\n } catch (err) {\n throw new Error('invalid instruction; ' + err);\n }\n if (data.instruction !== type.index) {\n throw new Error(`invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`);\n }\n return data;\n}\n\n/**\n * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11\n *\n * @internal\n */\nconst FeeCalculatorLayout = BufferLayout.nu64('lamportsPerSignature');\n\n/**\n * Calculator for transaction fees.\n *\n * @deprecated Deprecated since Solana v1.8.0.\n */\n\n/**\n * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32\n *\n * @internal\n */\nconst NonceAccountLayout = BufferLayout.struct([BufferLayout.u32('version'), BufferLayout.u32('state'), publicKey('authorizedPubkey'), publicKey('nonce'), BufferLayout.struct([FeeCalculatorLayout], 'feeCalculator')]);\nconst NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span;\n\n/**\n * A durable nonce is a 32 byte value encoded as a base58 string.\n */\n\n/**\n * NonceAccount class\n */\nclass NonceAccount {\n /**\n * @internal\n */\n constructor(args) {\n this.authorizedPubkey = void 0;\n this.nonce = void 0;\n this.feeCalculator = void 0;\n this.authorizedPubkey = args.authorizedPubkey;\n this.nonce = args.nonce;\n this.feeCalculator = args.feeCalculator;\n }\n\n /**\n * Deserialize NonceAccount from the account data.\n *\n * @param buffer account data\n * @return NonceAccount\n */\n static fromAccountData(buffer) {\n const nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0);\n return new NonceAccount({\n authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey),\n nonce: new PublicKey(nonceAccount.nonce).toString(),\n feeCalculator: nonceAccount.feeCalculator\n });\n }\n}\n\nfunction u64(property) {\n const layout = blob(8 /* bytes */, property);\n const decode = layout.decode.bind(layout);\n const encode = layout.encode.bind(layout);\n const bigIntLayout = layout;\n const codec = getU64Codec();\n bigIntLayout.decode = (buffer, offset) => {\n const src = decode(buffer, offset);\n return codec.decode(src);\n };\n bigIntLayout.encode = (bigInt, buffer, offset) => {\n const src = codec.encode(bigInt);\n return encode(src, buffer, offset);\n };\n return bigIntLayout;\n}\n\n/**\n * Create account system transaction params\n */\n\n/**\n * Transfer system transaction params\n */\n\n/**\n * Assign system transaction params\n */\n\n/**\n * Create account with seed system transaction params\n */\n\n/**\n * Create nonce account system transaction params\n */\n\n/**\n * Create nonce account with seed system transaction params\n */\n\n/**\n * Initialize nonce account system instruction params\n */\n\n/**\n * Advance nonce account system instruction params\n */\n\n/**\n * Withdraw nonce account system transaction params\n */\n\n/**\n * Authorize nonce account system transaction params\n */\n\n/**\n * Allocate account system transaction params\n */\n\n/**\n * Allocate account with seed system transaction params\n */\n\n/**\n * Assign account with seed system transaction params\n */\n\n/**\n * Transfer with seed system transaction params\n */\n\n/** Decoded transfer system transaction instruction */\n\n/** Decoded transferWithSeed system transaction instruction */\n\n/**\n * System Instruction class\n */\nclass SystemInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a system instruction and retrieve the instruction type.\n */\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [ixType, layout] of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType;\n break;\n }\n }\n if (!type) {\n throw new Error('Instruction type incorrect; not a SystemInstruction');\n }\n return type;\n }\n\n /**\n * Decode a create account system instruction and retrieve the instruction params.\n */\n static decodeCreateAccount(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n lamports,\n space,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Create, instruction.data);\n return {\n fromPubkey: instruction.keys[0].pubkey,\n newAccountPubkey: instruction.keys[1].pubkey,\n lamports,\n space,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode a transfer system instruction and retrieve the instruction params.\n */\n static decodeTransfer(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n lamports\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Transfer, instruction.data);\n return {\n fromPubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n lamports\n };\n }\n\n /**\n * Decode a transfer with seed system instruction and retrieve the instruction params.\n */\n static decodeTransferWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n lamports,\n seed,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed, instruction.data);\n return {\n fromPubkey: instruction.keys[0].pubkey,\n basePubkey: instruction.keys[1].pubkey,\n toPubkey: instruction.keys[2].pubkey,\n lamports,\n seed,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode an allocate system instruction and retrieve the instruction params.\n */\n static decodeAllocate(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n const {\n space\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Allocate, instruction.data);\n return {\n accountPubkey: instruction.keys[0].pubkey,\n space\n };\n }\n\n /**\n * Decode an allocate with seed system instruction and retrieve the instruction params.\n */\n static decodeAllocateWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n const {\n base,\n seed,\n space,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed, instruction.data);\n return {\n accountPubkey: instruction.keys[0].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n space,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode an assign system instruction and retrieve the instruction params.\n */\n static decodeAssign(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n const {\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Assign, instruction.data);\n return {\n accountPubkey: instruction.keys[0].pubkey,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode an assign with seed system instruction and retrieve the instruction params.\n */\n static decodeAssignWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n const {\n base,\n seed,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed, instruction.data);\n return {\n accountPubkey: instruction.keys[0].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode a create account with seed system instruction and retrieve the instruction params.\n */\n static decodeCreateWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n base,\n seed,\n lamports,\n space,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed, instruction.data);\n return {\n fromPubkey: instruction.keys[0].pubkey,\n newAccountPubkey: instruction.keys[1].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n lamports,\n space,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode a nonce initialize system instruction and retrieve the instruction params.\n */\n static decodeNonceInitialize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n authorized\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount, instruction.data);\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: new PublicKey(authorized)\n };\n }\n\n /**\n * Decode a nonce advance system instruction and retrieve the instruction params.\n */\n static decodeNonceAdvance(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount, instruction.data);\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey\n };\n }\n\n /**\n * Decode a nonce withdraw system instruction and retrieve the instruction params.\n */\n static decodeNonceWithdraw(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 5);\n const {\n lamports\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount, instruction.data);\n return {\n noncePubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n lamports\n };\n }\n\n /**\n * Decode a nonce authorize system instruction and retrieve the instruction params.\n */\n static decodeNonceAuthorize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n authorized\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount, instruction.data);\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[1].pubkey,\n newAuthorizedPubkey: new PublicKey(authorized)\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(SystemProgram.programId)) {\n throw new Error('invalid instruction; programId is not SystemProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys, expectedLength) {\n if (keys.length < expectedLength) {\n throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`);\n }\n }\n}\n\n/**\n * An enumeration of valid SystemInstructionType's\n */\n\n/**\n * An enumeration of valid system InstructionType's\n * @internal\n */\nconst SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze({\n Create: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports'), BufferLayout.ns64('space'), publicKey('programId')])\n },\n Assign: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('programId')])\n },\n Transfer: {\n index: 2,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), u64('lamports')])\n },\n CreateWithSeed: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('base'), rustString('seed'), BufferLayout.ns64('lamports'), BufferLayout.ns64('space'), publicKey('programId')])\n },\n AdvanceNonceAccount: {\n index: 4,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n WithdrawNonceAccount: {\n index: 5,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')])\n },\n InitializeNonceAccount: {\n index: 6,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('authorized')])\n },\n AuthorizeNonceAccount: {\n index: 7,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('authorized')])\n },\n Allocate: {\n index: 8,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('space')])\n },\n AllocateWithSeed: {\n index: 9,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('base'), rustString('seed'), BufferLayout.ns64('space'), publicKey('programId')])\n },\n AssignWithSeed: {\n index: 10,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('base'), rustString('seed'), publicKey('programId')])\n },\n TransferWithSeed: {\n index: 11,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), u64('lamports'), rustString('seed'), publicKey('programId')])\n },\n UpgradeNonceAccount: {\n index: 12,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n }\n});\n\n/**\n * Factory class for transactions to interact with the System program\n */\nclass SystemProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the System program\n */\n\n /**\n * Generate a transaction instruction that creates a new account\n */\n static createAccount(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Create;\n const data = encodeData(type, {\n lamports: params.lamports,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer())\n });\n return new TransactionInstruction({\n keys: [{\n pubkey: params.fromPubkey,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: params.newAccountPubkey,\n isSigner: true,\n isWritable: true\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that transfers lamports from one account to another\n */\n static transfer(params) {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;\n data = encodeData(type, {\n lamports: BigInt(params.lamports),\n seed: params.seed,\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.fromPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: params.toPubkey,\n isSigner: false,\n isWritable: true\n }];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;\n data = encodeData(type, {\n lamports: BigInt(params.lamports)\n });\n keys = [{\n pubkey: params.fromPubkey,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: params.toPubkey,\n isSigner: false,\n isWritable: true\n }];\n }\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that assigns an account to a program\n */\n static assign(params) {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n }];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Assign;\n data = encodeData(type, {\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: true,\n isWritable: true\n }];\n }\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that creates a new account at\n * an address generated with `from`, a seed, and programId\n */\n static createAccountWithSeed(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;\n const data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n lamports: params.lamports,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer())\n });\n let keys = [{\n pubkey: params.fromPubkey,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: params.newAccountPubkey,\n isSigner: false,\n isWritable: true\n }];\n if (!params.basePubkey.equals(params.fromPubkey)) {\n keys.push({\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n });\n }\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction that creates a new Nonce account\n */\n static createNonceAccount(params) {\n const transaction = new Transaction();\n if ('basePubkey' in params && 'seed' in params) {\n transaction.add(SystemProgram.createAccountWithSeed({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.noncePubkey,\n basePubkey: params.basePubkey,\n seed: params.seed,\n lamports: params.lamports,\n space: NONCE_ACCOUNT_LENGTH,\n programId: this.programId\n }));\n } else {\n transaction.add(SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.noncePubkey,\n lamports: params.lamports,\n space: NONCE_ACCOUNT_LENGTH,\n programId: this.programId\n }));\n }\n const initParams = {\n noncePubkey: params.noncePubkey,\n authorizedPubkey: params.authorizedPubkey\n };\n transaction.add(this.nonceInitialize(initParams));\n return transaction;\n }\n\n /**\n * Generate an instruction to initialize a Nonce account\n */\n static nonceInitialize(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;\n const data = encodeData(type, {\n authorized: toBuffer(params.authorizedPubkey.toBuffer())\n });\n const instructionData = {\n keys: [{\n pubkey: params.noncePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }],\n programId: this.programId,\n data\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate an instruction to advance the nonce in a Nonce account\n */\n static nonceAdvance(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount;\n const data = encodeData(type);\n const instructionData = {\n keys: [{\n pubkey: params.noncePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: params.authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a transaction instruction that withdraws lamports from a Nonce account\n */\n static nonceWithdraw(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount;\n const data = encodeData(type, {\n lamports: params.lamports\n });\n return new TransactionInstruction({\n keys: [{\n pubkey: params.noncePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.toPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: params.authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that authorizes a new PublicKey as the authority\n * on a Nonce account.\n */\n static nonceAuthorize(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;\n const data = encodeData(type, {\n authorized: toBuffer(params.newAuthorizedPubkey.toBuffer())\n });\n return new TransactionInstruction({\n keys: [{\n pubkey: params.noncePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that allocates space in an account without funding\n */\n static allocate(params) {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n }];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;\n data = encodeData(type, {\n space: params.space\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: true,\n isWritable: true\n }];\n }\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }\n}\nSystemProgram.programId = new PublicKey('11111111111111111111111111111111');\n\n// Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the\n// rest of the Transaction fields\n//\n// TODO: replace 300 with a proper constant for the size of the other\n// Transaction fields\nconst CHUNK_SIZE = PACKET_DATA_SIZE - 300;\n\n/**\n * Program loader interface\n */\nclass Loader {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Amount of program data placed in each load Transaction\n */\n\n /**\n * Minimum number of signatures required to load a program not including\n * retries\n *\n * Can be used to calculate transaction fees\n */\n static getMinNumSignatures(dataLength) {\n return 2 * (\n // Every transaction requires two signatures (payer + program)\n Math.ceil(dataLength / Loader.chunkSize) + 1 +\n // Add one for Create transaction\n 1) // Add one for Finalize transaction\n ;\n }\n\n /**\n * Loads a generic program\n *\n * @param connection The connection to use\n * @param payer System account that pays to load the program\n * @param program Account to load the program into\n * @param programId Public key that identifies the loader\n * @param data Program octets\n * @return true if program was loaded successfully, false if program was already loaded\n */\n static async load(connection, payer, program, programId, data) {\n {\n const balanceNeeded = await connection.getMinimumBalanceForRentExemption(data.length);\n\n // Fetch program account info to check if it has already been created\n const programInfo = await connection.getAccountInfo(program.publicKey, 'confirmed');\n let transaction = null;\n if (programInfo !== null) {\n if (programInfo.executable) {\n console.error('Program load failed, account is already executable');\n return false;\n }\n if (programInfo.data.length !== data.length) {\n transaction = transaction || new Transaction();\n transaction.add(SystemProgram.allocate({\n accountPubkey: program.publicKey,\n space: data.length\n }));\n }\n if (!programInfo.owner.equals(programId)) {\n transaction = transaction || new Transaction();\n transaction.add(SystemProgram.assign({\n accountPubkey: program.publicKey,\n programId\n }));\n }\n if (programInfo.lamports < balanceNeeded) {\n transaction = transaction || new Transaction();\n transaction.add(SystemProgram.transfer({\n fromPubkey: payer.publicKey,\n toPubkey: program.publicKey,\n lamports: balanceNeeded - programInfo.lamports\n }));\n }\n } else {\n transaction = new Transaction().add(SystemProgram.createAccount({\n fromPubkey: payer.publicKey,\n newAccountPubkey: program.publicKey,\n lamports: balanceNeeded > 0 ? balanceNeeded : 1,\n space: data.length,\n programId\n }));\n }\n\n // If the account is already created correctly, skip this step\n // and proceed directly to loading instructions\n if (transaction !== null) {\n await sendAndConfirmTransaction(connection, transaction, [payer, program], {\n commitment: 'confirmed'\n });\n }\n }\n const dataLayout = BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.u32('offset'), BufferLayout.u32('bytesLength'), BufferLayout.u32('bytesLengthPadding'), BufferLayout.seq(BufferLayout.u8('byte'), BufferLayout.offset(BufferLayout.u32(), -8), 'bytes')]);\n const chunkSize = Loader.chunkSize;\n let offset = 0;\n let array = data;\n let transactions = [];\n while (array.length > 0) {\n const bytes = array.slice(0, chunkSize);\n const data = Buffer.alloc(chunkSize + 16);\n dataLayout.encode({\n instruction: 0,\n // Load instruction\n offset,\n bytes: bytes,\n bytesLength: 0,\n bytesLengthPadding: 0\n }, data);\n const transaction = new Transaction().add({\n keys: [{\n pubkey: program.publicKey,\n isSigner: true,\n isWritable: true\n }],\n programId,\n data\n });\n transactions.push(sendAndConfirmTransaction(connection, transaction, [payer, program], {\n commitment: 'confirmed'\n }));\n\n // Delay between sends in an attempt to reduce rate limit errors\n if (connection._rpcEndpoint.includes('solana.com')) {\n const REQUESTS_PER_SECOND = 4;\n await sleep(1000 / REQUESTS_PER_SECOND);\n }\n offset += chunkSize;\n array = array.slice(chunkSize);\n }\n await Promise.all(transactions);\n\n // Finalize the account loaded with program data for execution\n {\n const dataLayout = BufferLayout.struct([BufferLayout.u32('instruction')]);\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode({\n instruction: 1 // Finalize instruction\n }, data);\n const transaction = new Transaction().add({\n keys: [{\n pubkey: program.publicKey,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }],\n programId,\n data\n });\n const deployCommitment = 'processed';\n const finalizeSignature = await connection.sendTransaction(transaction, [payer, program], {\n preflightCommitment: deployCommitment\n });\n const {\n context,\n value\n } = await connection.confirmTransaction({\n signature: finalizeSignature,\n lastValidBlockHeight: transaction.lastValidBlockHeight,\n blockhash: transaction.recentBlockhash\n }, deployCommitment);\n if (value.err) {\n throw new Error(`Transaction ${finalizeSignature} failed (${JSON.stringify(value)})`);\n }\n // We prevent programs from being usable until the slot after their deployment.\n // See https://github.com/solana-labs/solana/pull/29654\n while (true // eslint-disable-line no-constant-condition\n ) {\n try {\n const currentSlot = await connection.getSlot({\n commitment: deployCommitment\n });\n if (currentSlot > context.slot) {\n break;\n }\n } catch {\n /* empty */\n }\n await new Promise(resolve => setTimeout(resolve, Math.round(MS_PER_SLOT / 2)));\n }\n }\n\n // success\n return true;\n }\n}\nLoader.chunkSize = CHUNK_SIZE;\n\n/**\n * @deprecated Deprecated since Solana v1.17.20.\n */\nconst BPF_LOADER_PROGRAM_ID = new PublicKey('BPFLoader2111111111111111111111111111111111');\n\n/**\n * Factory class for transactions to interact with a program loader\n *\n * @deprecated Deprecated since Solana v1.17.20.\n */\nclass BpfLoader {\n /**\n * Minimum number of signatures required to load a program not including\n * retries\n *\n * Can be used to calculate transaction fees\n */\n static getMinNumSignatures(dataLength) {\n return Loader.getMinNumSignatures(dataLength);\n }\n\n /**\n * Load a SBF program\n *\n * @param connection The connection to use\n * @param payer Account that will pay program loading fees\n * @param program Account to load the program into\n * @param elf The entire ELF containing the SBF program\n * @param loaderProgramId The program id of the BPF loader to use\n * @return true if program was loaded successfully, false if program was already loaded\n */\n static load(connection, payer, program, elf, loaderProgramId) {\n return Loader.load(connection, payer, program, loaderProgramId, elf);\n }\n}\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar fastStableStringify$1;\nvar hasRequiredFastStableStringify;\n\nfunction requireFastStableStringify () {\n\tif (hasRequiredFastStableStringify) return fastStableStringify$1;\n\thasRequiredFastStableStringify = 1;\n\tvar objToString = Object.prototype.toString;\n\tvar objKeys = Object.keys || function(obj) {\n\t\t\tvar keys = [];\n\t\t\tfor (var name in obj) {\n\t\t\t\tkeys.push(name);\n\t\t\t}\n\t\t\treturn keys;\n\t\t};\n\n\tfunction stringify(val, isArrayProp) {\n\t\tvar i, max, str, keys, key, propVal, toStr;\n\t\tif (val === true) {\n\t\t\treturn \"true\";\n\t\t}\n\t\tif (val === false) {\n\t\t\treturn \"false\";\n\t\t}\n\t\tswitch (typeof val) {\n\t\t\tcase \"object\":\n\t\t\t\tif (val === null) {\n\t\t\t\t\treturn null;\n\t\t\t\t} else if (val.toJSON && typeof val.toJSON === \"function\") {\n\t\t\t\t\treturn stringify(val.toJSON(), isArrayProp);\n\t\t\t\t} else {\n\t\t\t\t\ttoStr = objToString.call(val);\n\t\t\t\t\tif (toStr === \"[object Array]\") {\n\t\t\t\t\t\tstr = '[';\n\t\t\t\t\t\tmax = val.length - 1;\n\t\t\t\t\t\tfor(i = 0; i < max; i++) {\n\t\t\t\t\t\t\tstr += stringify(val[i], true) + ',';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (max > -1) {\n\t\t\t\t\t\t\tstr += stringify(val[i], true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn str + ']';\n\t\t\t\t\t} else if (toStr === \"[object Object]\") {\n\t\t\t\t\t\t// only object is left\n\t\t\t\t\t\tkeys = objKeys(val).sort();\n\t\t\t\t\t\tmax = keys.length;\n\t\t\t\t\t\tstr = \"\";\n\t\t\t\t\t\ti = 0;\n\t\t\t\t\t\twhile (i < max) {\n\t\t\t\t\t\t\tkey = keys[i];\n\t\t\t\t\t\t\tpropVal = stringify(val[key], false);\n\t\t\t\t\t\t\tif (propVal !== undefined) {\n\t\t\t\t\t\t\t\tif (str) {\n\t\t\t\t\t\t\t\t\tstr += ',';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tstr += JSON.stringify(key) + ':' + propVal;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn '{' + str + '}';\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn JSON.stringify(val);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"function\":\n\t\t\tcase \"undefined\":\n\t\t\t\treturn isArrayProp ? null : undefined;\n\t\t\tcase \"string\":\n\t\t\t\treturn JSON.stringify(val);\n\t\t\tdefault:\n\t\t\t\treturn isFinite(val) ? val : null;\n\t\t}\n\t}\n\n\tfastStableStringify$1 = function(val) {\n\t\tvar returnVal = stringify(val, false);\n\t\tif (returnVal !== undefined) {\n\t\t\treturn ''+ returnVal;\n\t\t}\n\t};\n\treturn fastStableStringify$1;\n}\n\nvar fastStableStringifyExports = /*@__PURE__*/ requireFastStableStringify();\nvar fastStableStringify = /*@__PURE__*/getDefaultExportFromCjs(fastStableStringifyExports);\n\nconst MINIMUM_SLOT_PER_EPOCH = 32;\n\n// Returns the number of trailing zeros in the binary representation of self.\nfunction trailingZeros(n) {\n let trailingZeros = 0;\n while (n > 1) {\n n /= 2;\n trailingZeros++;\n }\n return trailingZeros;\n}\n\n// Returns the smallest power of two greater than or equal to n\nfunction nextPowerOfTwo(n) {\n if (n === 0) return 1;\n n--;\n n |= n >> 1;\n n |= n >> 2;\n n |= n >> 4;\n n |= n >> 8;\n n |= n >> 16;\n n |= n >> 32;\n return n + 1;\n}\n\n/**\n * Epoch schedule\n * (see https://docs.solana.com/terminology#epoch)\n * Can be retrieved with the {@link Connection.getEpochSchedule} method\n */\nclass EpochSchedule {\n constructor(slotsPerEpoch, leaderScheduleSlotOffset, warmup, firstNormalEpoch, firstNormalSlot) {\n /** The maximum number of slots in each epoch */\n this.slotsPerEpoch = void 0;\n /** The number of slots before beginning of an epoch to calculate a leader schedule for that epoch */\n this.leaderScheduleSlotOffset = void 0;\n /** Indicates whether epochs start short and grow */\n this.warmup = void 0;\n /** The first epoch with `slotsPerEpoch` slots */\n this.firstNormalEpoch = void 0;\n /** The first slot of `firstNormalEpoch` */\n this.firstNormalSlot = void 0;\n this.slotsPerEpoch = slotsPerEpoch;\n this.leaderScheduleSlotOffset = leaderScheduleSlotOffset;\n this.warmup = warmup;\n this.firstNormalEpoch = firstNormalEpoch;\n this.firstNormalSlot = firstNormalSlot;\n }\n getEpoch(slot) {\n return this.getEpochAndSlotIndex(slot)[0];\n }\n getEpochAndSlotIndex(slot) {\n if (slot < this.firstNormalSlot) {\n const epoch = trailingZeros(nextPowerOfTwo(slot + MINIMUM_SLOT_PER_EPOCH + 1)) - trailingZeros(MINIMUM_SLOT_PER_EPOCH) - 1;\n const epochLen = this.getSlotsInEpoch(epoch);\n const slotIndex = slot - (epochLen - MINIMUM_SLOT_PER_EPOCH);\n return [epoch, slotIndex];\n } else {\n const normalSlotIndex = slot - this.firstNormalSlot;\n const normalEpochIndex = Math.floor(normalSlotIndex / this.slotsPerEpoch);\n const epoch = this.firstNormalEpoch + normalEpochIndex;\n const slotIndex = normalSlotIndex % this.slotsPerEpoch;\n return [epoch, slotIndex];\n }\n }\n getFirstSlotInEpoch(epoch) {\n if (epoch <= this.firstNormalEpoch) {\n return (Math.pow(2, epoch) - 1) * MINIMUM_SLOT_PER_EPOCH;\n } else {\n return (epoch - this.firstNormalEpoch) * this.slotsPerEpoch + this.firstNormalSlot;\n }\n }\n getLastSlotInEpoch(epoch) {\n return this.getFirstSlotInEpoch(epoch) + this.getSlotsInEpoch(epoch) - 1;\n }\n getSlotsInEpoch(epoch) {\n if (epoch < this.firstNormalEpoch) {\n return Math.pow(2, epoch + trailingZeros(MINIMUM_SLOT_PER_EPOCH));\n } else {\n return this.slotsPerEpoch;\n }\n }\n}\n\nvar fetchImpl = globalThis.fetch;\n\nclass RpcWebSocketClient extends CommonClient {\n constructor(address, options, generate_request_id) {\n const webSocketFactory = url => {\n const rpc = WebSocket(url, {\n autoconnect: true,\n max_reconnects: 5,\n reconnect: true,\n reconnect_interval: 1000,\n ...options\n });\n if ('socket' in rpc) {\n this.underlyingSocket = rpc.socket;\n } else {\n this.underlyingSocket = rpc;\n }\n return rpc;\n };\n super(webSocketFactory, address, options, generate_request_id);\n this.underlyingSocket = void 0;\n }\n call(...args) {\n const readyState = this.underlyingSocket?.readyState;\n if (readyState === 1 /* WebSocket.OPEN */) {\n return super.call(...args);\n }\n return Promise.reject(new Error('Tried to call a JSON-RPC method `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')'));\n }\n notify(...args) {\n const readyState = this.underlyingSocket?.readyState;\n if (readyState === 1 /* WebSocket.OPEN */) {\n return super.notify(...args);\n }\n return Promise.reject(new Error('Tried to send a JSON-RPC notification `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')'));\n }\n}\n\n/**\n * @internal\n */\n\n/**\n * Decode account data buffer using an AccountType\n * @internal\n */\nfunction decodeData(type, data) {\n let decoded;\n try {\n decoded = type.layout.decode(data);\n } catch (err) {\n throw new Error('invalid instruction; ' + err);\n }\n if (decoded.typeIndex !== type.index) {\n throw new Error(`invalid account data; account type mismatch ${decoded.typeIndex} != ${type.index}`);\n }\n return decoded;\n}\n\n/// The serialized size of lookup table metadata\nconst LOOKUP_TABLE_META_SIZE = 56;\nclass AddressLookupTableAccount {\n constructor(args) {\n this.key = void 0;\n this.state = void 0;\n this.key = args.key;\n this.state = args.state;\n }\n isActive() {\n const U64_MAX = BigInt('0xffffffffffffffff');\n return this.state.deactivationSlot === U64_MAX;\n }\n static deserialize(accountData) {\n const meta = decodeData(LookupTableMetaLayout, accountData);\n const serializedAddressesLen = accountData.length - LOOKUP_TABLE_META_SIZE;\n assert(serializedAddressesLen >= 0, 'lookup table is invalid');\n assert(serializedAddressesLen % 32 === 0, 'lookup table is invalid');\n const numSerializedAddresses = serializedAddressesLen / 32;\n const {\n addresses\n } = BufferLayout.struct([BufferLayout.seq(publicKey(), numSerializedAddresses, 'addresses')]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE));\n return {\n deactivationSlot: meta.deactivationSlot,\n lastExtendedSlot: meta.lastExtendedSlot,\n lastExtendedSlotStartIndex: meta.lastExtendedStartIndex,\n authority: meta.authority.length !== 0 ? new PublicKey(meta.authority[0]) : undefined,\n addresses: addresses.map(address => new PublicKey(address))\n };\n }\n}\nconst LookupTableMetaLayout = {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('typeIndex'), u64('deactivationSlot'), BufferLayout.nu64('lastExtendedSlot'), BufferLayout.u8('lastExtendedStartIndex'), BufferLayout.u8(),\n // option\n BufferLayout.seq(publicKey(), BufferLayout.offset(BufferLayout.u8(), -1), 'authority')])\n};\n\nconst URL_RE = /^[^:]+:\\/\\/([^:[]+|\\[[^\\]]+\\])(:\\d+)?(.*)/i;\nfunction makeWebsocketUrl(endpoint) {\n const matches = endpoint.match(URL_RE);\n if (matches == null) {\n throw TypeError(`Failed to validate endpoint URL \\`${endpoint}\\``);\n }\n const [_,\n // eslint-disable-line @typescript-eslint/no-unused-vars\n hostish, portWithColon, rest] = matches;\n const protocol = endpoint.startsWith('https:') ? 'wss:' : 'ws:';\n const startPort = portWithColon == null ? null : parseInt(portWithColon.slice(1), 10);\n const websocketPort =\n // Only shift the port by +1 as a convention for ws(s) only if given endpoint\n // is explicitly specifying the endpoint port (HTTP-based RPC), assuming\n // we're directly trying to connect to agave-validator's ws listening port.\n // When the endpoint omits the port, we're connecting to the protocol\n // default ports: http(80) or https(443) and it's assumed we're behind a reverse\n // proxy which manages WebSocket upgrade and backend port redirection.\n startPort == null ? '' : `:${startPort + 1}`;\n return `${protocol}//${hostish}${websocketPort}${rest}`;\n}\n\nconst PublicKeyFromString = coerce(instance(PublicKey), string(), value => new PublicKey(value));\nconst RawAccountDataResult = tuple([string(), literal('base64')]);\nconst BufferFromRawAccountData = coerce(instance(Buffer), RawAccountDataResult, value => Buffer.from(value[0], 'base64'));\n\n/**\n * Attempt to use a recent blockhash for up to 30 seconds\n * @internal\n */\nconst BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000;\n\n/**\n * HACK.\n * Copied from rpc-websockets/dist/lib/client.\n * Otherwise, `yarn build` fails with:\n * https://gist.github.com/steveluscher/c057eca81d479ef705cdb53162f9971d\n */\n\n/** @internal */\n/** @internal */\n/** @internal */\n/** @internal */\n\n/** @internal */\n/**\n * @internal\n * Every subscription contains the args used to open the subscription with\n * the server, and a list of callers interested in notifications.\n */\n\n/**\n * @internal\n * A subscription may be in various states of connectedness. Only when it is\n * fully connected will it have a server subscription id associated with it.\n * This id can be returned to the server to unsubscribe the client entirely.\n */\n\n/**\n * A type that encapsulates a subscription's RPC method\n * names and notification (callback) signature.\n */\n\n/**\n * @internal\n * Utility type that keeps tagged unions intact while omitting properties.\n */\n\n/**\n * @internal\n * This type represents a single subscribable 'topic.' It's made up of:\n *\n * - The args used to open the subscription with the server,\n * - The state of the subscription, in terms of its connectedness, and\n * - The set of callbacks to call when the server publishes notifications\n *\n * This record gets indexed by `SubscriptionConfigHash` and is used to\n * set up subscriptions, fan out notifications, and track subscription state.\n */\n\n/**\n * @internal\n */\n\n/**\n * Extra contextual information for RPC responses\n */\n\n/**\n * Options for sending transactions\n */\n\n/**\n * Options for confirming transactions\n */\n\n/**\n * Options for getConfirmedSignaturesForAddress2\n */\n\n/**\n * Options for getSignaturesForAddress\n */\n\n/**\n * RPC Response with extra contextual information\n */\n\n/**\n * A strategy for confirming transactions that uses the last valid\n * block height for a given blockhash to check for transaction expiration.\n */\n\n/**\n * A strategy for confirming durable nonce transactions.\n */\n\n/**\n * Properties shared by all transaction confirmation strategies\n */\n\n/**\n * This type represents all transaction confirmation strategies\n */\n\n/* @internal */\nfunction assertEndpointUrl(putativeUrl) {\n if (/^https?:/.test(putativeUrl) === false) {\n throw new TypeError('Endpoint URL must start with `http:` or `https:`.');\n }\n return putativeUrl;\n}\n\n/** @internal */\nfunction extractCommitmentFromConfig(commitmentOrConfig) {\n let commitment;\n let config;\n if (typeof commitmentOrConfig === 'string') {\n commitment = commitmentOrConfig;\n } else if (commitmentOrConfig) {\n const {\n commitment: specifiedCommitment,\n ...specifiedConfig\n } = commitmentOrConfig;\n commitment = specifiedCommitment;\n config = specifiedConfig;\n }\n return {\n commitment,\n config\n };\n}\n\n/**\n * @internal\n */\nfunction applyDefaultMemcmpEncodingToFilters(filters) {\n return filters.map(filter => 'memcmp' in filter ? {\n ...filter,\n memcmp: {\n ...filter.memcmp,\n encoding: filter.memcmp.encoding ?? 'base58'\n }\n } : filter);\n}\n\n/**\n * @internal\n */\nfunction createRpcResult(result) {\n return union([type({\n jsonrpc: literal('2.0'),\n id: string(),\n result\n }), type({\n jsonrpc: literal('2.0'),\n id: string(),\n error: type({\n code: unknown(),\n message: string(),\n data: optional(any())\n })\n })]);\n}\nconst UnknownRpcResult = createRpcResult(unknown());\n\n/**\n * @internal\n */\nfunction jsonRpcResult(schema) {\n return coerce(createRpcResult(schema), UnknownRpcResult, value => {\n if ('error' in value) {\n return value;\n } else {\n return {\n ...value,\n result: create(value.result, schema)\n };\n }\n });\n}\n\n/**\n * @internal\n */\nfunction jsonRpcResultAndContext(value) {\n return jsonRpcResult(type({\n context: type({\n slot: number()\n }),\n value\n }));\n}\n\n/**\n * @internal\n */\nfunction notificationResultAndContext(value) {\n return type({\n context: type({\n slot: number()\n }),\n value\n });\n}\n\n/**\n * @internal\n */\nfunction versionedMessageFromResponse(version, response) {\n if (version === 0) {\n return new MessageV0({\n header: response.header,\n staticAccountKeys: response.accountKeys.map(accountKey => new PublicKey(accountKey)),\n recentBlockhash: response.recentBlockhash,\n compiledInstructions: response.instructions.map(ix => ({\n programIdIndex: ix.programIdIndex,\n accountKeyIndexes: ix.accounts,\n data: bs58.decode(ix.data)\n })),\n addressTableLookups: response.addressTableLookups\n });\n } else {\n return new Message(response);\n }\n}\n\n/**\n * The level of commitment desired when querying state\n *
\n *   'processed': Query the most recent block which has reached 1 confirmation by the connected node\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * 
\n */\n\n// Deprecated as of v1.5.5\n\n/**\n * A subset of Commitment levels, which are at least optimistically confirmed\n *
\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * 
\n */\n\n/**\n * Filter for largest accounts query\n *
\n *   'circulating':    Return the largest accounts that are part of the circulating supply\n *   'nonCirculating': Return the largest accounts that are not part of the circulating supply\n * 
\n */\n\n/**\n * Configuration object for changing `getAccountInfo` query behavior\n */\n\n/**\n * Configuration object for changing `getBalance` query behavior\n */\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\n\n/**\n * Configuration object for changing `getStakeMinimumDelegation` query behavior\n */\n\n/**\n * Configuration object for changing `getBlockHeight` query behavior\n */\n\n/**\n * Configuration object for changing `getEpochInfo` query behavior\n */\n\n/**\n * Configuration object for changing `getInflationReward` query behavior\n */\n\n/**\n * Configuration object for changing `getLatestBlockhash` query behavior\n */\n\n/**\n * Configuration object for changing `isBlockhashValid` query behavior\n */\n\n/**\n * Configuration object for changing `getSlot` query behavior\n */\n\n/**\n * Configuration object for changing `getSlotLeader` query behavior\n */\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\n\n/**\n * Configuration object for changing `getLargestAccounts` query behavior\n */\n\n/**\n * Configuration object for changing `getSupply` request behavior\n */\n\n/**\n * Configuration object for changing query behavior\n */\n\n/**\n * Information describing a cluster node\n */\n\n/**\n * Information describing a vote account\n */\n\n/**\n * A collection of cluster vote accounts\n */\n\n/**\n * Network Inflation\n * (see https://docs.solana.com/implemented-proposals/ed_overview)\n */\n\nconst GetInflationGovernorResult = type({\n foundation: number(),\n foundationTerm: number(),\n initial: number(),\n taper: number(),\n terminal: number()\n});\n\n/**\n * The inflation reward for an epoch\n */\n\n/**\n * Expected JSON RPC response for the \"getInflationReward\" message\n */\nconst GetInflationRewardResult = jsonRpcResult(array(nullable(type({\n epoch: number(),\n effectiveSlot: number(),\n amount: number(),\n postBalance: number(),\n commission: optional(nullable(number()))\n}))));\n\n/**\n * Configuration object for changing `getRecentPrioritizationFees` query behavior\n */\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesResult = array(type({\n slot: number(),\n prioritizationFee: number()\n}));\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateResult = type({\n total: number(),\n validator: number(),\n foundation: number(),\n epoch: number()\n});\n\n/**\n * Information about the current epoch\n */\n\nconst GetEpochInfoResult = type({\n epoch: number(),\n slotIndex: number(),\n slotsInEpoch: number(),\n absoluteSlot: number(),\n blockHeight: optional(number()),\n transactionCount: optional(number())\n});\nconst GetEpochScheduleResult = type({\n slotsPerEpoch: number(),\n leaderScheduleSlotOffset: number(),\n warmup: boolean(),\n firstNormalEpoch: number(),\n firstNormalSlot: number()\n});\n\n/**\n * Leader schedule\n * (see https://docs.solana.com/terminology#leader-schedule)\n */\n\nconst GetLeaderScheduleResult = record(string(), array(number()));\n\n/**\n * Transaction error or null\n */\nconst TransactionErrorResult = nullable(union([type({}), string()]));\n\n/**\n * Signature status for a transaction\n */\nconst SignatureStatusResult = type({\n err: TransactionErrorResult\n});\n\n/**\n * Transaction signature received notification\n */\nconst SignatureReceivedResult = literal('receivedSignature');\n\n/**\n * Version info for a node\n */\n\nconst VersionResult = type({\n 'solana-core': string(),\n 'feature-set': optional(number())\n});\nconst ParsedInstructionStruct = type({\n program: string(),\n programId: PublicKeyFromString,\n parsed: unknown()\n});\nconst PartiallyDecodedInstructionStruct = type({\n programId: PublicKeyFromString,\n accounts: array(PublicKeyFromString),\n data: string()\n});\nconst SimulatedTransactionResponseStruct = jsonRpcResultAndContext(type({\n err: nullable(union([type({}), string()])),\n logs: nullable(array(string())),\n accounts: optional(nullable(array(nullable(type({\n executable: boolean(),\n owner: string(),\n lamports: number(),\n data: array(string()),\n rentEpoch: optional(number())\n }))))),\n unitsConsumed: optional(number()),\n returnData: optional(nullable(type({\n programId: string(),\n data: tuple([string(), literal('base64')])\n }))),\n innerInstructions: optional(nullable(array(type({\n index: number(),\n instructions: array(union([ParsedInstructionStruct, PartiallyDecodedInstructionStruct]))\n }))))\n}));\n\n/**\n * Metadata for a parsed confirmed transaction on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link ParsedTransactionMeta} instead.\n */\n\n/**\n * Collection of addresses loaded by a transaction using address table lookups\n */\n\n/**\n * Metadata for a parsed transaction on the ledger\n */\n\n/**\n * Metadata for a confirmed transaction on the ledger\n */\n\n/**\n * A processed transaction from the RPC API\n */\n\n/**\n * A processed transaction from the RPC API\n */\n\n/**\n * A processed transaction message from the RPC API\n */\n\n/**\n * A confirmed transaction on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0.\n */\n\n/**\n * A partially decoded transaction instruction\n */\n\n/**\n * A parsed transaction message account\n */\n\n/**\n * A parsed transaction instruction\n */\n\n/**\n * A parsed address table lookup\n */\n\n/**\n * A parsed transaction message\n */\n\n/**\n * A parsed transaction\n */\n\n/**\n * A parsed and confirmed transaction on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link ParsedTransactionWithMeta} instead.\n */\n\n/**\n * A parsed transaction on the ledger with meta\n */\n\n/**\n * A processed block fetched from the RPC API\n */\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\n\n/**\n * A block with parsed transactions\n */\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `accounts`\n */\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `none`\n */\n\n/**\n * A processed block fetched from the RPC API\n */\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\n\n/**\n * A confirmed block on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0.\n */\n\n/**\n * A Block on the ledger with signatures only\n */\n\n/**\n * recent block production information\n */\n\n/**\n * Expected JSON RPC response for the \"getBlockProduction\" message\n */\nconst BlockProductionResponseStruct = jsonRpcResultAndContext(type({\n byIdentity: record(string(), array(number())),\n range: type({\n firstSlot: number(),\n lastSlot: number()\n })\n}));\n\n/**\n * A performance sample\n */\n\nfunction createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent) {\n const fetch = customFetch ? customFetch : fetchImpl;\n let agent;\n {\n if (httpAgent != null) {\n 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.');\n }\n }\n let fetchWithMiddleware;\n if (fetchMiddleware) {\n fetchWithMiddleware = async (info, init) => {\n const modifiedFetchArgs = await new Promise((resolve, reject) => {\n try {\n fetchMiddleware(info, init, (modifiedInfo, modifiedInit) => resolve([modifiedInfo, modifiedInit]));\n } catch (error) {\n reject(error);\n }\n });\n return await fetch(...modifiedFetchArgs);\n };\n }\n const clientBrowser = new RpcClient(async (request, callback) => {\n const options = {\n method: 'POST',\n body: request,\n agent,\n headers: Object.assign({\n 'Content-Type': 'application/json'\n }, httpHeaders || {}, COMMON_HTTP_HEADERS)\n };\n try {\n let too_many_requests_retries = 5;\n let res;\n let waitTime = 500;\n for (;;) {\n if (fetchWithMiddleware) {\n res = await fetchWithMiddleware(url, options);\n } else {\n res = await fetch(url, options);\n }\n if (res.status !== 429 /* Too many requests */) {\n break;\n }\n if (disableRetryOnRateLimit === true) {\n break;\n }\n too_many_requests_retries -= 1;\n if (too_many_requests_retries === 0) {\n break;\n }\n console.error(`Server responded with ${res.status} ${res.statusText}. Retrying after ${waitTime}ms delay...`);\n await sleep(waitTime);\n waitTime *= 2;\n }\n const text = await res.text();\n if (res.ok) {\n callback(null, text);\n } else {\n callback(new Error(`${res.status} ${res.statusText}: ${text}`));\n }\n } catch (err) {\n if (err instanceof Error) callback(err);\n }\n }, {});\n return clientBrowser;\n}\nfunction createRpcRequest(client) {\n return (method, args) => {\n return new Promise((resolve, reject) => {\n client.request(method, args, (err, response) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(response);\n });\n });\n };\n}\nfunction createRpcBatchRequest(client) {\n return requests => {\n return new Promise((resolve, reject) => {\n // Do nothing if requests is empty\n if (requests.length === 0) resolve([]);\n const batch = requests.map(params => {\n return client.request(params.methodName, params.args);\n });\n client.request(batch, (err, response) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(response);\n });\n });\n };\n}\n\n/**\n * Expected JSON RPC response for the \"getInflationGovernor\" message\n */\nconst GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult);\n\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateRpcResult = jsonRpcResult(GetInflationRateResult);\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesRpcResult = jsonRpcResult(GetRecentPrioritizationFeesResult);\n\n/**\n * Expected JSON RPC response for the \"getEpochInfo\" message\n */\nconst GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult);\n\n/**\n * Expected JSON RPC response for the \"getEpochSchedule\" message\n */\nconst GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"getLeaderSchedule\" message\n */\nconst GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"minimumLedgerSlot\" and \"getFirstAvailableBlock\" messages\n */\nconst SlotRpcResult = jsonRpcResult(number());\n\n/**\n * Supply\n */\n\n/**\n * Expected JSON RPC response for the \"getSupply\" message\n */\nconst GetSupplyRpcResult = jsonRpcResultAndContext(type({\n total: number(),\n circulating: number(),\n nonCirculating: number(),\n nonCirculatingAccounts: array(PublicKeyFromString)\n}));\n\n/**\n * Token amount object which returns a token amount in different formats\n * for various client use cases.\n */\n\n/**\n * Expected JSON RPC structure for token amounts\n */\nconst TokenAmountResult = type({\n amount: string(),\n uiAmount: nullable(number()),\n decimals: number(),\n uiAmountString: optional(string())\n});\n\n/**\n * Token address and balance.\n */\n\n/**\n * Expected JSON RPC response for the \"getTokenLargestAccounts\" message\n */\nconst GetTokenLargestAccountsResult = jsonRpcResultAndContext(array(type({\n address: PublicKeyFromString,\n amount: string(),\n uiAmount: nullable(number()),\n decimals: number(),\n uiAmountString: optional(string())\n})));\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message\n */\nconst GetTokenAccountsByOwner = jsonRpcResultAndContext(array(type({\n pubkey: PublicKeyFromString,\n account: type({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: BufferFromRawAccountData,\n rentEpoch: number()\n })\n})));\nconst ParsedAccountDataResult = type({\n program: string(),\n parsed: unknown(),\n space: number()\n});\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message with parsed data\n */\nconst GetParsedTokenAccountsByOwner = jsonRpcResultAndContext(array(type({\n pubkey: PublicKeyFromString,\n account: type({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: ParsedAccountDataResult,\n rentEpoch: number()\n })\n})));\n\n/**\n * Pair of an account address and its balance\n */\n\n/**\n * Expected JSON RPC response for the \"getLargestAccounts\" message\n */\nconst GetLargestAccountsRpcResult = jsonRpcResultAndContext(array(type({\n lamports: number(),\n address: PublicKeyFromString\n})));\n\n/**\n * @internal\n */\nconst AccountInfoResult = type({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: BufferFromRawAccountData,\n rentEpoch: number()\n});\n\n/**\n * @internal\n */\nconst KeyedAccountInfoResult = type({\n pubkey: PublicKeyFromString,\n account: AccountInfoResult\n});\nconst ParsedOrRawAccountData = coerce(union([instance(Buffer), ParsedAccountDataResult]), union([RawAccountDataResult, ParsedAccountDataResult]), value => {\n if (Array.isArray(value)) {\n return create(value, BufferFromRawAccountData);\n } else {\n return value;\n }\n});\n\n/**\n * @internal\n */\nconst ParsedAccountInfoResult = type({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: ParsedOrRawAccountData,\n rentEpoch: number()\n});\nconst KeyedParsedAccountInfoResult = type({\n pubkey: PublicKeyFromString,\n account: ParsedAccountInfoResult\n});\n\n/**\n * @internal\n */\nconst StakeActivationResult = type({\n state: union([literal('active'), literal('inactive'), literal('activating'), literal('deactivating')]),\n active: number(),\n inactive: number()\n});\n\n/**\n * Expected JSON RPC response for the \"getConfirmedSignaturesForAddress2\" message\n */\n\nconst GetConfirmedSignaturesForAddress2RpcResult = jsonRpcResult(array(type({\n signature: string(),\n slot: number(),\n err: TransactionErrorResult,\n memo: nullable(string()),\n blockTime: optional(nullable(number()))\n})));\n\n/**\n * Expected JSON RPC response for the \"getSignaturesForAddress\" message\n */\nconst GetSignaturesForAddressRpcResult = jsonRpcResult(array(type({\n signature: string(),\n slot: number(),\n err: TransactionErrorResult,\n memo: nullable(string()),\n blockTime: optional(nullable(number()))\n})));\n\n/***\n * Expected JSON RPC response for the \"accountNotification\" message\n */\nconst AccountNotificationResult = type({\n subscription: number(),\n result: notificationResultAndContext(AccountInfoResult)\n});\n\n/**\n * @internal\n */\nconst ProgramAccountInfoResult = type({\n pubkey: PublicKeyFromString,\n account: AccountInfoResult\n});\n\n/***\n * Expected JSON RPC response for the \"programNotification\" message\n */\nconst ProgramAccountNotificationResult = type({\n subscription: number(),\n result: notificationResultAndContext(ProgramAccountInfoResult)\n});\n\n/**\n * @internal\n */\nconst SlotInfoResult = type({\n parent: number(),\n slot: number(),\n root: number()\n});\n\n/**\n * Expected JSON RPC response for the \"slotNotification\" message\n */\nconst SlotNotificationResult = type({\n subscription: number(),\n result: SlotInfoResult\n});\n\n/**\n * Slot updates which can be used for tracking the live progress of a cluster.\n * - `\"firstShredReceived\"`: connected node received the first shred of a block.\n * Indicates that a new block that is being produced.\n * - `\"completed\"`: connected node has received all shreds of a block. Indicates\n * a block was recently produced.\n * - `\"optimisticConfirmation\"`: block was optimistically confirmed by the\n * cluster. It is not guaranteed that an optimistic confirmation notification\n * will be sent for every finalized blocks.\n * - `\"root\"`: the connected node rooted this block.\n * - `\"createdBank\"`: the connected node has started validating this block.\n * - `\"frozen\"`: the connected node has validated this block.\n * - `\"dead\"`: the connected node failed to validate this block.\n */\n\n/**\n * @internal\n */\nconst SlotUpdateResult = union([type({\n type: union([literal('firstShredReceived'), literal('completed'), literal('optimisticConfirmation'), literal('root')]),\n slot: number(),\n timestamp: number()\n}), type({\n type: literal('createdBank'),\n parent: number(),\n slot: number(),\n timestamp: number()\n}), type({\n type: literal('frozen'),\n slot: number(),\n timestamp: number(),\n stats: type({\n numTransactionEntries: number(),\n numSuccessfulTransactions: number(),\n numFailedTransactions: number(),\n maxTransactionsPerEntry: number()\n })\n}), type({\n type: literal('dead'),\n slot: number(),\n timestamp: number(),\n err: string()\n})]);\n\n/**\n * Expected JSON RPC response for the \"slotsUpdatesNotification\" message\n */\nconst SlotUpdateNotificationResult = type({\n subscription: number(),\n result: SlotUpdateResult\n});\n\n/**\n * Expected JSON RPC response for the \"signatureNotification\" message\n */\nconst SignatureNotificationResult = type({\n subscription: number(),\n result: notificationResultAndContext(union([SignatureStatusResult, SignatureReceivedResult]))\n});\n\n/**\n * Expected JSON RPC response for the \"rootNotification\" message\n */\nconst RootNotificationResult = type({\n subscription: number(),\n result: number()\n});\nconst ContactInfoResult = type({\n pubkey: string(),\n gossip: nullable(string()),\n tpu: nullable(string()),\n rpc: nullable(string()),\n version: nullable(string())\n});\nconst VoteAccountInfoResult = type({\n votePubkey: string(),\n nodePubkey: string(),\n activatedStake: number(),\n epochVoteAccount: boolean(),\n epochCredits: array(tuple([number(), number(), number()])),\n commission: number(),\n lastVote: number(),\n rootSlot: nullable(number())\n});\n\n/**\n * Expected JSON RPC response for the \"getVoteAccounts\" message\n */\nconst GetVoteAccounts = jsonRpcResult(type({\n current: array(VoteAccountInfoResult),\n delinquent: array(VoteAccountInfoResult)\n}));\nconst ConfirmationStatus = union([literal('processed'), literal('confirmed'), literal('finalized')]);\nconst SignatureStatusResponse = type({\n slot: number(),\n confirmations: nullable(number()),\n err: TransactionErrorResult,\n confirmationStatus: optional(ConfirmationStatus)\n});\n\n/**\n * Expected JSON RPC response for the \"getSignatureStatuses\" message\n */\nconst GetSignatureStatusesRpcResult = jsonRpcResultAndContext(array(nullable(SignatureStatusResponse)));\n\n/**\n * Expected JSON RPC response for the \"getMinimumBalanceForRentExemption\" message\n */\nconst GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number());\nconst AddressTableLookupStruct = type({\n accountKey: PublicKeyFromString,\n writableIndexes: array(number()),\n readonlyIndexes: array(number())\n});\nconst ConfirmedTransactionResult = type({\n signatures: array(string()),\n message: type({\n accountKeys: array(string()),\n header: type({\n numRequiredSignatures: number(),\n numReadonlySignedAccounts: number(),\n numReadonlyUnsignedAccounts: number()\n }),\n instructions: array(type({\n accounts: array(number()),\n data: string(),\n programIdIndex: number()\n })),\n recentBlockhash: string(),\n addressTableLookups: optional(array(AddressTableLookupStruct))\n })\n});\nconst AnnotatedAccountKey = type({\n pubkey: PublicKeyFromString,\n signer: boolean(),\n writable: boolean(),\n source: optional(union([literal('transaction'), literal('lookupTable')]))\n});\nconst ConfirmedTransactionAccountsModeResult = type({\n accountKeys: array(AnnotatedAccountKey),\n signatures: array(string())\n});\nconst ParsedInstructionResult = type({\n parsed: unknown(),\n program: string(),\n programId: PublicKeyFromString\n});\nconst RawInstructionResult = type({\n accounts: array(PublicKeyFromString),\n data: string(),\n programId: PublicKeyFromString\n});\nconst InstructionResult = union([RawInstructionResult, ParsedInstructionResult]);\nconst UnknownInstructionResult = union([type({\n parsed: unknown(),\n program: string(),\n programId: string()\n}), type({\n accounts: array(string()),\n data: string(),\n programId: string()\n})]);\nconst ParsedOrRawInstruction = coerce(InstructionResult, UnknownInstructionResult, value => {\n if ('accounts' in value) {\n return create(value, RawInstructionResult);\n } else {\n return create(value, ParsedInstructionResult);\n }\n});\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionResult = type({\n signatures: array(string()),\n message: type({\n accountKeys: array(AnnotatedAccountKey),\n instructions: array(ParsedOrRawInstruction),\n recentBlockhash: string(),\n addressTableLookups: optional(nullable(array(AddressTableLookupStruct)))\n })\n});\nconst TokenBalanceResult = type({\n accountIndex: number(),\n mint: string(),\n owner: optional(string()),\n programId: optional(string()),\n uiTokenAmount: TokenAmountResult\n});\nconst LoadedAddressesResult = type({\n writable: array(PublicKeyFromString),\n readonly: array(PublicKeyFromString)\n});\n\n/**\n * @internal\n */\nconst ConfirmedTransactionMetaResult = type({\n err: TransactionErrorResult,\n fee: number(),\n innerInstructions: optional(nullable(array(type({\n index: number(),\n instructions: array(type({\n accounts: array(number()),\n data: string(),\n programIdIndex: number()\n }))\n })))),\n preBalances: array(number()),\n postBalances: array(number()),\n logMessages: optional(nullable(array(string()))),\n preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n loadedAddresses: optional(LoadedAddressesResult),\n computeUnitsConsumed: optional(number()),\n costUnits: optional(number())\n});\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionMetaResult = type({\n err: TransactionErrorResult,\n fee: number(),\n innerInstructions: optional(nullable(array(type({\n index: number(),\n instructions: array(ParsedOrRawInstruction)\n })))),\n preBalances: array(number()),\n postBalances: array(number()),\n logMessages: optional(nullable(array(string()))),\n preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n loadedAddresses: optional(LoadedAddressesResult),\n computeUnitsConsumed: optional(number()),\n costUnits: optional(number())\n});\nconst TransactionVersionStruct = union([literal(0), literal('legacy')]);\n\n/** @internal */\nconst RewardsResult = type({\n pubkey: string(),\n lamports: number(),\n postBalance: nullable(number()),\n rewardType: nullable(string()),\n commission: optional(nullable(number()))\n});\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ConfirmedTransactionResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `none`\n */\nconst GetNoneModeBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `accounts`\n */\nconst GetAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ConfirmedTransactionAccountsModeResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message\n */\nconst GetParsedBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ParsedConfirmedTransactionResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message when `transactionDetails` is `accounts`\n */\nconst GetParsedAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ConfirmedTransactionAccountsModeResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message when `transactionDetails` is `none`\n */\nconst GetParsedNoneModeBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getConfirmedBlock\" message\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link GetBlockRpcResult} instead.\n */\nconst GetConfirmedBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ConfirmedTransactionResult,\n meta: nullable(ConfirmedTransactionMetaResult)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockSignaturesRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n signatures: array(string()),\n blockTime: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getTransaction\" message\n */\nconst GetTransactionRpcResult = jsonRpcResult(nullable(type({\n slot: number(),\n meta: nullable(ConfirmedTransactionMetaResult),\n blockTime: optional(nullable(number())),\n transaction: ConfirmedTransactionResult,\n version: optional(TransactionVersionStruct)\n})));\n\n/**\n * Expected parsed JSON RPC response for the \"getTransaction\" message\n */\nconst GetParsedTransactionRpcResult = jsonRpcResult(nullable(type({\n slot: number(),\n transaction: ParsedConfirmedTransactionResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n blockTime: optional(nullable(number())),\n version: optional(TransactionVersionStruct)\n})));\n\n/**\n * Expected JSON RPC response for the \"getLatestBlockhash\" message\n */\nconst GetLatestBlockhashRpcResult = jsonRpcResultAndContext(type({\n blockhash: string(),\n lastValidBlockHeight: number()\n}));\n\n/**\n * Expected JSON RPC response for the \"isBlockhashValid\" message\n */\nconst IsBlockhashValidRpcResult = jsonRpcResultAndContext(boolean());\nconst PerfSampleResult = type({\n slot: number(),\n numTransactions: number(),\n numSlots: number(),\n samplePeriodSecs: number()\n});\n\n/*\n * Expected JSON RPC response for \"getRecentPerformanceSamples\" message\n */\nconst GetRecentPerformanceSamplesRpcResult = jsonRpcResult(array(PerfSampleResult));\n\n/**\n * Expected JSON RPC response for the \"getFeeCalculatorForBlockhash\" message\n */\nconst GetFeeCalculatorRpcResult = jsonRpcResultAndContext(nullable(type({\n feeCalculator: type({\n lamportsPerSignature: number()\n })\n})));\n\n/**\n * Expected JSON RPC response for the \"requestAirdrop\" message\n */\nconst RequestAirdropRpcResult = jsonRpcResult(string());\n\n/**\n * Expected JSON RPC response for the \"sendTransaction\" message\n */\nconst SendTransactionRpcResult = jsonRpcResult(string());\n\n/**\n * Information about the latest slot being processed by a node\n */\n\n/**\n * Parsed account data\n */\n\n/**\n * Stake Activation data\n */\n\n/**\n * Data slice argument for getProgramAccounts\n */\n\n/**\n * Memory comparison filter for getProgramAccounts\n */\n\n/**\n * Data size comparison filter for getProgramAccounts\n */\n\n/**\n * A filter object for getProgramAccounts\n */\n\n/**\n * Configuration object for getProgramAccounts requests\n */\n\n/**\n * Configuration object for getParsedProgramAccounts\n */\n\n/**\n * Configuration object for getMultipleAccounts\n */\n\n/**\n * Configuration object for `getStakeActivation`\n */\n\n/**\n * Configuration object for `getStakeActivation`\n */\n\n/**\n * Configuration object for `getStakeActivation`\n */\n\n/**\n * Configuration object for `getNonce`\n */\n\n/**\n * Configuration object for `getNonceAndContext`\n */\n\n/**\n * Information describing an account\n */\n\n/**\n * Account information identified by pubkey\n */\n\n/**\n * Callback function for account change notifications\n */\n\n/**\n * Callback function for program account change notifications\n */\n\n/**\n * Callback function for slot change notifications\n */\n\n/**\n * Callback function for slot update notifications\n */\n\n/**\n * Callback function for signature status notifications\n */\n\n/**\n * Signature status notification with transaction result\n */\n\n/**\n * Signature received notification\n */\n\n/**\n * Callback function for signature notifications\n */\n\n/**\n * Signature subscription options\n */\n\n/**\n * Callback function for root change notifications\n */\n\n/**\n * @internal\n */\nconst LogsResult = type({\n err: TransactionErrorResult,\n logs: array(string()),\n signature: string()\n});\n\n/**\n * Logs result.\n */\n\n/**\n * Expected JSON RPC response for the \"logsNotification\" message.\n */\nconst LogsNotificationResult = type({\n result: notificationResultAndContext(LogsResult),\n subscription: number()\n});\n\n/**\n * Filter for log subscriptions.\n */\n\n/**\n * Callback function for log notifications.\n */\n\n/**\n * Signature result\n */\n\n/**\n * Transaction error\n */\n\n/**\n * Transaction confirmation status\n *
\n *   'processed': Transaction landed in a block which has reached 1 confirmation by the connected node\n *   'confirmed': Transaction landed in a block which has reached 1 confirmation by the cluster\n *   'finalized': Transaction landed in a block which has been finalized by the cluster\n * 
\n */\n\n/**\n * Signature status\n */\n\n/**\n * A confirmed signature with its status\n */\n\n/**\n * An object defining headers to be passed to the RPC server\n */\n\n/**\n * The type of the JavaScript `fetch()` API\n */\n\n/**\n * A callback used to augment the outgoing HTTP request\n */\n\n/**\n * Configuration for instantiating a Connection\n */\n\n/** @internal */\nconst COMMON_HTTP_HEADERS = {\n 'solana-client': `js/${\"1.0.0-maintenance\"}`\n};\n\n/**\n * A connection to a fullnode JSON RPC endpoint\n */\nclass Connection {\n /**\n * Establish a JSON RPC connection\n *\n * @param endpoint URL to the fullnode JSON RPC endpoint\n * @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object\n */\n constructor(endpoint, _commitmentOrConfig) {\n /** @internal */\n this._commitment = void 0;\n /** @internal */\n this._confirmTransactionInitialTimeout = void 0;\n /** @internal */\n this._rpcEndpoint = void 0;\n /** @internal */\n this._rpcWsEndpoint = void 0;\n /** @internal */\n this._rpcClient = void 0;\n /** @internal */\n this._rpcRequest = void 0;\n /** @internal */\n this._rpcBatchRequest = void 0;\n /** @internal */\n this._rpcWebSocket = void 0;\n /** @internal */\n this._rpcWebSocketConnected = false;\n /** @internal */\n this._rpcWebSocketHeartbeat = null;\n /** @internal */\n this._rpcWebSocketIdleTimeout = null;\n /** @internal\n * A number that we increment every time an active connection closes.\n * Used to determine whether the same socket connection that was open\n * when an async operation started is the same one that's active when\n * its continuation fires.\n *\n */\n this._rpcWebSocketGeneration = 0;\n /** @internal */\n this._disableBlockhashCaching = false;\n /** @internal */\n this._pollingBlockhash = false;\n /** @internal */\n this._blockhashInfo = {\n latestBlockhash: null,\n lastFetch: 0,\n transactionSignatures: [],\n simulatedSignatures: []\n };\n /** @internal */\n this._nextClientSubscriptionId = 0;\n /** @internal */\n this._subscriptionDisposeFunctionsByClientSubscriptionId = {};\n /** @internal */\n this._subscriptionHashByClientSubscriptionId = {};\n /** @internal */\n this._subscriptionStateChangeCallbacksByHash = {};\n /** @internal */\n this._subscriptionCallbacksByServerSubscriptionId = {};\n /** @internal */\n this._subscriptionsByHash = {};\n /**\n * Special case.\n * After a signature is processed, RPCs automatically dispose of the\n * subscription on the server side. We need to track which of these\n * subscriptions have been disposed in such a way, so that we know\n * whether the client is dealing with a not-yet-processed signature\n * (in which case we must tear down the server subscription) or an\n * already-processed signature (in which case the client can simply\n * clear out the subscription locally without telling the server).\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n /** @internal */\n this._subscriptionsAutoDisposedByRpc = new Set();\n /*\n * Returns the current block height of the node\n */\n this.getBlockHeight = (() => {\n const requestPromises = {};\n return async commitmentOrConfig => {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const requestHash = fastStableStringify(args);\n requestPromises[requestHash] = requestPromises[requestHash] ?? (async () => {\n try {\n const unsafeRes = await this._rpcRequest('getBlockHeight', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get block height information');\n }\n return res.result;\n } finally {\n delete requestPromises[requestHash];\n }\n })();\n return await requestPromises[requestHash];\n };\n })();\n let wsEndpoint;\n let httpHeaders;\n let fetch;\n let fetchMiddleware;\n let disableRetryOnRateLimit;\n let httpAgent;\n if (_commitmentOrConfig && typeof _commitmentOrConfig === 'string') {\n this._commitment = _commitmentOrConfig;\n } else if (_commitmentOrConfig) {\n this._commitment = _commitmentOrConfig.commitment;\n this._confirmTransactionInitialTimeout = _commitmentOrConfig.confirmTransactionInitialTimeout;\n wsEndpoint = _commitmentOrConfig.wsEndpoint;\n httpHeaders = _commitmentOrConfig.httpHeaders;\n fetch = _commitmentOrConfig.fetch;\n fetchMiddleware = _commitmentOrConfig.fetchMiddleware;\n disableRetryOnRateLimit = _commitmentOrConfig.disableRetryOnRateLimit;\n httpAgent = _commitmentOrConfig.httpAgent;\n }\n this._rpcEndpoint = assertEndpointUrl(endpoint);\n this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint);\n this._rpcClient = createRpcClient(endpoint, httpHeaders, fetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent);\n this._rpcRequest = createRpcRequest(this._rpcClient);\n this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient);\n this._rpcWebSocket = new RpcWebSocketClient(this._rpcWsEndpoint, {\n autoconnect: false,\n max_reconnects: Infinity\n });\n this._rpcWebSocket.on('open', this._wsOnOpen.bind(this));\n this._rpcWebSocket.on('error', this._wsOnError.bind(this));\n this._rpcWebSocket.on('close', this._wsOnClose.bind(this));\n this._rpcWebSocket.on('accountNotification', this._wsOnAccountNotification.bind(this));\n this._rpcWebSocket.on('programNotification', this._wsOnProgramAccountNotification.bind(this));\n this._rpcWebSocket.on('slotNotification', this._wsOnSlotNotification.bind(this));\n this._rpcWebSocket.on('slotsUpdatesNotification', this._wsOnSlotUpdatesNotification.bind(this));\n this._rpcWebSocket.on('signatureNotification', this._wsOnSignatureNotification.bind(this));\n this._rpcWebSocket.on('rootNotification', this._wsOnRootNotification.bind(this));\n this._rpcWebSocket.on('logsNotification', this._wsOnLogsNotification.bind(this));\n }\n\n /**\n * The default commitment used for requests\n */\n get commitment() {\n return this._commitment;\n }\n\n /**\n * The RPC endpoint\n */\n get rpcEndpoint() {\n return this._rpcEndpoint;\n }\n\n /**\n * Fetch the balance for the specified public key, return with context\n */\n async getBalanceAndContext(publicKey, commitmentOrConfig) {\n /** @internal */\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getBalance', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get balance for ${publicKey.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch the balance for the specified public key\n */\n async getBalance(publicKey, commitmentOrConfig) {\n return await this.getBalanceAndContext(publicKey, commitmentOrConfig).then(x => x.value).catch(e => {\n throw new Error('failed to get balance of account ' + publicKey.toBase58() + ': ' + e);\n });\n }\n\n /**\n * Fetch the estimated production time of a block\n */\n async getBlockTime(slot) {\n const unsafeRes = await this._rpcRequest('getBlockTime', [slot]);\n const res = create(unsafeRes, jsonRpcResult(nullable(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get block time for slot ${slot}`);\n }\n return res.result;\n }\n\n /**\n * Fetch the lowest slot that the node has information about in its ledger.\n * This value may increase over time if the node is configured to purge older ledger data\n */\n async getMinimumLedgerSlot() {\n const unsafeRes = await this._rpcRequest('minimumLedgerSlot', []);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get minimum ledger slot');\n }\n return res.result;\n }\n\n /**\n * Fetch the slot of the lowest confirmed block that has not been purged from the ledger\n */\n async getFirstAvailableBlock() {\n const unsafeRes = await this._rpcRequest('getFirstAvailableBlock', []);\n const res = create(unsafeRes, SlotRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get first available block');\n }\n return res.result;\n }\n\n /**\n * Fetch information about the current supply\n */\n async getSupply(config) {\n let configArg = {};\n if (typeof config === 'string') {\n configArg = {\n commitment: config\n };\n } else if (config) {\n configArg = {\n ...config,\n commitment: config && config.commitment || this.commitment\n };\n } else {\n configArg = {\n commitment: this.commitment\n };\n }\n const unsafeRes = await this._rpcRequest('getSupply', [configArg]);\n const res = create(unsafeRes, GetSupplyRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get supply');\n }\n return res.result;\n }\n\n /**\n * Fetch the current supply of a token mint\n */\n async getTokenSupply(tokenMintAddress, commitment) {\n const args = this._buildArgs([tokenMintAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenSupply', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get token supply');\n }\n return res.result;\n }\n\n /**\n * Fetch the current balance of a token account\n */\n async getTokenAccountBalance(tokenAddress, commitment) {\n const args = this._buildArgs([tokenAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenAccountBalance', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get token account balance');\n }\n return res.result;\n }\n\n /**\n * Fetch all the token accounts owned by the specified account\n *\n * @return {Promise}\n */\n async getTokenAccountsByOwner(ownerAddress, filter, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n let _args = [ownerAddress.toBase58()];\n if ('mint' in filter) {\n _args.push({\n mint: filter.mint.toBase58()\n });\n } else {\n _args.push({\n programId: filter.programId.toBase58()\n });\n }\n const args = this._buildArgs(_args, commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n const res = create(unsafeRes, GetTokenAccountsByOwner);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get token accounts owned by account ${ownerAddress.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch parsed token accounts owned by the specified account\n *\n * @return {Promise}>>>}\n */\n async getParsedTokenAccountsByOwner(ownerAddress, filter, commitment) {\n let _args = [ownerAddress.toBase58()];\n if ('mint' in filter) {\n _args.push({\n mint: filter.mint.toBase58()\n });\n } else {\n _args.push({\n programId: filter.programId.toBase58()\n });\n }\n const args = this._buildArgs(_args, commitment, 'jsonParsed');\n const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n const res = create(unsafeRes, GetParsedTokenAccountsByOwner);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get token accounts owned by account ${ownerAddress.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch the 20 largest accounts with their current balances\n */\n async getLargestAccounts(config) {\n const arg = {\n ...config,\n commitment: config && config.commitment || this.commitment\n };\n const args = arg.filter || arg.commitment ? [arg] : [];\n const unsafeRes = await this._rpcRequest('getLargestAccounts', args);\n const res = create(unsafeRes, GetLargestAccountsRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get largest accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch the 20 largest token accounts with their current balances\n * for a given mint.\n */\n async getTokenLargestAccounts(mintAddress, commitment) {\n const args = this._buildArgs([mintAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenLargestAccounts', args);\n const res = create(unsafeRes, GetTokenLargestAccountsResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get token largest accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for the specified public key, return with context\n */\n async getAccountInfoAndContext(publicKey, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(nullable(AccountInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get info about account ${publicKey.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch parsed account info for the specified public key\n */\n async getParsedAccountInfo(publicKey, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get info about account ${publicKey.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for the specified public key\n */\n async getAccountInfo(publicKey, commitmentOrConfig) {\n try {\n const res = await this.getAccountInfoAndContext(publicKey, commitmentOrConfig);\n return res.value;\n } catch (e) {\n throw new Error('failed to get info about account ' + publicKey.toBase58() + ': ' + e);\n }\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n */\n async getMultipleParsedAccounts(publicKeys, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const keys = publicKeys.map(key => key.toBase58());\n const args = this._buildArgs([keys], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult))));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get info for accounts ${keys}`);\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n */\n async getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const keys = publicKeys.map(key => key.toBase58());\n const args = this._buildArgs([keys], commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(array(nullable(AccountInfoResult))));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get info for accounts ${keys}`);\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys\n */\n async getMultipleAccountsInfo(publicKeys, commitmentOrConfig) {\n const res = await this.getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig);\n return res.value;\n }\n\n /**\n * Returns epoch activation information for a stake account that has been delegated\n *\n * @deprecated Deprecated since RPC v1.18; will be removed in a future version.\n */\n async getStakeActivation(publicKey, commitmentOrConfig, epoch) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment, undefined /* encoding */, {\n ...config,\n epoch: epoch != null ? epoch : config?.epoch\n });\n const unsafeRes = await this._rpcRequest('getStakeActivation', args);\n const res = create(unsafeRes, jsonRpcResult(StakeActivationResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get Stake Activation ${publicKey.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch all the accounts owned by the specified program id\n *\n * @return {Promise}>>}\n */\n\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n async getProgramAccounts(programId, configOrCommitment) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(configOrCommitment);\n const {\n encoding,\n ...configWithoutEncoding\n } = config || {};\n const args = this._buildArgs([programId.toBase58()], commitment, encoding || 'base64', {\n ...configWithoutEncoding,\n ...(configWithoutEncoding.filters ? {\n filters: applyDefaultMemcmpEncodingToFilters(configWithoutEncoding.filters)\n } : null)\n });\n const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n const baseSchema = array(KeyedAccountInfoResult);\n const res = configWithoutEncoding.withContext === true ? create(unsafeRes, jsonRpcResultAndContext(baseSchema)) : create(unsafeRes, jsonRpcResult(baseSchema));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get accounts owned by program ${programId.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch and parse all the accounts owned by the specified program id\n *\n * @return {Promise}>>}\n */\n async getParsedProgramAccounts(programId, configOrCommitment) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(configOrCommitment);\n const args = this._buildArgs([programId.toBase58()], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n const res = create(unsafeRes, jsonRpcResult(array(KeyedParsedAccountInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get accounts owned by program ${programId.toBase58()}`);\n }\n return res.result;\n }\n\n /** @deprecated Instead, call `confirmTransaction` and pass in {@link TransactionConfirmationStrategy} */\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n async confirmTransaction(strategy, commitment) {\n let rawSignature;\n if (typeof strategy == 'string') {\n rawSignature = strategy;\n } else {\n const config = strategy;\n if (config.abortSignal?.aborted) {\n return Promise.reject(config.abortSignal.reason);\n }\n rawSignature = config.signature;\n }\n let decodedSignature;\n try {\n decodedSignature = bs58.decode(rawSignature);\n } catch (err) {\n throw new Error('signature must be base58 encoded: ' + rawSignature);\n }\n assert(decodedSignature.length === 64, 'signature has invalid length');\n if (typeof strategy === 'string') {\n return await this.confirmTransactionUsingLegacyTimeoutStrategy({\n commitment: commitment || this.commitment,\n signature: rawSignature\n });\n } else if ('lastValidBlockHeight' in strategy) {\n return await this.confirmTransactionUsingBlockHeightExceedanceStrategy({\n commitment: commitment || this.commitment,\n strategy\n });\n } else {\n return await this.confirmTransactionUsingDurableNonceStrategy({\n commitment: commitment || this.commitment,\n strategy\n });\n }\n }\n getCancellationPromise(signal) {\n return new Promise((_, reject) => {\n if (signal == null) {\n return;\n }\n if (signal.aborted) {\n reject(signal.reason);\n } else {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n });\n }\n });\n }\n getTransactionConfirmationPromise({\n commitment,\n signature\n }) {\n let signatureSubscriptionId;\n let disposeSignatureSubscriptionStateChangeObserver;\n let done = false;\n const confirmationPromise = new Promise((resolve, reject) => {\n try {\n signatureSubscriptionId = this.onSignature(signature, (result, context) => {\n signatureSubscriptionId = undefined;\n const response = {\n context,\n value: result\n };\n resolve({\n __type: TransactionStatus.PROCESSED,\n response\n });\n }, commitment);\n const subscriptionSetupPromise = new Promise(resolveSubscriptionSetup => {\n if (signatureSubscriptionId == null) {\n resolveSubscriptionSetup();\n } else {\n disposeSignatureSubscriptionStateChangeObserver = this._onSubscriptionStateChange(signatureSubscriptionId, nextState => {\n if (nextState === 'subscribed') {\n resolveSubscriptionSetup();\n }\n });\n }\n });\n (async () => {\n await subscriptionSetupPromise;\n if (done) return;\n const response = await this.getSignatureStatus(signature);\n if (done) return;\n if (response == null) {\n return;\n }\n const {\n context,\n value\n } = response;\n if (value == null) {\n return;\n }\n if (value?.err) {\n reject(value.err);\n } else {\n switch (commitment) {\n case 'confirmed':\n case 'single':\n case 'singleGossip':\n {\n if (value.confirmationStatus === 'processed') {\n return;\n }\n break;\n }\n case 'finalized':\n case 'max':\n case 'root':\n {\n if (value.confirmationStatus === 'processed' || value.confirmationStatus === 'confirmed') {\n return;\n }\n break;\n }\n // exhaust enums to ensure full coverage\n case 'processed':\n case 'recent':\n }\n done = true;\n resolve({\n __type: TransactionStatus.PROCESSED,\n response: {\n context,\n value\n }\n });\n }\n })();\n } catch (err) {\n reject(err);\n }\n });\n const abortConfirmation = () => {\n if (disposeSignatureSubscriptionStateChangeObserver) {\n disposeSignatureSubscriptionStateChangeObserver();\n disposeSignatureSubscriptionStateChangeObserver = undefined;\n }\n if (signatureSubscriptionId != null) {\n this.removeSignatureListener(signatureSubscriptionId);\n signatureSubscriptionId = undefined;\n }\n };\n return {\n abortConfirmation,\n confirmationPromise\n };\n }\n async confirmTransactionUsingBlockHeightExceedanceStrategy({\n commitment,\n strategy: {\n abortSignal,\n lastValidBlockHeight,\n signature\n }\n }) {\n let done = false;\n const expiryPromise = new Promise(resolve => {\n const checkBlockHeight = async () => {\n try {\n const blockHeight = await this.getBlockHeight(commitment);\n return blockHeight;\n } catch (_e) {\n return -1;\n }\n };\n (async () => {\n let currentBlockHeight = await checkBlockHeight();\n if (done) return;\n while (currentBlockHeight <= lastValidBlockHeight) {\n await sleep(1000);\n if (done) return;\n currentBlockHeight = await checkBlockHeight();\n if (done) return;\n }\n resolve({\n __type: TransactionStatus.BLOCKHEIGHT_EXCEEDED\n });\n })();\n });\n const {\n abortConfirmation,\n confirmationPromise\n } = this.getTransactionConfirmationPromise({\n commitment,\n signature\n });\n const cancellationPromise = this.getCancellationPromise(abortSignal);\n let result;\n try {\n const outcome = await Promise.race([cancellationPromise, confirmationPromise, expiryPromise]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n throw new TransactionExpiredBlockheightExceededError(signature);\n }\n } finally {\n done = true;\n abortConfirmation();\n }\n return result;\n }\n async confirmTransactionUsingDurableNonceStrategy({\n commitment,\n strategy: {\n abortSignal,\n minContextSlot,\n nonceAccountPubkey,\n nonceValue,\n signature\n }\n }) {\n let done = false;\n const expiryPromise = new Promise(resolve => {\n let currentNonceValue = nonceValue;\n let lastCheckedSlot = null;\n const getCurrentNonceValue = async () => {\n try {\n const {\n context,\n value: nonceAccount\n } = await this.getNonceAndContext(nonceAccountPubkey, {\n commitment,\n minContextSlot\n });\n lastCheckedSlot = context.slot;\n return nonceAccount?.nonce;\n } catch (e) {\n // If for whatever reason we can't reach/read the nonce\n // account, just keep using the last-known value.\n return currentNonceValue;\n }\n };\n (async () => {\n currentNonceValue = await getCurrentNonceValue();\n if (done) return;\n while (true // eslint-disable-line no-constant-condition\n ) {\n if (nonceValue !== currentNonceValue) {\n resolve({\n __type: TransactionStatus.NONCE_INVALID,\n slotInWhichNonceDidAdvance: lastCheckedSlot\n });\n return;\n }\n await sleep(2000);\n if (done) return;\n currentNonceValue = await getCurrentNonceValue();\n if (done) return;\n }\n })();\n });\n const {\n abortConfirmation,\n confirmationPromise\n } = this.getTransactionConfirmationPromise({\n commitment,\n signature\n });\n const cancellationPromise = this.getCancellationPromise(abortSignal);\n let result;\n try {\n const outcome = await Promise.race([cancellationPromise, confirmationPromise, expiryPromise]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n // Double check that the transaction is indeed unconfirmed.\n let signatureStatus;\n while (true // eslint-disable-line no-constant-condition\n ) {\n const status = await this.getSignatureStatus(signature);\n if (status == null) {\n break;\n }\n if (status.context.slot < (outcome.slotInWhichNonceDidAdvance ?? minContextSlot)) {\n await sleep(400);\n continue;\n }\n signatureStatus = status;\n break;\n }\n if (signatureStatus?.value) {\n const commitmentForStatus = commitment || 'finalized';\n const {\n confirmationStatus\n } = signatureStatus.value;\n switch (commitmentForStatus) {\n case 'processed':\n case 'recent':\n if (confirmationStatus !== 'processed' && confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized') {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n case 'confirmed':\n case 'single':\n case 'singleGossip':\n if (confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized') {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n case 'finalized':\n case 'max':\n case 'root':\n if (confirmationStatus !== 'finalized') {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n default:\n // Exhaustive switch.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n (_ => {})(commitmentForStatus);\n }\n result = {\n context: signatureStatus.context,\n value: {\n err: signatureStatus.value.err\n }\n };\n } else {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n }\n } finally {\n done = true;\n abortConfirmation();\n }\n return result;\n }\n async confirmTransactionUsingLegacyTimeoutStrategy({\n commitment,\n signature\n }) {\n let timeoutId;\n const expiryPromise = new Promise(resolve => {\n let timeoutMs = this._confirmTransactionInitialTimeout || 60 * 1000;\n switch (commitment) {\n case 'processed':\n case 'recent':\n case 'single':\n case 'confirmed':\n case 'singleGossip':\n {\n timeoutMs = this._confirmTransactionInitialTimeout || 30 * 1000;\n break;\n }\n }\n timeoutId = setTimeout(() => resolve({\n __type: TransactionStatus.TIMED_OUT,\n timeoutMs\n }), timeoutMs);\n });\n const {\n abortConfirmation,\n confirmationPromise\n } = this.getTransactionConfirmationPromise({\n commitment,\n signature\n });\n let result;\n try {\n const outcome = await Promise.race([confirmationPromise, expiryPromise]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n throw new TransactionExpiredTimeoutError(signature, outcome.timeoutMs / 1000);\n }\n } finally {\n clearTimeout(timeoutId);\n abortConfirmation();\n }\n return result;\n }\n\n /**\n * Return the list of nodes that are currently participating in the cluster\n */\n async getClusterNodes() {\n const unsafeRes = await this._rpcRequest('getClusterNodes', []);\n const res = create(unsafeRes, jsonRpcResult(array(ContactInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get cluster nodes');\n }\n return res.result;\n }\n\n /**\n * Return the list of nodes that are currently participating in the cluster\n */\n async getVoteAccounts(commitment) {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getVoteAccounts', args);\n const res = create(unsafeRes, GetVoteAccounts);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get vote accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch the current slot that the node is processing\n */\n async getSlot(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getSlot', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot');\n }\n return res.result;\n }\n\n /**\n * Fetch the current slot leader of the cluster\n */\n async getSlotLeader(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getSlotLeader', args);\n const res = create(unsafeRes, jsonRpcResult(string()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot leader');\n }\n return res.result;\n }\n\n /**\n * Fetch `limit` number of slot leaders starting from `startSlot`\n *\n * @param startSlot fetch slot leaders starting from this slot\n * @param limit number of slot leaders to return\n */\n async getSlotLeaders(startSlot, limit) {\n const args = [startSlot, limit];\n const unsafeRes = await this._rpcRequest('getSlotLeaders', args);\n const res = create(unsafeRes, jsonRpcResult(array(PublicKeyFromString)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot leaders');\n }\n return res.result;\n }\n\n /**\n * Fetch the current status of a signature\n */\n async getSignatureStatus(signature, config) {\n const {\n context,\n value: values\n } = await this.getSignatureStatuses([signature], config);\n assert(values.length === 1);\n const value = values[0];\n return {\n context,\n value\n };\n }\n\n /**\n * Fetch the current statuses of a batch of signatures\n */\n async getSignatureStatuses(signatures, config) {\n const params = [signatures];\n if (config) {\n params.push(config);\n }\n const unsafeRes = await this._rpcRequest('getSignatureStatuses', params);\n const res = create(unsafeRes, GetSignatureStatusesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get signature status');\n }\n return res.result;\n }\n\n /**\n * Fetch the current transaction count of the cluster\n */\n async getTransactionCount(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getTransactionCount', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction count');\n }\n return res.result;\n }\n\n /**\n * Fetch the current total currency supply of the cluster in lamports\n *\n * @deprecated Deprecated since RPC v1.2.8. Please use {@link getSupply} instead.\n */\n async getTotalSupply(commitment) {\n const result = await this.getSupply({\n commitment,\n excludeNonCirculatingAccountsList: true\n });\n return result.value.total;\n }\n\n /**\n * Fetch the cluster InflationGovernor parameters\n */\n async getInflationGovernor(commitment) {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getInflationGovernor', args);\n const res = create(unsafeRes, GetInflationGovernorRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation');\n }\n return res.result;\n }\n\n /**\n * Fetch the inflation reward for a list of addresses for an epoch\n */\n async getInflationReward(addresses, epoch, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([addresses.map(pubkey => pubkey.toBase58())], commitment, undefined /* encoding */, {\n ...config,\n epoch: epoch != null ? epoch : config?.epoch\n });\n const unsafeRes = await this._rpcRequest('getInflationReward', args);\n const res = create(unsafeRes, GetInflationRewardResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation reward');\n }\n return res.result;\n }\n\n /**\n * Fetch the specific inflation values for the current epoch\n */\n async getInflationRate() {\n const unsafeRes = await this._rpcRequest('getInflationRate', []);\n const res = create(unsafeRes, GetInflationRateRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation rate');\n }\n return res.result;\n }\n\n /**\n * Fetch the Epoch Info parameters\n */\n async getEpochInfo(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getEpochInfo', args);\n const res = create(unsafeRes, GetEpochInfoRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get epoch info');\n }\n return res.result;\n }\n\n /**\n * Fetch the Epoch Schedule parameters\n */\n async getEpochSchedule() {\n const unsafeRes = await this._rpcRequest('getEpochSchedule', []);\n const res = create(unsafeRes, GetEpochScheduleRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get epoch schedule');\n }\n const epochSchedule = res.result;\n return new EpochSchedule(epochSchedule.slotsPerEpoch, epochSchedule.leaderScheduleSlotOffset, epochSchedule.warmup, epochSchedule.firstNormalEpoch, epochSchedule.firstNormalSlot);\n }\n\n /**\n * Fetch the leader schedule for the current epoch\n * @return {Promise>}\n */\n async getLeaderSchedule() {\n const unsafeRes = await this._rpcRequest('getLeaderSchedule', []);\n const res = create(unsafeRes, GetLeaderScheduleRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get leader schedule');\n }\n return res.result;\n }\n\n /**\n * Fetch the minimum balance needed to exempt an account of `dataLength`\n * size from rent\n */\n async getMinimumBalanceForRentExemption(dataLength, commitment) {\n const args = this._buildArgs([dataLength], commitment);\n const unsafeRes = await this._rpcRequest('getMinimumBalanceForRentExemption', args);\n const res = create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult);\n if ('error' in res) {\n console.warn('Unable to fetch minimum balance for rent exemption');\n return 0;\n }\n return res.result;\n }\n\n /**\n * Fetch a recent blockhash from the cluster, return with context\n * @return {Promise>}\n *\n * @deprecated Deprecated since RPC v1.9.0. Please use {@link getLatestBlockhash} instead.\n */\n async getRecentBlockhashAndContext(commitment) {\n const {\n context,\n value: {\n blockhash\n }\n } = await this.getLatestBlockhashAndContext(commitment);\n const feeCalculator = {\n get lamportsPerSignature() {\n 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.');\n },\n toJSON() {\n return {};\n }\n };\n return {\n context,\n value: {\n blockhash,\n feeCalculator\n }\n };\n }\n\n /**\n * Fetch recent performance samples\n * @return {Promise>}\n */\n async getRecentPerformanceSamples(limit) {\n const unsafeRes = await this._rpcRequest('getRecentPerformanceSamples', limit ? [limit] : []);\n const res = create(unsafeRes, GetRecentPerformanceSamplesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get recent performance samples');\n }\n return res.result;\n }\n\n /**\n * Fetch the fee calculator for a recent blockhash from the cluster, return with context\n *\n * @deprecated Deprecated since RPC v1.9.0. Please use {@link getFeeForMessage} instead.\n */\n async getFeeCalculatorForBlockhash(blockhash, commitment) {\n const args = this._buildArgs([blockhash], commitment);\n const unsafeRes = await this._rpcRequest('getFeeCalculatorForBlockhash', args);\n const res = create(unsafeRes, GetFeeCalculatorRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get fee calculator');\n }\n const {\n context,\n value\n } = res.result;\n return {\n context,\n value: value !== null ? value.feeCalculator : null\n };\n }\n\n /**\n * Fetch the fee for a message from the cluster, return with context\n */\n async getFeeForMessage(message, commitment) {\n const wireMessage = toBuffer(message.serialize()).toString('base64');\n const args = this._buildArgs([wireMessage], commitment);\n const unsafeRes = await this._rpcRequest('getFeeForMessage', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(nullable(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get fee for message');\n }\n if (res.result === null) {\n throw new Error('invalid blockhash');\n }\n return res.result;\n }\n\n /**\n * Fetch a list of prioritization fees from recent blocks.\n */\n async getRecentPrioritizationFees(config) {\n const accounts = config?.lockedWritableAccounts?.map(key => key.toBase58());\n const args = accounts?.length ? [accounts] : [];\n const unsafeRes = await this._rpcRequest('getRecentPrioritizationFees', args);\n const res = create(unsafeRes, GetRecentPrioritizationFeesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get recent prioritization fees');\n }\n return res.result;\n }\n /**\n * Fetch a recent blockhash from the cluster\n * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>}\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link getLatestBlockhash} instead.\n */\n async getRecentBlockhash(commitment) {\n try {\n const res = await this.getRecentBlockhashAndContext(commitment);\n return res.value;\n } catch (e) {\n throw new Error('failed to get recent blockhash: ' + e);\n }\n }\n\n /**\n * Fetch the latest blockhash from the cluster\n * @return {Promise}\n */\n async getLatestBlockhash(commitmentOrConfig) {\n try {\n const res = await this.getLatestBlockhashAndContext(commitmentOrConfig);\n return res.value;\n } catch (e) {\n throw new Error('failed to get recent blockhash: ' + e);\n }\n }\n\n /**\n * Fetch the latest blockhash from the cluster\n * @return {Promise}\n */\n async getLatestBlockhashAndContext(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getLatestBlockhash', args);\n const res = create(unsafeRes, GetLatestBlockhashRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get latest blockhash');\n }\n return res.result;\n }\n\n /**\n * Returns whether a blockhash is still valid or not\n */\n async isBlockhashValid(blockhash, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgs([blockhash], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('isBlockhashValid', args);\n const res = create(unsafeRes, IsBlockhashValidRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to determine if the blockhash `' + blockhash + '`is valid');\n }\n return res.result;\n }\n\n /**\n * Fetch the node version\n */\n async getVersion() {\n const unsafeRes = await this._rpcRequest('getVersion', []);\n const res = create(unsafeRes, jsonRpcResult(VersionResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get version');\n }\n return res.result;\n }\n\n /**\n * Fetch the genesis hash\n */\n async getGenesisHash() {\n const unsafeRes = await this._rpcRequest('getGenesisHash', []);\n const res = create(unsafeRes, jsonRpcResult(string()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get genesis hash');\n }\n return res.result;\n }\n\n /**\n * Fetch a processed block from the cluster.\n *\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n\n /**\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Fetch a processed block from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Fetch a processed block from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(slot, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getBlock', args);\n try {\n switch (config?.transactionDetails) {\n case 'accounts':\n {\n const res = create(unsafeRes, GetAccountsModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n case 'none':\n {\n const res = create(unsafeRes, GetNoneModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n default:\n {\n const res = create(unsafeRes, GetBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n const {\n result\n } = res;\n return result ? {\n ...result,\n transactions: result.transactions.map(({\n transaction,\n meta,\n version\n }) => ({\n meta,\n transaction: {\n ...transaction,\n message: versionedMessageFromResponse(version, transaction.message)\n },\n version\n }))\n } : null;\n }\n }\n } catch (e) {\n throw new SolanaJSONRPCError(e, 'failed to get confirmed block');\n }\n }\n\n /**\n * Fetch parsed transaction details for a confirmed or finalized block\n */\n\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n async getParsedBlock(slot, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed([slot], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getBlock', args);\n try {\n switch (config?.transactionDetails) {\n case 'accounts':\n {\n const res = create(unsafeRes, GetParsedAccountsModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n case 'none':\n {\n const res = create(unsafeRes, GetParsedNoneModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n default:\n {\n const res = create(unsafeRes, GetParsedBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n }\n } catch (e) {\n throw new SolanaJSONRPCError(e, 'failed to get block');\n }\n }\n /*\n * Returns recent block production information from the current or previous epoch\n */\n async getBlockProduction(configOrCommitment) {\n let extra;\n let commitment;\n if (typeof configOrCommitment === 'string') {\n commitment = configOrCommitment;\n } else if (configOrCommitment) {\n const {\n commitment: c,\n ...rest\n } = configOrCommitment;\n commitment = c;\n extra = rest;\n }\n const args = this._buildArgs([], commitment, 'base64', extra);\n const unsafeRes = await this._rpcRequest('getBlockProduction', args);\n const res = create(unsafeRes, BlockProductionResponseStruct);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get block production information');\n }\n return res.result;\n }\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n *\n * @deprecated Instead, call `getTransaction` using a\n * `GetVersionedTransactionConfig` by setting the\n * `maxSupportedTransactionVersion` property.\n */\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransaction(signature, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n const result = res.result;\n if (!result) return result;\n return {\n ...result,\n transaction: {\n ...result.transaction,\n message: versionedMessageFromResponse(result.version, result.transaction.message)\n }\n };\n }\n\n /**\n * Fetch parsed transaction details for a confirmed or finalized transaction\n */\n async getParsedTransaction(signature, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n return res.result;\n }\n\n /**\n * Fetch parsed transaction details for a batch of confirmed transactions\n */\n async getParsedTransactions(signatures, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config);\n return {\n methodName: 'getTransaction',\n args\n };\n });\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map(unsafeRes => {\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n }\n return res.result;\n });\n return res;\n }\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link TransactionResponse}.\n *\n * @deprecated Instead, call `getTransactions` using a\n * `GetVersionedTransactionConfig` by setting the\n * `maxSupportedTransactionVersion` property.\n */\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link\n * VersionedTransactionResponse}.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link\n * VersionedTransactionResponse}.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransactions(signatures, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, undefined /* encoding */, config);\n return {\n methodName: 'getTransaction',\n args\n };\n });\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map(unsafeRes => {\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n }\n const result = res.result;\n if (!result) return result;\n return {\n ...result,\n transaction: {\n ...result.transaction,\n message: versionedMessageFromResponse(result.version, result.transaction.message)\n }\n };\n });\n return res;\n }\n\n /**\n * Fetch a list of Transactions and transaction statuses from the cluster\n * for a confirmed block.\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getBlock} instead.\n */\n async getConfirmedBlock(slot, commitment) {\n const args = this._buildArgsAtLeastConfirmed([slot], commitment);\n const unsafeRes = await this._rpcRequest('getBlock', args);\n const res = create(unsafeRes, GetConfirmedBlockRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Confirmed block ' + slot + ' not found');\n }\n const block = {\n ...result,\n transactions: result.transactions.map(({\n transaction,\n meta\n }) => {\n const message = new Message(transaction.message);\n return {\n meta,\n transaction: {\n ...transaction,\n message\n }\n };\n })\n };\n return {\n ...block,\n transactions: block.transactions.map(({\n transaction,\n meta\n }) => {\n return {\n meta,\n transaction: Transaction.populate(transaction.message, transaction.signatures)\n };\n })\n };\n }\n\n /**\n * Fetch confirmed blocks between two slots\n */\n async getBlocks(startSlot, endSlot, commitment) {\n const args = this._buildArgsAtLeastConfirmed(endSlot !== undefined ? [startSlot, endSlot] : [startSlot], commitment);\n const unsafeRes = await this._rpcRequest('getBlocks', args);\n const res = create(unsafeRes, jsonRpcResult(array(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get blocks');\n }\n return res.result;\n }\n\n /**\n * Fetch a list of Signatures from the cluster for a block, excluding rewards\n */\n async getBlockSignatures(slot, commitment) {\n const args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, {\n transactionDetails: 'signatures',\n rewards: false\n });\n const unsafeRes = await this._rpcRequest('getBlock', args);\n const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Block ' + slot + ' not found');\n }\n return result;\n }\n\n /**\n * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getBlockSignatures} instead.\n */\n async getConfirmedBlockSignatures(slot, commitment) {\n const args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, {\n transactionDetails: 'signatures',\n rewards: false\n });\n const unsafeRes = await this._rpcRequest('getBlock', args);\n const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Confirmed block ' + slot + ' not found');\n }\n return result;\n }\n\n /**\n * Fetch a transaction details for a confirmed transaction\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getTransaction} instead.\n */\n async getConfirmedTransaction(signature, commitment) {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment);\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n const result = res.result;\n if (!result) return result;\n const message = new Message(result.transaction.message);\n const signatures = result.transaction.signatures;\n return {\n ...result,\n transaction: Transaction.populate(message, signatures)\n };\n }\n\n /**\n * Fetch parsed transaction details for a confirmed transaction\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getParsedTransaction} instead.\n */\n async getParsedConfirmedTransaction(signature, commitment) {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed');\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transaction');\n }\n return res.result;\n }\n\n /**\n * Fetch parsed transaction details for a batch of confirmed transactions\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getParsedTransactions} instead.\n */\n async getParsedConfirmedTransactions(signatures, commitment) {\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed');\n return {\n methodName: 'getTransaction',\n args\n };\n });\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map(unsafeRes => {\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transactions');\n }\n return res.result;\n });\n return res;\n }\n\n /**\n * Fetch a list of all the confirmed signatures for transactions involving an address\n * within a specified slot range. Max range allowed is 10,000 slots.\n *\n * @deprecated Deprecated since RPC v1.3. Please use {@link getConfirmedSignaturesForAddress2} instead.\n *\n * @param address queried address\n * @param startSlot start slot, inclusive\n * @param endSlot end slot, inclusive\n */\n async getConfirmedSignaturesForAddress(address, startSlot, endSlot) {\n let options = {};\n let firstAvailableBlock = await this.getFirstAvailableBlock();\n while (!('until' in options)) {\n startSlot--;\n if (startSlot <= 0 || startSlot < firstAvailableBlock) {\n break;\n }\n try {\n const block = await this.getConfirmedBlockSignatures(startSlot, 'finalized');\n if (block.signatures.length > 0) {\n options.until = block.signatures[block.signatures.length - 1].toString();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('skipped')) {\n continue;\n } else {\n throw err;\n }\n }\n }\n let highestConfirmedRoot = await this.getSlot('finalized');\n while (!('before' in options)) {\n endSlot++;\n if (endSlot > highestConfirmedRoot) {\n break;\n }\n try {\n const block = await this.getConfirmedBlockSignatures(endSlot);\n if (block.signatures.length > 0) {\n options.before = block.signatures[block.signatures.length - 1].toString();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('skipped')) {\n continue;\n } else {\n throw err;\n }\n }\n }\n const confirmedSignatureInfo = await this.getConfirmedSignaturesForAddress2(address, options);\n return confirmedSignatureInfo.map(info => info.signature);\n }\n\n /**\n * Returns confirmed signatures for transactions involving an\n * address backwards in time from the provided signature or most recent confirmed block\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getSignaturesForAddress} instead.\n */\n async getConfirmedSignaturesForAddress2(address, options, commitment) {\n const args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options);\n const unsafeRes = await this._rpcRequest('getConfirmedSignaturesForAddress2', args);\n const res = create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed signatures for address');\n }\n return res.result;\n }\n\n /**\n * Returns confirmed signatures for transactions involving an\n * address backwards in time from the provided signature or most recent confirmed block\n *\n *\n * @param address queried address\n * @param options\n */\n async getSignaturesForAddress(address, options, commitment) {\n const args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options);\n const unsafeRes = await this._rpcRequest('getSignaturesForAddress', args);\n const res = create(unsafeRes, GetSignaturesForAddressRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get signatures for address');\n }\n return res.result;\n }\n async getAddressLookupTable(accountKey, config) {\n const {\n context,\n value: accountInfo\n } = await this.getAccountInfoAndContext(accountKey, config);\n let value = null;\n if (accountInfo !== null) {\n value = new AddressLookupTableAccount({\n key: accountKey,\n state: AddressLookupTableAccount.deserialize(accountInfo.data)\n });\n }\n return {\n context,\n value\n };\n }\n\n /**\n * Fetch the contents of a Nonce account from the cluster, return with context\n */\n async getNonceAndContext(nonceAccount, commitmentOrConfig) {\n const {\n context,\n value: accountInfo\n } = await this.getAccountInfoAndContext(nonceAccount, commitmentOrConfig);\n let value = null;\n if (accountInfo !== null) {\n value = NonceAccount.fromAccountData(accountInfo.data);\n }\n return {\n context,\n value\n };\n }\n\n /**\n * Fetch the contents of a Nonce account from the cluster\n */\n async getNonce(nonceAccount, commitmentOrConfig) {\n return await this.getNonceAndContext(nonceAccount, commitmentOrConfig).then(x => x.value).catch(e => {\n throw new Error('failed to get nonce for account ' + nonceAccount.toBase58() + ': ' + e);\n });\n }\n\n /**\n * Request an allocation of lamports to the specified address\n *\n * ```typescript\n * import { Connection, PublicKey, LAMPORTS_PER_SOL } from \"@solana/web3.js\";\n *\n * (async () => {\n * const connection = new Connection(\"https://api.testnet.solana.com\", \"confirmed\");\n * const myAddress = new PublicKey(\"2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM\");\n * const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL);\n * await connection.confirmTransaction(signature);\n * })();\n * ```\n */\n async requestAirdrop(to, lamports) {\n const unsafeRes = await this._rpcRequest('requestAirdrop', [to.toBase58(), lamports]);\n const res = create(unsafeRes, RequestAirdropRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `airdrop to ${to.toBase58()} failed`);\n }\n return res.result;\n }\n\n /**\n * @internal\n */\n async _blockhashWithExpiryBlockHeight(disableCache) {\n if (!disableCache) {\n // Wait for polling to finish\n while (this._pollingBlockhash) {\n await sleep(100);\n }\n const timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch;\n const expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS;\n if (this._blockhashInfo.latestBlockhash !== null && !expired) {\n return this._blockhashInfo.latestBlockhash;\n }\n }\n return await this._pollNewBlockhash();\n }\n\n /**\n * @internal\n */\n async _pollNewBlockhash() {\n this._pollingBlockhash = true;\n try {\n const startTime = Date.now();\n const cachedLatestBlockhash = this._blockhashInfo.latestBlockhash;\n const cachedBlockhash = cachedLatestBlockhash ? cachedLatestBlockhash.blockhash : null;\n for (let i = 0; i < 50; i++) {\n const latestBlockhash = await this.getLatestBlockhash('finalized');\n if (cachedBlockhash !== latestBlockhash.blockhash) {\n this._blockhashInfo = {\n latestBlockhash,\n lastFetch: Date.now(),\n transactionSignatures: [],\n simulatedSignatures: []\n };\n return latestBlockhash;\n }\n\n // Sleep for approximately half a slot\n await sleep(MS_PER_SLOT / 2);\n }\n throw new Error(`Unable to obtain a new blockhash after ${Date.now() - startTime}ms`);\n } finally {\n this._pollingBlockhash = false;\n }\n }\n\n /**\n * get the stake minimum delegation\n */\n async getStakeMinimumDelegation(config) {\n const {\n commitment,\n config: configArg\n } = extractCommitmentFromConfig(config);\n const args = this._buildArgs([], commitment, 'base64', configArg);\n const unsafeRes = await this._rpcRequest('getStakeMinimumDelegation', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get stake minimum delegation`);\n }\n return res.result;\n }\n\n /**\n * Simulate a transaction\n *\n * @deprecated Instead, call {@link simulateTransaction} with {@link\n * VersionedTransaction} and {@link SimulateTransactionConfig} parameters\n */\n\n /**\n * Simulate a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Simulate a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n async simulateTransaction(transactionOrMessage, configOrSigners, includeAccounts) {\n if ('message' in transactionOrMessage) {\n const versionedTx = transactionOrMessage;\n const wireTransaction = versionedTx.serialize();\n const encodedTransaction = Buffer.from(wireTransaction).toString('base64');\n if (Array.isArray(configOrSigners) || includeAccounts !== undefined) {\n throw new Error('Invalid arguments');\n }\n const config = configOrSigners || {};\n config.encoding = 'base64';\n if (!('commitment' in config)) {\n config.commitment = this.commitment;\n }\n if (configOrSigners && typeof configOrSigners === 'object' && 'innerInstructions' in configOrSigners) {\n config.innerInstructions = configOrSigners.innerInstructions;\n }\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n if ('error' in res) {\n throw new Error('failed to simulate transaction: ' + res.error.message);\n }\n return res.result;\n }\n let transaction;\n if (transactionOrMessage instanceof Transaction) {\n let originalTx = transactionOrMessage;\n transaction = new Transaction();\n transaction.feePayer = originalTx.feePayer;\n transaction.instructions = transactionOrMessage.instructions;\n transaction.nonceInfo = originalTx.nonceInfo;\n transaction.signatures = originalTx.signatures;\n } else {\n transaction = Transaction.populate(transactionOrMessage);\n // HACK: this function relies on mutating the populated transaction\n transaction._message = transaction._json = undefined;\n }\n if (configOrSigners !== undefined && !Array.isArray(configOrSigners)) {\n throw new Error('Invalid arguments');\n }\n const signers = configOrSigners;\n if (transaction.nonceInfo && signers) {\n transaction.sign(...signers);\n } else {\n let disableCache = this._disableBlockhashCaching;\n for (;;) {\n const latestBlockhash = await this._blockhashWithExpiryBlockHeight(disableCache);\n transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n transaction.recentBlockhash = latestBlockhash.blockhash;\n if (!signers) break;\n transaction.sign(...signers);\n if (!transaction.signature) {\n throw new Error('!signature'); // should never happen\n }\n const signature = transaction.signature.toString('base64');\n if (!this._blockhashInfo.simulatedSignatures.includes(signature) && !this._blockhashInfo.transactionSignatures.includes(signature)) {\n // The signature of this transaction has not been seen before with the\n // current recentBlockhash, all done. Let's break\n this._blockhashInfo.simulatedSignatures.push(signature);\n break;\n } else {\n // This transaction would be treated as duplicate (its derived signature\n // matched to one of already recorded signatures).\n // So, we must fetch a new blockhash for a different signature by disabling\n // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n disableCache = true;\n }\n }\n }\n const message = transaction._compile();\n const signData = message.serialize();\n const wireTransaction = transaction._serialize(signData);\n const encodedTransaction = wireTransaction.toString('base64');\n const config = {\n encoding: 'base64',\n commitment: this.commitment\n };\n if (includeAccounts) {\n const addresses = (Array.isArray(includeAccounts) ? includeAccounts : message.nonProgramIds()).map(key => key.toBase58());\n config['accounts'] = {\n encoding: 'base64',\n addresses\n };\n }\n if (signers) {\n config.sigVerify = true;\n }\n if (configOrSigners && typeof configOrSigners === 'object' && 'innerInstructions' in configOrSigners) {\n config.innerInstructions = configOrSigners.innerInstructions;\n }\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n if ('error' in res) {\n let logs;\n if ('data' in res.error) {\n logs = res.error.data.logs;\n if (logs && Array.isArray(logs)) {\n const traceIndent = '\\n ';\n const logTrace = traceIndent + logs.join(traceIndent);\n console.error(res.error.message, logTrace);\n }\n }\n throw new SendTransactionError({\n action: 'simulate',\n signature: '',\n transactionMessage: res.error.message,\n logs: logs\n });\n }\n return res.result;\n }\n\n /**\n * Sign and send a transaction\n *\n * @deprecated Instead, call {@link sendTransaction} with a {@link\n * VersionedTransaction}\n */\n\n /**\n * Send a signed transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Sign and send a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n async sendTransaction(transaction, signersOrOptions, options) {\n if ('version' in transaction) {\n if (signersOrOptions && Array.isArray(signersOrOptions)) {\n throw new Error('Invalid arguments');\n }\n const wireTransaction = transaction.serialize();\n return await this.sendRawTransaction(wireTransaction, signersOrOptions);\n }\n if (signersOrOptions === undefined || !Array.isArray(signersOrOptions)) {\n throw new Error('Invalid arguments');\n }\n const signers = signersOrOptions;\n if (transaction.nonceInfo) {\n transaction.sign(...signers);\n } else {\n let disableCache = this._disableBlockhashCaching;\n for (;;) {\n const latestBlockhash = await this._blockhashWithExpiryBlockHeight(disableCache);\n transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n transaction.recentBlockhash = latestBlockhash.blockhash;\n transaction.sign(...signers);\n if (!transaction.signature) {\n throw new Error('!signature'); // should never happen\n }\n const signature = transaction.signature.toString('base64');\n if (!this._blockhashInfo.transactionSignatures.includes(signature)) {\n // The signature of this transaction has not been seen before with the\n // current recentBlockhash, all done. Let's break\n this._blockhashInfo.transactionSignatures.push(signature);\n break;\n } else {\n // This transaction would be treated as duplicate (its derived signature\n // matched to one of already recorded signatures).\n // So, we must fetch a new blockhash for a different signature by disabling\n // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n disableCache = true;\n }\n }\n }\n const wireTransaction = transaction.serialize();\n return await this.sendRawTransaction(wireTransaction, options);\n }\n\n /**\n * Send a transaction that has already been signed and serialized into the\n * wire format\n */\n async sendRawTransaction(rawTransaction, options) {\n const encodedTransaction = toBuffer(rawTransaction).toString('base64');\n const result = await this.sendEncodedTransaction(encodedTransaction, options);\n return result;\n }\n\n /**\n * Send a transaction that has already been signed, serialized into the\n * wire format, and encoded as a base64 string\n */\n async sendEncodedTransaction(encodedTransaction, options) {\n const config = {\n encoding: 'base64'\n };\n const skipPreflight = options && options.skipPreflight;\n const preflightCommitment = skipPreflight === true ? 'processed' // FIXME Remove when https://github.com/anza-xyz/agave/pull/483 is deployed.\n : options && options.preflightCommitment || this.commitment;\n if (options && options.maxRetries != null) {\n config.maxRetries = options.maxRetries;\n }\n if (options && options.minContextSlot != null) {\n config.minContextSlot = options.minContextSlot;\n }\n if (skipPreflight) {\n config.skipPreflight = skipPreflight;\n }\n if (preflightCommitment) {\n config.preflightCommitment = preflightCommitment;\n }\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('sendTransaction', args);\n const res = create(unsafeRes, SendTransactionRpcResult);\n if ('error' in res) {\n let logs = undefined;\n if ('data' in res.error) {\n logs = res.error.data.logs;\n }\n throw new SendTransactionError({\n action: skipPreflight ? 'send' : 'simulate',\n signature: '',\n transactionMessage: res.error.message,\n logs: logs\n });\n }\n return res.result;\n }\n\n /**\n * @internal\n */\n _wsOnOpen() {\n this._rpcWebSocketConnected = true;\n this._rpcWebSocketHeartbeat = setInterval(() => {\n // Ping server every 5s to prevent idle timeouts\n (async () => {\n try {\n await this._rpcWebSocket.notify('ping');\n // eslint-disable-next-line no-empty\n } catch {}\n })();\n }, 5000);\n this._updateSubscriptions();\n }\n\n /**\n * @internal\n */\n _wsOnError(err) {\n this._rpcWebSocketConnected = false;\n console.error('ws error:', err.message);\n }\n\n /**\n * @internal\n */\n _wsOnClose(code) {\n this._rpcWebSocketConnected = false;\n this._rpcWebSocketGeneration = (this._rpcWebSocketGeneration + 1) % Number.MAX_SAFE_INTEGER;\n if (this._rpcWebSocketIdleTimeout) {\n clearTimeout(this._rpcWebSocketIdleTimeout);\n this._rpcWebSocketIdleTimeout = null;\n }\n if (this._rpcWebSocketHeartbeat) {\n clearInterval(this._rpcWebSocketHeartbeat);\n this._rpcWebSocketHeartbeat = null;\n }\n if (code === 1000) {\n // explicit close, check if any subscriptions have been made since close\n this._updateSubscriptions();\n return;\n }\n\n // implicit close, prepare subscriptions for auto-reconnect\n this._subscriptionCallbacksByServerSubscriptionId = {};\n Object.entries(this._subscriptionsByHash).forEach(([hash, subscription]) => {\n this._setSubscription(hash, {\n ...subscription,\n state: 'pending'\n });\n });\n }\n\n /**\n * @internal\n */\n _setSubscription(hash, nextSubscription) {\n const prevState = this._subscriptionsByHash[hash]?.state;\n this._subscriptionsByHash[hash] = nextSubscription;\n if (prevState !== nextSubscription.state) {\n const stateChangeCallbacks = this._subscriptionStateChangeCallbacksByHash[hash];\n if (stateChangeCallbacks) {\n stateChangeCallbacks.forEach(cb => {\n try {\n cb(nextSubscription.state);\n // eslint-disable-next-line no-empty\n } catch {}\n });\n }\n }\n }\n\n /**\n * @internal\n */\n _onSubscriptionStateChange(clientSubscriptionId, callback) {\n const hash = this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n if (hash == null) {\n return () => {};\n }\n const stateChangeCallbacks = this._subscriptionStateChangeCallbacksByHash[hash] ||= new Set();\n stateChangeCallbacks.add(callback);\n return () => {\n stateChangeCallbacks.delete(callback);\n if (stateChangeCallbacks.size === 0) {\n delete this._subscriptionStateChangeCallbacksByHash[hash];\n }\n };\n }\n\n /**\n * @internal\n */\n async _updateSubscriptions() {\n if (Object.keys(this._subscriptionsByHash).length === 0) {\n if (this._rpcWebSocketConnected) {\n this._rpcWebSocketConnected = false;\n this._rpcWebSocketIdleTimeout = setTimeout(() => {\n this._rpcWebSocketIdleTimeout = null;\n try {\n this._rpcWebSocket.close();\n } catch (err) {\n // swallow error if socket has already been closed.\n if (err instanceof Error) {\n console.log(`Error when closing socket connection: ${err.message}`);\n }\n }\n }, 500);\n }\n return;\n }\n if (this._rpcWebSocketIdleTimeout !== null) {\n clearTimeout(this._rpcWebSocketIdleTimeout);\n this._rpcWebSocketIdleTimeout = null;\n this._rpcWebSocketConnected = true;\n }\n if (!this._rpcWebSocketConnected) {\n this._rpcWebSocket.connect();\n return;\n }\n const activeWebSocketGeneration = this._rpcWebSocketGeneration;\n const isCurrentConnectionStillActive = () => {\n return activeWebSocketGeneration === this._rpcWebSocketGeneration;\n };\n await Promise.all(\n // Don't be tempted to change this to `Object.entries`. We call\n // `_updateSubscriptions` recursively when processing the state,\n // so it's important that we look up the *current* version of\n // each subscription, every time we process a hash.\n Object.keys(this._subscriptionsByHash).map(async hash => {\n const subscription = this._subscriptionsByHash[hash];\n if (subscription === undefined) {\n // This entry has since been deleted. Skip.\n return;\n }\n switch (subscription.state) {\n case 'pending':\n case 'unsubscribed':\n if (subscription.callbacks.size === 0) {\n /**\n * You can end up here when:\n *\n * - a subscription has recently unsubscribed\n * without having new callbacks added to it\n * while the unsubscribe was in flight, or\n * - when a pending subscription has its\n * listeners removed before a request was\n * sent to the server.\n *\n * Being that nobody is interested in this\n * subscription any longer, delete it.\n */\n delete this._subscriptionsByHash[hash];\n if (subscription.state === 'unsubscribed') {\n delete this._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId];\n }\n await this._updateSubscriptions();\n return;\n }\n await (async () => {\n const {\n args,\n method\n } = subscription;\n try {\n this._setSubscription(hash, {\n ...subscription,\n state: 'subscribing'\n });\n const serverSubscriptionId = await this._rpcWebSocket.call(method, args);\n this._setSubscription(hash, {\n ...subscription,\n serverSubscriptionId,\n state: 'subscribed'\n });\n this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId] = subscription.callbacks;\n await this._updateSubscriptions();\n } catch (e) {\n console.error(`Received ${e instanceof Error ? '' : 'JSON-RPC '}error calling \\`${method}\\``, {\n args,\n error: e\n });\n if (!isCurrentConnectionStillActive()) {\n return;\n }\n // TODO: Maybe add an 'errored' state or a retry limit?\n this._setSubscription(hash, {\n ...subscription,\n state: 'pending'\n });\n await this._updateSubscriptions();\n }\n })();\n break;\n case 'subscribed':\n if (subscription.callbacks.size === 0) {\n // By the time we successfully set up a subscription\n // with the server, the client stopped caring about it.\n // Tear it down now.\n await (async () => {\n const {\n serverSubscriptionId,\n unsubscribeMethod\n } = subscription;\n if (this._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)) {\n /**\n * Special case.\n * If we're dealing with a subscription that has been auto-\n * disposed by the RPC, then we can skip the RPC call to\n * tear down the subscription here.\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n this._subscriptionsAutoDisposedByRpc.delete(serverSubscriptionId);\n } else {\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribing'\n });\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribing'\n });\n try {\n await this._rpcWebSocket.call(unsubscribeMethod, [serverSubscriptionId]);\n } catch (e) {\n if (e instanceof Error) {\n console.error(`${unsubscribeMethod} error:`, e.message);\n }\n if (!isCurrentConnectionStillActive()) {\n return;\n }\n // TODO: Maybe add an 'errored' state or a retry limit?\n this._setSubscription(hash, {\n ...subscription,\n state: 'subscribed'\n });\n await this._updateSubscriptions();\n return;\n }\n }\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribed'\n });\n await this._updateSubscriptions();\n })();\n }\n break;\n }\n }));\n }\n\n /**\n * @internal\n */\n _handleServerNotification(serverSubscriptionId, callbackArgs) {\n const callbacks = this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId];\n if (callbacks === undefined) {\n return;\n }\n callbacks.forEach(cb => {\n try {\n cb(\n // I failed to find a way to convince TypeScript that `cb` is of type\n // `TCallback` which is certainly compatible with `Parameters`.\n // See https://github.com/microsoft/TypeScript/issues/47615\n // @ts-ignore\n ...callbackArgs);\n } catch (e) {\n console.error(e);\n }\n });\n }\n\n /**\n * @internal\n */\n _wsOnAccountNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, AccountNotificationResult);\n this._handleServerNotification(subscription, [result.value, result.context]);\n }\n\n /**\n * @internal\n */\n _makeSubscription(subscriptionConfig,\n /**\n * When preparing `args` for a call to `_makeSubscription`, be sure\n * to carefully apply a default `commitment` property, if necessary.\n *\n * - If the user supplied a `commitment` use that.\n * - Otherwise, if the `Connection::commitment` is set, use that.\n * - Otherwise, set it to the RPC server default: `finalized`.\n *\n * This is extremely important to ensure that these two fundamentally\n * identical subscriptions produce the same identifying hash:\n *\n * - A subscription made without specifying a commitment.\n * - A subscription made where the commitment specified is the same\n * as the default applied to the subscription above.\n *\n * Example; these two subscriptions must produce the same hash:\n *\n * - An `accountSubscribe` subscription for `'PUBKEY'`\n * - An `accountSubscribe` subscription for `'PUBKEY'` with commitment\n * `'finalized'`.\n *\n * See the 'making a subscription with defaulted params omitted' test\n * in `connection-subscriptions.ts` for more.\n */\n args) {\n const clientSubscriptionId = this._nextClientSubscriptionId++;\n const hash = fastStableStringify([subscriptionConfig.method, args]);\n const existingSubscription = this._subscriptionsByHash[hash];\n if (existingSubscription === undefined) {\n this._subscriptionsByHash[hash] = {\n ...subscriptionConfig,\n args,\n callbacks: new Set([subscriptionConfig.callback]),\n state: 'pending'\n };\n } else {\n existingSubscription.callbacks.add(subscriptionConfig.callback);\n }\n this._subscriptionHashByClientSubscriptionId[clientSubscriptionId] = hash;\n this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId] = async () => {\n delete this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];\n delete this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n const subscription = this._subscriptionsByHash[hash];\n assert(subscription !== undefined, `Could not find a \\`Subscription\\` when tearing down client subscription #${clientSubscriptionId}`);\n subscription.callbacks.delete(subscriptionConfig.callback);\n await this._updateSubscriptions();\n };\n this._updateSubscriptions();\n return clientSubscriptionId;\n }\n\n /**\n * Register a callback to be invoked whenever the specified account changes\n *\n * @param publicKey Public key of the account to monitor\n * @param callback Function to invoke whenever the account is changed\n * @param config\n * @return subscription id\n */\n\n /** @deprecated Instead, pass in an {@link AccountSubscriptionConfig} */\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n onAccountChange(publicKey, callback, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment || this._commitment || 'finalized',\n // Apply connection/server default.\n 'base64', config);\n return this._makeSubscription({\n callback,\n method: 'accountSubscribe',\n unsubscribeMethod: 'accountUnsubscribe'\n }, args);\n }\n\n /**\n * Deregister an account notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeAccountChangeListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'account change');\n }\n\n /**\n * @internal\n */\n _wsOnProgramAccountNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, ProgramAccountNotificationResult);\n this._handleServerNotification(subscription, [{\n accountId: result.value.pubkey,\n accountInfo: result.value.account\n }, result.context]);\n }\n\n /**\n * Register a callback to be invoked whenever accounts owned by the\n * specified program change\n *\n * @param programId Public key of the program to monitor\n * @param callback Function to invoke whenever the account is changed\n * @param config\n * @return subscription id\n */\n\n /** @deprecated Instead, pass in a {@link ProgramAccountSubscriptionConfig} */\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n onProgramAccountChange(programId, callback, commitmentOrConfig, maybeFilters) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([programId.toBase58()], commitment || this._commitment || 'finalized',\n // Apply connection/server default.\n 'base64' /* encoding */, config ? config : maybeFilters ? {\n filters: applyDefaultMemcmpEncodingToFilters(maybeFilters)\n } : undefined /* extra */);\n return this._makeSubscription({\n callback,\n method: 'programSubscribe',\n unsubscribeMethod: 'programUnsubscribe'\n }, args);\n }\n\n /**\n * Deregister an account notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeProgramAccountChangeListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'program account change');\n }\n\n /**\n * Registers a callback to be invoked whenever logs are emitted.\n */\n onLogs(filter, callback, commitment) {\n const args = this._buildArgs([typeof filter === 'object' ? {\n mentions: [filter.toString()]\n } : filter], commitment || this._commitment || 'finalized' // Apply connection/server default.\n );\n return this._makeSubscription({\n callback,\n method: 'logsSubscribe',\n unsubscribeMethod: 'logsUnsubscribe'\n }, args);\n }\n\n /**\n * Deregister a logs callback.\n *\n * @param clientSubscriptionId client subscription id to deregister.\n */\n async removeOnLogsListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'logs');\n }\n\n /**\n * @internal\n */\n _wsOnLogsNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, LogsNotificationResult);\n this._handleServerNotification(subscription, [result.value, result.context]);\n }\n\n /**\n * @internal\n */\n _wsOnSlotNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, SlotNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon slot changes\n *\n * @param callback Function to invoke whenever the slot changes\n * @return subscription id\n */\n onSlotChange(callback) {\n return this._makeSubscription({\n callback,\n method: 'slotSubscribe',\n unsubscribeMethod: 'slotUnsubscribe'\n }, [] /* args */);\n }\n\n /**\n * Deregister a slot notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeSlotChangeListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'slot change');\n }\n\n /**\n * @internal\n */\n _wsOnSlotUpdatesNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, SlotUpdateNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s\n * may be useful to track live progress of a cluster.\n *\n * @param callback Function to invoke whenever the slot updates\n * @return subscription id\n */\n onSlotUpdate(callback) {\n return this._makeSubscription({\n callback,\n method: 'slotsUpdatesSubscribe',\n unsubscribeMethod: 'slotsUpdatesUnsubscribe'\n }, [] /* args */);\n }\n\n /**\n * Deregister a slot update notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeSlotUpdateListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'slot update');\n }\n\n /**\n * @internal\n */\n\n async _unsubscribeClientSubscription(clientSubscriptionId, subscriptionName) {\n const dispose = this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];\n if (dispose) {\n await dispose();\n } else {\n console.warn('Ignored unsubscribe request because an active subscription with id ' + `\\`${clientSubscriptionId}\\` for '${subscriptionName}' events ` + 'could not be found.');\n }\n }\n _buildArgs(args, override, encoding, extra) {\n const commitment = override || this._commitment;\n if (commitment || encoding || extra) {\n let options = {};\n if (encoding) {\n options.encoding = encoding;\n }\n if (commitment) {\n options.commitment = commitment;\n }\n if (extra) {\n options = Object.assign(options, extra);\n }\n args.push(options);\n }\n return args;\n }\n\n /**\n * @internal\n */\n _buildArgsAtLeastConfirmed(args, override, encoding, extra) {\n const commitment = override || this._commitment;\n if (commitment && !['confirmed', 'finalized'].includes(commitment)) {\n throw new Error('Using Connection with default commitment: `' + this._commitment + '`, but method requires at least `confirmed`');\n }\n return this._buildArgs(args, override, encoding, extra);\n }\n\n /**\n * @internal\n */\n _wsOnSignatureNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, SignatureNotificationResult);\n if (result.value !== 'receivedSignature') {\n /**\n * Special case.\n * After a signature is processed, RPCs automatically dispose of the\n * subscription on the server side. We need to track which of these\n * subscriptions have been disposed in such a way, so that we know\n * whether the client is dealing with a not-yet-processed signature\n * (in which case we must tear down the server subscription) or an\n * already-processed signature (in which case the client can simply\n * clear out the subscription locally without telling the server).\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n this._subscriptionsAutoDisposedByRpc.add(subscription);\n }\n this._handleServerNotification(subscription, result.value === 'receivedSignature' ? [{\n type: 'received'\n }, result.context] : [{\n type: 'status',\n result: result.value\n }, result.context]);\n }\n\n /**\n * Register a callback to be invoked upon signature updates\n *\n * @param signature Transaction signature string in base 58\n * @param callback Function to invoke on signature notifications\n * @param commitment Specify the commitment level signature must reach before notification\n * @return subscription id\n */\n onSignature(signature, callback, commitment) {\n const args = this._buildArgs([signature], commitment || this._commitment || 'finalized' // Apply connection/server default.\n );\n const clientSubscriptionId = this._makeSubscription({\n callback: (notification, context) => {\n if (notification.type === 'status') {\n callback(notification.result, context);\n // Signatures subscriptions are auto-removed by the RPC service\n // so no need to explicitly send an unsubscribe message.\n try {\n this.removeSignatureListener(clientSubscriptionId);\n // eslint-disable-next-line no-empty\n } catch (_err) {\n // Already removed.\n }\n }\n },\n method: 'signatureSubscribe',\n unsubscribeMethod: 'signatureUnsubscribe'\n }, args);\n return clientSubscriptionId;\n }\n\n /**\n * Register a callback to be invoked when a transaction is\n * received and/or processed.\n *\n * @param signature Transaction signature string in base 58\n * @param callback Function to invoke on signature notifications\n * @param options Enable received notifications and set the commitment\n * level that signature must reach before notification\n * @return subscription id\n */\n onSignatureWithOptions(signature, callback, options) {\n const {\n commitment,\n ...extra\n } = {\n ...options,\n commitment: options && options.commitment || this._commitment || 'finalized' // Apply connection/server default.\n };\n const args = this._buildArgs([signature], commitment, undefined /* encoding */, extra);\n const clientSubscriptionId = this._makeSubscription({\n callback: (notification, context) => {\n callback(notification, context);\n // Signatures subscriptions are auto-removed by the RPC service\n // so no need to explicitly send an unsubscribe message.\n try {\n this.removeSignatureListener(clientSubscriptionId);\n // eslint-disable-next-line no-empty\n } catch (_err) {\n // Already removed.\n }\n },\n method: 'signatureSubscribe',\n unsubscribeMethod: 'signatureUnsubscribe'\n }, args);\n return clientSubscriptionId;\n }\n\n /**\n * Deregister a signature notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeSignatureListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'signature result');\n }\n\n /**\n * @internal\n */\n _wsOnRootNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, RootNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon root changes\n *\n * @param callback Function to invoke whenever the root changes\n * @return subscription id\n */\n onRootChange(callback) {\n return this._makeSubscription({\n callback,\n method: 'rootSubscribe',\n unsubscribeMethod: 'rootUnsubscribe'\n }, [] /* args */);\n }\n\n /**\n * Deregister a root notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeRootChangeListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'root change');\n }\n}\n\n/**\n * Keypair signer interface\n */\n\n/**\n * An account keypair used for signing transactions.\n */\nclass Keypair {\n /**\n * Create a new keypair instance.\n * Generate random keypair if no {@link Ed25519Keypair} is provided.\n *\n * @param {Ed25519Keypair} keypair ed25519 keypair\n */\n constructor(keypair) {\n this._keypair = void 0;\n this._keypair = keypair ?? generateKeypair();\n }\n\n /**\n * Generate a new random keypair\n *\n * @returns {Keypair} Keypair\n */\n static generate() {\n return new Keypair(generateKeypair());\n }\n\n /**\n * Create a keypair from a raw secret key byte array.\n *\n * This method should only be used to recreate a keypair from a previously\n * generated secret key. Generating keypairs from a random seed should be done\n * with the {@link Keypair.fromSeed} method.\n *\n * @throws error if the provided secret key is invalid and validation is not skipped.\n *\n * @param secretKey secret key byte array\n * @param options skip secret key validation\n *\n * @returns {Keypair} Keypair\n */\n static fromSecretKey(secretKey, options) {\n if (secretKey.byteLength !== 64) {\n throw new Error('bad secret key size');\n }\n const publicKey = secretKey.slice(32, 64);\n if (!options || !options.skipValidation) {\n const privateScalar = secretKey.slice(0, 32);\n const computedPublicKey = getPublicKey(privateScalar);\n for (let ii = 0; ii < 32; ii++) {\n if (publicKey[ii] !== computedPublicKey[ii]) {\n throw new Error('provided secretKey is invalid');\n }\n }\n }\n return new Keypair({\n publicKey,\n secretKey\n });\n }\n\n /**\n * Generate a keypair from a 32 byte seed.\n *\n * @param seed seed byte array\n *\n * @returns {Keypair} Keypair\n */\n static fromSeed(seed) {\n const publicKey = getPublicKey(seed);\n const secretKey = new Uint8Array(64);\n secretKey.set(seed);\n secretKey.set(publicKey, 32);\n return new Keypair({\n publicKey,\n secretKey\n });\n }\n\n /**\n * The public key for this keypair\n *\n * @returns {PublicKey} PublicKey\n */\n get publicKey() {\n return new PublicKey(this._keypair.publicKey);\n }\n\n /**\n * The raw secret key for this keypair\n * @returns {Uint8Array} Secret key in an array of Uint8 bytes\n */\n get secretKey() {\n return new Uint8Array(this._keypair.secretKey);\n }\n}\n\n/**\n * An enumeration of valid LookupTableInstructionType's\n */\n\n/**\n * An enumeration of valid address lookup table InstructionType's\n * @internal\n */\nconst LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({\n CreateLookupTable: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), u64('recentSlot'), BufferLayout.u8('bumpSeed')])\n },\n FreezeLookupTable: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n ExtendLookupTable: {\n index: 2,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), u64(), BufferLayout.seq(publicKey(), BufferLayout.offset(BufferLayout.u32(), -8), 'addresses')])\n },\n DeactivateLookupTable: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n CloseLookupTable: {\n index: 4,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n }\n});\nclass AddressLookupTableInstruction {\n /**\n * @internal\n */\n constructor() {}\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const index = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [layoutType, layout] of Object.entries(LOOKUP_TABLE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == index) {\n type = layoutType;\n break;\n }\n }\n if (!type) {\n throw new Error('Invalid Instruction. Should be a LookupTable Instruction');\n }\n return type;\n }\n static decodeCreateLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 4);\n const {\n recentSlot\n } = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable, instruction.data);\n return {\n authority: instruction.keys[1].pubkey,\n payer: instruction.keys[2].pubkey,\n recentSlot: Number(recentSlot)\n };\n }\n static decodeExtendLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n if (instruction.keys.length < 2) {\n throw new Error(`invalid instruction; found ${instruction.keys.length} keys, expected at least 2`);\n }\n const {\n addresses\n } = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable, instruction.data);\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n payer: instruction.keys.length > 2 ? instruction.keys[2].pubkey : undefined,\n addresses: addresses.map(buffer => new PublicKey(buffer))\n };\n }\n static decodeCloseLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 3);\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n recipient: instruction.keys[2].pubkey\n };\n }\n static decodeFreezeLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 2);\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey\n };\n }\n static decodeDeactivateLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 2);\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(AddressLookupTableProgram.programId)) {\n throw new Error('invalid instruction; programId is not AddressLookupTable Program');\n }\n }\n /**\n * @internal\n */\n static checkKeysLength(keys, expectedLength) {\n if (keys.length < expectedLength) {\n throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`);\n }\n }\n}\nclass AddressLookupTableProgram {\n /**\n * @internal\n */\n constructor() {}\n static createLookupTable(params) {\n const [lookupTableAddress, bumpSeed] = PublicKey.findProgramAddressSync([params.authority.toBuffer(), getU64Encoder().encode(params.recentSlot)], this.programId);\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;\n const data = encodeData(type, {\n recentSlot: BigInt(params.recentSlot),\n bumpSeed: bumpSeed\n });\n const keys = [{\n pubkey: lookupTableAddress,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: params.payer,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false\n }];\n return [new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n }), lookupTableAddress];\n }\n static freezeLookupTable(params) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;\n const data = encodeData(type);\n const keys = [{\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }];\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n });\n }\n static extendLookupTable(params) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;\n const data = encodeData(type, {\n addresses: params.addresses.map(addr => addr.toBytes())\n });\n const keys = [{\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }];\n if (params.payer) {\n keys.push({\n pubkey: params.payer,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false\n });\n }\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n });\n }\n static deactivateLookupTable(params) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;\n const data = encodeData(type);\n const keys = [{\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }];\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n });\n }\n static closeLookupTable(params) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;\n const data = encodeData(type);\n const keys = [{\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: params.recipient,\n isSigner: false,\n isWritable: true\n }];\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n });\n }\n}\nAddressLookupTableProgram.programId = new PublicKey('AddressLookupTab1e1111111111111111111111111');\n\n/**\n * Compute Budget Instruction class\n */\nclass ComputeBudgetInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a compute budget instruction and retrieve the instruction type.\n */\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u8('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [ixType, layout] of Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType;\n break;\n }\n }\n if (!type) {\n throw new Error('Instruction type incorrect; not a ComputeBudgetInstruction');\n }\n return type;\n }\n\n /**\n * Decode request units compute budget instruction and retrieve the instruction params.\n */\n static decodeRequestUnits(instruction) {\n this.checkProgramId(instruction.programId);\n const {\n units,\n additionalFee\n } = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits, instruction.data);\n return {\n units,\n additionalFee\n };\n }\n\n /**\n * Decode request heap frame compute budget instruction and retrieve the instruction params.\n */\n static decodeRequestHeapFrame(instruction) {\n this.checkProgramId(instruction.programId);\n const {\n bytes\n } = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame, instruction.data);\n return {\n bytes\n };\n }\n\n /**\n * Decode set compute unit limit compute budget instruction and retrieve the instruction params.\n */\n static decodeSetComputeUnitLimit(instruction) {\n this.checkProgramId(instruction.programId);\n const {\n units\n } = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit, instruction.data);\n return {\n units\n };\n }\n\n /**\n * Decode set compute unit price compute budget instruction and retrieve the instruction params.\n */\n static decodeSetComputeUnitPrice(instruction) {\n this.checkProgramId(instruction.programId);\n const {\n microLamports\n } = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice, instruction.data);\n return {\n microLamports\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(ComputeBudgetProgram.programId)) {\n throw new Error('invalid instruction; programId is not ComputeBudgetProgram');\n }\n }\n}\n\n/**\n * An enumeration of valid ComputeBudgetInstructionType's\n */\n\n/**\n * Request units instruction params\n */\n\n/**\n * Request heap frame instruction params\n */\n\n/**\n * Set compute unit limit instruction params\n */\n\n/**\n * Set compute unit price instruction params\n */\n\n/**\n * An enumeration of valid ComputeBudget InstructionType's\n * @internal\n */\nconst COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({\n RequestUnits: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u8('instruction'), BufferLayout.u32('units'), BufferLayout.u32('additionalFee')])\n },\n RequestHeapFrame: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u8('instruction'), BufferLayout.u32('bytes')])\n },\n SetComputeUnitLimit: {\n index: 2,\n layout: BufferLayout.struct([BufferLayout.u8('instruction'), BufferLayout.u32('units')])\n },\n SetComputeUnitPrice: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u8('instruction'), u64('microLamports')])\n }\n});\n\n/**\n * Factory class for transaction instructions to interact with the Compute Budget program\n */\nclass ComputeBudgetProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Compute Budget program\n */\n\n /**\n * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}\n */\n static requestUnits(params) {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data\n });\n }\n static requestHeapFrame(params) {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data\n });\n }\n static setComputeUnitLimit(params) {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data\n });\n }\n static setComputeUnitPrice(params) {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;\n const data = encodeData(type, {\n microLamports: BigInt(params.microLamports)\n });\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data\n });\n }\n}\nComputeBudgetProgram.programId = new PublicKey('ComputeBudget111111111111111111111111111111');\n\nconst PRIVATE_KEY_BYTES$1 = 64;\nconst PUBLIC_KEY_BYTES$1 = 32;\nconst SIGNATURE_BYTES = 64;\n\n/**\n * Params for creating an ed25519 instruction using a public key\n */\n\n/**\n * Params for creating an ed25519 instruction using a private key\n */\n\nconst ED25519_INSTRUCTION_LAYOUT = BufferLayout.struct([BufferLayout.u8('numSignatures'), BufferLayout.u8('padding'), BufferLayout.u16('signatureOffset'), BufferLayout.u16('signatureInstructionIndex'), BufferLayout.u16('publicKeyOffset'), BufferLayout.u16('publicKeyInstructionIndex'), BufferLayout.u16('messageDataOffset'), BufferLayout.u16('messageDataSize'), BufferLayout.u16('messageInstructionIndex')]);\nclass Ed25519Program {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the ed25519 program\n */\n\n /**\n * Create an ed25519 instruction with a public key and signature. The\n * public key must be a buffer that is 32 bytes long, and the signature\n * must be a buffer of 64 bytes.\n */\n static createInstructionWithPublicKey(params) {\n const {\n publicKey,\n message,\n signature,\n instructionIndex\n } = params;\n assert(publicKey.length === PUBLIC_KEY_BYTES$1, `Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey.length} bytes`);\n assert(signature.length === SIGNATURE_BYTES, `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);\n const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;\n const signatureOffset = publicKeyOffset + publicKey.length;\n const messageDataOffset = signatureOffset + signature.length;\n const numSignatures = 1;\n const instructionData = Buffer.alloc(messageDataOffset + message.length);\n const index = instructionIndex == null ? 0xffff // An index of `u16::MAX` makes it default to the current instruction.\n : instructionIndex;\n ED25519_INSTRUCTION_LAYOUT.encode({\n numSignatures,\n padding: 0,\n signatureOffset,\n signatureInstructionIndex: index,\n publicKeyOffset,\n publicKeyInstructionIndex: index,\n messageDataOffset,\n messageDataSize: message.length,\n messageInstructionIndex: index\n }, instructionData);\n instructionData.fill(publicKey, publicKeyOffset);\n instructionData.fill(signature, signatureOffset);\n instructionData.fill(message, messageDataOffset);\n return new TransactionInstruction({\n keys: [],\n programId: Ed25519Program.programId,\n data: instructionData\n });\n }\n\n /**\n * Create an ed25519 instruction with a private key. The private key\n * must be a buffer that is 64 bytes long.\n */\n static createInstructionWithPrivateKey(params) {\n const {\n privateKey,\n message,\n instructionIndex\n } = params;\n assert(privateKey.length === PRIVATE_KEY_BYTES$1, `Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);\n try {\n const keypair = Keypair.fromSecretKey(privateKey);\n const publicKey = keypair.publicKey.toBytes();\n const signature = sign(message, keypair.secretKey);\n return this.createInstructionWithPublicKey({\n publicKey,\n message,\n signature,\n instructionIndex\n });\n } catch (error) {\n throw new Error(`Error creating instruction; ${error}`);\n }\n }\n}\nEd25519Program.programId = new PublicKey('Ed25519SigVerify111111111111111111111111111');\n\nconst ecdsaSign = (msgHash, privKey) => {\n const signature = secp256k1.sign(msgHash, privKey);\n return [signature.toCompactRawBytes(), signature.recovery];\n};\nsecp256k1.utils.isValidPrivateKey;\nconst publicKeyCreate = secp256k1.getPublicKey;\n\nconst PRIVATE_KEY_BYTES = 32;\nconst ETHEREUM_ADDRESS_BYTES = 20;\nconst PUBLIC_KEY_BYTES = 64;\nconst SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;\n\n/**\n * Params for creating an secp256k1 instruction using a public key\n */\n\n/**\n * Params for creating an secp256k1 instruction using an Ethereum address\n */\n\n/**\n * Params for creating an secp256k1 instruction using a private key\n */\n\nconst SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct([BufferLayout.u8('numSignatures'), BufferLayout.u16('signatureOffset'), BufferLayout.u8('signatureInstructionIndex'), BufferLayout.u16('ethAddressOffset'), BufferLayout.u8('ethAddressInstructionIndex'), BufferLayout.u16('messageDataOffset'), BufferLayout.u16('messageDataSize'), BufferLayout.u8('messageInstructionIndex'), BufferLayout.blob(20, 'ethAddress'), BufferLayout.blob(64, 'signature'), BufferLayout.u8('recoveryId')]);\nclass Secp256k1Program {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the secp256k1 program\n */\n\n /**\n * Construct an Ethereum address from a secp256k1 public key buffer.\n * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer\n */\n static publicKeyToEthAddress(publicKey) {\n assert(publicKey.length === PUBLIC_KEY_BYTES, `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`);\n try {\n return Buffer.from(keccak_256(toBuffer(publicKey))).slice(-ETHEREUM_ADDRESS_BYTES);\n } catch (error) {\n throw new Error(`Error constructing Ethereum address: ${error}`);\n }\n }\n\n /**\n * Create an secp256k1 instruction with a public key. The public key\n * must be a buffer that is 64 bytes long.\n */\n static createInstructionWithPublicKey(params) {\n const {\n publicKey,\n message,\n signature,\n recoveryId,\n instructionIndex\n } = params;\n return Secp256k1Program.createInstructionWithEthAddress({\n ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey),\n message,\n signature,\n recoveryId,\n instructionIndex\n });\n }\n\n /**\n * Create an secp256k1 instruction with an Ethereum address. The address\n * must be a hex string or a buffer that is 20 bytes long.\n */\n static createInstructionWithEthAddress(params) {\n const {\n ethAddress: rawAddress,\n message,\n signature,\n recoveryId,\n instructionIndex = 0\n } = params;\n let ethAddress;\n if (typeof rawAddress === 'string') {\n if (rawAddress.startsWith('0x')) {\n ethAddress = Buffer.from(rawAddress.substr(2), 'hex');\n } else {\n ethAddress = Buffer.from(rawAddress, 'hex');\n }\n } else {\n ethAddress = rawAddress;\n }\n assert(ethAddress.length === ETHEREUM_ADDRESS_BYTES, `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`);\n const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;\n const ethAddressOffset = dataStart;\n const signatureOffset = dataStart + ethAddress.length;\n const messageDataOffset = signatureOffset + signature.length + 1;\n const numSignatures = 1;\n const instructionData = Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length);\n SECP256K1_INSTRUCTION_LAYOUT.encode({\n numSignatures,\n signatureOffset,\n signatureInstructionIndex: instructionIndex,\n ethAddressOffset,\n ethAddressInstructionIndex: instructionIndex,\n messageDataOffset,\n messageDataSize: message.length,\n messageInstructionIndex: instructionIndex,\n signature: toBuffer(signature),\n ethAddress: toBuffer(ethAddress),\n recoveryId\n }, instructionData);\n instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);\n return new TransactionInstruction({\n keys: [],\n programId: Secp256k1Program.programId,\n data: instructionData\n });\n }\n\n /**\n * Create an secp256k1 instruction with a private key. The private key\n * must be a buffer that is 32 bytes long.\n */\n static createInstructionWithPrivateKey(params) {\n const {\n privateKey: pkey,\n message,\n instructionIndex\n } = params;\n assert(pkey.length === PRIVATE_KEY_BYTES, `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`);\n try {\n const privateKey = toBuffer(pkey);\n const publicKey = publicKeyCreate(privateKey, false /* isCompressed */).slice(1); // throw away leading byte\n const messageHash = Buffer.from(keccak_256(toBuffer(message)));\n const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);\n return this.createInstructionWithPublicKey({\n publicKey,\n message,\n signature,\n recoveryId,\n instructionIndex\n });\n } catch (error) {\n throw new Error(`Error creating instruction; ${error}`);\n }\n }\n}\nSecp256k1Program.programId = new PublicKey('KeccakSecp256k11111111111111111111111111111');\n\nvar _Lockup;\n\n/**\n * Address of the stake config account which configures the rate\n * of stake warmup and cooldown as well as the slashing penalty.\n */\nconst STAKE_CONFIG_ID = new PublicKey('StakeConfig11111111111111111111111111111111');\n\n/**\n * Stake account authority info\n */\nclass Authorized {\n /**\n * Create a new Authorized object\n * @param staker the stake authority\n * @param withdrawer the withdraw authority\n */\n constructor(staker, withdrawer) {\n /** stake authority */\n this.staker = void 0;\n /** withdraw authority */\n this.withdrawer = void 0;\n this.staker = staker;\n this.withdrawer = withdrawer;\n }\n}\n/**\n * Stake account lockup info\n */\nclass Lockup {\n /**\n * Create a new Lockup object\n */\n constructor(unixTimestamp, epoch, custodian) {\n /** Unix timestamp of lockup expiration */\n this.unixTimestamp = void 0;\n /** Epoch of lockup expiration */\n this.epoch = void 0;\n /** Lockup custodian authority */\n this.custodian = void 0;\n this.unixTimestamp = unixTimestamp;\n this.epoch = epoch;\n this.custodian = custodian;\n }\n\n /**\n * Default, inactive Lockup value\n */\n}\n_Lockup = Lockup;\nLockup.default = new _Lockup(0, 0, PublicKey.default);\n/**\n * Create stake account transaction params\n */\n/**\n * Create stake account with seed transaction params\n */\n/**\n * Initialize stake instruction params\n */\n/**\n * Delegate stake instruction params\n */\n/**\n * Authorize stake instruction params\n */\n/**\n * Authorize stake instruction params using a derived key\n */\n/**\n * Split stake instruction params\n */\n/**\n * Split with seed transaction params\n */\n/**\n * Withdraw stake instruction params\n */\n/**\n * Deactivate stake instruction params\n */\n/**\n * Merge stake instruction params\n */\n/**\n * Stake Instruction class\n */\nclass StakeInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a stake instruction and retrieve the instruction type.\n */\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [ixType, layout] of Object.entries(STAKE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType;\n break;\n }\n }\n if (!type) {\n throw new Error('Instruction type incorrect; not a StakeInstruction');\n }\n return type;\n }\n\n /**\n * Decode a initialize stake instruction and retrieve the instruction params.\n */\n static decodeInitialize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n authorized,\n lockup\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Initialize, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n authorized: new Authorized(new PublicKey(authorized.staker), new PublicKey(authorized.withdrawer)),\n lockup: new Lockup(lockup.unixTimestamp, lockup.epoch, new PublicKey(lockup.custodian))\n };\n }\n\n /**\n * Decode a delegate stake instruction and retrieve the instruction params.\n */\n static decodeDelegate(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 6);\n decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Delegate, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n votePubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[5].pubkey\n };\n }\n\n /**\n * Decode an authorize stake instruction and retrieve the instruction params.\n */\n static decodeAuthorize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n newAuthorized,\n stakeAuthorizationType\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Authorize, instruction.data);\n const o = {\n stakePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n stakeAuthorizationType: {\n index: stakeAuthorizationType\n }\n };\n if (instruction.keys.length > 3) {\n o.custodianPubkey = instruction.keys[3].pubkey;\n }\n return o;\n }\n\n /**\n * Decode an authorize-with-seed stake instruction and retrieve the instruction params.\n */\n static decodeAuthorizeWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n newAuthorized,\n stakeAuthorizationType,\n authoritySeed,\n authorityOwner\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data);\n const o = {\n stakePubkey: instruction.keys[0].pubkey,\n authorityBase: instruction.keys[1].pubkey,\n authoritySeed: authoritySeed,\n authorityOwner: new PublicKey(authorityOwner),\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n stakeAuthorizationType: {\n index: stakeAuthorizationType\n }\n };\n if (instruction.keys.length > 3) {\n o.custodianPubkey = instruction.keys[3].pubkey;\n }\n return o;\n }\n\n /**\n * Decode a split stake instruction and retrieve the instruction params.\n */\n static decodeSplit(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n lamports\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Split, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n splitStakePubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n lamports\n };\n }\n\n /**\n * Decode a merge stake instruction and retrieve the instruction params.\n */\n static decodeMerge(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Merge, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n sourceStakePubKey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey\n };\n }\n\n /**\n * Decode a withdraw stake instruction and retrieve the instruction params.\n */\n static decodeWithdraw(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 5);\n const {\n lamports\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data);\n const o = {\n stakePubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n lamports\n };\n if (instruction.keys.length > 5) {\n o.custodianPubkey = instruction.keys[5].pubkey;\n }\n return o;\n }\n\n /**\n * Decode a deactivate stake instruction and retrieve the instruction params.\n */\n static decodeDeactivate(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Deactivate, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(StakeProgram.programId)) {\n throw new Error('invalid instruction; programId is not StakeProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys, expectedLength) {\n if (keys.length < expectedLength) {\n throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`);\n }\n }\n}\n\n/**\n * An enumeration of valid StakeInstructionType's\n */\n\n/**\n * An enumeration of valid stake InstructionType's\n * @internal\n */\nconst STAKE_INSTRUCTION_LAYOUTS = Object.freeze({\n Initialize: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), authorized(), lockup()])\n },\n Authorize: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('newAuthorized'), BufferLayout.u32('stakeAuthorizationType')])\n },\n Delegate: {\n index: 2,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n Split: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')])\n },\n Withdraw: {\n index: 4,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')])\n },\n Deactivate: {\n index: 5,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n Merge: {\n index: 7,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n AuthorizeWithSeed: {\n index: 8,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('newAuthorized'), BufferLayout.u32('stakeAuthorizationType'), rustString('authoritySeed'), publicKey('authorityOwner')])\n }\n});\n\n/**\n * Stake authorization type\n */\n\n/**\n * An enumeration of valid StakeAuthorizationLayout's\n */\nconst StakeAuthorizationLayout = Object.freeze({\n Staker: {\n index: 0\n },\n Withdrawer: {\n index: 1\n }\n});\n\n/**\n * Factory class for transactions to interact with the Stake program\n */\nclass StakeProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Stake program\n */\n\n /**\n * Generate an Initialize instruction to add to a Stake Create transaction\n */\n static initialize(params) {\n const {\n stakePubkey,\n authorized,\n lockup: maybeLockup\n } = params;\n const lockup = maybeLockup || Lockup.default;\n const type = STAKE_INSTRUCTION_LAYOUTS.Initialize;\n const data = encodeData(type, {\n authorized: {\n staker: toBuffer(authorized.staker.toBuffer()),\n withdrawer: toBuffer(authorized.withdrawer.toBuffer())\n },\n lockup: {\n unixTimestamp: lockup.unixTimestamp,\n epoch: lockup.epoch,\n custodian: toBuffer(lockup.custodian.toBuffer())\n }\n });\n const instructionData = {\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }],\n programId: this.programId,\n data\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a Transaction that creates a new Stake account at\n * an address generated with `from`, a seed, and the Stake programId\n */\n static createAccountWithSeed(params) {\n const transaction = new Transaction();\n transaction.add(SystemProgram.createAccountWithSeed({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.stakePubkey,\n basePubkey: params.basePubkey,\n seed: params.seed,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId\n }));\n const {\n stakePubkey,\n authorized,\n lockup\n } = params;\n return transaction.add(this.initialize({\n stakePubkey,\n authorized,\n lockup\n }));\n }\n\n /**\n * Generate a Transaction that creates a new Stake account\n */\n static createAccount(params) {\n const transaction = new Transaction();\n transaction.add(SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.stakePubkey,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId\n }));\n const {\n stakePubkey,\n authorized,\n lockup\n } = params;\n return transaction.add(this.initialize({\n stakePubkey,\n authorized,\n lockup\n }));\n }\n\n /**\n * Generate a Transaction that delegates Stake tokens to a validator\n * Vote PublicKey. This transaction can also be used to redelegate Stake\n * to a new validator Vote PublicKey.\n */\n static delegate(params) {\n const {\n stakePubkey,\n authorizedPubkey,\n votePubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Delegate;\n const data = encodeData(type);\n return new Transaction().add({\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: votePubkey,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: STAKE_CONFIG_ID,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that authorizes a new PublicKey as Staker\n * or Withdrawer on the Stake account.\n */\n static authorize(params) {\n const {\n stakePubkey,\n authorizedPubkey,\n newAuthorizedPubkey,\n stakeAuthorizationType,\n custodianPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Authorize;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n stakeAuthorizationType: stakeAuthorizationType.index\n });\n const keys = [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: true,\n isWritable: false\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that authorizes a new PublicKey as Staker\n * or Withdrawer on the Stake account.\n */\n static authorizeWithSeed(params) {\n const {\n stakePubkey,\n authorityBase,\n authoritySeed,\n authorityOwner,\n newAuthorizedPubkey,\n stakeAuthorizationType,\n custodianPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n stakeAuthorizationType: stakeAuthorizationType.index,\n authoritySeed: authoritySeed,\n authorityOwner: toBuffer(authorityOwner.toBuffer())\n });\n const keys = [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: authorityBase,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: true,\n isWritable: false\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * @internal\n */\n static splitInstruction(params) {\n const {\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n lamports\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Split;\n const data = encodeData(type, {\n lamports\n });\n return new TransactionInstruction({\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: splitStakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that splits Stake tokens into another stake account\n */\n static split(params,\n // Compute the cost of allocating the new stake account in lamports\n rentExemptReserve) {\n const transaction = new Transaction();\n transaction.add(SystemProgram.createAccount({\n fromPubkey: params.authorizedPubkey,\n newAccountPubkey: params.splitStakePubkey,\n lamports: rentExemptReserve,\n space: this.space,\n programId: this.programId\n }));\n return transaction.add(this.splitInstruction(params));\n }\n\n /**\n * Generate a Transaction that splits Stake tokens into another account\n * derived from a base public key and seed\n */\n static splitWithSeed(params,\n // If this stake account is new, compute the cost of allocating it in lamports\n rentExemptReserve) {\n const {\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n basePubkey,\n seed,\n lamports\n } = params;\n const transaction = new Transaction();\n transaction.add(SystemProgram.allocate({\n accountPubkey: splitStakePubkey,\n basePubkey,\n seed,\n space: this.space,\n programId: this.programId\n }));\n if (rentExemptReserve && rentExemptReserve > 0) {\n transaction.add(SystemProgram.transfer({\n fromPubkey: params.authorizedPubkey,\n toPubkey: splitStakePubkey,\n lamports: rentExemptReserve\n }));\n }\n return transaction.add(this.splitInstruction({\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n lamports\n }));\n }\n\n /**\n * Generate a Transaction that merges Stake accounts.\n */\n static merge(params) {\n const {\n stakePubkey,\n sourceStakePubKey,\n authorizedPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Merge;\n const data = encodeData(type);\n return new Transaction().add({\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: sourceStakePubKey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that withdraws deactivated Stake tokens.\n */\n static withdraw(params) {\n const {\n stakePubkey,\n authorizedPubkey,\n toPubkey,\n lamports,\n custodianPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Withdraw;\n const data = encodeData(type, {\n lamports\n });\n const keys = [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: toPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: true,\n isWritable: false\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that deactivates Stake tokens.\n */\n static deactivate(params) {\n const {\n stakePubkey,\n authorizedPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Deactivate;\n const data = encodeData(type);\n return new Transaction().add({\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n}\nStakeProgram.programId = new PublicKey('Stake11111111111111111111111111111111111111');\n/**\n * Max space of a Stake account\n *\n * This is generated from the solana-stake-program StakeState struct as\n * `StakeStateV2::size_of()`:\n * https://docs.rs/solana-stake-program/latest/solana_stake_program/stake_state/enum.StakeStateV2.html\n */\nStakeProgram.space = 200;\n\n/**\n * Vote account info\n */\nclass VoteInit {\n /** [0, 100] */\n\n constructor(nodePubkey, authorizedVoter, authorizedWithdrawer, commission) {\n this.nodePubkey = void 0;\n this.authorizedVoter = void 0;\n this.authorizedWithdrawer = void 0;\n this.commission = void 0;\n this.nodePubkey = nodePubkey;\n this.authorizedVoter = authorizedVoter;\n this.authorizedWithdrawer = authorizedWithdrawer;\n this.commission = commission;\n }\n}\n\n/**\n * Create vote account transaction params\n */\n\n/**\n * InitializeAccount instruction params\n */\n\n/**\n * Authorize instruction params\n */\n\n/**\n * AuthorizeWithSeed instruction params\n */\n\n/**\n * Withdraw from vote account transaction params\n */\n\n/**\n * Update validator identity (node pubkey) vote account instruction params.\n */\n\n/**\n * Vote Instruction class\n */\nclass VoteInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a vote instruction and retrieve the instruction type.\n */\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [ixType, layout] of Object.entries(VOTE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType;\n break;\n }\n }\n if (!type) {\n throw new Error('Instruction type incorrect; not a VoteInstruction');\n }\n return type;\n }\n\n /**\n * Decode an initialize vote instruction and retrieve the instruction params.\n */\n static decodeInitializeAccount(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 4);\n const {\n voteInit\n } = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount, instruction.data);\n return {\n votePubkey: instruction.keys[0].pubkey,\n nodePubkey: instruction.keys[3].pubkey,\n voteInit: new VoteInit(new PublicKey(voteInit.nodePubkey), new PublicKey(voteInit.authorizedVoter), new PublicKey(voteInit.authorizedWithdrawer), voteInit.commission)\n };\n }\n\n /**\n * Decode an authorize instruction and retrieve the instruction params.\n */\n static decodeAuthorize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n newAuthorized,\n voteAuthorizationType\n } = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Authorize, instruction.data);\n return {\n votePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n voteAuthorizationType: {\n index: voteAuthorizationType\n }\n };\n }\n\n /**\n * Decode an authorize instruction and retrieve the instruction params.\n */\n static decodeAuthorizeWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n voteAuthorizeWithSeedArgs: {\n currentAuthorityDerivedKeyOwnerPubkey,\n currentAuthorityDerivedKeySeed,\n newAuthorized,\n voteAuthorizationType\n }\n } = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data);\n return {\n currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey,\n currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(currentAuthorityDerivedKeyOwnerPubkey),\n currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n voteAuthorizationType: {\n index: voteAuthorizationType\n },\n votePubkey: instruction.keys[0].pubkey\n };\n }\n\n /**\n * Decode a withdraw instruction and retrieve the instruction params.\n */\n static decodeWithdraw(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n lamports\n } = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data);\n return {\n votePubkey: instruction.keys[0].pubkey,\n authorizedWithdrawerPubkey: instruction.keys[2].pubkey,\n lamports,\n toPubkey: instruction.keys[1].pubkey\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(VoteProgram.programId)) {\n throw new Error('invalid instruction; programId is not VoteProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys, expectedLength) {\n if (keys.length < expectedLength) {\n throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`);\n }\n }\n}\n\n/**\n * An enumeration of valid VoteInstructionType's\n */\n\n/** @internal */\n\nconst VOTE_INSTRUCTION_LAYOUTS = Object.freeze({\n InitializeAccount: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), voteInit()])\n },\n Authorize: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('newAuthorized'), BufferLayout.u32('voteAuthorizationType')])\n },\n Withdraw: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')])\n },\n UpdateValidatorIdentity: {\n index: 4,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n AuthorizeWithSeed: {\n index: 10,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), voteAuthorizeWithSeedArgs()])\n }\n});\n\n/**\n * VoteAuthorize type\n */\n\n/**\n * An enumeration of valid VoteAuthorization layouts.\n */\nconst VoteAuthorizationLayout = Object.freeze({\n Voter: {\n index: 0\n },\n Withdrawer: {\n index: 1\n }\n});\n\n/**\n * Factory class for transactions to interact with the Vote program\n */\nclass VoteProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Vote program\n */\n\n /**\n * Generate an Initialize instruction.\n */\n static initializeAccount(params) {\n const {\n votePubkey,\n nodePubkey,\n voteInit\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;\n const data = encodeData(type, {\n voteInit: {\n nodePubkey: toBuffer(voteInit.nodePubkey.toBuffer()),\n authorizedVoter: toBuffer(voteInit.authorizedVoter.toBuffer()),\n authorizedWithdrawer: toBuffer(voteInit.authorizedWithdrawer.toBuffer()),\n commission: voteInit.commission\n }\n });\n const instructionData = {\n keys: [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: nodePubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a transaction that creates a new Vote account.\n */\n static createAccount(params) {\n const transaction = new Transaction();\n transaction.add(SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.votePubkey,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId\n }));\n return transaction.add(this.initializeAccount({\n votePubkey: params.votePubkey,\n nodePubkey: params.voteInit.nodePubkey,\n voteInit: params.voteInit\n }));\n }\n\n /**\n * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.\n */\n static authorize(params) {\n const {\n votePubkey,\n authorizedPubkey,\n newAuthorizedPubkey,\n voteAuthorizationType\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.Authorize;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n voteAuthorizationType: voteAuthorizationType.index\n });\n const keys = [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }];\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account\n * where the current Voter or Withdrawer authority is a derived key.\n */\n static authorizeWithSeed(params) {\n const {\n currentAuthorityDerivedKeyBasePubkey,\n currentAuthorityDerivedKeyOwnerPubkey,\n currentAuthorityDerivedKeySeed,\n newAuthorizedPubkey,\n voteAuthorizationType,\n votePubkey\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n const data = encodeData(type, {\n voteAuthorizeWithSeedArgs: {\n currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()),\n currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n voteAuthorizationType: voteAuthorizationType.index\n }\n });\n const keys = [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: currentAuthorityDerivedKeyBasePubkey,\n isSigner: true,\n isWritable: false\n }];\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction to withdraw from a Vote account.\n */\n static withdraw(params) {\n const {\n votePubkey,\n authorizedWithdrawerPubkey,\n lamports,\n toPubkey\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.Withdraw;\n const data = encodeData(type, {\n lamports\n });\n const keys = [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: toPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: authorizedWithdrawerPubkey,\n isSigner: true,\n isWritable: false\n }];\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction to withdraw safely from a Vote account.\n *\n * This function was created as a safeguard for vote accounts running validators, `safeWithdraw`\n * checks that the withdraw amount will not exceed the specified balance while leaving enough left\n * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the\n * `withdraw` method directly.\n */\n static safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) {\n if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {\n throw new Error('Withdraw will leave vote account with insufficient funds.');\n }\n return VoteProgram.withdraw(params);\n }\n\n /**\n * Generate a transaction to update the validator identity (node pubkey) of a Vote account.\n */\n static updateValidatorIdentity(params) {\n const {\n votePubkey,\n authorizedWithdrawerPubkey,\n nodePubkey\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.UpdateValidatorIdentity;\n const data = encodeData(type);\n const keys = [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: nodePubkey,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: authorizedWithdrawerPubkey,\n isSigner: true,\n isWritable: false\n }];\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n}\nVoteProgram.programId = new PublicKey('Vote111111111111111111111111111111111111111');\n/**\n * Max space of a Vote account\n *\n * This is generated from the solana-vote-program VoteState struct as\n * `VoteState::size_of()`:\n * https://docs.rs/solana-vote-program/1.9.5/solana_vote_program/vote_state/struct.VoteState.html#method.size_of\n *\n * KEEP IN SYNC WITH `VoteState::size_of()` in https://github.com/solana-labs/solana/blob/a474cb24b9238f5edcc982f65c0b37d4a1046f7e/sdk/program/src/vote/state/mod.rs#L340-L342\n */\nVoteProgram.space = 3762;\n\nconst VALIDATOR_INFO_KEY = new PublicKey('Va1idator1nfo111111111111111111111111111111');\n\n/**\n * @internal\n */\n\n/**\n * Info used to identity validators.\n */\n\nconst InfoString = type({\n name: string(),\n website: optional(string()),\n details: optional(string()),\n iconUrl: optional(string()),\n keybaseUsername: optional(string())\n});\n\n/**\n * ValidatorInfo class\n */\nclass ValidatorInfo {\n /**\n * Construct a valid ValidatorInfo\n *\n * @param key validator public key\n * @param info validator information\n */\n constructor(key, info) {\n /**\n * validator public key\n */\n this.key = void 0;\n /**\n * validator information\n */\n this.info = void 0;\n this.key = key;\n this.info = info;\n }\n\n /**\n * Deserialize ValidatorInfo from the config account data. Exactly two config\n * keys are required in the data.\n *\n * @param buffer config account data\n * @return null if info was not found\n */\n static fromConfigData(buffer) {\n let byteArray = [...buffer];\n const configKeyCount = decodeLength(byteArray);\n if (configKeyCount !== 2) return null;\n const configKeys = [];\n for (let i = 0; i < 2; i++) {\n const publicKey = new PublicKey(guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH));\n const isSigner = guardedShift(byteArray) === 1;\n configKeys.push({\n publicKey,\n isSigner\n });\n }\n if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) {\n if (configKeys[1].isSigner) {\n const rawInfo = rustString().decode(Buffer.from(byteArray));\n const info = JSON.parse(rawInfo);\n assert$1(info, InfoString);\n return new ValidatorInfo(configKeys[1].publicKey, info);\n }\n }\n return null;\n }\n}\n\nconst VOTE_PROGRAM_ID = new PublicKey('Vote111111111111111111111111111111111111111');\n\n/**\n * History of how many credits earned by the end of each epoch\n */\n\n/**\n * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88\n *\n * @internal\n */\nconst VoteAccountLayout = BufferLayout.struct([publicKey('nodePubkey'), publicKey('authorizedWithdrawer'), BufferLayout.u8('commission'), BufferLayout.nu64(),\n// votes.length\nBufferLayout.seq(BufferLayout.struct([BufferLayout.nu64('slot'), BufferLayout.u32('confirmationCount')]), BufferLayout.offset(BufferLayout.u32(), -8), 'votes'), BufferLayout.u8('rootSlotValid'), BufferLayout.nu64('rootSlot'), BufferLayout.nu64(),\n// authorizedVoters.length\nBufferLayout.seq(BufferLayout.struct([BufferLayout.nu64('epoch'), publicKey('authorizedVoter')]), BufferLayout.offset(BufferLayout.u32(), -8), 'authorizedVoters'), BufferLayout.struct([BufferLayout.seq(BufferLayout.struct([publicKey('authorizedPubkey'), BufferLayout.nu64('epochOfLastAuthorizedSwitch'), BufferLayout.nu64('targetEpoch')]), 32, 'buf'), BufferLayout.nu64('idx'), BufferLayout.u8('isEmpty')], 'priorVoters'), BufferLayout.nu64(),\n// epochCredits.length\nBufferLayout.seq(BufferLayout.struct([BufferLayout.nu64('epoch'), BufferLayout.nu64('credits'), BufferLayout.nu64('prevCredits')]), BufferLayout.offset(BufferLayout.u32(), -8), 'epochCredits'), BufferLayout.struct([BufferLayout.nu64('slot'), BufferLayout.nu64('timestamp')], 'lastTimestamp')]);\n/**\n * VoteAccount class\n */\nclass VoteAccount {\n /**\n * @internal\n */\n constructor(args) {\n this.nodePubkey = void 0;\n this.authorizedWithdrawer = void 0;\n this.commission = void 0;\n this.rootSlot = void 0;\n this.votes = void 0;\n this.authorizedVoters = void 0;\n this.priorVoters = void 0;\n this.epochCredits = void 0;\n this.lastTimestamp = void 0;\n this.nodePubkey = args.nodePubkey;\n this.authorizedWithdrawer = args.authorizedWithdrawer;\n this.commission = args.commission;\n this.rootSlot = args.rootSlot;\n this.votes = args.votes;\n this.authorizedVoters = args.authorizedVoters;\n this.priorVoters = args.priorVoters;\n this.epochCredits = args.epochCredits;\n this.lastTimestamp = args.lastTimestamp;\n }\n\n /**\n * Deserialize VoteAccount from the account data.\n *\n * @param buffer account data\n * @return VoteAccount\n */\n static fromAccountData(buffer) {\n const versionOffset = 4;\n const va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset);\n let rootSlot = va.rootSlot;\n if (!va.rootSlotValid) {\n rootSlot = null;\n }\n return new VoteAccount({\n nodePubkey: new PublicKey(va.nodePubkey),\n authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer),\n commission: va.commission,\n votes: va.votes,\n rootSlot,\n authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter),\n priorVoters: getPriorVoters(va.priorVoters),\n epochCredits: va.epochCredits,\n lastTimestamp: va.lastTimestamp\n });\n }\n}\nfunction parseAuthorizedVoter({\n authorizedVoter,\n epoch\n}) {\n return {\n epoch,\n authorizedVoter: new PublicKey(authorizedVoter)\n };\n}\nfunction parsePriorVoters({\n authorizedPubkey,\n epochOfLastAuthorizedSwitch,\n targetEpoch\n}) {\n return {\n authorizedPubkey: new PublicKey(authorizedPubkey),\n epochOfLastAuthorizedSwitch,\n targetEpoch\n };\n}\nfunction getPriorVoters({\n buf,\n idx,\n isEmpty\n}) {\n if (isEmpty) {\n return [];\n }\n return [...buf.slice(idx + 1).map(parsePriorVoters), ...buf.slice(0, idx).map(parsePriorVoters)];\n}\n\nconst endpoint = {\n http: {\n devnet: 'http://api.devnet.solana.com',\n testnet: 'http://api.testnet.solana.com',\n 'mainnet-beta': 'http://api.mainnet-beta.solana.com/'\n },\n https: {\n devnet: 'https://api.devnet.solana.com',\n testnet: 'https://api.testnet.solana.com',\n 'mainnet-beta': 'https://api.mainnet-beta.solana.com/'\n }\n};\n/**\n * Retrieves the RPC API URL for the specified cluster\n * @param {Cluster} [cluster=\"devnet\"] - The cluster name of the RPC API URL to use. Possible options: 'devnet' | 'testnet' | 'mainnet-beta'\n * @param {boolean} [tls=\"http\"] - Use TLS when connecting to cluster.\n *\n * @returns {string} URL string of the RPC endpoint\n */\nfunction clusterApiUrl(cluster, tls) {\n const key = tls === false ? 'http' : 'https';\n if (!cluster) {\n return endpoint[key]['devnet'];\n }\n const url = endpoint[key][cluster];\n if (!url) {\n throw new Error(`Unknown ${key} cluster: ${cluster}`);\n }\n return url;\n}\n\n/**\n * Send and confirm a raw transaction\n *\n * If `commitment` option is not specified, defaults to 'max' commitment.\n *\n * @param {Connection} connection\n * @param {Buffer} rawTransaction\n * @param {TransactionConfirmationStrategy} confirmationStrategy\n * @param {ConfirmOptions} [options]\n * @returns {Promise}\n */\n\n/**\n * @deprecated Calling `sendAndConfirmRawTransaction()` without a `confirmationStrategy`\n * is no longer supported and will be removed in a future version.\n */\n// eslint-disable-next-line no-redeclare\n\n// eslint-disable-next-line no-redeclare\nasync function sendAndConfirmRawTransaction(connection, rawTransaction, confirmationStrategyOrConfirmOptions, maybeConfirmOptions) {\n let confirmationStrategy;\n let options;\n if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'lastValidBlockHeight')) {\n confirmationStrategy = confirmationStrategyOrConfirmOptions;\n options = maybeConfirmOptions;\n } else if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'nonceValue')) {\n confirmationStrategy = confirmationStrategyOrConfirmOptions;\n options = maybeConfirmOptions;\n } else {\n options = confirmationStrategyOrConfirmOptions;\n }\n const sendOptions = options && {\n skipPreflight: options.skipPreflight,\n preflightCommitment: options.preflightCommitment || options.commitment,\n minContextSlot: options.minContextSlot\n };\n const signature = await connection.sendRawTransaction(rawTransaction, sendOptions);\n const commitment = options && options.commitment;\n const confirmationPromise = confirmationStrategy ? connection.confirmTransaction(confirmationStrategy, commitment) : connection.confirmTransaction(signature, commitment);\n const status = (await confirmationPromise).value;\n if (status.err) {\n if (signature != null) {\n throw new SendTransactionError({\n action: sendOptions?.skipPreflight ? 'send' : 'simulate',\n signature: signature,\n transactionMessage: `Status: (${JSON.stringify(status)})`\n });\n }\n throw new Error(`Raw transaction ${signature} failed (${JSON.stringify(status)})`);\n }\n return signature;\n}\n\n/**\n * There are 1-billion lamports in one SOL\n */\nconst LAMPORTS_PER_SOL = 1000000000;\n\nexport { Account, AddressLookupTableAccount, AddressLookupTableInstruction, AddressLookupTableProgram, Authorized, BLOCKHASH_CACHE_TIMEOUT_MS, BPF_LOADER_DEPRECATED_PROGRAM_ID, BPF_LOADER_PROGRAM_ID, BpfLoader, COMPUTE_BUDGET_INSTRUCTION_LAYOUTS, ComputeBudgetInstruction, ComputeBudgetProgram, Connection, Ed25519Program, Enum, EpochSchedule, FeeCalculatorLayout, Keypair, LAMPORTS_PER_SOL, LOOKUP_TABLE_INSTRUCTION_LAYOUTS, Loader, Lockup, MAX_SEED_LENGTH, Message, MessageAccountKeys, MessageV0, NONCE_ACCOUNT_LENGTH, NonceAccount, PACKET_DATA_SIZE, PUBLIC_KEY_LENGTH, PublicKey, SIGNATURE_LENGTH_IN_BYTES, SOLANA_SCHEMA, STAKE_CONFIG_ID, STAKE_INSTRUCTION_LAYOUTS, SYSTEM_INSTRUCTION_LAYOUTS, SYSVAR_CLOCK_PUBKEY, SYSVAR_EPOCH_SCHEDULE_PUBKEY, SYSVAR_INSTRUCTIONS_PUBKEY, SYSVAR_RECENT_BLOCKHASHES_PUBKEY, SYSVAR_RENT_PUBKEY, SYSVAR_REWARDS_PUBKEY, SYSVAR_SLOT_HASHES_PUBKEY, SYSVAR_SLOT_HISTORY_PUBKEY, SYSVAR_STAKE_HISTORY_PUBKEY, Secp256k1Program, SendTransactionError, SolanaJSONRPCError, SolanaJSONRPCErrorCode, StakeAuthorizationLayout, StakeInstruction, StakeProgram, Struct, SystemInstruction, SystemProgram, Transaction, TransactionExpiredBlockheightExceededError, TransactionExpiredNonceInvalidError, TransactionExpiredTimeoutError, TransactionInstruction, TransactionMessage, TransactionStatus, VALIDATOR_INFO_KEY, VERSION_PREFIX_MASK, VOTE_PROGRAM_ID, ValidatorInfo, VersionedMessage, VersionedTransaction, VoteAccount, VoteAuthorizationLayout, VoteInit, VoteInstruction, VoteProgram, clusterApiUrl, sendAndConfirmRawTransaction, sendAndConfirmTransaction };\n//# sourceMappingURL=index.browser.esm.js.map\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/**\n * The base error class of hpke-js.\n * @group Errors\n */\nexport class HpkeError extends Error {\n constructor(e) {\n let message;\n if (e instanceof Error) {\n message = e.message;\n }\n else if (typeof e === \"string\") {\n message = e;\n }\n else {\n message = \"\";\n }\n super(message);\n this.name = this.constructor.name;\n }\n}\n/**\n * Invalid parameter.\n * @group Errors\n */\nexport class InvalidParamError extends HpkeError {\n}\n/**\n * KEM input or output validation failure.\n * @group Errors\n */\nexport class ValidationError extends HpkeError {\n}\n/**\n * Public or private key serialization failure.\n * @group Errors\n */\nexport class SerializeError extends HpkeError {\n}\n/**\n * Public or private key deserialization failure.\n * @group Errors\n */\nexport class DeserializeError extends HpkeError {\n}\n/**\n * encap() failure.\n * @group Errors\n */\nexport class EncapError extends HpkeError {\n}\n/**\n * decap() failure.\n * @group Errors\n */\nexport class DecapError extends HpkeError {\n}\n/**\n * Secret export failure.\n * @group Errors\n */\nexport class ExportError extends HpkeError {\n}\n/**\n * seal() failure.\n * @group Errors\n */\nexport class SealError extends HpkeError {\n}\n/**\n * open() failure.\n * @group Errors\n */\nexport class OpenError extends HpkeError {\n}\n/**\n * Sequence number overflow on the encryption context.\n * @group Errors\n */\nexport class MessageLimitReachedError extends HpkeError {\n}\n/**\n * Key pair derivation failure.\n * @group Errors\n */\nexport class DeriveKeyPairError extends HpkeError {\n}\n/**\n * Not supported failure.\n * @group Errors\n */\nexport class NotSupportedError extends HpkeError {\n}\n","const dntGlobals = {};\nexport const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\nfunction createMergeProxy(baseObj, extObj) {\n return new Proxy(baseObj, {\n get(_target, prop, _receiver) {\n if (prop in extObj) {\n return extObj[prop];\n }\n else {\n return baseObj[prop];\n }\n },\n set(_target, prop, value) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n baseObj[prop] = value;\n return true;\n },\n deleteProperty(_target, prop) {\n let success = false;\n if (prop in extObj) {\n delete extObj[prop];\n success = true;\n }\n if (prop in baseObj) {\n delete baseObj[prop];\n success = true;\n }\n return success;\n },\n ownKeys(_target) {\n const baseKeys = Reflect.ownKeys(baseObj);\n const extKeys = Reflect.ownKeys(extObj);\n const extKeysSet = new Set(extKeys);\n return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n },\n defineProperty(_target, prop, desc) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n Reflect.defineProperty(baseObj, prop, desc);\n return true;\n },\n getOwnPropertyDescriptor(_target, prop) {\n if (prop in extObj) {\n return Reflect.getOwnPropertyDescriptor(extObj, prop);\n }\n else {\n return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n }\n },\n has(_target, prop) {\n return prop in extObj || prop in baseObj;\n },\n });\n}\n","import * as dntShim from \"../_dnt.shims.js\";\nimport { NotSupportedError } from \"./errors.js\";\nasync function loadSubtleCrypto() {\n if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) {\n // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc.\n return globalThis.crypto.subtle;\n }\n // Node.js <= v18\n try {\n // @ts-ignore: to ignore \"crypto\"\n const { webcrypto } = await import(\"crypto\"); // node:crypto\n return webcrypto.subtle;\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n}\nexport class NativeAlgorithm {\n constructor() {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: undefined\n });\n }\n async _setup() {\n if (this._api !== undefined) {\n return;\n }\n this._api = await loadSubtleCrypto();\n }\n}\n","/**\n * The supported HPKE modes.\n */\nexport const Mode = {\n Base: 0x00,\n Psk: 0x01,\n Auth: 0x02,\n AuthPsk: 0x03,\n};\n/**\n * The supported Key Encapsulation Mechanism (KEM) identifiers.\n */\nexport const KemId = {\n NotAssigned: 0x0000,\n DhkemP256HkdfSha256: 0x0010,\n DhkemP384HkdfSha384: 0x0011,\n DhkemP521HkdfSha512: 0x0012,\n DhkemSecp256k1HkdfSha256: 0x0013,\n DhkemX25519HkdfSha256: 0x0020,\n DhkemX448HkdfSha512: 0x0021,\n HybridkemX25519Kyber768: 0x0030,\n MlKem512: 0x0040,\n MlKem768: 0x0041,\n MlKem1024: 0x0042,\n XWing: 0x647a,\n};\n/**\n * The supported Key Derivation Function (KDF) identifiers.\n */\nexport const KdfId = {\n HkdfSha256: 0x0001,\n HkdfSha384: 0x0002,\n HkdfSha512: 0x0003,\n};\n/**\n * The supported Authenticated Encryption with Associated Data (AEAD) identifiers.\n */\nexport const AeadId = {\n Aes128Gcm: 0x0001,\n Aes256Gcm: 0x0002,\n Chacha20Poly1305: 0x0003,\n ExportOnly: 0xFFFF,\n};\n","// The input length limit (psk, psk_id, info, exporter_context, ikm).\nexport const INPUT_LENGTH_LIMIT = 8192;\nexport const INFO_LENGTH_LIMIT = 65536;\n// The minimum length of a PSK.\nexport const MINIMUM_PSK_LENGTH = 32;\n// b\"\"\nexport const EMPTY = new Uint8Array(0);\n","// b\"KEM\"\nexport const SUITE_ID_HEADER_KEM = new Uint8Array([\n 75,\n 69,\n 77,\n 0,\n 0,\n]);\n","import * as dntShim from \"../../_dnt.shims.js\";\nimport { KemId } from \"../identifiers.js\";\nexport const isDenoV1 = () => \n// deno-lint-ignore no-explicit-any\ndntShim.dntGlobalThis.process === undefined;\n/**\n * Checks whether the runtime is Deno or not (Node.js).\n * @returns boolean - true if the runtime is Deno, false Node.js.\n */\nexport function isDeno() {\n // deno-lint-ignore no-explicit-any\n if (dntShim.dntGlobalThis.process === undefined) {\n return true;\n }\n // deno-lint-ignore no-explicit-any\n return dntShim.dntGlobalThis.process?.versions?.deno !== undefined;\n}\n/**\n * Checks whetehr the type of input is CryptoKeyPair or not.\n */\nexport const isCryptoKeyPair = (x) => typeof x === \"object\" &&\n x !== null &&\n typeof x.privateKey === \"object\" &&\n typeof x.publicKey === \"object\";\n/**\n * Converts integer to octet string. I2OSP implementation.\n */\nexport function i2Osp(n, w) {\n if (w <= 0) {\n throw new Error(\"i2Osp: too small size\");\n }\n if (n >= 256 ** w) {\n throw new Error(\"i2Osp: too large integer\");\n }\n const ret = new Uint8Array(w);\n for (let i = 0; i < w && n; i++) {\n ret[w - (i + 1)] = n % 256;\n n = n >> 8;\n }\n return ret;\n}\n/**\n * Concatenates two Uint8Arrays.\n * @param a Uint8Array\n * @param b Uint8Array\n * @returns Concatenated Uint8Array\n */\nexport function concat(a, b) {\n const ret = new Uint8Array(a.length + b.length);\n ret.set(a, 0);\n ret.set(b, a.length);\n return ret;\n}\n/**\n * Decodes Base64Url-encoded data.\n * @param v Base64Url-encoded string\n * @returns Uint8Array\n */\nexport function base64UrlToBytes(v) {\n const base64 = v.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const byteString = atob(base64);\n const ret = new Uint8Array(byteString.length);\n for (let i = 0; i < byteString.length; i++) {\n ret[i] = byteString.charCodeAt(i);\n }\n return ret;\n}\n/**\n * Encodes Uint8Array to Base64Url.\n * @param v Uint8Array\n * @returns Base64Url-encoded string\n */\nexport function bytesToBase64Url(v) {\n return btoa(String.fromCharCode(...v))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=*$/g, \"\");\n}\n/**\n * Decodes hex string to Uint8Array.\n * @param v Hex string\n * @returns Uint8Array\n * @throws Error if the input is not a hex string.\n */\nexport function hexToBytes(v) {\n if (v.length === 0) {\n return new Uint8Array([]);\n }\n const res = v.match(/[\\da-f]{2}/gi);\n if (res == null) {\n throw new Error(\"Not hex string.\");\n }\n return new Uint8Array(res.map(function (h) {\n return parseInt(h, 16);\n }));\n}\n/**\n * Encodes Uint8Array to hex string.\n * @param v Uint8Array\n * @returns Hex string\n */\nexport function bytesToHex(v) {\n return [...v].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/**\n * Converts KemId to KeyAlgorithm.\n * @param kem KemId\n * @returns KeyAlgorithm\n */\nexport function kemToKeyGenAlgorithm(kem) {\n switch (kem) {\n case KemId.DhkemP256HkdfSha256:\n return {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n };\n case KemId.DhkemP384HkdfSha384:\n return {\n name: \"ECDH\",\n namedCurve: \"P-384\",\n };\n case KemId.DhkemP521HkdfSha512:\n return {\n name: \"ECDH\",\n namedCurve: \"P-521\",\n };\n default:\n // case KemId.DhkemX25519HkdfSha256\n return {\n name: \"X25519\",\n };\n }\n}\nexport async function loadSubtleCrypto() {\n if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) {\n // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc.\n return globalThis.crypto.subtle;\n }\n // Node.js <= v18\n try {\n // @ts-ignore: to ignore \"crypto\"\n const { webcrypto } = await import(\"crypto\"); // node:crypto\n return webcrypto.subtle;\n }\n catch (_e) {\n throw new Error(\"Failed to load SubtleCrypto\");\n }\n}\nexport async function loadCrypto() {\n if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) {\n // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc.\n return globalThis.crypto;\n }\n // Node.js <= v18\n try {\n // @ts-ignore: to ignore \"crypto\"\n const { webcrypto } = await import(\"crypto\"); // node:crypto\n return webcrypto;\n }\n catch (_e) {\n throw new Error(\"Web Cryptograph API not supported\");\n }\n}\n/**\n * XOR for Uint8Array.\n */\nexport function xor(a, b) {\n if (a.byteLength !== b.byteLength) {\n throw new Error(\"xor: different length inputs\");\n }\n const buf = new Uint8Array(a.byteLength);\n for (let i = 0; i < a.byteLength; i++) {\n buf[i] = a[i] ^ b[i];\n }\n return buf;\n}\n","import { EMPTY, INPUT_LENGTH_LIMIT } from \"../consts.js\";\nimport { DecapError, EncapError, InvalidParamError } from \"../errors.js\";\nimport { SUITE_ID_HEADER_KEM } from \"../interfaces/kemInterface.js\";\nimport { concat, i2Osp, isCryptoKeyPair } from \"../utils/misc.js\";\n// b\"eae_prk\"\nconst LABEL_EAE_PRK = new Uint8Array([101, 97, 101, 95, 112, 114, 107]);\n// b\"shared_secret\"\n// deno-fmt-ignore\nconst LABEL_SHARED_SECRET = new Uint8Array([\n 115, 104, 97, 114, 101, 100, 95, 115, 101, 99,\n 114, 101, 116,\n]);\nfunction concat3(a, b, c) {\n const ret = new Uint8Array(a.length + b.length + c.length);\n ret.set(a, 0);\n ret.set(b, a.length);\n ret.set(c, a.length + b.length);\n return ret;\n}\nexport class Dhkem {\n constructor(id, prim, kdf) {\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"_prim\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.id = id;\n this._prim = prim;\n this._kdf = kdf;\n const suiteId = new Uint8Array(SUITE_ID_HEADER_KEM);\n suiteId.set(i2Osp(this.id, 2), 3);\n this._kdf.init(suiteId);\n }\n async serializePublicKey(key) {\n return await this._prim.serializePublicKey(key);\n }\n async deserializePublicKey(key) {\n return await this._prim.deserializePublicKey(key);\n }\n async serializePrivateKey(key) {\n return await this._prim.serializePrivateKey(key);\n }\n async deserializePrivateKey(key) {\n return await this._prim.deserializePrivateKey(key);\n }\n async importKey(format, key, isPublic = true) {\n return await this._prim.importKey(format, key, isPublic);\n }\n async generateKeyPair() {\n return await this._prim.generateKeyPair();\n }\n async deriveKeyPair(ikm) {\n if (ikm.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long ikm\");\n }\n return await this._prim.deriveKeyPair(ikm);\n }\n async encap(params) {\n let ke;\n if (params.ekm === undefined) {\n ke = await this.generateKeyPair();\n }\n else if (isCryptoKeyPair(params.ekm)) {\n // params.ekm is only used for testing.\n ke = params.ekm;\n }\n else {\n // params.ekm is only used for testing.\n ke = await this.deriveKeyPair(params.ekm);\n }\n const enc = await this._prim.serializePublicKey(ke.publicKey);\n const pkrm = await this._prim.serializePublicKey(params.recipientPublicKey);\n try {\n let dh;\n if (params.senderKey === undefined) {\n dh = new Uint8Array(await this._prim.dh(ke.privateKey, params.recipientPublicKey));\n }\n else {\n const sks = isCryptoKeyPair(params.senderKey)\n ? params.senderKey.privateKey\n : params.senderKey;\n const dh1 = new Uint8Array(await this._prim.dh(ke.privateKey, params.recipientPublicKey));\n const dh2 = new Uint8Array(await this._prim.dh(sks, params.recipientPublicKey));\n dh = concat(dh1, dh2);\n }\n let kemContext;\n if (params.senderKey === undefined) {\n kemContext = concat(new Uint8Array(enc), new Uint8Array(pkrm));\n }\n else {\n const pks = isCryptoKeyPair(params.senderKey)\n ? params.senderKey.publicKey\n : await this._prim.derivePublicKey(params.senderKey);\n const pksm = await this._prim.serializePublicKey(pks);\n kemContext = concat3(new Uint8Array(enc), new Uint8Array(pkrm), new Uint8Array(pksm));\n }\n const sharedSecret = await this._generateSharedSecret(dh, kemContext);\n return {\n enc: enc,\n sharedSecret: sharedSecret,\n };\n }\n catch (e) {\n throw new EncapError(e);\n }\n }\n async decap(params) {\n const pke = await this._prim.deserializePublicKey(params.enc);\n const skr = isCryptoKeyPair(params.recipientKey)\n ? params.recipientKey.privateKey\n : params.recipientKey;\n const pkr = isCryptoKeyPair(params.recipientKey)\n ? params.recipientKey.publicKey\n : await this._prim.derivePublicKey(params.recipientKey);\n const pkrm = await this._prim.serializePublicKey(pkr);\n try {\n let dh;\n if (params.senderPublicKey === undefined) {\n dh = new Uint8Array(await this._prim.dh(skr, pke));\n }\n else {\n const dh1 = new Uint8Array(await this._prim.dh(skr, pke));\n const dh2 = new Uint8Array(await this._prim.dh(skr, params.senderPublicKey));\n dh = concat(dh1, dh2);\n }\n let kemContext;\n if (params.senderPublicKey === undefined) {\n kemContext = concat(new Uint8Array(params.enc), new Uint8Array(pkrm));\n }\n else {\n const pksm = await this._prim.serializePublicKey(params.senderPublicKey);\n kemContext = new Uint8Array(params.enc.byteLength + pkrm.byteLength + pksm.byteLength);\n kemContext.set(new Uint8Array(params.enc), 0);\n kemContext.set(new Uint8Array(pkrm), params.enc.byteLength);\n kemContext.set(new Uint8Array(pksm), params.enc.byteLength + pkrm.byteLength);\n }\n return await this._generateSharedSecret(dh, kemContext);\n }\n catch (e) {\n throw new DecapError(e);\n }\n }\n async _generateSharedSecret(dh, kemContext) {\n const labeledIkm = this._kdf.buildLabeledIkm(LABEL_EAE_PRK, dh);\n const labeledInfo = this._kdf.buildLabeledInfo(LABEL_SHARED_SECRET, kemContext, this.secretSize);\n return await this._kdf.extractAndExpand(EMPTY.buffer, labeledIkm.buffer, labeledInfo.buffer, this.secretSize);\n }\n}\n","// The key usages for KEM.\nexport const KEM_USAGES = [\"deriveBits\"];\n// b\"dkp_prk\"\nexport const LABEL_DKP_PRK = new Uint8Array([\n 100,\n 107,\n 112,\n 95,\n 112,\n 114,\n 107,\n]);\n// b\"sk\"\nexport const LABEL_SK = new Uint8Array([115, 107]);\n","/**\n * The minimum inplementation of bignum to derive an EC key pair.\n */\nexport class Bignum {\n constructor(size) {\n Object.defineProperty(this, \"_num\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._num = new Uint8Array(size);\n }\n val() {\n return this._num;\n }\n reset() {\n this._num.fill(0);\n }\n set(src) {\n if (src.length !== this._num.length) {\n throw new Error(\"Bignum.set: invalid argument\");\n }\n this._num.set(src);\n }\n isZero() {\n for (let i = 0; i < this._num.length; i++) {\n if (this._num[i] !== 0) {\n return false;\n }\n }\n return true;\n }\n lessThan(v) {\n if (v.length !== this._num.length) {\n throw new Error(\"Bignum.lessThan: invalid argument\");\n }\n for (let i = 0; i < this._num.length; i++) {\n if (this._num[i] < v[i]) {\n return true;\n }\n if (this._num[i] > v[i]) {\n return false;\n }\n }\n return false;\n }\n}\n","import { NativeAlgorithm } from \"../../algorithm.js\";\nimport { EMPTY } from \"../../consts.js\";\nimport { DeriveKeyPairError, DeserializeError, NotSupportedError, SerializeError, } from \"../../errors.js\";\nimport { KemId } from \"../../identifiers.js\";\nimport { KEM_USAGES, LABEL_DKP_PRK } from \"../../interfaces/dhkemPrimitives.js\";\nimport { Bignum } from \"../../utils/bignum.js\";\nimport { base64UrlToBytes, i2Osp } from \"../../utils/misc.js\";\n// b\"candidate\"\n// deno-fmt-ignore\nconst LABEL_CANDIDATE = new Uint8Array([\n 99, 97, 110, 100, 105, 100, 97, 116, 101,\n]);\n// the order of the curve being used.\n// deno-fmt-ignore\nconst ORDER_P_256 = new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84,\n 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,\n]);\n// deno-fmt-ignore\nconst ORDER_P_384 = new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf,\n 0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a,\n 0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x73,\n]);\n// deno-fmt-ignore\nconst ORDER_P_521 = new Uint8Array([\n 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xfa, 0x51, 0x86, 0x87, 0x83, 0xbf, 0x2f,\n 0x96, 0x6b, 0x7f, 0xcc, 0x01, 0x48, 0xf7, 0x09,\n 0xa5, 0xd0, 0x3b, 0xb5, 0xc9, 0xb8, 0x89, 0x9c,\n 0x47, 0xae, 0xbb, 0x6f, 0xb7, 0x1e, 0x91, 0x38,\n 0x64, 0x09,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_256 = new Uint8Array([\n 48, 65, 2, 1, 0, 48, 19, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 8, 42, 134,\n 72, 206, 61, 3, 1, 7, 4, 39, 48, 37,\n 2, 1, 1, 4, 32,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_384 = new Uint8Array([\n 48, 78, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 34, 4, 55, 48, 53, 2, 1, 1,\n 4, 48,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_521 = new Uint8Array([\n 48, 96, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 35, 4, 73, 48, 71, 2, 1, 1,\n 4, 66,\n]);\nexport class Ec extends NativeAlgorithm {\n constructor(kem, hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // EC specific arguments for deriving key pair.\n Object.defineProperty(this, \"_order\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_bitmask\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._hkdf = hkdf;\n switch (kem) {\n case KemId.DhkemP256HkdfSha256:\n this._alg = { name: \"ECDH\", namedCurve: \"P-256\" };\n this._nPk = 65;\n this._nSk = 32;\n this._nDh = 32;\n this._order = ORDER_P_256;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_256;\n break;\n case KemId.DhkemP384HkdfSha384:\n this._alg = { name: \"ECDH\", namedCurve: \"P-384\" };\n this._nPk = 97;\n this._nSk = 48;\n this._nDh = 48;\n this._order = ORDER_P_384;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_384;\n break;\n default:\n // case KemId.DhkemP521HkdfSha512:\n this._alg = { name: \"ECDH\", namedCurve: \"P-521\" };\n this._nPk = 133;\n this._nSk = 66;\n this._nDh = 66;\n this._order = ORDER_P_521;\n this._bitmask = 0x01;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_521;\n break;\n }\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(this._alg, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY.buffer, LABEL_DKP_PRK, new Uint8Array(ikm));\n const bn = new Bignum(this._nSk);\n for (let counter = 0; bn.isZero() || !bn.lessThan(this._order); counter++) {\n if (counter > 255) {\n throw new Error(\"Faild to derive a key pair\");\n }\n const bytes = new Uint8Array(await this._hkdf.labeledExpand(dkpPrk, LABEL_CANDIDATE, i2Osp(counter, 1), this._nSk));\n bytes[0] = bytes[0] & this._bitmask;\n bn.set(bytes);\n }\n const sk = await this._deserializePkcs8Key(bn.val());\n bn.reset();\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async dh(sk, pk) {\n try {\n await this._setup();\n const bits = await this._api.deriveBits({\n name: \"ECDH\",\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.crv === \"undefined\" || key.crv !== this._alg.namedCurve) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import { EMPTY } from \"../consts.js\";\nimport { InvalidParamError } from \"../errors.js\";\nimport { KdfId } from \"../identifiers.js\";\nimport { NativeAlgorithm } from \"../algorithm.js\";\n// b\"HPKE-v1\"\nconst HPKE_VERSION = new Uint8Array([72, 80, 75, 69, 45, 118, 49]);\nexport class HkdfNative extends NativeAlgorithm {\n constructor() {\n super();\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha256\n });\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: EMPTY\n });\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-256\",\n length: 256,\n }\n });\n }\n init(suiteId) {\n this._suiteId = suiteId;\n }\n buildLabeledIkm(label, ikm) {\n this._checkInit();\n const ret = new Uint8Array(7 + this._suiteId.byteLength + label.byteLength + ikm.byteLength);\n ret.set(HPKE_VERSION, 0);\n ret.set(this._suiteId, 7);\n ret.set(label, 7 + this._suiteId.byteLength);\n ret.set(ikm, 7 + this._suiteId.byteLength + label.byteLength);\n return ret;\n }\n buildLabeledInfo(label, info, len) {\n this._checkInit();\n const ret = new Uint8Array(9 + this._suiteId.byteLength + label.byteLength + info.byteLength);\n ret.set(new Uint8Array([0, len]), 0);\n ret.set(HPKE_VERSION, 2);\n ret.set(this._suiteId, 9);\n ret.set(label, 9 + this._suiteId.byteLength);\n ret.set(info, 9 + this._suiteId.byteLength + label.byteLength);\n return ret;\n }\n async extract(salt, ikm) {\n await this._setup();\n if (salt.byteLength === 0) {\n salt = new ArrayBuffer(this.hashSize);\n }\n if (salt.byteLength !== this.hashSize) {\n throw new InvalidParamError(\"The salt length must be the same as the hashSize\");\n }\n const key = await this._api.importKey(\"raw\", salt, this.algHash, false, [\n \"sign\",\n ]);\n return await this._api.sign(\"HMAC\", key, ikm);\n }\n async expand(prk, info, len) {\n await this._setup();\n const key = await this._api.importKey(\"raw\", prk, this.algHash, false, [\n \"sign\",\n ]);\n const okm = new ArrayBuffer(len);\n const p = new Uint8Array(okm);\n let prev = EMPTY;\n const mid = new Uint8Array(info);\n const tail = new Uint8Array(1);\n if (len > 255 * this.hashSize) {\n throw new Error(\"Entropy limit reached\");\n }\n const tmp = new Uint8Array(this.hashSize + mid.length + 1);\n for (let i = 1, cur = 0; cur < p.length; i++) {\n tail[0] = i;\n tmp.set(prev, 0);\n tmp.set(mid, prev.length);\n tmp.set(tail, prev.length + mid.length);\n prev = new Uint8Array(await this._api.sign(\"HMAC\", key, tmp.slice(0, prev.length + mid.length + 1)));\n if (p.length - cur >= prev.length) {\n p.set(prev, cur);\n cur += prev.length;\n }\n else {\n p.set(prev.slice(0, p.length - cur), cur);\n cur += p.length - cur;\n }\n }\n return okm;\n }\n async extractAndExpand(salt, ikm, info, len) {\n await this._setup();\n const baseKey = await this._api.importKey(\"raw\", ikm, \"HKDF\", false, [\"deriveBits\"]);\n return await this._api.deriveBits({\n name: \"HKDF\",\n hash: this.algHash.hash,\n salt: salt,\n info: info,\n }, baseKey, len * 8);\n }\n async labeledExtract(salt, label, ikm) {\n return await this.extract(salt, this.buildLabeledIkm(label, ikm).buffer);\n }\n async labeledExpand(prk, label, info, len) {\n return await this.expand(prk, this.buildLabeledInfo(label, info, len).buffer, len);\n }\n _checkInit() {\n if (this._suiteId === EMPTY) {\n throw new Error(\"Not initialized. Call init()\");\n }\n }\n}\nexport class HkdfSha256Native extends HkdfNative {\n constructor() {\n super(...arguments);\n /** KdfId.HkdfSha256 (0x0001) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha256\n });\n /** 32 */\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n /** The parameters for Web Cryptography API */\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-256\",\n length: 256,\n }\n });\n }\n}\nexport class HkdfSha384Native extends HkdfNative {\n constructor() {\n super(...arguments);\n /** KdfId.HkdfSha384 (0x0002) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha384\n });\n /** 48 */\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 48\n });\n /** The parameters for Web Cryptography API */\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-384\",\n length: 384,\n }\n });\n }\n}\nexport class HkdfSha512Native extends HkdfNative {\n constructor() {\n super(...arguments);\n /** KdfId.HkdfSha512 (0x0003) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha512\n });\n /** 64 */\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 64\n });\n /** The parameters for Web Cryptography API */\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-512\",\n length: 512,\n }\n });\n }\n}\n","// The key usages for AEAD.\nexport const AEAD_USAGES = [\"encrypt\", \"decrypt\"];\n","/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/abstract/montgomery.ts\n */\n/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytesAsync, validateObject, } from \"../utils/noble.js\";\nimport { createKeygen } from \"./curve.js\";\nimport { mod } from \"./modular.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nfunction validateOpts(curve) {\n validateObject(curve, {\n adjustScalarBytes: \"function\",\n powPminus2: \"function\",\n });\n return Object.freeze({ ...curve });\n}\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;\n const is25519 = type === \"x25519\";\n if (!is25519 && type !== \"x448\")\n throw new Error(\"invalid type\");\n const randomBytes_ = rand || randomBytesAsync;\n const montgomeryBits = is25519 ? 255 : 448;\n const fieldLen = is25519 ? 32 : 56;\n const Gu = is25519 ? BigInt(9) : BigInt(5);\n // RFC 7748 #5:\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and\n // (156326 - 2) / 4 = 39081 for curve448/X448\n // const a = is25519 ? 156326n : 486662n;\n const a24 = is25519 ? BigInt(121665) : BigInt(39081);\n // RFC: x25519 \"the resulting integer is of the form 2^254 plus\n // eight times a value between 0 and 2^251 - 1 (inclusive)\"\n // x448: \"2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)\"\n const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);\n const maxAdded = is25519\n ? BigInt(8) * _2n ** BigInt(251) - _1n\n : BigInt(4) * _2n ** BigInt(445) - _1n;\n const maxScalar = minScalar + maxAdded + _1n; // (inclusive)\n const modP = (n) => mod(n, P);\n const GuBytes = encodeU(Gu);\n function encodeU(u) {\n return numberToBytesLE(modP(u), fieldLen);\n }\n function decodeU(u) {\n const _u = copyBytes(abytes(u, fieldLen, \"uCoordinate\"));\n // RFC: When receiving such an array, implementations of X25519\n // (but not X448) MUST mask the most significant bit in the final byte.\n if (is25519)\n _u[31] &= 127; // 0b0111_1111\n // RFC: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime. The non-canonical\n // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224\n // - 1 through 2^448 - 1 for X448.\n return modP(bytesToNumberLE(_u));\n }\n function decodeScalar(scalar) {\n return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, \"scalar\"))));\n }\n function scalarMult(scalar, u) {\n const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));\n // Some public keys are useless, of low-order. Curve author doesn't think\n // it needs to be validated, but we do it nonetheless.\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error(\"invalid private or public key received\");\n return encodeU(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n const getPublicKey = scalarMultBase;\n const getSharedSecret = scalarMult;\n // cswap from RFC7748 \"example code\"\n function cswap(swap, x_2, x_3) {\n // dummy = mask(swap) AND (x_2 XOR x_3)\n // Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n // and x_3, computed, e.g., as mask(swap) = 0 - swap.\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy\n x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy\n return { x_2, x_3 };\n }\n /**\n * Montgomery x-only multiplication ladder.\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange(\"u\", u, _0n, P);\n aInRange(\"scalar\", scalar, minScalar, maxScalar);\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent\n return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))\n }\n const lengths = {\n secretKey: fieldLen,\n publicKey: fieldLen,\n seed: fieldLen,\n };\n const randomSecretKey = async (seed) => {\n if (seed === undefined) {\n seed = await randomBytes_(fieldLen);\n }\n abytes(seed, lengths.seed, \"seed\");\n return seed;\n };\n const utils = { randomSecretKey };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getSharedSecret,\n getPublicKey,\n scalarMult,\n scalarMultBase,\n utils,\n GuBytes: GuBytes.slice(),\n lengths,\n });\n}\n","import { AEAD_USAGES, AeadId, NativeAlgorithm } from \"@hpke/common\";\nexport class AesGcmContext extends NativeAlgorithm {\n constructor(key) {\n super();\n Object.defineProperty(this, \"_rawKey\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_key\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: undefined\n });\n this._rawKey = key;\n }\n async seal(iv, data, aad) {\n await this._setupKey();\n const alg = {\n name: \"AES-GCM\",\n iv: iv,\n additionalData: aad,\n };\n const ct = await this._api.encrypt(alg, this._key, data);\n return ct;\n }\n async open(iv, data, aad) {\n await this._setupKey();\n const alg = {\n name: \"AES-GCM\",\n iv: iv,\n additionalData: aad,\n };\n const pt = await this._api.decrypt(alg, this._key, data);\n return pt;\n }\n async _setupKey() {\n if (this._key !== undefined) {\n return;\n }\n await this._setup();\n const key = await this._importKey(this._rawKey);\n (new Uint8Array(this._rawKey)).fill(0);\n this._key = key;\n return;\n }\n async _importKey(key) {\n return await this._api.importKey(\"raw\", key, { name: \"AES-GCM\" }, true, AEAD_USAGES);\n }\n}\n/**\n * The AES-128-GCM for HPKE AEAD implementing {@link AeadInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `aead` parameter of {@link CipherSuiteParams} instead of `AeadId.Aes128Gcm`.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class Aes128Gcm {\n constructor() {\n /** AeadId.Aes128Gcm (0x0001) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: AeadId.Aes128Gcm\n });\n /** 16 */\n Object.defineProperty(this, \"keySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n /** 12 */\n Object.defineProperty(this, \"nonceSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 12\n });\n /** 16 */\n Object.defineProperty(this, \"tagSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n }\n createEncryptionContext(key) {\n return new AesGcmContext(key);\n }\n}\n/**\n * The AES-256-GCM for HPKE AEAD implementing {@link AeadInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `aead` parameter of {@link CipherSuiteParams} instead of `AeadId.Aes256Gcm`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes256Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes256Gcm(),\n * });\n * ```\n */\nexport class Aes256Gcm extends Aes128Gcm {\n constructor() {\n super(...arguments);\n /** AeadId.Aes256Gcm (0x0002) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: AeadId.Aes256Gcm\n });\n /** 32 */\n Object.defineProperty(this, \"keySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n /** 12 */\n Object.defineProperty(this, \"nonceSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 12\n });\n /** 16 */\n Object.defineProperty(this, \"tagSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n }\n}\n","import { NotSupportedError } from \"@hpke/common\";\nexport function emitNotSupported() {\n return new Promise((_resolve, reject) => {\n reject(new NotSupportedError(\"Not supported\"));\n });\n}\n","import { ExportError, INPUT_LENGTH_LIMIT, InvalidParamError, } from \"@hpke/common\";\nimport { emitNotSupported } from \"./utils/emitNotSupported.js\";\n// b\"sec\"\nconst LABEL_SEC = new Uint8Array([115, 101, 99]);\nexport class ExporterContextImpl {\n constructor(api, kdf, exporterSecret) {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"exporterSecret\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._api = api;\n this._kdf = kdf;\n this.exporterSecret = exporterSecret;\n }\n async seal(_data, _aad) {\n return await emitNotSupported();\n }\n async open(_data, _aad) {\n return await emitNotSupported();\n }\n async export(exporterContext, len) {\n if (exporterContext.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long exporter context\");\n }\n try {\n return await this._kdf.labeledExpand(this.exporterSecret, LABEL_SEC, new Uint8Array(exporterContext), len);\n }\n catch (e) {\n throw new ExportError(e);\n }\n }\n}\nexport class RecipientExporterContextImpl extends ExporterContextImpl {\n}\nexport class SenderExporterContextImpl extends ExporterContextImpl {\n constructor(api, kdf, exporterSecret, enc) {\n super(api, kdf, exporterSecret);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.enc = enc;\n return;\n }\n}\n","import { i2Osp, MessageLimitReachedError, xor } from \"@hpke/common\";\nimport { ExporterContextImpl } from \"./exporterContext.js\";\nexport class EncryptionContextImpl extends ExporterContextImpl {\n constructor(api, kdf, params) {\n super(api, kdf, params.exporterSecret);\n // AEAD id.\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The length in bytes of a key for the algorithm.\n Object.defineProperty(this, \"_nK\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The length in bytes of a nonce for the algorithm.\n Object.defineProperty(this, \"_nN\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The length in bytes of an authentication tag for the algorithm.\n Object.defineProperty(this, \"_nT\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The end-to-end encryption key information.\n Object.defineProperty(this, \"_ctx\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n if (params.key === undefined || params.baseNonce === undefined ||\n params.seq === undefined) {\n throw new Error(\"Required parameters are missing\");\n }\n this._aead = params.aead;\n this._nK = this._aead.keySize;\n this._nN = this._aead.nonceSize;\n this._nT = this._aead.tagSize;\n const key = this._aead.createEncryptionContext(params.key);\n this._ctx = {\n key: key,\n baseNonce: params.baseNonce,\n seq: params.seq,\n };\n }\n computeNonce(k) {\n const seqBytes = i2Osp(k.seq, k.baseNonce.byteLength);\n return xor(k.baseNonce, seqBytes).buffer;\n }\n incrementSeq(k) {\n // if (this.seq >= (1 << (8 * this.baseNonce.byteLength)) - 1) {\n if (k.seq > Number.MAX_SAFE_INTEGER) {\n throw new MessageLimitReachedError(\"Message limit reached\");\n }\n k.seq += 1;\n return;\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _Mutex_locked;\nexport class Mutex {\n constructor() {\n _Mutex_locked.set(this, Promise.resolve());\n }\n async lock() {\n let releaseLock;\n const nextLock = new Promise((resolve) => {\n releaseLock = resolve;\n });\n const previousLock = __classPrivateFieldGet(this, _Mutex_locked, \"f\");\n __classPrivateFieldSet(this, _Mutex_locked, nextLock, \"f\");\n await previousLock;\n return releaseLock;\n }\n}\n_Mutex_locked = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _RecipientContextImpl_mutex;\nimport { EMPTY, OpenError } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class RecipientContextImpl extends EncryptionContextImpl {\n constructor() {\n super(...arguments);\n _RecipientContextImpl_mutex.set(this, void 0);\n }\n async open(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _RecipientContextImpl_mutex, __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\").lock();\n let pt;\n try {\n pt = await this._ctx.key.open(this.computeNonce(this._ctx), data, aad);\n }\n catch (e) {\n throw new OpenError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return pt;\n }\n}\n_RecipientContextImpl_mutex = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _SenderContextImpl_mutex;\nimport { EMPTY, SealError } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class SenderContextImpl extends EncryptionContextImpl {\n constructor(api, kdf, params, enc) {\n super(api, kdf, params);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n _SenderContextImpl_mutex.set(this, void 0);\n this.enc = enc;\n }\n async seal(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _SenderContextImpl_mutex, __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\").lock();\n let ct;\n try {\n ct = await this._ctx.key.seal(this.computeNonce(this._ctx), data, aad);\n }\n catch (e) {\n throw new SealError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return ct;\n }\n}\n_SenderContextImpl_mutex = new WeakMap();\n","import { AeadId, EMPTY, i2Osp, INFO_LENGTH_LIMIT, INPUT_LENGTH_LIMIT, InvalidParamError, MINIMUM_PSK_LENGTH, Mode, NativeAlgorithm, } from \"@hpke/common\";\nimport { RecipientExporterContextImpl, SenderExporterContextImpl, } from \"./exporterContext.js\";\nimport { RecipientContextImpl } from \"./recipientContext.js\";\nimport { SenderContextImpl } from \"./senderContext.js\";\n// b\"base_nonce\"\n// deno-fmt-ignore\nconst LABEL_BASE_NONCE = new Uint8Array([\n 98, 97, 115, 101, 95, 110, 111, 110, 99, 101,\n]);\n// b\"exp\"\nconst LABEL_EXP = new Uint8Array([101, 120, 112]);\n// b\"info_hash\"\n// deno-fmt-ignore\nconst LABEL_INFO_HASH = new Uint8Array([\n 105, 110, 102, 111, 95, 104, 97, 115, 104,\n]);\n// b\"key\"\nconst LABEL_KEY = new Uint8Array([107, 101, 121]);\n// b\"psk_id_hash\"\n// deno-fmt-ignore\nconst LABEL_PSK_ID_HASH = new Uint8Array([\n 112, 115, 107, 95, 105, 100, 95, 104, 97, 115, 104,\n]);\n// b\"secret\"\nconst LABEL_SECRET = new Uint8Array([115, 101, 99, 114, 101, 116]);\n// b\"HPKE\"\n// deno-fmt-ignore\nconst SUITE_ID_HEADER_HPKE = new Uint8Array([\n 72, 80, 75, 69, 0, 0, 0, 0, 0, 0,\n]);\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This is the super class of {@link CipherSuite} and the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuite | @hpke/core#CipherSuite} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - DHKEM(X25519, HKDF-SHA256)\n * - DHKEM(X448, HKDF-SHA512)\n * - ChaCha20Poly1305\n *\n * In addtion, the HKDF functions contained in this class can only derive\n * keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * // Use an extension module.\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuiteNative extends NativeAlgorithm {\n /**\n * @param params A set of parameters for building a cipher suite.\n *\n * If the error occurred, throws {@link InvalidParamError}.\n *\n * @throws {@link InvalidParamError}\n */\n constructor(params) {\n super();\n Object.defineProperty(this, \"_kem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // KEM\n if (typeof params.kem === \"number\") {\n throw new InvalidParamError(\"KemId cannot be used\");\n }\n this._kem = params.kem;\n // KDF\n if (typeof params.kdf === \"number\") {\n throw new InvalidParamError(\"KdfId cannot be used\");\n }\n this._kdf = params.kdf;\n // AEAD\n if (typeof params.aead === \"number\") {\n throw new InvalidParamError(\"AeadId cannot be used\");\n }\n this._aead = params.aead;\n this._suiteId = new Uint8Array(SUITE_ID_HEADER_HPKE);\n this._suiteId.set(i2Osp(this._kem.id, 2), 4);\n this._suiteId.set(i2Osp(this._kdf.id, 2), 6);\n this._suiteId.set(i2Osp(this._aead.id, 2), 8);\n this._kdf.init(this._suiteId);\n }\n /**\n * Gets the KEM context of the ciphersuite.\n */\n get kem() {\n return this._kem;\n }\n /**\n * Gets the KDF context of the ciphersuite.\n */\n get kdf() {\n return this._kdf;\n }\n /**\n * Gets the AEAD context of the ciphersuite.\n */\n get aead() {\n return this._aead;\n }\n /**\n * Creates an encryption context for a sender.\n *\n * If the error occurred, throws {@link DecapError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the sender encryption context.\n * @returns A sender encryption context.\n * @throws {@link EncapError}, {@link ValidationError}\n */\n async createSenderContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const dh = await this._kem.encap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleS(mode, dh.sharedSecret, dh.enc, params);\n }\n /**\n * Creates an encryption context for a recipient.\n *\n * If the error occurred, throws {@link DecapError}\n * | {@link DeserializeError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the recipient encryption context.\n * @returns A recipient encryption context.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link ValidationError}\n */\n async createRecipientContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const sharedSecret = await this._kem.decap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderPublicKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderPublicKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleR(mode, sharedSecret, params);\n }\n /**\n * Encrypts a message to a recipient.\n *\n * If the error occurred, throws `EncapError` | `MessageLimitReachedError` | `SealError` | `ValidationError`.\n *\n * @param params A set of parameters for building a sender encryption context.\n * @param pt A plain text as bytes to be encrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A cipher text and an encapsulated key as bytes.\n * @throws {@link EncapError}, {@link MessageLimitReachedError}, {@link SealError}, {@link ValidationError}\n */\n async seal(params, pt, aad = EMPTY.buffer) {\n const ctx = await this.createSenderContext(params);\n return {\n ct: await ctx.seal(pt, aad),\n enc: ctx.enc,\n };\n }\n /**\n * Decrypts a message from a sender.\n *\n * If the error occurred, throws `DecapError` | `DeserializeError` | `OpenError` | `ValidationError`.\n *\n * @param params A set of parameters for building a recipient encryption context.\n * @param ct An encrypted text as bytes to be decrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A decrypted plain text as bytes.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link OpenError}, {@link ValidationError}\n */\n async open(params, ct, aad = EMPTY.buffer) {\n const ctx = await this.createRecipientContext(params);\n return await ctx.open(ct, aad);\n }\n // private verifyPskInputs(mode: Mode, params: KeyScheduleParams) {\n // const gotPsk = (params.psk !== undefined);\n // const gotPskId = (params.psk !== undefined && params.psk.id.byteLength > 0);\n // if (gotPsk !== gotPskId) {\n // throw new Error('Inconsistent PSK inputs');\n // }\n // if (gotPsk && (mode === Mode.Base || mode === Mode.Auth)) {\n // throw new Error('PSK input provided when not needed');\n // }\n // if (!gotPsk && (mode === Mode.Psk || mode === Mode.AuthPsk)) {\n // throw new Error('Missing required PSK input');\n // }\n // return;\n // }\n async _keySchedule(mode, sharedSecret, params) {\n // Currently, there is no point in executing this function\n // because this hpke library does not allow users to explicitly specify the mode.\n //\n // this.verifyPskInputs(mode, params);\n const pskId = params.psk === undefined\n ? EMPTY\n : new Uint8Array(params.psk.id);\n const pskIdHash = await this._kdf.labeledExtract(EMPTY.buffer, LABEL_PSK_ID_HASH, pskId);\n const info = params.info === undefined\n ? EMPTY\n : new Uint8Array(params.info);\n const infoHash = await this._kdf.labeledExtract(EMPTY.buffer, LABEL_INFO_HASH, info);\n const keyScheduleContext = new Uint8Array(1 + pskIdHash.byteLength + infoHash.byteLength);\n keyScheduleContext.set(new Uint8Array([mode]), 0);\n keyScheduleContext.set(new Uint8Array(pskIdHash), 1);\n keyScheduleContext.set(new Uint8Array(infoHash), 1 + pskIdHash.byteLength);\n const psk = params.psk === undefined\n ? EMPTY\n : new Uint8Array(params.psk.key);\n const ikm = this._kdf.buildLabeledIkm(LABEL_SECRET, psk)\n .buffer;\n const exporterSecretInfo = this._kdf.buildLabeledInfo(LABEL_EXP, keyScheduleContext, this._kdf.hashSize).buffer;\n const exporterSecret = await this._kdf.extractAndExpand(sharedSecret, ikm, exporterSecretInfo, this._kdf.hashSize);\n if (this._aead.id === AeadId.ExportOnly) {\n return { aead: this._aead, exporterSecret: exporterSecret };\n }\n const keyInfo = this._kdf.buildLabeledInfo(LABEL_KEY, keyScheduleContext, this._aead.keySize).buffer;\n const key = await this._kdf.extractAndExpand(sharedSecret, ikm, keyInfo, this._aead.keySize);\n const baseNonceInfo = this._kdf.buildLabeledInfo(LABEL_BASE_NONCE, keyScheduleContext, this._aead.nonceSize).buffer;\n const baseNonce = await this._kdf.extractAndExpand(sharedSecret, ikm, baseNonceInfo, this._aead.nonceSize);\n return {\n aead: this._aead,\n exporterSecret: exporterSecret,\n key: key,\n baseNonce: new Uint8Array(baseNonce),\n seq: 0,\n };\n }\n async _keyScheduleS(mode, sharedSecret, enc, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new SenderExporterContextImpl(this._api, this._kdf, res.exporterSecret, enc);\n }\n return new SenderContextImpl(this._api, this._kdf, res, enc);\n }\n async _keyScheduleR(mode, sharedSecret, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new RecipientExporterContextImpl(this._api, this._kdf, res.exporterSecret);\n }\n return new RecipientContextImpl(this._api, this._kdf, res);\n }\n _validateInputLength(params) {\n if (params.info !== undefined &&\n params.info.byteLength > INFO_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long info\");\n }\n if (params.psk !== undefined) {\n if (params.psk.key.byteLength < MINIMUM_PSK_LENGTH) {\n throw new InvalidParamError(`PSK must have at least ${MINIMUM_PSK_LENGTH} bytes`);\n }\n if (params.psk.key.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.key\");\n }\n if (params.psk.id.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.id\");\n }\n }\n return;\n }\n}\n","import { Dhkem, Ec, HkdfSha256Native, HkdfSha384Native, HkdfSha512Native, KemId, } from \"@hpke/common\";\nexport class DhkemP256HkdfSha256Native extends Dhkem {\n constructor() {\n const kdf = new HkdfSha256Native();\n const prim = new Ec(KemId.DhkemP256HkdfSha256, kdf);\n super(KemId.DhkemP256HkdfSha256, prim, kdf);\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KemId.DhkemP256HkdfSha256\n });\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 65\n });\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 65\n });\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n }\n}\nexport class DhkemP384HkdfSha384Native extends Dhkem {\n constructor() {\n const kdf = new HkdfSha384Native();\n const prim = new Ec(KemId.DhkemP384HkdfSha384, kdf);\n super(KemId.DhkemP384HkdfSha384, prim, kdf);\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KemId.DhkemP384HkdfSha384\n });\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 48\n });\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 97\n });\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 97\n });\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 48\n });\n }\n}\nexport class DhkemP521HkdfSha512Native extends Dhkem {\n constructor() {\n const kdf = new HkdfSha512Native();\n const prim = new Ec(KemId.DhkemP521HkdfSha512, kdf);\n super(KemId.DhkemP521HkdfSha512, prim, kdf);\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KemId.DhkemP521HkdfSha512\n });\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 64\n });\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 133\n });\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 133\n });\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 64\n });\n }\n}\n","import { HkdfSha256Native, HkdfSha384Native, HkdfSha512Native, } from \"@hpke/common\";\nimport { CipherSuiteNative } from \"./cipherSuiteNative.js\";\nimport { DhkemP256HkdfSha256Native, DhkemP384HkdfSha384Native, DhkemP521HkdfSha512Native, } from \"./kems/dhkemNative.js\";\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This class is the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuiteNative | @hpke/core#CipherSuiteNative} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - `DHKEM(X25519, HKDF-SHA256)`\n * - `DHKEM(X448, HKDF-SHA512)`\n * - `ChaCha20Poly1305`\n *\n * In addtion, the HKDF functions contained in this `CipherSuiteNative`\n * class can only derive keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuite extends CipherSuiteNative {\n}\n/**\n * The DHKEM(P-256, HKDF-SHA256) for HPKE KEM implementing {@link KemInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KemId.DhkemP256HkdfSha256`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class DhkemP256HkdfSha256 extends DhkemP256HkdfSha256Native {\n}\n/**\n * The DHKEM(P-384, HKDF-SHA384) for HPKE KEM implementing {@link KemInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KemId.DhkemP384HkdfSha384`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP384HkdfSha384,\n * HkdfSha384,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP384HkdfSha384(),\n * kdf: new HkdfSha384(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class DhkemP384HkdfSha384 extends DhkemP384HkdfSha384Native {\n}\n/**\n * The DHKEM(P-521, HKDF-SHA512) for HPKE KEM implementing {@link KemInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KemId.DhkemP521HkdfSha512`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes256Gcm,\n * CipherSuite,\n * DhkemP521HkdfSha512,\n * HkdfSha512,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP521HkdfSha512(),\n * kdf: new HkdfSha512(),\n * aead: new Aes256Gcm(),\n * });\n * ```\n */\nexport class DhkemP521HkdfSha512 extends DhkemP521HkdfSha512Native {\n}\n/**\n * The HKDF-SHA256 for HPKE KDF implementing {@link KdfInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha256`.\n *\n * The KDF class can only derive keys of the same length as the `hashSize`.\n * If you want to derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class HkdfSha256 extends HkdfSha256Native {\n}\n/**\n * The HKDF-SHA384 for HPKE KDF implementing {@link KdfInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha384`.\n *\n * The KDF class can only derive keys of the same length as the `hashSize`.\n * If you want to derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP384HkdfSha384,\n * HkdfSha384,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP384HkdfSha384(),\n * kdf: new HkdfSha384(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class HkdfSha384 extends HkdfSha384Native {\n}\n/**\n * The HKDF-SHA512 for HPKE KDF implementing {@link KdfInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha512`.\n *\n * The KDF class can only derive keys of the same length as the `hashSize`.\n * If you want to derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes256Gcm,\n * CipherSuite,\n * DhkemP521HkdfSha512,\n * HkdfSha512,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP521HkdfSha512(),\n * kdf: new HkdfSha512(),\n * aead: new Aes256Gcm(),\n * });\n * ```\n */\nexport class HkdfSha512 extends HkdfSha512Native {\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, } from \"@hpke/common\";\nconst ALG_NAME = \"X25519\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X25519 = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,\n]);\nexport class X25519 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 32;\n this._nSk = 32;\n this._nDh = 32;\n this._pkcs8AlgId = PKCS8_ALG_ID_X25519;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY.buffer, LABEL_DKP_PRK, new Uint8Array(ikm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, } from \"@hpke/common\";\nconst ALG_NAME = \"X448\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X448 = new Uint8Array([\n 0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38,\n]);\nexport class X448 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 56;\n this._nSk = 56;\n this._nDh = 56;\n this._pkcs8AlgId = PKCS8_ALG_ID_X448;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY.buffer, LABEL_DKP_PRK, new Uint8Array(ikm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","'use strict';\n\n// This is free and unencumbered software released into the public domain.\n// See LICENSE.md for more information.\n\n//\n// Utilities\n//\n\n/**\n * @param {number} a The number to test.\n * @param {number} min The minimum value in the range, inclusive.\n * @param {number} max The maximum value in the range, inclusive.\n * @return {boolean} True if a >= min and a <= max.\n */\nfunction inRange(a, min, max) {\n return min <= a && a <= max;\n}\n\n/**\n * @param {*} o\n * @return {Object}\n */\nfunction ToDictionary(o) {\n if (o === undefined) return {};\n if (o === Object(o)) return o;\n throw TypeError('Could not convert argument to dictionary');\n}\n\n/**\n * @param {string} string Input string of UTF-16 code units.\n * @return {!Array.} Code points.\n */\nfunction stringToCodePoints(string) {\n // https://heycam.github.io/webidl/#dfn-obtain-unicode\n\n // 1. Let S be the DOMString value.\n var s = String(string);\n\n // 2. Let n be the length of S.\n var n = s.length;\n\n // 3. Initialize i to 0.\n var i = 0;\n\n // 4. Initialize U to be an empty sequence of Unicode characters.\n var u = [];\n\n // 5. While i < n:\n while (i < n) {\n\n // 1. Let c be the code unit in S at index i.\n var c = s.charCodeAt(i);\n\n // 2. Depending on the value of c:\n\n // c < 0xD800 or c > 0xDFFF\n if (c < 0xD800 || c > 0xDFFF) {\n // Append to U the Unicode character with code point c.\n u.push(c);\n }\n\n // 0xDC00 ≤ c ≤ 0xDFFF\n else if (0xDC00 <= c && c <= 0xDFFF) {\n // Append to U a U+FFFD REPLACEMENT CHARACTER.\n u.push(0xFFFD);\n }\n\n // 0xD800 ≤ c ≤ 0xDBFF\n else if (0xD800 <= c && c <= 0xDBFF) {\n // 1. If i = n−1, then append to U a U+FFFD REPLACEMENT\n // CHARACTER.\n if (i === n - 1) {\n u.push(0xFFFD);\n }\n // 2. Otherwise, i < n−1:\n else {\n // 1. Let d be the code unit in S at index i+1.\n var d = string.charCodeAt(i + 1);\n\n // 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:\n if (0xDC00 <= d && d <= 0xDFFF) {\n // 1. Let a be c & 0x3FF.\n var a = c & 0x3FF;\n\n // 2. Let b be d & 0x3FF.\n var b = d & 0x3FF;\n\n // 3. Append to U the Unicode character with code point\n // 2^16+2^10*a+b.\n u.push(0x10000 + (a << 10) + b);\n\n // 4. Set i to i+1.\n i += 1;\n }\n\n // 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a\n // U+FFFD REPLACEMENT CHARACTER.\n else {\n u.push(0xFFFD);\n }\n }\n }\n\n // 3. Set i to i+1.\n i += 1;\n }\n\n // 6. Return U.\n return u;\n}\n\n/**\n * @param {!Array.} code_points Array of code points.\n * @return {string} string String of UTF-16 code units.\n */\nfunction codePointsToString(code_points) {\n var s = '';\n for (var i = 0; i < code_points.length; ++i) {\n var cp = code_points[i];\n if (cp <= 0xFFFF) {\n s += String.fromCharCode(cp);\n } else {\n cp -= 0x10000;\n s += String.fromCharCode((cp >> 10) + 0xD800,\n (cp & 0x3FF) + 0xDC00);\n }\n }\n return s;\n}\n\n\n//\n// Implementation of Encoding specification\n// https://encoding.spec.whatwg.org/\n//\n\n//\n// 3. Terminology\n//\n\n/**\n * End-of-stream is a special token that signifies no more tokens\n * are in the stream.\n * @const\n */ var end_of_stream = -1;\n\n/**\n * A stream represents an ordered sequence of tokens.\n *\n * @constructor\n * @param {!(Array.|Uint8Array)} tokens Array of tokens that provide the\n * stream.\n */\nfunction Stream(tokens) {\n /** @type {!Array.} */\n this.tokens = [].slice.call(tokens);\n}\n\nStream.prototype = {\n /**\n * @return {boolean} True if end-of-stream has been hit.\n */\n endOfStream: function() {\n return !this.tokens.length;\n },\n\n /**\n * When a token is read from a stream, the first token in the\n * stream must be returned and subsequently removed, and\n * end-of-stream must be returned otherwise.\n *\n * @return {number} Get the next token from the stream, or\n * end_of_stream.\n */\n read: function() {\n if (!this.tokens.length)\n return end_of_stream;\n return this.tokens.shift();\n },\n\n /**\n * When one or more tokens are prepended to a stream, those tokens\n * must be inserted, in given order, before the first token in the\n * stream.\n *\n * @param {(number|!Array.)} token The token(s) to prepend to the stream.\n */\n prepend: function(token) {\n if (Array.isArray(token)) {\n var tokens = /**@type {!Array.}*/(token);\n while (tokens.length)\n this.tokens.unshift(tokens.pop());\n } else {\n this.tokens.unshift(token);\n }\n },\n\n /**\n * When one or more tokens are pushed to a stream, those tokens\n * must be inserted, in given order, after the last token in the\n * stream.\n *\n * @param {(number|!Array.)} token The tokens(s) to prepend to the stream.\n */\n push: function(token) {\n if (Array.isArray(token)) {\n var tokens = /**@type {!Array.}*/(token);\n while (tokens.length)\n this.tokens.push(tokens.shift());\n } else {\n this.tokens.push(token);\n }\n }\n};\n\n//\n// 4. Encodings\n//\n\n// 4.1 Encoders and decoders\n\n/** @const */\nvar finished = -1;\n\n/**\n * @param {boolean} fatal If true, decoding errors raise an exception.\n * @param {number=} opt_code_point Override the standard fallback code point.\n * @return {number} The code point to insert on a decoding error.\n */\nfunction decoderError(fatal, opt_code_point) {\n if (fatal)\n throw TypeError('Decoder error');\n return opt_code_point || 0xFFFD;\n}\n\n//\n// 7. API\n//\n\n/** @const */ var DEFAULT_ENCODING = 'utf-8';\n\n// 7.1 Interface TextDecoder\n\n/**\n * @constructor\n * @param {string=} encoding The label of the encoding;\n * defaults to 'utf-8'.\n * @param {Object=} options\n */\nfunction TextDecoder(encoding, options) {\n if (!(this instanceof TextDecoder)) {\n return new TextDecoder(encoding, options);\n }\n encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;\n if (encoding !== DEFAULT_ENCODING) {\n throw new Error('Encoding not supported. Only utf-8 is supported');\n }\n options = ToDictionary(options);\n\n /** @private @type {boolean} */\n this._streaming = false;\n /** @private @type {boolean} */\n this._BOMseen = false;\n /** @private @type {?Decoder} */\n this._decoder = null;\n /** @private @type {boolean} */\n this._fatal = Boolean(options['fatal']);\n /** @private @type {boolean} */\n this._ignoreBOM = Boolean(options['ignoreBOM']);\n\n Object.defineProperty(this, 'encoding', {value: 'utf-8'});\n Object.defineProperty(this, 'fatal', {value: this._fatal});\n Object.defineProperty(this, 'ignoreBOM', {value: this._ignoreBOM});\n}\n\nTextDecoder.prototype = {\n /**\n * @param {ArrayBufferView=} input The buffer of bytes to decode.\n * @param {Object=} options\n * @return {string} The decoded string.\n */\n decode: function decode(input, options) {\n var bytes;\n if (typeof input === 'object' && input instanceof ArrayBuffer) {\n bytes = new Uint8Array(input);\n } else if (typeof input === 'object' && 'buffer' in input &&\n input.buffer instanceof ArrayBuffer) {\n bytes = new Uint8Array(input.buffer,\n input.byteOffset,\n input.byteLength);\n } else {\n bytes = new Uint8Array(0);\n }\n\n options = ToDictionary(options);\n\n if (!this._streaming) {\n this._decoder = new UTF8Decoder({fatal: this._fatal});\n this._BOMseen = false;\n }\n this._streaming = Boolean(options['stream']);\n\n var input_stream = new Stream(bytes);\n\n var code_points = [];\n\n /** @type {?(number|!Array.)} */\n var result;\n\n while (!input_stream.endOfStream()) {\n result = this._decoder.handler(input_stream, input_stream.read());\n if (result === finished)\n break;\n if (result === null)\n continue;\n if (Array.isArray(result))\n code_points.push.apply(code_points, /**@type {!Array.}*/(result));\n else\n code_points.push(result);\n }\n if (!this._streaming) {\n do {\n result = this._decoder.handler(input_stream, input_stream.read());\n if (result === finished)\n break;\n if (result === null)\n continue;\n if (Array.isArray(result))\n code_points.push.apply(code_points, /**@type {!Array.}*/(result));\n else\n code_points.push(result);\n } while (!input_stream.endOfStream());\n this._decoder = null;\n }\n\n if (code_points.length) {\n // If encoding is one of utf-8, utf-16be, and utf-16le, and\n // ignore BOM flag and BOM seen flag are unset, run these\n // subsubsteps:\n if (['utf-8'].indexOf(this.encoding) !== -1 &&\n !this._ignoreBOM && !this._BOMseen) {\n // If token is U+FEFF, set BOM seen flag.\n if (code_points[0] === 0xFEFF) {\n this._BOMseen = true;\n code_points.shift();\n } else {\n // Otherwise, if token is not end-of-stream, set BOM seen\n // flag and append token to output.\n this._BOMseen = true;\n }\n }\n }\n\n return codePointsToString(code_points);\n }\n};\n\n// 7.2 Interface TextEncoder\n\n/**\n * @constructor\n * @param {string=} encoding The label of the encoding;\n * defaults to 'utf-8'.\n * @param {Object=} options\n */\nfunction TextEncoder(encoding, options) {\n if (!(this instanceof TextEncoder))\n return new TextEncoder(encoding, options);\n encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;\n if (encoding !== DEFAULT_ENCODING) {\n throw new Error('Encoding not supported. Only utf-8 is supported');\n }\n options = ToDictionary(options);\n\n /** @private @type {boolean} */\n this._streaming = false;\n /** @private @type {?Encoder} */\n this._encoder = null;\n /** @private @type {{fatal: boolean}} */\n this._options = {fatal: Boolean(options['fatal'])};\n\n Object.defineProperty(this, 'encoding', {value: 'utf-8'});\n}\n\nTextEncoder.prototype = {\n /**\n * @param {string=} opt_string The string to encode.\n * @param {Object=} options\n * @return {Uint8Array} Encoded bytes, as a Uint8Array.\n */\n encode: function encode(opt_string, options) {\n opt_string = opt_string ? String(opt_string) : '';\n options = ToDictionary(options);\n\n // NOTE: This option is nonstandard. None of the encodings\n // permitted for encoding (i.e. UTF-8, UTF-16) are stateful,\n // so streaming is not necessary.\n if (!this._streaming)\n this._encoder = new UTF8Encoder(this._options);\n this._streaming = Boolean(options['stream']);\n\n var bytes = [];\n var input_stream = new Stream(stringToCodePoints(opt_string));\n /** @type {?(number|!Array.)} */\n var result;\n while (!input_stream.endOfStream()) {\n result = this._encoder.handler(input_stream, input_stream.read());\n if (result === finished)\n break;\n if (Array.isArray(result))\n bytes.push.apply(bytes, /**@type {!Array.}*/(result));\n else\n bytes.push(result);\n }\n if (!this._streaming) {\n while (true) {\n result = this._encoder.handler(input_stream, input_stream.read());\n if (result === finished)\n break;\n if (Array.isArray(result))\n bytes.push.apply(bytes, /**@type {!Array.}*/(result));\n else\n bytes.push(result);\n }\n this._encoder = null;\n }\n return new Uint8Array(bytes);\n }\n};\n\n//\n// 8. The encoding\n//\n\n// 8.1 utf-8\n\n/**\n * @constructor\n * @implements {Decoder}\n * @param {{fatal: boolean}} options\n */\nfunction UTF8Decoder(options) {\n var fatal = options.fatal;\n\n // utf-8's decoder's has an associated utf-8 code point, utf-8\n // bytes seen, and utf-8 bytes needed (all initially 0), a utf-8\n // lower boundary (initially 0x80), and a utf-8 upper boundary\n // (initially 0xBF).\n var /** @type {number} */ utf8_code_point = 0,\n /** @type {number} */ utf8_bytes_seen = 0,\n /** @type {number} */ utf8_bytes_needed = 0,\n /** @type {number} */ utf8_lower_boundary = 0x80,\n /** @type {number} */ utf8_upper_boundary = 0xBF;\n\n /**\n * @param {Stream} stream The stream of bytes being decoded.\n * @param {number} bite The next byte read from the stream.\n * @return {?(number|!Array.)} The next code point(s)\n * decoded, or null if not enough data exists in the input\n * stream to decode a complete code point.\n */\n this.handler = function(stream, bite) {\n // 1. If byte is end-of-stream and utf-8 bytes needed is not 0,\n // set utf-8 bytes needed to 0 and return error.\n if (bite === end_of_stream && utf8_bytes_needed !== 0) {\n utf8_bytes_needed = 0;\n return decoderError(fatal);\n }\n\n // 2. If byte is end-of-stream, return finished.\n if (bite === end_of_stream)\n return finished;\n\n // 3. If utf-8 bytes needed is 0, based on byte:\n if (utf8_bytes_needed === 0) {\n\n // 0x00 to 0x7F\n if (inRange(bite, 0x00, 0x7F)) {\n // Return a code point whose value is byte.\n return bite;\n }\n\n // 0xC2 to 0xDF\n if (inRange(bite, 0xC2, 0xDF)) {\n // Set utf-8 bytes needed to 1 and utf-8 code point to byte\n // − 0xC0.\n utf8_bytes_needed = 1;\n utf8_code_point = bite - 0xC0;\n }\n\n // 0xE0 to 0xEF\n else if (inRange(bite, 0xE0, 0xEF)) {\n // 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.\n if (bite === 0xE0)\n utf8_lower_boundary = 0xA0;\n // 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.\n if (bite === 0xED)\n utf8_upper_boundary = 0x9F;\n // 3. Set utf-8 bytes needed to 2 and utf-8 code point to\n // byte − 0xE0.\n utf8_bytes_needed = 2;\n utf8_code_point = bite - 0xE0;\n }\n\n // 0xF0 to 0xF4\n else if (inRange(bite, 0xF0, 0xF4)) {\n // 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.\n if (bite === 0xF0)\n utf8_lower_boundary = 0x90;\n // 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.\n if (bite === 0xF4)\n utf8_upper_boundary = 0x8F;\n // 3. Set utf-8 bytes needed to 3 and utf-8 code point to\n // byte − 0xF0.\n utf8_bytes_needed = 3;\n utf8_code_point = bite - 0xF0;\n }\n\n // Otherwise\n else {\n // Return error.\n return decoderError(fatal);\n }\n\n // Then (byte is in the range 0xC2 to 0xF4) set utf-8 code\n // point to utf-8 code point << (6 × utf-8 bytes needed) and\n // return continue.\n utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed);\n return null;\n }\n\n // 4. If byte is not in the range utf-8 lower boundary to utf-8\n // upper boundary, run these substeps:\n if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {\n\n // 1. Set utf-8 code point, utf-8 bytes needed, and utf-8\n // bytes seen to 0, set utf-8 lower boundary to 0x80, and set\n // utf-8 upper boundary to 0xBF.\n utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;\n utf8_lower_boundary = 0x80;\n utf8_upper_boundary = 0xBF;\n\n // 2. Prepend byte to stream.\n stream.prepend(bite);\n\n // 3. Return error.\n return decoderError(fatal);\n }\n\n // 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary\n // to 0xBF.\n utf8_lower_boundary = 0x80;\n utf8_upper_boundary = 0xBF;\n\n // 6. Increase utf-8 bytes seen by one and set utf-8 code point\n // to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes\n // needed − utf-8 bytes seen)).\n utf8_bytes_seen += 1;\n utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen));\n\n // 7. If utf-8 bytes seen is not equal to utf-8 bytes needed,\n // continue.\n if (utf8_bytes_seen !== utf8_bytes_needed)\n return null;\n\n // 8. Let code point be utf-8 code point.\n var code_point = utf8_code_point;\n\n // 9. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes\n // seen to 0.\n utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;\n\n // 10. Return a code point whose value is code point.\n return code_point;\n };\n}\n\n/**\n * @constructor\n * @implements {Encoder}\n * @param {{fatal: boolean}} options\n */\nfunction UTF8Encoder(options) {\n var fatal = options.fatal;\n /**\n * @param {Stream} stream Input stream.\n * @param {number} code_point Next code point read from the stream.\n * @return {(number|!Array.)} Byte(s) to emit.\n */\n this.handler = function(stream, code_point) {\n // 1. If code point is end-of-stream, return finished.\n if (code_point === end_of_stream)\n return finished;\n\n // 2. If code point is in the range U+0000 to U+007F, return a\n // byte whose value is code point.\n if (inRange(code_point, 0x0000, 0x007f))\n return code_point;\n\n // 3. Set count and offset based on the range code point is in:\n var count, offset;\n // U+0080 to U+07FF: 1 and 0xC0\n if (inRange(code_point, 0x0080, 0x07FF)) {\n count = 1;\n offset = 0xC0;\n }\n // U+0800 to U+FFFF: 2 and 0xE0\n else if (inRange(code_point, 0x0800, 0xFFFF)) {\n count = 2;\n offset = 0xE0;\n }\n // U+10000 to U+10FFFF: 3 and 0xF0\n else if (inRange(code_point, 0x10000, 0x10FFFF)) {\n count = 3;\n offset = 0xF0;\n }\n\n // 4.Let bytes be a byte sequence whose first byte is (code\n // point >> (6 × count)) + offset.\n var bytes = [(code_point >> (6 * count)) + offset];\n\n // 5. Run these substeps while count is greater than 0:\n while (count > 0) {\n\n // 1. Set temp to code point >> (6 × (count − 1)).\n var temp = code_point >> (6 * (count - 1));\n\n // 2. Append to bytes 0x80 | (temp & 0x3F).\n bytes.push(0x80 | (temp & 0x3F));\n\n // 3. Decrease count by one.\n count -= 1;\n }\n\n // 6. Return bytes bytes, in order.\n return bytes;\n };\n}\n\nexports.TextEncoder = TextEncoder;\nexports.TextDecoder = TextDecoder;","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n","'use strict';\n\nconst uuid = require('uuid').v4;\n\n/**\n * Generates a JSON-RPC 1.0 or 2.0 request\n * @param {String} method Name of method to call\n * @param {Array|Object} params Array of parameters passed to the method as specified, or an object of parameter names and corresponding value\n * @param {String|Number|null} [id] Request ID can be a string, number, null for explicit notification or left out for automatic generation\n * @param {Object} [options]\n * @param {Number} [options.version=2] JSON-RPC version to use (1 or 2)\n * @param {Boolean} [options.notificationIdNull=false] When true, version 2 requests will set id to null instead of omitting it\n * @param {Function} [options.generator] Passed the request, and the options object and is expected to return a request ID\n * @throws {TypeError} If any of the parameters are invalid\n * @return {Object} A JSON-RPC 1.0 or 2.0 request\n * @memberOf Utils\n */\nconst generateRequest = function(method, params, id, options) {\n if(typeof method !== 'string') {\n throw new TypeError(method + ' must be a string');\n }\n\n options = options || {};\n\n // check valid version provided\n const version = typeof options.version === 'number' ? options.version : 2;\n if (version !== 1 && version !== 2) {\n throw new TypeError(version + ' must be 1 or 2');\n }\n\n const request = {\n method: method\n };\n\n if(version === 2) {\n request.jsonrpc = '2.0';\n }\n\n if(params) {\n // params given, but invalid?\n if(typeof params !== 'object' && !Array.isArray(params)) {\n throw new TypeError(params + ' must be an object, array or omitted');\n }\n request.params = params;\n }\n\n // if id was left out, generate one (null means explicit notification)\n if(typeof(id) === 'undefined') {\n const generator = typeof options.generator === 'function' ? options.generator : function() { return uuid(); };\n request.id = generator(request, options);\n } else if (version === 2 && id === null) {\n // we have a version 2 notification\n if (options.notificationIdNull) {\n request.id = null; // id will not be set at all unless option provided\n }\n } else {\n request.id = id;\n }\n\n return request;\n};\n\nmodule.exports = generateRequest;\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","export default /^(?:[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;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var 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(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","'use strict'\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n// @ts-ignore\nvar _Buffer = require('safe-buffer').Buffer\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256)\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i)\n var xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n var BASE = ALPHABET.length\n var LEADER = ALPHABET.charAt(0)\n var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }\n if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0\n var length = 0\n var pbegin = 0\n var pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n var b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return _Buffer.alloc(0) }\n var psz = 0\n // Skip and count leading '1's.\n var zeroes = 0\n var length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size)\n // Process the characters.\n while (psz < source.length) {\n // Find code of next character\n var charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n var carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n var i = 0\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n var it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n var vch = _Buffer.allocUnsafe(zeroes + (size - it4))\n vch.fill(0x00, 0, zeroes)\n var j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nmodule.exports = base\n","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [number & 0x3ffffff];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [0];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this._strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // '0' - '9'\n if (c >= 48 && c <= 57) {\n return c - 48;\n // 'A' - 'F'\n } else if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n } else {\n assert(false, 'Invalid character in ' + string);\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this._strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var b = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n b = c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n b = c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n b = c;\n }\n assert(c >= 0 && b < mul, 'Invalid character');\n r += b;\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [0];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this._strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n function move (dest, src) {\n dest.words = src.words;\n dest.length = src.length;\n dest.negative = src.negative;\n dest.red = src.red;\n }\n\n BN.prototype._move = function _move (dest) {\n move(dest, this);\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype._strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n // Check Symbol.for because not everywhere where Symbol defined\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility\n if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {\n try {\n BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;\n } catch (e) {\n BN.prototype.inspect = inspect;\n }\n } else {\n BN.prototype.inspect = inspect;\n }\n\n function inspect () {\n return (this.red ? '';\n }\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modrn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16, 2);\n };\n\n if (Buffer) {\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n return this.toArrayLike(Buffer, endian, length);\n };\n }\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n var allocate = function allocate (ArrayType, size) {\n if (ArrayType.allocUnsafe) {\n return ArrayType.allocUnsafe(size);\n }\n return new ArrayType(size);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n this._strip();\n\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n var res = allocate(ArrayType, reqLength);\n var postfix = endian === 'le' ? 'LE' : 'BE';\n this['_toArrayLike' + postfix](res, byteLength);\n return res;\n };\n\n BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {\n var position = 0;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position++] = word & 0xff;\n if (position < res.length) {\n res[position++] = (word >> 8) & 0xff;\n }\n if (position < res.length) {\n res[position++] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position < res.length) {\n res[position++] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position < res.length) {\n res[position++] = carry;\n\n while (position < res.length) {\n res[position++] = 0;\n }\n }\n };\n\n BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {\n var position = res.length - 1;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position--] = word & 0xff;\n if (position >= 0) {\n res[position--] = (word >> 8) & 0xff;\n }\n if (position >= 0) {\n res[position--] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position >= 0) {\n res[position--] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position >= 0) {\n res[position--] = carry;\n\n while (position >= 0) {\n res[position--] = 0;\n }\n }\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] >>> wbit) & 0x01;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this._strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this._strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this._strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this._strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this._strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this._strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n function jumboMulTo (self, num, out) {\n // Temporary disable, see https://github.com/indutny/bn.js/issues/211\n // var fftm = new FFTM();\n // return fftm.mulp(self, num, out);\n return bigMulTo(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out._strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n this.length = num === 0 ? 1 : this.length;\n\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this._strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) <= num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this._strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this._strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this._strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q._strip();\n }\n a._strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modrn = function modrn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return isNegNum ? -acc : acc;\n };\n\n // WARNING: DEPRECATED\n BN.prototype.modn = function modn (num) {\n return this.modrn(num);\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n this._strip();\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this._strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is a BN v4 instance\n r.strip();\n } else {\n // r is a BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n\n move(a, a.umod(this.m)._forceRed(this));\n return a;\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\nconst P = 2n ** 255n - 19n; // ed25519 is twisted edwards curve\nconst N = 2n ** 252n + 27742317777372353535851937790883648493n; // curve's (group) order\nconst Gx = 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an; // base point x\nconst Gy = 0x6666666666666666666666666666666666666666666666666666666666666658n; // base point y\nconst CURVE = {\n a: -1n,\n d: 37095705934669439343138083508754565189542113879843219016388785533085940283555n,\n p: P, n: N, h: 8, Gx, Gy // field prime, curve (group) order, cofactor\n};\nconst err = (m = '') => { throw new Error(m); }; // error helper, messes-up stack trace\nconst str = (s) => typeof s === 'string'; // is string\nconst au8 = (a, l) => // is Uint8Array (of specific length)\n !(a instanceof Uint8Array) || (typeof l === 'number' && l > 0 && a.length !== l) ?\n err('Uint8Array expected') : a;\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst toU8 = (a, len) => au8(str(a) ? h2b(a) : u8n(a), len); // norm(hex/u8a) to u8a\nconst mod = (a, b = P) => { let r = a % b; return r >= 0n ? r : b + r; }; // mod division\nconst isPoint = (p) => (p instanceof Point ? p : err('Point expected')); // is xyzt point\nlet Gpows = undefined; // precomputes for base point G\nclass Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n }\n static fromAffine(p) { return new Point(p.x, p.y, 1n, mod(p.x * p.y)); }\n static fromHex(hex, strict = true) {\n const { d } = CURVE;\n hex = toU8(hex, 32);\n const normed = hex.slice(); // copy the array to not mess it up\n normed[31] = hex[31] & ~0x80; // adjust first LE byte = last BE byte\n const y = b2n_LE(normed); // decode as little-endian, convert to num\n if (y === 0n) { // y=0 is valid, proceed\n }\n else {\n if (strict && !(0n < y && y < P))\n err('bad y coord 1'); // strict=true [1..P-1]\n if (!strict && !(0n < y && y < 2n ** 256n))\n err('bad y coord 2'); // strict=false [1..2^256-1]\n }\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(d * y2 + 1n); // v=dy²+1\n let { isValid, value: x } = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (!isValid)\n err('bad y coordinate 3'); // not square root: bad point\n const isXOdd = (x & 1n) === 1n; // adjust sign of x coordinate\n const isHeadOdd = (hex[31] & 0x80) !== 0;\n if (isHeadOdd !== isXOdd)\n x = mod(-x);\n return new Point(x, y, 1n, mod(x * y)); // Z=1, T=xy\n }\n get x() { return this.toAffine().x; } // .x, .y will call expensive toAffine.\n get y() { return this.toAffine().y; } // Should be used with care.\n equals(other) {\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = isPoint(other); // isPoint() checks class equality\n const X1Z2 = mod(X1 * Z2), X2Z1 = mod(X2 * Z1);\n const Y1Z2 = mod(Y1 * Z2), Y2Z1 = mod(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() { return this.equals(I); }\n negate() {\n return new Point(mod(-this.ex), this.ey, this.ez, mod(-this.et));\n }\n double() {\n const { ex: X1, ey: Y1, ez: Z1 } = this; // Cost: 4M + 4S + 1*a + 6add + 1*2\n const { a } = CURVE; // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n const A = mod(X1 * X1);\n const B = mod(Y1 * Y1);\n const C = mod(2n * mod(Z1 * Z1));\n const D = mod(a * A);\n const x1y1 = X1 + Y1;\n const E = mod(mod(x1y1 * x1y1) - A - B);\n const G = D + B;\n const F = G - C;\n const H = D - B;\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n add(other) {\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; // Cost: 8M + 1*k + 8add + 1*2.\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = isPoint(other); // doesn't check if other on-curve\n const { a, d } = CURVE; // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3\n const A = mod(X1 * X2);\n const B = mod(Y1 * Y2);\n const C = mod(T1 * d * T2);\n const D = mod(Z1 * Z2);\n const E = mod((X1 + Y1) * (X2 + Y2) - A - B);\n const F = mod(D - C);\n const G = mod(D + C);\n const H = mod(B - a * A);\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n mul(n, safe = true) {\n if (n === 0n)\n return safe === true ? err('cannot multiply by 0') : I;\n if (!(typeof n === 'bigint' && 0n < n && n < N))\n err('invalid scalar, must be < L');\n if (!safe && this.is0() || n === 1n)\n return this; // safe=true bans 0. safe=false allows 0.\n if (this.equals(G))\n return wNAF(n).p; // use wNAF precomputes for base points\n let p = I, f = G; // init result point & fake point\n for (let d = this; n > 0n; d = d.double(), n >>= 1n) { // double-and-add ladder\n if (n & 1n)\n p = p.add(d); // if bit is present, add to point\n else if (safe)\n f = f.add(d); // if not, add to fake for timing safety\n }\n return p;\n }\n multiply(scalar) { return this.mul(scalar); } // Aliases for compatibilty\n clearCofactor() { return this.mul(BigInt(CURVE.h), false); } // multiply by cofactor\n isSmallOrder() { return this.clearCofactor().is0(); } // check if P is small order\n isTorsionFree() {\n let p = this.mul(N / 2n, false).double(); // ensures the point is not \"bad\".\n if (N % 2n)\n p = p.add(this); // P^(N+1) // P*N == (P*(N/2))*2+P\n return p.is0();\n }\n toAffine() {\n const { ex: x, ey: y, ez: z } = this; // (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy)\n if (this.is0())\n return { x: 0n, y: 0n }; // fast-path for zero point\n const iz = invert(z); // z^-1: invert z\n if (mod(z * iz) !== 1n)\n err('invalid inverse'); // (z * z^-1) must be 1, otherwise bad math\n return { x: mod(x * iz), y: mod(y * iz) }; // x = x*z^-1; y = y*z^-1\n }\n toRawBytes() {\n const { x, y } = this.toAffine(); // convert to affine 2d point\n const b = n2b_32LE(y); // encode number to 32 bytes\n b[31] |= x & 1n ? 0x80 : 0; // store sign in first LE byte\n return b;\n }\n toHex() { return b2h(this.toRawBytes()); } // encode to hex string\n}\nPoint.BASE = new Point(Gx, Gy, 1n, mod(Gx * Gy)); // Generator / Base point\nPoint.ZERO = new Point(0n, 1n, 1n, 0n); // Identity / Zero point\nconst { BASE: G, ZERO: I } = Point; // Generator, identity points\nconst padh = (num, pad) => num.toString(16).padStart(pad, '0');\nconst b2h = (b) => Array.from(b).map(e => padh(e, 2)).join(''); // bytes to hex\nconst h2b = (hex) => {\n const l = hex.length; // error if not string,\n if (!str(hex) || l % 2)\n err('hex invalid 1'); // or has odd length like 3, 5.\n const arr = u8n(l / 2); // create result array\n for (let i = 0; i < arr.length; i++) {\n const j = i * 2;\n const h = hex.slice(j, j + 2); // hexByte. slice is faster than substr\n const b = Number.parseInt(h, 16); // byte, created from string part\n if (Number.isNaN(b) || b < 0)\n err('hex invalid 2'); // byte must be valid 0 <= byte < 256\n arr[i] = b;\n }\n return arr;\n};\nconst n2b_32LE = (num) => h2b(padh(num, 32 * 2)).reverse(); // number to bytes LE\nconst b2n_LE = (b) => BigInt('0x' + b2h(u8n(au8(b)).reverse())); // bytes LE to num\nconst concatB = (...arrs) => {\n const r = u8n(arrs.reduce((sum, a) => sum + au8(a).length, 0)); // create u8a of summed length\n let pad = 0; // walk through each array,\n arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type\n return r;\n};\nconst invert = (num, md = P) => {\n if (num === 0n || md <= 0n)\n err('no inverse n=' + num + ' mod=' + md); // no neg exponent for now\n let a = mod(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n while (a !== 0n) { // uses euclidean gcd algorithm\n const q = b / a, r = b % a; // not constant-time\n const m = x - u * q, n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n return b === 1n ? mod(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst pow2 = (x, power) => {\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n};\nconst pow_2_252_3 = (x) => {\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n};\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\nconst uvRatio = (u, v) => {\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7).pow_p_5_8; // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n)\n x = mod(-x); // edIsNegative\n return { isValid: useRoot1 || useRoot2, value: x };\n};\nconst modL_LE = (hash) => mod(b2n_LE(hash), N); // modulo L; but little-endian\nlet _shaS;\nconst sha512a = (...m) => etc.sha512Async(...m); // Async SHA512\nconst sha512s = (...m) => // Sync SHA512, not set by default\n typeof _shaS === 'function' ? _shaS(...m) : err('etc.sha512Sync not set');\nconst hash2extK = (hashed) => {\n const head = hashed.slice(0, 32); // slice creates a copy, unlike subarray\n head[0] &= 248; // Clamp bits: 0b1111_1000,\n head[31] &= 127; // 0b0111_1111,\n head[31] |= 64; // 0b0100_0000\n const prefix = hashed.slice(32, 64); // private key \"prefix\"\n const scalar = modL_LE(head); // modular division over curve order\n const point = G.mul(scalar); // public key point\n const pointBytes = point.toRawBytes(); // point serialized to Uint8Array\n return { head, prefix, scalar, point, pointBytes };\n};\n// RFC8032 5.1.5; getPublicKey async, sync. Hash priv key and extract point.\nconst getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, 32)).then(hash2extK);\nconst getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, 32)));\nconst getPublicKeyAsync = (priv) => getExtendedPublicKeyAsync(priv).then(p => p.pointBytes);\nconst getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;\nfunction hashFinish(asynchronous, res) {\n if (asynchronous)\n return sha512a(res.hashable).then(res.finish);\n return res.finish(sha512s(res.hashable));\n}\nconst _sign = (e, rBytes, msg) => {\n const { pointBytes: P, scalar: s } = e;\n const r = modL_LE(rBytes); // r was created outside, reduce it modulo L\n const R = G.mul(r).toRawBytes(); // R = [r]B\n const hashable = concatB(R, P, msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n const S = mod(r + modL_LE(hashed) * s, N); // S = (r + k * s) mod L; 0 <= s < l\n return au8(concatB(R, n2b_32LE(S)), 64); // 64-byte sig: 32b R.x + 32b LE(S)\n };\n return { hashable, finish };\n};\nconst signAsync = async (msg, privKey) => {\n const m = toU8(msg); // RFC8032 5.1.6: sign msg with key async\n const e = await getExtendedPublicKeyAsync(privKey); // pub,prfx\n const rBytes = await sha512a(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinish(true, _sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\nconst sign = (msg, privKey) => {\n const m = toU8(msg); // RFC8032 5.1.6: sign msg with key sync\n const e = getExtendedPublicKey(privKey); // pub,prfx\n const rBytes = sha512s(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinish(false, _sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\nconst _verify = (sig, msg, pub) => {\n msg = toU8(msg); // Message hex str/Bytes\n sig = toU8(sig, 64); // Signature hex str/Bytes, must be 64 bytes\n const A = Point.fromHex(pub, false); // public key A decoded\n const R = Point.fromHex(sig.slice(0, 32), false); // 0 <= R < 2^256: ZIP215 R can be >= P\n const s = b2n_LE(sig.slice(32, 64)); // Decode second half as an integer S\n const SB = G.mul(s, false); // in the range 0 <= s < L\n const hashable = concatB(R.toRawBytes(), A.toRawBytes(), msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n const k = modL_LE(hashed); // decode in little-endian, modulo L\n const RkA = R.add(A.mul(k, false)); // [8]R + [8][k]A'\n return RkA.add(SB.negate()).clearCofactor().is0(); // [8][S]B = [8]R + [8][k]A'\n };\n return { hashable, finish };\n};\n// RFC8032 5.1.7: verification async, sync\nconst verifyAsync = async (s, m, p) => hashFinish(true, _verify(s, m, p));\nconst verify = (s, m, p) => hashFinish(false, _verify(s, m, p));\nconst cr = () => // We support: 1) browsers 2) node.js 19+\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\nconst etc = {\n bytesToHex: b2h, hexToBytes: h2b, concatBytes: concatB,\n mod, invert,\n randomBytes: (len) => {\n const crypto = cr(); // Can be shimmed in node.js <= 18 to prevent error:\n // import { webcrypto } from 'node:crypto';\n // if (!globalThis.crypto) globalThis.crypto = webcrypto;\n if (!crypto)\n err('crypto.getRandomValues must be defined');\n return crypto.getRandomValues(u8n(len));\n },\n sha512Async: async (...messages) => {\n const crypto = cr();\n if (!crypto)\n err('crypto.subtle or etc.sha512Async must be defined');\n const m = concatB(...messages);\n return u8n(await crypto.subtle.digest('SHA-512', m.buffer));\n },\n sha512Sync: undefined, // Actual logic below\n};\nObject.defineProperties(etc, { sha512Sync: {\n configurable: false, get() { return _shaS; }, set(f) { if (!_shaS)\n _shaS = f; },\n } });\nconst utils = {\n getExtendedPublicKeyAsync, getExtendedPublicKey,\n randomPrivateKey: () => etc.randomBytes(32),\n precompute(w = 8, p = G) { p.multiply(3n); return p; }, // no-op\n};\nconst W = 8; // Precomputes-related code. W = window size\nconst precompute = () => {\n const points = []; // 10x sign(), 2x verify(). To achieve this,\n const windows = 256 / W + 1; // app needs to spend 40ms+ to calculate\n let p = G, b = p; // a lot of points related to base point G.\n for (let w = 0; w < windows; w++) { // Points are stored in array and used\n b = p; // any time Gx multiplication is done.\n points.push(b); // They consume 16-32 MiB of RAM.\n for (let i = 1; i < 2 ** (W - 1); i++) {\n b = b.add(p);\n points.push(b);\n }\n p = b.double(); // Precomputes don't speed-up getSharedKey,\n } // which multiplies user point by scalar,\n return points; // when precomputes are using base point\n};\nconst wNAF = (n) => {\n // Compared to other point mult methods,\n const comp = Gpows || (Gpows = precompute()); // stores 2x less points using subtraction\n const neg = (cnd, p) => { let n = p.negate(); return cnd ? n : p; }; // negate\n let p = I, f = G; // f must be G, or could become I in the end\n const windows = 1 + 256 / W; // W=8 17 windows\n const wsize = 2 ** (W - 1); // W=8 128 window size\n const mask = BigInt(2 ** W - 1); // W=8 will create mask 0b11111111\n const maxNum = 2 ** W; // W=8 256\n const shiftBy = BigInt(W); // W=8 8\n for (let w = 0; w < windows; w++) {\n const off = w * wsize;\n let wbits = Number(n & mask); // extract W bits.\n n >>= shiftBy; // shift number by W bits.\n if (wbits > wsize) {\n wbits -= maxNum;\n n += 1n;\n } // split if bits > max: +224 => 256-32\n const off1 = off, off2 = off + Math.abs(wbits) - 1; // offsets, evaluate both\n const cnd1 = w % 2 !== 0, cnd2 = wbits < 0; // conditions, evaluate both\n if (wbits === 0) {\n f = f.add(neg(cnd1, comp[off1])); // bits are 0: add garbage to fake point\n }\n else { // ^ can't add off2, off2 = I\n p = p.add(neg(cnd2, comp[off2])); // bits are 1: add to result point\n }\n }\n return { p, f }; // return both real and fake points for JIT\n}; // !! you can disable precomputes by commenting-out call of the wNAF() inside Point#mul()\nexport { getPublicKey, getPublicKeyAsync, sign, verify, // Remove the export to easily use in REPL\nsignAsync, verifyAsync, CURVE, etc, utils, Point as ExtendedPoint }; // envs like browser console\n","/* The MIT License (MIT)\n *\n * Copyright 2015-2018 Peter A. Bigot\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n/**\n * Support for translating between Uint8Array instances and JavaScript\n * native types.\n *\n * {@link module:Layout~Layout|Layout} is the basis of a class\n * hierarchy that associates property names with sequences of encoded\n * bytes.\n *\n * Layouts are supported for these scalar (numeric) types:\n * * {@link module:Layout~UInt|Unsigned integers in little-endian\n * format} with {@link module:Layout.u8|8-bit}, {@link\n * module:Layout.u16|16-bit}, {@link module:Layout.u24|24-bit},\n * {@link module:Layout.u32|32-bit}, {@link\n * module:Layout.u40|40-bit}, and {@link module:Layout.u48|48-bit}\n * representation ranges;\n * * {@link module:Layout~UIntBE|Unsigned integers in big-endian\n * format} with {@link module:Layout.u16be|16-bit}, {@link\n * module:Layout.u24be|24-bit}, {@link module:Layout.u32be|32-bit},\n * {@link module:Layout.u40be|40-bit}, and {@link\n * module:Layout.u48be|48-bit} representation ranges;\n * * {@link module:Layout~Int|Signed integers in little-endian\n * format} with {@link module:Layout.s8|8-bit}, {@link\n * module:Layout.s16|16-bit}, {@link module:Layout.s24|24-bit},\n * {@link module:Layout.s32|32-bit}, {@link\n * module:Layout.s40|40-bit}, and {@link module:Layout.s48|48-bit}\n * representation ranges;\n * * {@link module:Layout~IntBE|Signed integers in big-endian format}\n * with {@link module:Layout.s16be|16-bit}, {@link\n * module:Layout.s24be|24-bit}, {@link module:Layout.s32be|32-bit},\n * {@link module:Layout.s40be|40-bit}, and {@link\n * module:Layout.s48be|48-bit} representation ranges;\n * * 64-bit integral values that decode to an exact (if magnitude is\n * less than 2^53) or nearby integral Number in {@link\n * module:Layout.nu64|unsigned little-endian}, {@link\n * module:Layout.nu64be|unsigned big-endian}, {@link\n * module:Layout.ns64|signed little-endian}, and {@link\n * module:Layout.ns64be|unsigned big-endian} encodings;\n * * 32-bit floating point values with {@link\n * module:Layout.f32|little-endian} and {@link\n * module:Layout.f32be|big-endian} representations;\n * * 64-bit floating point values with {@link\n * module:Layout.f64|little-endian} and {@link\n * module:Layout.f64be|big-endian} representations;\n * * {@link module:Layout.const|Constants} that take no space in the\n * encoded expression.\n *\n * and for these aggregate types:\n * * {@link module:Layout.seq|Sequence}s of instances of a {@link\n * module:Layout~Layout|Layout}, with JavaScript representation as\n * an Array and constant or data-dependent {@link\n * module:Layout~Sequence#count|length};\n * * {@link module:Layout.struct|Structure}s that aggregate a\n * heterogeneous sequence of {@link module:Layout~Layout|Layout}\n * instances, with JavaScript representation as an Object;\n * * {@link module:Layout.union|Union}s that support multiple {@link\n * module:Layout~VariantLayout|variant layouts} over a fixed\n * (padded) or variable (not padded) span of bytes, using an\n * unsigned integer at the start of the data or a separate {@link\n * module:Layout.unionLayoutDiscriminator|layout element} to\n * determine which layout to use when interpreting the buffer\n * contents;\n * * {@link module:Layout.bits|BitStructure}s that contain a sequence\n * of individual {@link\n * module:Layout~BitStructure#addField|BitField}s packed into an 8,\n * 16, 24, or 32-bit unsigned integer starting at the least- or\n * most-significant bit;\n * * {@link module:Layout.cstr|C strings} of varying length;\n * * {@link module:Layout.blob|Blobs} of fixed- or variable-{@link\n * module:Layout~Blob#length|length} raw data.\n *\n * All {@link module:Layout~Layout|Layout} instances are immutable\n * after construction, to prevent internal state from becoming\n * inconsistent.\n *\n * @local Layout\n * @local ExternalLayout\n * @local GreedyCount\n * @local OffsetLayout\n * @local UInt\n * @local UIntBE\n * @local Int\n * @local IntBE\n * @local NearUInt64\n * @local NearUInt64BE\n * @local NearInt64\n * @local NearInt64BE\n * @local Float\n * @local FloatBE\n * @local Double\n * @local DoubleBE\n * @local Sequence\n * @local Structure\n * @local UnionDiscriminator\n * @local UnionLayoutDiscriminator\n * @local Union\n * @local VariantLayout\n * @local BitStructure\n * @local BitField\n * @local Boolean\n * @local Blob\n * @local CString\n * @local Constant\n * @local bindConstructorLayout\n * @module Layout\n * @license MIT\n * @author Peter A. Bigot\n * @see {@link https://github.com/pabigot/buffer-layout|buffer-layout on GitHub}\n */\n'use strict';\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.s16 = exports.s8 = exports.nu64be = exports.u48be = exports.u40be = exports.u32be = exports.u24be = exports.u16be = exports.nu64 = exports.u48 = exports.u40 = exports.u32 = exports.u24 = exports.u16 = exports.u8 = exports.offset = exports.greedy = exports.Constant = exports.UTF8 = exports.CString = exports.Blob = exports.Boolean = exports.BitField = exports.BitStructure = exports.VariantLayout = exports.Union = exports.UnionLayoutDiscriminator = exports.UnionDiscriminator = exports.Structure = exports.Sequence = exports.DoubleBE = exports.Double = exports.FloatBE = exports.Float = exports.NearInt64BE = exports.NearInt64 = exports.NearUInt64BE = exports.NearUInt64 = exports.IntBE = exports.Int = exports.UIntBE = exports.UInt = exports.OffsetLayout = exports.GreedyCount = exports.ExternalLayout = exports.bindConstructorLayout = exports.nameWithProperty = exports.Layout = exports.uint8ArrayToBuffer = exports.checkUint8Array = void 0;\nexports.constant = exports.utf8 = exports.cstr = exports.blob = exports.unionLayoutDiscriminator = exports.union = exports.seq = exports.bits = exports.struct = exports.f64be = exports.f64 = exports.f32be = exports.f32 = exports.ns64be = exports.s48be = exports.s40be = exports.s32be = exports.s24be = exports.s16be = exports.ns64 = exports.s48 = exports.s40 = exports.s32 = exports.s24 = void 0;\nconst buffer_1 = require(\"buffer\");\n/* Check if a value is a Uint8Array.\n *\n * @ignore */\nfunction checkUint8Array(b) {\n if (!(b instanceof Uint8Array)) {\n throw new TypeError('b must be a Uint8Array');\n }\n}\nexports.checkUint8Array = checkUint8Array;\n/* Create a Buffer instance from a Uint8Array.\n *\n * @ignore */\nfunction uint8ArrayToBuffer(b) {\n checkUint8Array(b);\n return buffer_1.Buffer.from(b.buffer, b.byteOffset, b.length);\n}\nexports.uint8ArrayToBuffer = uint8ArrayToBuffer;\n/**\n * Base class for layout objects.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * Layout#encode|encode} or {@link Layout#decode|decode} functions.\n *\n * @param {Number} span - Initializer for {@link Layout#span|span}. The\n * parameter must be an integer; a negative value signifies that the\n * span is {@link Layout#getSpan|value-specific}.\n *\n * @param {string} [property] - Initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n */\nclass Layout {\n constructor(span, property) {\n if (!Number.isInteger(span)) {\n throw new TypeError('span must be an integer');\n }\n /** The span of the layout in bytes.\n *\n * Positive values are generally expected.\n *\n * Zero will only appear in {@link Constant}s and in {@link\n * Sequence}s where the {@link Sequence#count|count} is zero.\n *\n * A negative value indicates that the span is value-specific, and\n * must be obtained using {@link Layout#getSpan|getSpan}. */\n this.span = span;\n /** The property name used when this layout is represented in an\n * Object.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances. If left undefined the span of the unnamed layout will\n * be treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n /** Function to create an Object into which decoded properties will\n * be written.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances, which means:\n * * {@link Structure}\n * * {@link Union}\n * * {@link VariantLayout}\n * * {@link BitStructure}\n *\n * If left undefined the JavaScript representation of these layouts\n * will be Object instances.\n *\n * See {@link bindConstructorLayout}.\n */\n makeDestinationObject() {\n return {};\n }\n /**\n * Calculate the span of a specific instance of a layout.\n *\n * @param {Uint8Array} b - the buffer that contains an encoded instance.\n *\n * @param {Number} [offset] - the offset at which the encoded instance\n * starts. If absent a zero offset is inferred.\n *\n * @return {Number} - the number of bytes covered by the layout\n * instance. If this method is not overridden in a subclass the\n * definition-time constant {@link Layout#span|span} will be\n * returned.\n *\n * @throws {RangeError} - if the length of the value cannot be\n * determined.\n */\n getSpan(b, offset) {\n if (0 > this.span) {\n throw new RangeError('indeterminate span');\n }\n return this.span;\n }\n /**\n * Replicate the layout using a new property.\n *\n * This function must be used to get a structurally-equivalent layout\n * with a different name since all {@link Layout} instances are\n * immutable.\n *\n * **NOTE** This is a shallow copy. All fields except {@link\n * Layout#property|property} are strictly equal to the origin layout.\n *\n * @param {String} property - the value for {@link\n * Layout#property|property} in the replica.\n *\n * @returns {Layout} - the copy with {@link Layout#property|property}\n * set to `property`.\n */\n replicate(property) {\n const rv = Object.create(this.constructor.prototype);\n Object.assign(rv, this);\n rv.property = property;\n return rv;\n }\n /**\n * Create an object from layout properties and an array of values.\n *\n * **NOTE** This function returns `undefined` if invoked on a layout\n * that does not return its value as an Object. Objects are\n * returned for things that are a {@link Structure}, which includes\n * {@link VariantLayout|variant layouts} if they are structures, and\n * excludes {@link Union}s. If you want this feature for a union\n * you must use {@link Union.getVariant|getVariant} to select the\n * desired layout.\n *\n * @param {Array} values - an array of values that correspond to the\n * default order for properties. As with {@link Layout#decode|decode}\n * layout elements that have no property name are skipped when\n * iterating over the array values. Only the top-level properties are\n * assigned; arguments are not assigned to properties of contained\n * layouts. Any unused values are ignored.\n *\n * @return {(Object|undefined)}\n */\n fromArray(values) {\n return undefined;\n }\n}\nexports.Layout = Layout;\n/* Provide text that carries a name (such as for a function that will\n * be throwing an error) annotated with the property of a given layout\n * (such as one for which the value was unacceptable).\n *\n * @ignore */\nfunction nameWithProperty(name, lo) {\n if (lo.property) {\n return name + '[' + lo.property + ']';\n }\n return name;\n}\nexports.nameWithProperty = nameWithProperty;\n/**\n * Augment a class so that instances can be encoded/decoded using a\n * given layout.\n *\n * Calling this function couples `Class` with `layout` in several ways:\n *\n * * `Class.layout_` becomes a static member property equal to `layout`;\n * * `layout.boundConstructor_` becomes a static member property equal\n * to `Class`;\n * * The {@link Layout#makeDestinationObject|makeDestinationObject()}\n * property of `layout` is set to a function that returns a `new\n * Class()`;\n * * `Class.decode(b, offset)` becomes a static member function that\n * delegates to {@link Layout#decode|layout.decode}. The\n * synthesized function may be captured and extended.\n * * `Class.prototype.encode(b, offset)` provides an instance member\n * function that delegates to {@link Layout#encode|layout.encode}\n * with `src` set to `this`. The synthesized function may be\n * captured and extended, but when the extension is invoked `this`\n * must be explicitly bound to the instance.\n *\n * @param {class} Class - a JavaScript class with a nullary\n * constructor.\n *\n * @param {Layout} layout - the {@link Layout} instance used to encode\n * instances of `Class`.\n */\n// `Class` must be a constructor Function, but the assignment of a `layout_` property to it makes it difficult to type\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction bindConstructorLayout(Class, layout) {\n if ('function' !== typeof Class) {\n throw new TypeError('Class must be constructor');\n }\n if (Object.prototype.hasOwnProperty.call(Class, 'layout_')) {\n throw new Error('Class is already bound to a layout');\n }\n if (!(layout && (layout instanceof Layout))) {\n throw new TypeError('layout must be a Layout');\n }\n if (Object.prototype.hasOwnProperty.call(layout, 'boundConstructor_')) {\n throw new Error('layout is already bound to a constructor');\n }\n Class.layout_ = layout;\n layout.boundConstructor_ = Class;\n layout.makeDestinationObject = (() => new Class());\n Object.defineProperty(Class.prototype, 'encode', {\n value(b, offset) {\n return layout.encode(this, b, offset);\n },\n writable: true,\n });\n Object.defineProperty(Class, 'decode', {\n value(b, offset) {\n return layout.decode(b, offset);\n },\n writable: true,\n });\n}\nexports.bindConstructorLayout = bindConstructorLayout;\n/**\n * An object that behaves like a layout but does not consume space\n * within its containing layout.\n *\n * This is primarily used to obtain metadata about a member, such as a\n * {@link OffsetLayout} that can provide data about a {@link\n * Layout#getSpan|value-specific span}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support {@link\n * ExternalLayout#isCount|isCount} or other {@link Layout} functions.\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n * @augments {Layout}\n */\nclass ExternalLayout extends Layout {\n /**\n * Return `true` iff the external layout decodes to an unsigned\n * integer layout.\n *\n * In that case it can be used as the source of {@link\n * Sequence#count|Sequence counts}, {@link Blob#length|Blob lengths},\n * or as {@link UnionLayoutDiscriminator#layout|external union\n * discriminators}.\n *\n * @abstract\n */\n isCount() {\n throw new Error('ExternalLayout is abstract');\n }\n}\nexports.ExternalLayout = ExternalLayout;\n/**\n * An {@link ExternalLayout} that determines its {@link\n * Layout#decode|value} based on offset into and length of the buffer\n * on which it is invoked.\n *\n * *Factory*: {@link module:Layout.greedy|greedy}\n *\n * @param {Number} [elementSpan] - initializer for {@link\n * GreedyCount#elementSpan|elementSpan}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {ExternalLayout}\n */\nclass GreedyCount extends ExternalLayout {\n constructor(elementSpan = 1, property) {\n if ((!Number.isInteger(elementSpan)) || (0 >= elementSpan)) {\n throw new TypeError('elementSpan must be a (positive) integer');\n }\n super(-1, property);\n /** The layout for individual elements of the sequence. The value\n * must be a positive integer. If not provided, the value will be\n * 1. */\n this.elementSpan = elementSpan;\n }\n /** @override */\n isCount() {\n return true;\n }\n /** @override */\n decode(b, offset = 0) {\n checkUint8Array(b);\n const rem = b.length - offset;\n return Math.floor(rem / this.elementSpan);\n }\n /** @override */\n encode(src, b, offset) {\n return 0;\n }\n}\nexports.GreedyCount = GreedyCount;\n/**\n * An {@link ExternalLayout} that supports accessing a {@link Layout}\n * at a fixed offset from the start of another Layout. The offset may\n * be before, within, or after the base layout.\n *\n * *Factory*: {@link module:Layout.offset|offset}\n *\n * @param {Layout} layout - initializer for {@link\n * OffsetLayout#layout|layout}, modulo `property`.\n *\n * @param {Number} [offset] - Initializes {@link\n * OffsetLayout#offset|offset}. Defaults to zero.\n *\n * @param {string} [property] - Optional new property name for a\n * {@link Layout#replicate| replica} of `layout` to be used as {@link\n * OffsetLayout#layout|layout}. If not provided the `layout` is used\n * unchanged.\n *\n * @augments {Layout}\n */\nclass OffsetLayout extends ExternalLayout {\n constructor(layout, offset = 0, property) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n if (!Number.isInteger(offset)) {\n throw new TypeError('offset must be integer or undefined');\n }\n super(layout.span, property || layout.property);\n /** The subordinated layout. */\n this.layout = layout;\n /** The location of {@link OffsetLayout#layout} relative to the\n * start of another layout.\n *\n * The value may be positive or negative, but an error will thrown\n * if at the point of use it goes outside the span of the Uint8Array\n * being accessed. */\n this.offset = offset;\n }\n /** @override */\n isCount() {\n return ((this.layout instanceof UInt)\n || (this.layout instanceof UIntBE));\n }\n /** @override */\n decode(b, offset = 0) {\n return this.layout.decode(b, offset + this.offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n return this.layout.encode(src, b, offset + this.offset);\n }\n}\nexports.OffsetLayout = OffsetLayout;\n/**\n * Represent an unsigned integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.u8|u8}, {@link\n * module:Layout.u16|u16}, {@link module:Layout.u24|u24}, {@link\n * module:Layout.u32|u32}, {@link module:Layout.u40|u40}, {@link\n * module:Layout.u48|u48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UInt extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readUIntLE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeUIntLE(src, offset, this.span);\n return this.span;\n }\n}\nexports.UInt = UInt;\n/**\n * Represent an unsigned integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.u8be|u8be}, {@link\n * module:Layout.u16be|u16be}, {@link module:Layout.u24be|u24be},\n * {@link module:Layout.u32be|u32be}, {@link\n * module:Layout.u40be|u40be}, {@link module:Layout.u48be|u48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UIntBE extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readUIntBE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeUIntBE(src, offset, this.span);\n return this.span;\n }\n}\nexports.UIntBE = UIntBE;\n/**\n * Represent a signed integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.s8|s8}, {@link\n * module:Layout.s16|s16}, {@link module:Layout.s24|s24}, {@link\n * module:Layout.s32|s32}, {@link module:Layout.s40|s40}, {@link\n * module:Layout.s48|s48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Int extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readIntLE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeIntLE(src, offset, this.span);\n return this.span;\n }\n}\nexports.Int = Int;\n/**\n * Represent a signed integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.s8be|s8be}, {@link\n * module:Layout.s16be|s16be}, {@link module:Layout.s24be|s24be},\n * {@link module:Layout.s32be|s32be}, {@link\n * module:Layout.s40be|s40be}, {@link module:Layout.s48be|s48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass IntBE extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readIntBE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeIntBE(src, offset, this.span);\n return this.span;\n }\n}\nexports.IntBE = IntBE;\nconst V2E32 = Math.pow(2, 32);\n/* True modulus high and low 32-bit words, where low word is always\n * non-negative. */\nfunction divmodInt64(src) {\n const hi32 = Math.floor(src / V2E32);\n const lo32 = src - (hi32 * V2E32);\n return { hi32, lo32 };\n}\n/* Reconstruct Number from quotient and non-negative remainder */\nfunction roundedInt64(hi32, lo32) {\n return hi32 * V2E32 + lo32;\n}\n/**\n * Represent an unsigned 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64|nu64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const lo32 = buffer.readUInt32LE(offset);\n const hi32 = buffer.readUInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeUInt32LE(split.lo32, offset);\n buffer.writeUInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\nexports.NearUInt64 = NearUInt64;\n/**\n * Represent an unsigned 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64be|nu64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const hi32 = buffer.readUInt32BE(offset);\n const lo32 = buffer.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeUInt32BE(split.hi32, offset);\n buffer.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\nexports.NearUInt64BE = NearUInt64BE;\n/**\n * Represent a signed 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64|ns64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const lo32 = buffer.readUInt32LE(offset);\n const hi32 = buffer.readInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeUInt32LE(split.lo32, offset);\n buffer.writeInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\nexports.NearInt64 = NearInt64;\n/**\n * Represent a signed 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64be|ns64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const hi32 = buffer.readInt32BE(offset);\n const lo32 = buffer.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeInt32BE(split.hi32, offset);\n buffer.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\nexports.NearInt64BE = NearInt64BE;\n/**\n * Represent a 32-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f32|f32}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Float extends Layout {\n constructor(property) {\n super(4, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readFloatLE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeFloatLE(src, offset);\n return 4;\n }\n}\nexports.Float = Float;\n/**\n * Represent a 32-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f32be|f32be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass FloatBE extends Layout {\n constructor(property) {\n super(4, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readFloatBE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeFloatBE(src, offset);\n return 4;\n }\n}\nexports.FloatBE = FloatBE;\n/**\n * Represent a 64-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f64|f64}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Double extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readDoubleLE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeDoubleLE(src, offset);\n return 8;\n }\n}\nexports.Double = Double;\n/**\n * Represent a 64-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f64be|f64be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass DoubleBE extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readDoubleBE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeDoubleBE(src, offset);\n return 8;\n }\n}\nexports.DoubleBE = DoubleBE;\n/**\n * Represent a contiguous sequence of a specific layout as an Array.\n *\n * *Factory*: {@link module:Layout.seq|seq}\n *\n * @param {Layout} elementLayout - initializer for {@link\n * Sequence#elementLayout|elementLayout}.\n *\n * @param {(Number|ExternalLayout)} count - initializer for {@link\n * Sequence#count|count}. The parameter must be either a positive\n * integer or an instance of {@link ExternalLayout}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Sequence extends Layout {\n constructor(elementLayout, count, property) {\n if (!(elementLayout instanceof Layout)) {\n throw new TypeError('elementLayout must be a Layout');\n }\n if (!(((count instanceof ExternalLayout) && count.isCount())\n || (Number.isInteger(count) && (0 <= count)))) {\n throw new TypeError('count must be non-negative integer '\n + 'or an unsigned integer ExternalLayout');\n }\n let span = -1;\n if ((!(count instanceof ExternalLayout))\n && (0 < elementLayout.span)) {\n span = count * elementLayout.span;\n }\n super(span, property);\n /** The layout for individual elements of the sequence. */\n this.elementLayout = elementLayout;\n /** The number of elements in the sequence.\n *\n * This will be either a non-negative integer or an instance of\n * {@link ExternalLayout} for which {@link\n * ExternalLayout#isCount|isCount()} is `true`. */\n this.count = count;\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n return this.span;\n }\n let span = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n if (0 < this.elementLayout.span) {\n span = count * this.elementLayout.span;\n }\n else {\n let idx = 0;\n while (idx < count) {\n span += this.elementLayout.getSpan(b, offset + span);\n ++idx;\n }\n }\n return span;\n }\n /** @override */\n decode(b, offset = 0) {\n const rv = [];\n let i = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n while (i < count) {\n rv.push(this.elementLayout.decode(b, offset));\n offset += this.elementLayout.getSpan(b, offset);\n i += 1;\n }\n return rv;\n }\n /** Implement {@link Layout#encode|encode} for {@link Sequence}.\n *\n * **NOTE** If `src` is shorter than {@link Sequence#count|count} then\n * the unused space in the buffer is left unchanged. If `src` is\n * longer than {@link Sequence#count|count} the unneeded elements are\n * ignored.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset = 0) {\n const elo = this.elementLayout;\n const span = src.reduce((span, v) => {\n return span + elo.encode(v, b, offset + span);\n }, 0);\n if (this.count instanceof ExternalLayout) {\n this.count.encode(src.length, b, offset);\n }\n return span;\n }\n}\nexports.Sequence = Sequence;\n/**\n * Represent a contiguous sequence of arbitrary layout elements as an\n * Object.\n *\n * *Factory*: {@link module:Layout.struct|struct}\n *\n * **NOTE** The {@link Layout#span|span} of the structure is variable\n * if any layout in {@link Structure#fields|fields} has a variable\n * span. When {@link Layout#encode|encoding} we must have a value for\n * all variable-length fields, or we wouldn't be able to figure out\n * how much space to use for storage. We can only identify the value\n * for a field when it has a {@link Layout#property|property}. As\n * such, although a structure may contain both unnamed fields and\n * variable-length fields, it cannot contain an unnamed\n * variable-length field.\n *\n * @param {Layout[]} fields - initializer for {@link\n * Structure#fields|fields}. An error is raised if this contains a\n * variable-length field for which a {@link Layout#property|property}\n * is not defined.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @param {Boolean} [decodePrefixes] - initializer for {@link\n * Structure#decodePrefixes|property}.\n *\n * @throws {Error} - if `fields` contains an unnamed variable-length\n * layout.\n *\n * @augments {Layout}\n */\nclass Structure extends Layout {\n constructor(fields, property, decodePrefixes) {\n if (!(Array.isArray(fields)\n && fields.reduce((acc, v) => acc && (v instanceof Layout), true))) {\n throw new TypeError('fields must be array of Layout instances');\n }\n if (('boolean' === typeof property)\n && (undefined === decodePrefixes)) {\n decodePrefixes = property;\n property = undefined;\n }\n /* Verify absence of unnamed variable-length fields. */\n for (const fd of fields) {\n if ((0 > fd.span)\n && (undefined === fd.property)) {\n throw new Error('fields cannot contain unnamed variable-length layout');\n }\n }\n let span = -1;\n try {\n span = fields.reduce((span, fd) => span + fd.getSpan(), 0);\n }\n catch (e) {\n // ignore error\n }\n super(span, property);\n /** The sequence of {@link Layout} values that comprise the\n * structure.\n *\n * The individual elements need not be the same type, and may be\n * either scalar or aggregate layouts. If a member layout leaves\n * its {@link Layout#property|property} undefined the\n * corresponding region of the buffer associated with the element\n * will not be mutated.\n *\n * @type {Layout[]} */\n this.fields = fields;\n /** Control behavior of {@link Layout#decode|decode()} given short\n * buffers.\n *\n * In some situations a structure many be extended with additional\n * fields over time, with older installations providing only a\n * prefix of the full structure. If this property is `true`\n * decoding will accept those buffers and leave subsequent fields\n * undefined, as long as the buffer ends at a field boundary.\n * Defaults to `false`. */\n this.decodePrefixes = !!decodePrefixes;\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n return this.span;\n }\n let span = 0;\n try {\n span = this.fields.reduce((span, fd) => {\n const fsp = fd.getSpan(b, offset);\n offset += fsp;\n return span + fsp;\n }, 0);\n }\n catch (e) {\n throw new RangeError('indeterminate span');\n }\n return span;\n }\n /** @override */\n decode(b, offset = 0) {\n checkUint8Array(b);\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(b, offset);\n }\n offset += fd.getSpan(b, offset);\n if (this.decodePrefixes\n && (b.length === offset)) {\n break;\n }\n }\n return dest;\n }\n /** Implement {@link Layout#encode|encode} for {@link Structure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the buffer is\n * left unmodified. */\n encode(src, b, offset = 0) {\n const firstOffset = offset;\n let lastOffset = 0;\n let lastWrote = 0;\n for (const fd of this.fields) {\n let span = fd.span;\n lastWrote = (0 < span) ? span : 0;\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n lastWrote = fd.encode(fv, b, offset);\n if (0 > span) {\n /* Read the as-encoded span, which is not necessarily the\n * same as what we wrote. */\n span = fd.getSpan(b, offset);\n }\n }\n }\n lastOffset = offset;\n offset += span;\n }\n /* Use (lastOffset + lastWrote) instead of offset because the last\n * item may have had a dynamic length and we don't want to include\n * the padding between it and the end of the space reserved for\n * it. */\n return (lastOffset + lastWrote) - firstOffset;\n }\n /** @override */\n fromArray(values) {\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if ((undefined !== fd.property)\n && (0 < values.length)) {\n dest[fd.property] = values.shift();\n }\n }\n return dest;\n }\n /**\n * Get access to the layout of a given property.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Layout} - the layout associated with `property`, or\n * undefined if there is no such property.\n */\n layoutFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n return undefined;\n }\n /**\n * Get the offset of a structure member.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Number} - the offset in bytes to the start of `property`\n * within the structure, or undefined if `property` is not a field\n * within the structure. If the property is a member but follows a\n * variable-length structure member a negative number will be\n * returned.\n */\n offsetOf(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n let offset = 0;\n for (const fd of this.fields) {\n if (fd.property === property) {\n return offset;\n }\n if (0 > fd.span) {\n offset = -1;\n }\n else if (0 <= offset) {\n offset += fd.span;\n }\n }\n return undefined;\n }\n}\nexports.Structure = Structure;\n/**\n * An object that can provide a {@link\n * Union#discriminator|discriminator} API for {@link Union}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * UnionDiscriminator#encode|encode} or {@link\n * UnionDiscriminator#decode|decode} functions.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}.\n *\n * @abstract\n */\nclass UnionDiscriminator {\n constructor(property) {\n /** The {@link Layout#property|property} to be used when the\n * discriminator is referenced in isolation (generally when {@link\n * Union#decode|Union decode} cannot delegate to a specific\n * variant). */\n this.property = property;\n }\n /** Analog to {@link Layout#decode|Layout decode} for union discriminators.\n *\n * The implementation of this method need not reference the buffer if\n * variant information is available through other means. */\n decode(b, offset) {\n throw new Error('UnionDiscriminator is abstract');\n }\n /** Analog to {@link Layout#decode|Layout encode} for union discriminators.\n *\n * The implementation of this method need not store the value if\n * variant information is maintained through other means. */\n encode(src, b, offset) {\n throw new Error('UnionDiscriminator is abstract');\n }\n}\nexports.UnionDiscriminator = UnionDiscriminator;\n/**\n * An object that can provide a {@link\n * UnionDiscriminator|discriminator API} for {@link Union} using an\n * unsigned integral {@link Layout} instance located either inside or\n * outside the union.\n *\n * @param {ExternalLayout} layout - initializes {@link\n * UnionLayoutDiscriminator#layout|layout}. Must satisfy {@link\n * ExternalLayout#isCount|isCount()}.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}, superseding the property\n * from `layout`, but defaulting to `variant` if neither `property`\n * nor layout provide a property name.\n *\n * @augments {UnionDiscriminator}\n */\nclass UnionLayoutDiscriminator extends UnionDiscriminator {\n constructor(layout, property) {\n if (!((layout instanceof ExternalLayout)\n && layout.isCount())) {\n throw new TypeError('layout must be an unsigned integer ExternalLayout');\n }\n super(property || layout.property || 'variant');\n /** The {@link ExternalLayout} used to access the discriminator\n * value. */\n this.layout = layout;\n }\n /** Delegate decoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n decode(b, offset) {\n return this.layout.decode(b, offset);\n }\n /** Delegate encoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n encode(src, b, offset) {\n return this.layout.encode(src, b, offset);\n }\n}\nexports.UnionLayoutDiscriminator = UnionLayoutDiscriminator;\n/**\n * Represent any number of span-compatible layouts.\n *\n * *Factory*: {@link module:Layout.union|union}\n *\n * If the union has a {@link Union#defaultLayout|default layout} that\n * layout must have a non-negative {@link Layout#span|span}. The span\n * of a fixed-span union includes its {@link\n * Union#discriminator|discriminator} if the variant is a {@link\n * Union#usesPrefixDiscriminator|prefix of the union}, plus the span\n * of its {@link Union#defaultLayout|default layout}.\n *\n * If the union does not have a default layout then the encoded span\n * of the union depends on the encoded span of its variant (which may\n * be fixed or variable).\n *\n * {@link VariantLayout#layout|Variant layout}s are added through\n * {@link Union#addVariant|addVariant}. If the union has a default\n * layout, the span of the {@link VariantLayout#layout|layout\n * contained by the variant} must not exceed the span of the {@link\n * Union#defaultLayout|default layout} (minus the span of a {@link\n * Union#usesPrefixDiscriminator|prefix disriminator}, if used). The\n * span of the variant will equal the span of the union itself.\n *\n * The variant for a buffer can only be identified from the {@link\n * Union#discriminator|discriminator} {@link\n * UnionDiscriminator#property|property} (in the case of the {@link\n * Union#defaultLayout|default layout}), or by using {@link\n * Union#getVariant|getVariant} and examining the resulting {@link\n * VariantLayout} instance.\n *\n * A variant compatible with a JavaScript object can be identified\n * using {@link Union#getSourceVariant|getSourceVariant}.\n *\n * @param {(UnionDiscriminator|ExternalLayout|Layout)} discr - How to\n * identify the layout used to interpret the union contents. The\n * parameter must be an instance of {@link UnionDiscriminator}, an\n * {@link ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}, or {@link UInt} (or {@link\n * UIntBE}). When a non-external layout element is passed the layout\n * appears at the start of the union. In all cases the (synthesized)\n * {@link UnionDiscriminator} instance is recorded as {@link\n * Union#discriminator|discriminator}.\n *\n * @param {(Layout|null)} defaultLayout - initializer for {@link\n * Union#defaultLayout|defaultLayout}. If absent defaults to `null`.\n * If `null` there is no default layout: the union has data-dependent\n * length and attempts to decode or encode unrecognized variants will\n * throw an exception. A {@link Layout} instance must have a\n * non-negative {@link Layout#span|span}, and if it lacks a {@link\n * Layout#property|property} the {@link\n * Union#defaultLayout|defaultLayout} will be a {@link\n * Layout#replicate|replica} with property `content`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Union extends Layout {\n constructor(discr, defaultLayout, property) {\n let discriminator;\n if ((discr instanceof UInt)\n || (discr instanceof UIntBE)) {\n discriminator = new UnionLayoutDiscriminator(new OffsetLayout(discr));\n }\n else if ((discr instanceof ExternalLayout)\n && discr.isCount()) {\n discriminator = new UnionLayoutDiscriminator(discr);\n }\n else if (!(discr instanceof UnionDiscriminator)) {\n throw new TypeError('discr must be a UnionDiscriminator '\n + 'or an unsigned integer layout');\n }\n else {\n discriminator = discr;\n }\n if (undefined === defaultLayout) {\n defaultLayout = null;\n }\n if (!((null === defaultLayout)\n || (defaultLayout instanceof Layout))) {\n throw new TypeError('defaultLayout must be null or a Layout');\n }\n if (null !== defaultLayout) {\n if (0 > defaultLayout.span) {\n throw new Error('defaultLayout must have constant span');\n }\n if (undefined === defaultLayout.property) {\n defaultLayout = defaultLayout.replicate('content');\n }\n }\n /* The union span can be estimated only if there's a default\n * layout. The union spans its default layout, plus any prefix\n * variant layout. By construction both layouts, if present, have\n * non-negative span. */\n let span = -1;\n if (defaultLayout) {\n span = defaultLayout.span;\n if ((0 <= span) && ((discr instanceof UInt)\n || (discr instanceof UIntBE))) {\n span += discriminator.layout.span;\n }\n }\n super(span, property);\n /** The interface for the discriminator value in isolation.\n *\n * This a {@link UnionDiscriminator} either passed to the\n * constructor or synthesized from the `discr` constructor\n * argument. {@link\n * Union#usesPrefixDiscriminator|usesPrefixDiscriminator} will be\n * `true` iff the `discr` parameter was a non-offset {@link\n * Layout} instance. */\n this.discriminator = discriminator;\n /** `true` if the {@link Union#discriminator|discriminator} is the\n * first field in the union.\n *\n * If `false` the discriminator is obtained from somewhere\n * else. */\n this.usesPrefixDiscriminator = (discr instanceof UInt)\n || (discr instanceof UIntBE);\n /** The layout for non-discriminator content when the value of the\n * discriminator is not recognized.\n *\n * This is the value passed to the constructor. It is\n * structurally equivalent to the second component of {@link\n * Union#layout|layout} but may have a different property\n * name. */\n this.defaultLayout = defaultLayout;\n /** A registry of allowed variants.\n *\n * The keys are unsigned integers which should be compatible with\n * {@link Union.discriminator|discriminator}. The property value\n * is the corresponding {@link VariantLayout} instances assigned\n * to this union by {@link Union#addVariant|addVariant}.\n *\n * **NOTE** The registry remains mutable so that variants can be\n * {@link Union#addVariant|added} at any time. Users should not\n * manipulate the content of this property. */\n this.registry = {};\n /* Private variable used when invoking getSourceVariant */\n let boundGetSourceVariant = this.defaultGetSourceVariant.bind(this);\n /** Function to infer the variant selected by a source object.\n *\n * Defaults to {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant} but may\n * be overridden using {@link\n * Union#configGetSourceVariant|configGetSourceVariant}.\n *\n * @param {Object} src - as with {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * @returns {(undefined|VariantLayout)} The default variant\n * (`undefined`) or first registered variant that uses a property\n * available in `src`. */\n this.getSourceVariant = function (src) {\n return boundGetSourceVariant(src);\n };\n /** Function to override the implementation of {@link\n * Union#getSourceVariant|getSourceVariant}.\n *\n * Use this if the desired variant cannot be identified using the\n * algorithm of {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * **NOTE** The provided function will be invoked bound to this\n * Union instance, providing local access to {@link\n * Union#registry|registry}.\n *\n * @param {Function} gsv - a function that follows the API of\n * {@link Union#defaultGetSourceVariant|defaultGetSourceVariant}. */\n this.configGetSourceVariant = function (gsv) {\n boundGetSourceVariant = gsv.bind(this);\n };\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n return this.span;\n }\n /* Default layouts always have non-negative span, so we don't have\n * one and we have to recognize the variant which will in turn\n * determine the span. */\n const vlo = this.getVariant(b, offset);\n if (!vlo) {\n throw new Error('unable to determine span for unrecognized variant');\n }\n return vlo.getSpan(b, offset);\n }\n /**\n * Method to infer a registered Union variant compatible with `src`.\n *\n * The first satisfied rule in the following sequence defines the\n * return value:\n * * If `src` has properties matching the Union discriminator and\n * the default layout, `undefined` is returned regardless of the\n * value of the discriminator property (this ensures the default\n * layout will be used);\n * * If `src` has a property matching the Union discriminator, the\n * value of the discriminator identifies a registered variant, and\n * either (a) the variant has no layout, or (b) `src` has the\n * variant's property, then the variant is returned (because the\n * source satisfies the constraints of the variant it identifies);\n * * If `src` does not have a property matching the Union\n * discriminator, but does have a property matching a registered\n * variant, then the variant is returned (because the source\n * matches a variant without an explicit conflict);\n * * An error is thrown (because we either can't identify a variant,\n * or we were explicitly told the variant but can't satisfy it).\n *\n * @param {Object} src - an object presumed to be compatible with\n * the content of the Union.\n *\n * @return {(undefined|VariantLayout)} - as described above.\n *\n * @throws {Error} - if `src` cannot be associated with a default or\n * registered variant.\n */\n defaultGetSourceVariant(src) {\n if (Object.prototype.hasOwnProperty.call(src, this.discriminator.property)) {\n if (this.defaultLayout && this.defaultLayout.property\n && Object.prototype.hasOwnProperty.call(src, this.defaultLayout.property)) {\n return undefined;\n }\n const vlo = this.registry[src[this.discriminator.property]];\n if (vlo\n && ((!vlo.layout)\n || (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)))) {\n return vlo;\n }\n }\n else {\n for (const tag in this.registry) {\n const vlo = this.registry[tag];\n if (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)) {\n return vlo;\n }\n }\n }\n throw new Error('unable to infer src variant');\n }\n /** Implement {@link Layout#decode|decode} for {@link Union}.\n *\n * If the variant is {@link Union#addVariant|registered} the return\n * value is an instance of that variant, with no explicit\n * discriminator. Otherwise the {@link Union#defaultLayout|default\n * layout} is used to decode the content. */\n decode(b, offset = 0) {\n let dest;\n const dlo = this.discriminator;\n const discr = dlo.decode(b, offset);\n const clo = this.registry[discr];\n if (undefined === clo) {\n const defaultLayout = this.defaultLayout;\n let contentOffset = 0;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dest = this.makeDestinationObject();\n dest[dlo.property] = discr;\n // defaultLayout.property can be undefined, but this is allowed by buffer-layout\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n dest[defaultLayout.property] = defaultLayout.decode(b, offset + contentOffset);\n }\n else {\n dest = clo.decode(b, offset);\n }\n return dest;\n }\n /** Implement {@link Layout#encode|encode} for {@link Union}.\n *\n * This API assumes the `src` object is consistent with the union's\n * {@link Union#defaultLayout|default layout}. To encode variants\n * use the appropriate variant-specific {@link VariantLayout#encode}\n * method. */\n encode(src, b, offset = 0) {\n const vlo = this.getSourceVariant(src);\n if (undefined === vlo) {\n const dlo = this.discriminator;\n // this.defaultLayout is not undefined when vlo is undefined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const clo = this.defaultLayout;\n let contentOffset = 0;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dlo.encode(src[dlo.property], b, offset);\n // clo.property is not undefined when vlo is undefined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return contentOffset + clo.encode(src[clo.property], b, offset + contentOffset);\n }\n return vlo.encode(src, b, offset);\n }\n /** Register a new variant structure within a union. The newly\n * created variant is returned.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} layout - initializer for {@link\n * VariantLayout#layout|layout}.\n *\n * @param {String} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {VariantLayout} */\n addVariant(variant, layout, property) {\n const rv = new VariantLayout(this, variant, layout, property);\n this.registry[variant] = rv;\n return rv;\n }\n /**\n * Get the layout associated with a registered variant.\n *\n * If `vb` does not produce a registered variant the function returns\n * `undefined`.\n *\n * @param {(Number|Uint8Array)} vb - either the variant number, or a\n * buffer from which the discriminator is to be read.\n *\n * @param {Number} offset - offset into `vb` for the start of the\n * union. Used only when `vb` is an instance of {Uint8Array}.\n *\n * @return {({VariantLayout}|undefined)}\n */\n getVariant(vb, offset = 0) {\n let variant;\n if (vb instanceof Uint8Array) {\n variant = this.discriminator.decode(vb, offset);\n }\n else {\n variant = vb;\n }\n return this.registry[variant];\n }\n}\nexports.Union = Union;\n/**\n * Represent a specific variant within a containing union.\n *\n * **NOTE** The {@link Layout#span|span} of the variant may include\n * the span of the {@link Union#discriminator|discriminator} used to\n * identify it, but values read and written using the variant strictly\n * conform to the content of {@link VariantLayout#layout|layout}.\n *\n * **NOTE** User code should not invoke this constructor directly. Use\n * the union {@link Union#addVariant|addVariant} helper method.\n *\n * @param {Union} union - initializer for {@link\n * VariantLayout#union|union}.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} [layout] - initializer for {@link\n * VariantLayout#layout|layout}. If absent the variant carries no\n * data.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}. Unlike many other layouts, variant\n * layouts normally include a property name so they can be identified\n * within their containing {@link Union}. The property identifier may\n * be absent only if `layout` is is absent.\n *\n * @augments {Layout}\n */\nclass VariantLayout extends Layout {\n constructor(union, variant, layout, property) {\n if (!(union instanceof Union)) {\n throw new TypeError('union must be a Union');\n }\n if ((!Number.isInteger(variant)) || (0 > variant)) {\n throw new TypeError('variant must be a (non-negative) integer');\n }\n if (('string' === typeof layout)\n && (undefined === property)) {\n property = layout;\n layout = null;\n }\n if (layout) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n if ((null !== union.defaultLayout)\n && (0 <= layout.span)\n && (layout.span > union.defaultLayout.span)) {\n throw new Error('variant span exceeds span of containing union');\n }\n if ('string' !== typeof property) {\n throw new TypeError('variant must have a String property');\n }\n }\n let span = union.span;\n if (0 > union.span) {\n span = layout ? layout.span : 0;\n if ((0 <= span) && union.usesPrefixDiscriminator) {\n span += union.discriminator.layout.span;\n }\n }\n super(span, property);\n /** The {@link Union} to which this variant belongs. */\n this.union = union;\n /** The unsigned integral value identifying this variant within\n * the {@link Union#discriminator|discriminator} of the containing\n * union. */\n this.variant = variant;\n /** The {@link Layout} to be used when reading/writing the\n * non-discriminator part of the {@link\n * VariantLayout#union|union}. If `null` the variant carries no\n * data. */\n this.layout = layout || null;\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n /* Will be equal to the containing union span if that is not\n * variable. */\n return this.span;\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n /* Span is defined solely by the variant (and prefix discriminator) */\n let span = 0;\n if (this.layout) {\n span = this.layout.getSpan(b, offset + contentOffset);\n }\n return contentOffset + span;\n }\n /** @override */\n decode(b, offset = 0) {\n const dest = this.makeDestinationObject();\n if (this !== this.union.getVariant(b, offset)) {\n throw new Error('variant mismatch');\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout) {\n dest[this.property] = this.layout.decode(b, offset + contentOffset);\n }\n else if (this.property) {\n dest[this.property] = true;\n }\n else if (this.union.usesPrefixDiscriminator) {\n dest[this.union.discriminator.property] = this.variant;\n }\n return dest;\n }\n /** @override */\n encode(src, b, offset = 0) {\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout\n && (!Object.prototype.hasOwnProperty.call(src, this.property))) {\n throw new TypeError('variant lacks property ' + this.property);\n }\n this.union.discriminator.encode(this.variant, b, offset);\n let span = contentOffset;\n if (this.layout) {\n this.layout.encode(src[this.property], b, offset + contentOffset);\n span += this.layout.getSpan(b, offset + contentOffset);\n if ((0 <= this.union.span)\n && (span > this.union.span)) {\n throw new Error('encoded variant overruns containing union');\n }\n }\n return span;\n }\n /** Delegate {@link Layout#fromArray|fromArray} to {@link\n * VariantLayout#layout|layout}. */\n fromArray(values) {\n if (this.layout) {\n return this.layout.fromArray(values);\n }\n return undefined;\n }\n}\nexports.VariantLayout = VariantLayout;\n/** JavaScript chose to define bitwise operations as operating on\n * signed 32-bit values in 2's complement form, meaning any integer\n * with bit 31 set is going to look negative. For right shifts that's\n * not a problem, because `>>>` is a logical shift, but for every\n * other bitwise operator we have to compensate for possible negative\n * results. */\nfunction fixBitwiseResult(v) {\n if (0 > v) {\n v += 0x100000000;\n }\n return v;\n}\n/**\n * Contain a sequence of bit fields as an unsigned integer.\n *\n * *Factory*: {@link module:Layout.bits|bits}\n *\n * This is a container element; within it there are {@link BitField}\n * instances that provide the extracted properties. The container\n * simply defines the aggregate representation and its bit ordering.\n * The representation is an object containing properties with numeric\n * or {@link Boolean} values.\n *\n * {@link BitField}s are added with the {@link\n * BitStructure#addField|addField} and {@link\n * BitStructure#addBoolean|addBoolean} methods.\n\n * @param {Layout} word - initializer for {@link\n * BitStructure#word|word}. The parameter must be an instance of\n * {@link UInt} (or {@link UIntBE}) that is no more than 4 bytes wide.\n *\n * @param {bool} [msb] - `true` if the bit numbering starts at the\n * most significant bit of the containing word; `false` (default) if\n * it starts at the least significant bit of the containing word. If\n * the parameter at this position is a string and `property` is\n * `undefined` the value of this argument will instead be used as the\n * value of `property`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass BitStructure extends Layout {\n constructor(word, msb, property) {\n if (!((word instanceof UInt)\n || (word instanceof UIntBE))) {\n throw new TypeError('word must be a UInt or UIntBE layout');\n }\n if (('string' === typeof msb)\n && (undefined === property)) {\n property = msb;\n msb = false;\n }\n if (4 < word.span) {\n throw new RangeError('word cannot exceed 32 bits');\n }\n super(word.span, property);\n /** The layout used for the packed value. {@link BitField}\n * instances are packed sequentially depending on {@link\n * BitStructure#msb|msb}. */\n this.word = word;\n /** Whether the bit sequences are packed starting at the most\n * significant bit growing down (`true`), or the least significant\n * bit growing up (`false`).\n *\n * **NOTE** Regardless of this value, the least significant bit of\n * any {@link BitField} value is the least significant bit of the\n * corresponding section of the packed value. */\n this.msb = !!msb;\n /** The sequence of {@link BitField} layouts that comprise the\n * packed structure.\n *\n * **NOTE** The array remains mutable to allow fields to be {@link\n * BitStructure#addField|added} after construction. Users should\n * not manipulate the content of this property.*/\n this.fields = [];\n /* Storage for the value. Capture a variable instead of using an\n * instance property because we don't want anything to change the\n * value without going through the mutator. */\n let value = 0;\n this._packedSetValue = function (v) {\n value = fixBitwiseResult(v);\n return this;\n };\n this._packedGetValue = function () {\n return value;\n };\n }\n /** @override */\n decode(b, offset = 0) {\n const dest = this.makeDestinationObject();\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(b);\n }\n }\n return dest;\n }\n /** Implement {@link Layout#encode|encode} for {@link BitStructure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the packed\n * value is left unmodified. Unused bits are also left unmodified. */\n encode(src, b, offset = 0) {\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n fd.encode(fv);\n }\n }\n }\n return this.word.encode(this._packedGetValue(), b, offset);\n }\n /** Register a new bitfield with a containing bit structure. The\n * resulting bitfield is returned.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {BitField} */\n addField(bits, property) {\n const bf = new BitField(this, bits, property);\n this.fields.push(bf);\n return bf;\n }\n /** As with {@link BitStructure#addField|addField} for single-bit\n * fields with `boolean` value representation.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {Boolean} */\n // `Boolean` conflicts with the native primitive type\n // eslint-disable-next-line @typescript-eslint/ban-types\n addBoolean(property) {\n // This is my Boolean, not the Javascript one.\n const bf = new Boolean(this, property);\n this.fields.push(bf);\n return bf;\n }\n /**\n * Get access to the bit field for a given property.\n *\n * @param {String} property - the bit field of interest.\n *\n * @return {BitField} - the field associated with `property`, or\n * undefined if there is no such property.\n */\n fieldFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n return undefined;\n }\n}\nexports.BitStructure = BitStructure;\n/**\n * Represent a sequence of bits within a {@link BitStructure}.\n *\n * All bit field values are represented as unsigned integers.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addField|addField} helper\n * method.\n *\n * **NOTE** BitField instances are not instances of {@link Layout}\n * since {@link Layout#span|span} measures 8-bit units.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n */\nclass BitField {\n constructor(container, bits, property) {\n if (!(container instanceof BitStructure)) {\n throw new TypeError('container must be a BitStructure');\n }\n if ((!Number.isInteger(bits)) || (0 >= bits)) {\n throw new TypeError('bits must be positive integer');\n }\n const totalBits = 8 * container.span;\n const usedBits = container.fields.reduce((sum, fd) => sum + fd.bits, 0);\n if ((bits + usedBits) > totalBits) {\n throw new Error('bits too long for span remainder ('\n + (totalBits - usedBits) + ' of '\n + totalBits + ' remain)');\n }\n /** The {@link BitStructure} instance to which this bit field\n * belongs. */\n this.container = container;\n /** The span of this value in bits. */\n this.bits = bits;\n /** A mask of {@link BitField#bits|bits} bits isolating value bits\n * that fit within the field.\n *\n * That is, it masks a value that has not yet been shifted into\n * position within its containing packed integer. */\n this.valueMask = (1 << bits) - 1;\n if (32 === bits) { // shifted value out of range\n this.valueMask = 0xFFFFFFFF;\n }\n /** The offset of the value within the containing packed unsigned\n * integer. The least significant bit of the packed value is at\n * offset zero, regardless of bit ordering used. */\n this.start = usedBits;\n if (this.container.msb) {\n this.start = totalBits - usedBits - bits;\n }\n /** A mask of {@link BitField#bits|bits} isolating the field value\n * within the containing packed unsigned integer. */\n this.wordMask = fixBitwiseResult(this.valueMask << this.start);\n /** The property name used when this bitfield is represented in an\n * Object.\n *\n * Intended to be functionally equivalent to {@link\n * Layout#property}.\n *\n * If left undefined the corresponding span of bits will be\n * treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n /** Store a value into the corresponding subsequence of the containing\n * bit field. */\n decode(b, offset) {\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(word & this.wordMask);\n const value = wordValue >>> this.start;\n return value;\n }\n /** Store a value into the corresponding subsequence of the containing\n * bit field.\n *\n * **NOTE** This is not a specialization of {@link\n * Layout#encode|Layout.encode} and there is no return value. */\n encode(value) {\n if ('number' !== typeof value\n || !Number.isInteger(value)\n || (value !== fixBitwiseResult(value & this.valueMask))) {\n throw new TypeError(nameWithProperty('BitField.encode', this)\n + ' value must be integer not exceeding ' + this.valueMask);\n }\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(value << this.start);\n this.container._packedSetValue(fixBitwiseResult(word & ~this.wordMask)\n | wordValue);\n }\n}\nexports.BitField = BitField;\n/**\n * Represent a single bit within a {@link BitStructure} as a\n * JavaScript boolean.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addBoolean|addBoolean} helper\n * method.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {BitField}\n */\n/* eslint-disable no-extend-native */\nclass Boolean extends BitField {\n constructor(container, property) {\n super(container, 1, property);\n }\n /** Override {@link BitField#decode|decode} for {@link Boolean|Boolean}.\n *\n * @returns {boolean} */\n decode(b, offset) {\n return !!super.decode(b, offset);\n }\n /** @override */\n encode(value) {\n if ('boolean' === typeof value) {\n // BitField requires integer values\n value = +value;\n }\n super.encode(value);\n }\n}\nexports.Boolean = Boolean;\n/* eslint-enable no-extend-native */\n/**\n * Contain a fixed-length block of arbitrary data, represented as a\n * Uint8Array.\n *\n * *Factory*: {@link module:Layout.blob|blob}\n *\n * @param {(Number|ExternalLayout)} length - initializes {@link\n * Blob#length|length}.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Blob extends Layout {\n constructor(length, property) {\n if (!(((length instanceof ExternalLayout) && length.isCount())\n || (Number.isInteger(length) && (0 <= length)))) {\n throw new TypeError('length must be positive integer '\n + 'or an unsigned integer ExternalLayout');\n }\n let span = -1;\n if (!(length instanceof ExternalLayout)) {\n span = length;\n }\n super(span, property);\n /** The number of bytes in the blob.\n *\n * This may be a non-negative integer, or an instance of {@link\n * ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}. */\n this.length = length;\n }\n /** @override */\n getSpan(b, offset) {\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return span;\n }\n /** @override */\n decode(b, offset = 0) {\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return uint8ArrayToBuffer(b).slice(offset, offset + span);\n }\n /** Implement {@link Layout#encode|encode} for {@link Blob}.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset) {\n let span = this.length;\n if (this.length instanceof ExternalLayout) {\n span = src.length;\n }\n if (!(src instanceof Uint8Array && span === src.length)) {\n throw new TypeError(nameWithProperty('Blob.encode', this)\n + ' requires (length ' + span + ') Uint8Array as src');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Uint8Array');\n }\n const srcBuffer = uint8ArrayToBuffer(src);\n uint8ArrayToBuffer(b).write(srcBuffer.toString('hex'), offset, span, 'hex');\n if (this.length instanceof ExternalLayout) {\n this.length.encode(span, b, offset);\n }\n return span;\n }\n}\nexports.Blob = Blob;\n/**\n * Contain a `NUL`-terminated UTF8 string.\n *\n * *Factory*: {@link module:Layout.cstr|cstr}\n *\n * **NOTE** Any UTF8 string that incorporates a zero-valued byte will\n * not be correctly decoded by this layout.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass CString extends Layout {\n constructor(property) {\n super(-1, property);\n }\n /** @override */\n getSpan(b, offset = 0) {\n checkUint8Array(b);\n let idx = offset;\n while ((idx < b.length) && (0 !== b[idx])) {\n idx += 1;\n }\n return 1 + idx - offset;\n }\n /** @override */\n decode(b, offset = 0) {\n const span = this.getSpan(b, offset);\n return uint8ArrayToBuffer(b).slice(offset, offset + span - 1).toString('utf-8');\n }\n /** @override */\n encode(src, b, offset = 0) {\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = String(src);\n }\n const srcb = buffer_1.Buffer.from(src, 'utf8');\n const span = srcb.length;\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n const buffer = uint8ArrayToBuffer(b);\n srcb.copy(buffer, offset);\n buffer[offset + span] = 0;\n return span + 1;\n }\n}\nexports.CString = CString;\n/**\n * Contain a UTF8 string with implicit length.\n *\n * *Factory*: {@link module:Layout.utf8|utf8}\n *\n * **NOTE** Because the length is implicit in the size of the buffer\n * this layout should be used only in isolation, or in a situation\n * where the length can be expressed by operating on a slice of the\n * containing buffer.\n *\n * @param {Number} [maxSpan] - the maximum length allowed for encoded\n * string content. If not provided there is no bound on the allowed\n * content.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UTF8 extends Layout {\n constructor(maxSpan, property) {\n if (('string' === typeof maxSpan) && (undefined === property)) {\n property = maxSpan;\n maxSpan = undefined;\n }\n if (undefined === maxSpan) {\n maxSpan = -1;\n }\n else if (!Number.isInteger(maxSpan)) {\n throw new TypeError('maxSpan must be an integer');\n }\n super(-1, property);\n /** The maximum span of the layout in bytes.\n *\n * Positive values are generally expected. Zero is abnormal.\n * Attempts to encode or decode a value that exceeds this length\n * will throw a `RangeError`.\n *\n * A negative value indicates that there is no bound on the length\n * of the content. */\n this.maxSpan = maxSpan;\n }\n /** @override */\n getSpan(b, offset = 0) {\n checkUint8Array(b);\n return b.length - offset;\n }\n /** @override */\n decode(b, offset = 0) {\n const span = this.getSpan(b, offset);\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n return uint8ArrayToBuffer(b).slice(offset, offset + span).toString('utf-8');\n }\n /** @override */\n encode(src, b, offset = 0) {\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = String(src);\n }\n const srcb = buffer_1.Buffer.from(src, 'utf8');\n const span = srcb.length;\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n srcb.copy(uint8ArrayToBuffer(b), offset);\n return span;\n }\n}\nexports.UTF8 = UTF8;\n/**\n * Contain a constant value.\n *\n * This layout may be used in cases where a JavaScript value can be\n * inferred without an expression in the binary encoding. An example\n * would be a {@link VariantLayout|variant layout} where the content\n * is implied by the union {@link Union#discriminator|discriminator}.\n *\n * @param {Object|Number|String} value - initializer for {@link\n * Constant#value|value}. If the value is an object (or array) and\n * the application intends the object to remain unchanged regardless\n * of what is done to values decoded by this layout, the value should\n * be frozen prior passing it to this constructor.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Constant extends Layout {\n constructor(value, property) {\n super(0, property);\n /** The value produced by this constant when the layout is {@link\n * Constant#decode|decoded}.\n *\n * Any JavaScript value including `null` and `undefined` is\n * permitted.\n *\n * **WARNING** If `value` passed in the constructor was not\n * frozen, it is possible for users of decoded values to change\n * the content of the value. */\n this.value = value;\n }\n /** @override */\n decode(b, offset) {\n return this.value;\n }\n /** @override */\n encode(src, b, offset) {\n /* Constants take no space */\n return 0;\n }\n}\nexports.Constant = Constant;\n/** Factory for {@link GreedyCount}. */\nexports.greedy = ((elementSpan, property) => new GreedyCount(elementSpan, property));\n/** Factory for {@link OffsetLayout}. */\nexports.offset = ((layout, offset, property) => new OffsetLayout(layout, offset, property));\n/** Factory for {@link UInt|unsigned int layouts} spanning one\n * byte. */\nexports.u8 = ((property) => new UInt(1, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16 = ((property) => new UInt(2, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24 = ((property) => new UInt(3, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32 = ((property) => new UInt(4, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40 = ((property) => new UInt(5, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48 = ((property) => new UInt(6, property));\n/** Factory for {@link NearUInt64|little-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64 = ((property) => new NearUInt64(property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16be = ((property) => new UIntBE(2, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24be = ((property) => new UIntBE(3, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32be = ((property) => new UIntBE(4, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40be = ((property) => new UIntBE(5, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48be = ((property) => new UIntBE(6, property));\n/** Factory for {@link NearUInt64BE|big-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64be = ((property) => new NearUInt64BE(property));\n/** Factory for {@link Int|signed int layouts} spanning one\n * byte. */\nexports.s8 = ((property) => new Int(1, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning two bytes. */\nexports.s16 = ((property) => new Int(2, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning three bytes. */\nexports.s24 = ((property) => new Int(3, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning four bytes. */\nexports.s32 = ((property) => new Int(4, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning five bytes. */\nexports.s40 = ((property) => new Int(5, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning six bytes. */\nexports.s48 = ((property) => new Int(6, property));\n/** Factory for {@link NearInt64|little-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64 = ((property) => new NearInt64(property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning two bytes. */\nexports.s16be = ((property) => new IntBE(2, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning three bytes. */\nexports.s24be = ((property) => new IntBE(3, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning four bytes. */\nexports.s32be = ((property) => new IntBE(4, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning five bytes. */\nexports.s40be = ((property) => new IntBE(5, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning six bytes. */\nexports.s48be = ((property) => new IntBE(6, property));\n/** Factory for {@link NearInt64BE|big-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64be = ((property) => new NearInt64BE(property));\n/** Factory for {@link Float|little-endian 32-bit floating point} values. */\nexports.f32 = ((property) => new Float(property));\n/** Factory for {@link FloatBE|big-endian 32-bit floating point} values. */\nexports.f32be = ((property) => new FloatBE(property));\n/** Factory for {@link Double|little-endian 64-bit floating point} values. */\nexports.f64 = ((property) => new Double(property));\n/** Factory for {@link DoubleBE|big-endian 64-bit floating point} values. */\nexports.f64be = ((property) => new DoubleBE(property));\n/** Factory for {@link Structure} values. */\nexports.struct = ((fields, property, decodePrefixes) => new Structure(fields, property, decodePrefixes));\n/** Factory for {@link BitStructure} values. */\nexports.bits = ((word, msb, property) => new BitStructure(word, msb, property));\n/** Factory for {@link Sequence} values. */\nexports.seq = ((elementLayout, count, property) => new Sequence(elementLayout, count, property));\n/** Factory for {@link Union} values. */\nexports.union = ((discr, defaultLayout, property) => new Union(discr, defaultLayout, property));\n/** Factory for {@link UnionLayoutDiscriminator} values. */\nexports.unionLayoutDiscriminator = ((layout, property) => new UnionLayoutDiscriminator(layout, property));\n/** Factory for {@link Blob} values. */\nexports.blob = ((length, property) => new Blob(length, property));\n/** Factory for {@link CString} values. */\nexports.cstr = ((property) => new CString(property));\n/** Factory for {@link UTF8} values. */\nexports.utf8 = ((maxSpan, property) => new UTF8(maxSpan, property));\n/** Factory for {@link Constant} values. */\nexports.constant = ((value, property) => new Constant(value, property));\n//# sourceMappingURL=Layout.js.map","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.deserializeUnchecked = exports.deserialize = exports.serialize = exports.BinaryReader = exports.BinaryWriter = exports.BorshError = exports.baseDecode = exports.baseEncode = void 0;\nconst bn_js_1 = __importDefault(require(\"bn.js\"));\nconst bs58_1 = __importDefault(require(\"bs58\"));\n// TODO: Make sure this polyfill not included when not required\nconst encoding = __importStar(require(\"text-encoding-utf-8\"));\nconst ResolvedTextDecoder = typeof TextDecoder !== \"function\" ? encoding.TextDecoder : TextDecoder;\nconst textDecoder = new ResolvedTextDecoder(\"utf-8\", { fatal: true });\nfunction baseEncode(value) {\n if (typeof value === \"string\") {\n value = Buffer.from(value, \"utf8\");\n }\n return bs58_1.default.encode(Buffer.from(value));\n}\nexports.baseEncode = baseEncode;\nfunction baseDecode(value) {\n return Buffer.from(bs58_1.default.decode(value));\n}\nexports.baseDecode = baseDecode;\nconst INITIAL_LENGTH = 1024;\nclass BorshError extends Error {\n constructor(message) {\n super(message);\n this.fieldPath = [];\n this.originalMessage = message;\n }\n addToFieldPath(fieldName) {\n this.fieldPath.splice(0, 0, fieldName);\n // NOTE: Modifying message directly as jest doesn't use .toString()\n this.message = this.originalMessage + \": \" + this.fieldPath.join(\".\");\n }\n}\nexports.BorshError = BorshError;\n/// Binary encoder.\nclass BinaryWriter {\n constructor() {\n this.buf = Buffer.alloc(INITIAL_LENGTH);\n this.length = 0;\n }\n maybeResize() {\n if (this.buf.length < 16 + this.length) {\n this.buf = Buffer.concat([this.buf, Buffer.alloc(INITIAL_LENGTH)]);\n }\n }\n writeU8(value) {\n this.maybeResize();\n this.buf.writeUInt8(value, this.length);\n this.length += 1;\n }\n writeU16(value) {\n this.maybeResize();\n this.buf.writeUInt16LE(value, this.length);\n this.length += 2;\n }\n writeU32(value) {\n this.maybeResize();\n this.buf.writeUInt32LE(value, this.length);\n this.length += 4;\n }\n writeU64(value) {\n this.maybeResize();\n this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray(\"le\", 8)));\n }\n writeU128(value) {\n this.maybeResize();\n this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray(\"le\", 16)));\n }\n writeU256(value) {\n this.maybeResize();\n this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray(\"le\", 32)));\n }\n writeU512(value) {\n this.maybeResize();\n this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray(\"le\", 64)));\n }\n writeBuffer(buffer) {\n // Buffer.from is needed as this.buf.subarray can return plain Uint8Array in browser\n this.buf = Buffer.concat([\n Buffer.from(this.buf.subarray(0, this.length)),\n buffer,\n Buffer.alloc(INITIAL_LENGTH),\n ]);\n this.length += buffer.length;\n }\n writeString(str) {\n this.maybeResize();\n const b = Buffer.from(str, \"utf8\");\n this.writeU32(b.length);\n this.writeBuffer(b);\n }\n writeFixedArray(array) {\n this.writeBuffer(Buffer.from(array));\n }\n writeArray(array, fn) {\n this.maybeResize();\n this.writeU32(array.length);\n for (const elem of array) {\n this.maybeResize();\n fn(elem);\n }\n }\n toArray() {\n return this.buf.subarray(0, this.length);\n }\n}\nexports.BinaryWriter = BinaryWriter;\nfunction handlingRangeError(target, propertyKey, propertyDescriptor) {\n const originalMethod = propertyDescriptor.value;\n propertyDescriptor.value = function (...args) {\n try {\n return originalMethod.apply(this, args);\n }\n catch (e) {\n if (e instanceof RangeError) {\n const code = e.code;\n if ([\"ERR_BUFFER_OUT_OF_BOUNDS\", \"ERR_OUT_OF_RANGE\"].indexOf(code) >= 0) {\n throw new BorshError(\"Reached the end of buffer when deserializing\");\n }\n }\n throw e;\n }\n };\n}\nclass BinaryReader {\n constructor(buf) {\n this.buf = buf;\n this.offset = 0;\n }\n readU8() {\n const value = this.buf.readUInt8(this.offset);\n this.offset += 1;\n return value;\n }\n readU16() {\n const value = this.buf.readUInt16LE(this.offset);\n this.offset += 2;\n return value;\n }\n readU32() {\n const value = this.buf.readUInt32LE(this.offset);\n this.offset += 4;\n return value;\n }\n readU64() {\n const buf = this.readBuffer(8);\n return new bn_js_1.default(buf, \"le\");\n }\n readU128() {\n const buf = this.readBuffer(16);\n return new bn_js_1.default(buf, \"le\");\n }\n readU256() {\n const buf = this.readBuffer(32);\n return new bn_js_1.default(buf, \"le\");\n }\n readU512() {\n const buf = this.readBuffer(64);\n return new bn_js_1.default(buf, \"le\");\n }\n readBuffer(len) {\n if (this.offset + len > this.buf.length) {\n throw new BorshError(`Expected buffer length ${len} isn't within bounds`);\n }\n const result = this.buf.slice(this.offset, this.offset + len);\n this.offset += len;\n return result;\n }\n readString() {\n const len = this.readU32();\n const buf = this.readBuffer(len);\n try {\n // NOTE: Using TextDecoder to fail on invalid UTF-8\n return textDecoder.decode(buf);\n }\n catch (e) {\n throw new BorshError(`Error decoding UTF-8 string: ${e}`);\n }\n }\n readFixedArray(len) {\n return new Uint8Array(this.readBuffer(len));\n }\n readArray(fn) {\n const len = this.readU32();\n const result = Array();\n for (let i = 0; i < len; ++i) {\n result.push(fn());\n }\n return result;\n }\n}\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU8\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU16\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU32\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU64\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU128\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU256\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU512\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readString\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readFixedArray\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readArray\", null);\nexports.BinaryReader = BinaryReader;\nfunction capitalizeFirstLetter(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\nfunction serializeField(schema, fieldName, value, fieldType, writer) {\n try {\n // TODO: Handle missing values properly (make sure they never result in just skipped write)\n if (typeof fieldType === \"string\") {\n writer[`write${capitalizeFirstLetter(fieldType)}`](value);\n }\n else if (fieldType instanceof Array) {\n if (typeof fieldType[0] === \"number\") {\n if (value.length !== fieldType[0]) {\n throw new BorshError(`Expecting byte array of length ${fieldType[0]}, but got ${value.length} bytes`);\n }\n writer.writeFixedArray(value);\n }\n else if (fieldType.length === 2 && typeof fieldType[1] === \"number\") {\n if (value.length !== fieldType[1]) {\n throw new BorshError(`Expecting byte array of length ${fieldType[1]}, but got ${value.length} bytes`);\n }\n for (let i = 0; i < fieldType[1]; i++) {\n serializeField(schema, null, value[i], fieldType[0], writer);\n }\n }\n else {\n writer.writeArray(value, (item) => {\n serializeField(schema, fieldName, item, fieldType[0], writer);\n });\n }\n }\n else if (fieldType.kind !== undefined) {\n switch (fieldType.kind) {\n case \"option\": {\n if (value === null || value === undefined) {\n writer.writeU8(0);\n }\n else {\n writer.writeU8(1);\n serializeField(schema, fieldName, value, fieldType.type, writer);\n }\n break;\n }\n case \"map\": {\n writer.writeU32(value.size);\n value.forEach((val, key) => {\n serializeField(schema, fieldName, key, fieldType.key, writer);\n serializeField(schema, fieldName, val, fieldType.value, writer);\n });\n break;\n }\n default:\n throw new BorshError(`FieldType ${fieldType} unrecognized`);\n }\n }\n else {\n serializeStruct(schema, value, writer);\n }\n }\n catch (error) {\n if (error instanceof BorshError) {\n error.addToFieldPath(fieldName);\n }\n throw error;\n }\n}\nfunction serializeStruct(schema, obj, writer) {\n if (typeof obj.borshSerialize === \"function\") {\n obj.borshSerialize(writer);\n return;\n }\n const structSchema = schema.get(obj.constructor);\n if (!structSchema) {\n throw new BorshError(`Class ${obj.constructor.name} is missing in schema`);\n }\n if (structSchema.kind === \"struct\") {\n structSchema.fields.map(([fieldName, fieldType]) => {\n serializeField(schema, fieldName, obj[fieldName], fieldType, writer);\n });\n }\n else if (structSchema.kind === \"enum\") {\n const name = obj[structSchema.field];\n for (let idx = 0; idx < structSchema.values.length; ++idx) {\n const [fieldName, fieldType] = structSchema.values[idx];\n if (fieldName === name) {\n writer.writeU8(idx);\n serializeField(schema, fieldName, obj[fieldName], fieldType, writer);\n break;\n }\n }\n }\n else {\n throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${obj.constructor.name}`);\n }\n}\n/// Serialize given object using schema of the form:\n/// { class_name -> [ [field_name, field_type], .. ], .. }\nfunction serialize(schema, obj, Writer = BinaryWriter) {\n const writer = new Writer();\n serializeStruct(schema, obj, writer);\n return writer.toArray();\n}\nexports.serialize = serialize;\nfunction deserializeField(schema, fieldName, fieldType, reader) {\n try {\n if (typeof fieldType === \"string\") {\n return reader[`read${capitalizeFirstLetter(fieldType)}`]();\n }\n if (fieldType instanceof Array) {\n if (typeof fieldType[0] === \"number\") {\n return reader.readFixedArray(fieldType[0]);\n }\n else if (typeof fieldType[1] === \"number\") {\n const arr = [];\n for (let i = 0; i < fieldType[1]; i++) {\n arr.push(deserializeField(schema, null, fieldType[0], reader));\n }\n return arr;\n }\n else {\n return reader.readArray(() => deserializeField(schema, fieldName, fieldType[0], reader));\n }\n }\n if (fieldType.kind === \"option\") {\n const option = reader.readU8();\n if (option) {\n return deserializeField(schema, fieldName, fieldType.type, reader);\n }\n return undefined;\n }\n if (fieldType.kind === \"map\") {\n let map = new Map();\n const length = reader.readU32();\n for (let i = 0; i < length; i++) {\n const key = deserializeField(schema, fieldName, fieldType.key, reader);\n const val = deserializeField(schema, fieldName, fieldType.value, reader);\n map.set(key, val);\n }\n return map;\n }\n return deserializeStruct(schema, fieldType, reader);\n }\n catch (error) {\n if (error instanceof BorshError) {\n error.addToFieldPath(fieldName);\n }\n throw error;\n }\n}\nfunction deserializeStruct(schema, classType, reader) {\n if (typeof classType.borshDeserialize === \"function\") {\n return classType.borshDeserialize(reader);\n }\n const structSchema = schema.get(classType);\n if (!structSchema) {\n throw new BorshError(`Class ${classType.name} is missing in schema`);\n }\n if (structSchema.kind === \"struct\") {\n const result = {};\n for (const [fieldName, fieldType] of schema.get(classType).fields) {\n result[fieldName] = deserializeField(schema, fieldName, fieldType, reader);\n }\n return new classType(result);\n }\n if (structSchema.kind === \"enum\") {\n const idx = reader.readU8();\n if (idx >= structSchema.values.length) {\n throw new BorshError(`Enum index: ${idx} is out of range`);\n }\n const [fieldName, fieldType] = structSchema.values[idx];\n const fieldValue = deserializeField(schema, fieldName, fieldType, reader);\n return new classType({ [fieldName]: fieldValue });\n }\n throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${classType.constructor.name}`);\n}\n/// Deserializes object from bytes using schema.\nfunction deserialize(schema, classType, buffer, Reader = BinaryReader) {\n const reader = new Reader(buffer);\n const result = deserializeStruct(schema, classType, reader);\n if (reader.offset < buffer.length) {\n throw new BorshError(`Unexpected ${buffer.length - reader.offset} bytes after deserialized data`);\n }\n return result;\n}\nexports.deserialize = deserialize;\n/// Deserializes object from bytes using schema, without checking the length read\nfunction deserializeUnchecked(schema, classType, buffer, Reader = BinaryReader) {\n const reader = new Reader(buffer);\n return deserializeStruct(schema, classType, reader);\n}\nexports.deserializeUnchecked = deserializeUnchecked;\n","var basex = require('base-x')\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`Wrong positive integer: ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`Expected boolean, not ${b}`);\n}\nfunction bytes(b, ...lengths) {\n if (!(b instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nconst u8a = (a) => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n if (!u8a(data))\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Base SHA2 class (RFC 6234)\nexport class SHA2 extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_sha2.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { SHA2 } from './_sha2.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends SHA2 {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _0 = new Uint8Array(16);\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_16(x, xi, y, yi) {\n return vn(x,xi,y,yi,16);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction core_salsa20(o, p, k, c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n x0 = x0 + j0 | 0;\n x1 = x1 + j1 | 0;\n x2 = x2 + j2 | 0;\n x3 = x3 + j3 | 0;\n x4 = x4 + j4 | 0;\n x5 = x5 + j5 | 0;\n x6 = x6 + j6 | 0;\n x7 = x7 + j7 | 0;\n x8 = x8 + j8 | 0;\n x9 = x9 + j9 | 0;\n x10 = x10 + j10 | 0;\n x11 = x11 + j11 | 0;\n x12 = x12 + j12 | 0;\n x13 = x13 + j13 | 0;\n x14 = x14 + j14 | 0;\n x15 = x15 + j15 | 0;\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x1 >>> 0 & 0xff;\n o[ 5] = x1 >>> 8 & 0xff;\n o[ 6] = x1 >>> 16 & 0xff;\n o[ 7] = x1 >>> 24 & 0xff;\n\n o[ 8] = x2 >>> 0 & 0xff;\n o[ 9] = x2 >>> 8 & 0xff;\n o[10] = x2 >>> 16 & 0xff;\n o[11] = x2 >>> 24 & 0xff;\n\n o[12] = x3 >>> 0 & 0xff;\n o[13] = x3 >>> 8 & 0xff;\n o[14] = x3 >>> 16 & 0xff;\n o[15] = x3 >>> 24 & 0xff;\n\n o[16] = x4 >>> 0 & 0xff;\n o[17] = x4 >>> 8 & 0xff;\n o[18] = x4 >>> 16 & 0xff;\n o[19] = x4 >>> 24 & 0xff;\n\n o[20] = x5 >>> 0 & 0xff;\n o[21] = x5 >>> 8 & 0xff;\n o[22] = x5 >>> 16 & 0xff;\n o[23] = x5 >>> 24 & 0xff;\n\n o[24] = x6 >>> 0 & 0xff;\n o[25] = x6 >>> 8 & 0xff;\n o[26] = x6 >>> 16 & 0xff;\n o[27] = x6 >>> 24 & 0xff;\n\n o[28] = x7 >>> 0 & 0xff;\n o[29] = x7 >>> 8 & 0xff;\n o[30] = x7 >>> 16 & 0xff;\n o[31] = x7 >>> 24 & 0xff;\n\n o[32] = x8 >>> 0 & 0xff;\n o[33] = x8 >>> 8 & 0xff;\n o[34] = x8 >>> 16 & 0xff;\n o[35] = x8 >>> 24 & 0xff;\n\n o[36] = x9 >>> 0 & 0xff;\n o[37] = x9 >>> 8 & 0xff;\n o[38] = x9 >>> 16 & 0xff;\n o[39] = x9 >>> 24 & 0xff;\n\n o[40] = x10 >>> 0 & 0xff;\n o[41] = x10 >>> 8 & 0xff;\n o[42] = x10 >>> 16 & 0xff;\n o[43] = x10 >>> 24 & 0xff;\n\n o[44] = x11 >>> 0 & 0xff;\n o[45] = x11 >>> 8 & 0xff;\n o[46] = x11 >>> 16 & 0xff;\n o[47] = x11 >>> 24 & 0xff;\n\n o[48] = x12 >>> 0 & 0xff;\n o[49] = x12 >>> 8 & 0xff;\n o[50] = x12 >>> 16 & 0xff;\n o[51] = x12 >>> 24 & 0xff;\n\n o[52] = x13 >>> 0 & 0xff;\n o[53] = x13 >>> 8 & 0xff;\n o[54] = x13 >>> 16 & 0xff;\n o[55] = x13 >>> 24 & 0xff;\n\n o[56] = x14 >>> 0 & 0xff;\n o[57] = x14 >>> 8 & 0xff;\n o[58] = x14 >>> 16 & 0xff;\n o[59] = x14 >>> 24 & 0xff;\n\n o[60] = x15 >>> 0 & 0xff;\n o[61] = x15 >>> 8 & 0xff;\n o[62] = x15 >>> 16 & 0xff;\n o[63] = x15 >>> 24 & 0xff;\n}\n\nfunction core_hsalsa20(o,p,k,c) {\n var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,\n j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,\n j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,\n j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,\n j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,\n j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,\n j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,\n j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,\n j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,\n j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,\n j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,\n j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,\n j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,\n j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,\n j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,\n j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;\n\n var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,\n x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,\n x15 = j15, u;\n\n for (var i = 0; i < 20; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u<<7 | u>>>(32-7);\n u = x4 + x0 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x4 | 0;\n x12 ^= u<<13 | u>>>(32-13);\n u = x12 + x8 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x1 | 0;\n x9 ^= u<<7 | u>>>(32-7);\n u = x9 + x5 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x9 | 0;\n x1 ^= u<<13 | u>>>(32-13);\n u = x1 + x13 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x6 | 0;\n x14 ^= u<<7 | u>>>(32-7);\n u = x14 + x10 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x14 | 0;\n x6 ^= u<<13 | u>>>(32-13);\n u = x6 + x2 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x11 | 0;\n x3 ^= u<<7 | u>>>(32-7);\n u = x3 + x15 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x3 | 0;\n x11 ^= u<<13 | u>>>(32-13);\n u = x11 + x7 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n\n u = x0 + x3 | 0;\n x1 ^= u<<7 | u>>>(32-7);\n u = x1 + x0 | 0;\n x2 ^= u<<9 | u>>>(32-9);\n u = x2 + x1 | 0;\n x3 ^= u<<13 | u>>>(32-13);\n u = x3 + x2 | 0;\n x0 ^= u<<18 | u>>>(32-18);\n\n u = x5 + x4 | 0;\n x6 ^= u<<7 | u>>>(32-7);\n u = x6 + x5 | 0;\n x7 ^= u<<9 | u>>>(32-9);\n u = x7 + x6 | 0;\n x4 ^= u<<13 | u>>>(32-13);\n u = x4 + x7 | 0;\n x5 ^= u<<18 | u>>>(32-18);\n\n u = x10 + x9 | 0;\n x11 ^= u<<7 | u>>>(32-7);\n u = x11 + x10 | 0;\n x8 ^= u<<9 | u>>>(32-9);\n u = x8 + x11 | 0;\n x9 ^= u<<13 | u>>>(32-13);\n u = x9 + x8 | 0;\n x10 ^= u<<18 | u>>>(32-18);\n\n u = x15 + x14 | 0;\n x12 ^= u<<7 | u>>>(32-7);\n u = x12 + x15 | 0;\n x13 ^= u<<9 | u>>>(32-9);\n u = x13 + x12 | 0;\n x14 ^= u<<13 | u>>>(32-13);\n u = x14 + x13 | 0;\n x15 ^= u<<18 | u>>>(32-18);\n }\n\n o[ 0] = x0 >>> 0 & 0xff;\n o[ 1] = x0 >>> 8 & 0xff;\n o[ 2] = x0 >>> 16 & 0xff;\n o[ 3] = x0 >>> 24 & 0xff;\n\n o[ 4] = x5 >>> 0 & 0xff;\n o[ 5] = x5 >>> 8 & 0xff;\n o[ 6] = x5 >>> 16 & 0xff;\n o[ 7] = x5 >>> 24 & 0xff;\n\n o[ 8] = x10 >>> 0 & 0xff;\n o[ 9] = x10 >>> 8 & 0xff;\n o[10] = x10 >>> 16 & 0xff;\n o[11] = x10 >>> 24 & 0xff;\n\n o[12] = x15 >>> 0 & 0xff;\n o[13] = x15 >>> 8 & 0xff;\n o[14] = x15 >>> 16 & 0xff;\n o[15] = x15 >>> 24 & 0xff;\n\n o[16] = x6 >>> 0 & 0xff;\n o[17] = x6 >>> 8 & 0xff;\n o[18] = x6 >>> 16 & 0xff;\n o[19] = x6 >>> 24 & 0xff;\n\n o[20] = x7 >>> 0 & 0xff;\n o[21] = x7 >>> 8 & 0xff;\n o[22] = x7 >>> 16 & 0xff;\n o[23] = x7 >>> 24 & 0xff;\n\n o[24] = x8 >>> 0 & 0xff;\n o[25] = x8 >>> 8 & 0xff;\n o[26] = x8 >>> 16 & 0xff;\n o[27] = x8 >>> 24 & 0xff;\n\n o[28] = x9 >>> 0 & 0xff;\n o[29] = x9 >>> 8 & 0xff;\n o[30] = x9 >>> 16 & 0xff;\n o[31] = x9 >>> 24 & 0xff;\n}\n\nfunction crypto_core_salsa20(out,inp,k,c) {\n core_salsa20(out,inp,k,c);\n}\n\nfunction crypto_core_hsalsa20(out,inp,k,c) {\n core_hsalsa20(out,inp,k,c);\n}\n\nvar sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);\n // \"expand 32-byte k\"\n\nfunction crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n mpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];\n }\n return 0;\n}\n\nfunction crypto_stream_salsa20(c,cpos,b,n,k) {\n var z = new Uint8Array(16), x = new Uint8Array(64);\n var u, i;\n for (i = 0; i < 16; i++) z[i] = 0;\n for (i = 0; i < 8; i++) z[i] = n[i];\n while (b >= 64) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < 64; i++) c[cpos+i] = x[i];\n u = 1;\n for (i = 8; i < 16; i++) {\n u = u + (z[i] & 0xff) | 0;\n z[i] = u & 0xff;\n u >>>= 8;\n }\n b -= 64;\n cpos += 64;\n }\n if (b > 0) {\n crypto_core_salsa20(x,z,k,sigma);\n for (i = 0; i < b; i++) c[cpos+i] = x[i];\n }\n return 0;\n}\n\nfunction crypto_stream(c,cpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20(c,cpos,d,sn,s);\n}\n\nfunction crypto_stream_xor(c,cpos,m,mpos,d,n,k) {\n var s = new Uint8Array(32);\n crypto_core_hsalsa20(s,n,k,sigma);\n var sn = new Uint8Array(8);\n for (var i = 0; i < 8; i++) sn[i] = n[i+16];\n return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);\n}\n\n/*\n* Port of Andrew Moon's Poly1305-donna-16. Public domain.\n* https://github.com/floodyberry/poly1305-donna\n*/\n\nvar poly1305 = function(key) {\n this.buffer = new Uint8Array(16);\n this.r = new Uint16Array(10);\n this.h = new Uint16Array(10);\n this.pad = new Uint16Array(8);\n this.leftover = 0;\n this.fin = 0;\n\n var t0, t1, t2, t3, t4, t5, t6, t7;\n\n t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;\n t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = ((t4 >>> 1)) & 0x1ffe;\n t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = ((t7 >>> 5)) & 0x007f;\n\n this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;\n this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;\n this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;\n this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;\n this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;\n this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;\n this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;\n this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;\n};\n\npoly1305.prototype.blocks = function(m, mpos, bytes) {\n var hibit = this.fin ? 0 : (1 << 11);\n var t0, t1, t2, t3, t4, t5, t6, t7, c;\n var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;\n\n var h0 = this.h[0],\n h1 = this.h[1],\n h2 = this.h[2],\n h3 = this.h[3],\n h4 = this.h[4],\n h5 = this.h[5],\n h6 = this.h[6],\n h7 = this.h[7],\n h8 = this.h[8],\n h9 = this.h[9];\n\n var r0 = this.r[0],\n r1 = this.r[1],\n r2 = this.r[2],\n r3 = this.r[3],\n r4 = this.r[4],\n r5 = this.r[5],\n r6 = this.r[6],\n r7 = this.r[7],\n r8 = this.r[8],\n r9 = this.r[9];\n\n while (bytes >= 16) {\n t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;\n t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n c = 0;\n\n d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this.h[0] = h0;\n this.h[1] = h1;\n this.h[2] = h2;\n this.h[3] = h3;\n this.h[4] = h4;\n this.h[5] = h5;\n this.h[6] = h6;\n this.h[7] = h7;\n this.h[8] = h8;\n this.h[9] = h9;\n};\n\npoly1305.prototype.finish = function(mac, macpos) {\n var g = new Uint16Array(10);\n var c, mask, f, i;\n\n if (this.leftover) {\n i = this.leftover;\n this.buffer[i++] = 1;\n for (; i < 16; i++) this.buffer[i] = 0;\n this.fin = 1;\n this.blocks(this.buffer, 0, 16);\n }\n\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this.h[i] += c;\n c = this.h[i] >>> 13;\n this.h[i] &= 0x1fff;\n }\n this.h[0] += (c * 5);\n c = this.h[0] >>> 13;\n this.h[0] &= 0x1fff;\n this.h[1] += c;\n c = this.h[1] >>> 13;\n this.h[1] &= 0x1fff;\n this.h[2] += c;\n\n g[0] = this.h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this.h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];\n\n this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;\n this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;\n this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;\n this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;\n this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;\n this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;\n this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;\n this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;\n\n f = this.h[0] + this.pad[0];\n this.h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;\n this.h[i] = f & 0xffff;\n }\n\n mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;\n mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;\n mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;\n mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;\n mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;\n mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;\n mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;\n mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;\n mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;\n mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;\n mac[macpos+10] = (this.h[5] >>> 0) & 0xff;\n mac[macpos+11] = (this.h[5] >>> 8) & 0xff;\n mac[macpos+12] = (this.h[6] >>> 0) & 0xff;\n mac[macpos+13] = (this.h[6] >>> 8) & 0xff;\n mac[macpos+14] = (this.h[7] >>> 0) & 0xff;\n mac[macpos+15] = (this.h[7] >>> 8) & 0xff;\n};\n\npoly1305.prototype.update = function(m, mpos, bytes) {\n var i, want;\n\n if (this.leftover) {\n want = (16 - this.leftover);\n if (want > bytes)\n want = bytes;\n for (i = 0; i < want; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n bytes -= want;\n mpos += want;\n this.leftover += want;\n if (this.leftover < 16)\n return;\n this.blocks(this.buffer, 0, 16);\n this.leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this.blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (i = 0; i < bytes; i++)\n this.buffer[this.leftover + i] = m[mpos+i];\n this.leftover += bytes;\n }\n};\n\nfunction crypto_onetimeauth(out, outpos, m, mpos, n, k) {\n var s = new poly1305(k);\n s.update(m, mpos, n);\n s.finish(out, outpos);\n return 0;\n}\n\nfunction crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {\n var x = new Uint8Array(16);\n crypto_onetimeauth(x,0,m,mpos,n,k);\n return crypto_verify_16(h,hpos,x,0);\n}\n\nfunction crypto_secretbox(c,m,d,n,k) {\n var i;\n if (d < 32) return -1;\n crypto_stream_xor(c,0,m,0,d,n,k);\n crypto_onetimeauth(c, 16, c, 32, d - 32, c);\n for (i = 0; i < 16; i++) c[i] = 0;\n return 0;\n}\n\nfunction crypto_secretbox_open(m,c,d,n,k) {\n var i;\n var x = new Uint8Array(32);\n if (d < 32) return -1;\n crypto_stream(x,0,32,n,k);\n if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;\n crypto_stream_xor(m,0,c,0,d,n,k);\n for (i = 0; i < 32; i++) m[i] = 0;\n return 0;\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction crypto_box_beforenm(k, y, x) {\n var s = new Uint8Array(32);\n crypto_scalarmult(s, x, y);\n return crypto_core_hsalsa20(k, _0, s, sigma);\n}\n\nvar crypto_box_afternm = crypto_secretbox;\nvar crypto_box_open_afternm = crypto_secretbox_open;\n\nfunction crypto_box(c, m, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_afternm(c, m, d, n, k);\n}\n\nfunction crypto_box_open(m, c, d, n, y, x) {\n var k = new Uint8Array(32);\n crypto_box_beforenm(k, y, x);\n return crypto_box_open_afternm(m, c, d, n, k);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_secretbox_KEYBYTES = 32,\n crypto_secretbox_NONCEBYTES = 24,\n crypto_secretbox_ZEROBYTES = 32,\n crypto_secretbox_BOXZEROBYTES = 16,\n crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_box_BEFORENMBYTES = 32,\n crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,\n crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,\n crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32,\n crypto_hash_BYTES = 64;\n\nnacl.lowlevel = {\n crypto_core_hsalsa20: crypto_core_hsalsa20,\n crypto_stream_xor: crypto_stream_xor,\n crypto_stream: crypto_stream,\n crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,\n crypto_stream_salsa20: crypto_stream_salsa20,\n crypto_onetimeauth: crypto_onetimeauth,\n crypto_onetimeauth_verify: crypto_onetimeauth_verify,\n crypto_verify_16: crypto_verify_16,\n crypto_verify_32: crypto_verify_32,\n crypto_secretbox: crypto_secretbox,\n crypto_secretbox_open: crypto_secretbox_open,\n crypto_scalarmult: crypto_scalarmult,\n crypto_scalarmult_base: crypto_scalarmult_base,\n crypto_box_beforenm: crypto_box_beforenm,\n crypto_box_afternm: crypto_box_afternm,\n crypto_box: crypto_box,\n crypto_box_open: crypto_box_open,\n crypto_box_keypair: crypto_box_keypair,\n crypto_hash: crypto_hash,\n crypto_sign: crypto_sign,\n crypto_sign_keypair: crypto_sign_keypair,\n crypto_sign_open: crypto_sign_open,\n\n crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,\n crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,\n crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,\n crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,\n crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,\n crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,\n crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,\n crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,\n crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,\n crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,\n crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,\n crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,\n crypto_sign_BYTES: crypto_sign_BYTES,\n crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,\n crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,\n crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,\n crypto_hash_BYTES: crypto_hash_BYTES,\n\n gf: gf,\n D: D,\n L: L,\n pack25519: pack25519,\n unpack25519: unpack25519,\n M: M,\n A: A,\n S: S,\n Z: Z,\n pow2523: pow2523,\n add: add,\n set25519: set25519,\n modL: modL,\n scalarmult: scalarmult,\n scalarbase: scalarbase,\n};\n\n/* High-level API */\n\nfunction checkLengths(k, n) {\n if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');\n if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');\n}\n\nfunction checkBoxLengths(pk, sk) {\n if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');\n if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');\n}\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.randomBytes = function(n) {\n var b = new Uint8Array(n);\n randombytes(b, n);\n return b;\n};\n\nnacl.secretbox = function(msg, nonce, key) {\n checkArrayTypes(msg, nonce, key);\n checkLengths(key, nonce);\n var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);\n var c = new Uint8Array(m.length);\n for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];\n crypto_secretbox(c, m, m.length, nonce, key);\n return c.subarray(crypto_secretbox_BOXZEROBYTES);\n};\n\nnacl.secretbox.open = function(box, nonce, key) {\n checkArrayTypes(box, nonce, key);\n checkLengths(key, nonce);\n var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);\n var m = new Uint8Array(c.length);\n for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];\n if (c.length < 32) return null;\n if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null;\n return m.subarray(crypto_secretbox_ZEROBYTES);\n};\n\nnacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;\nnacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;\nnacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.scalarMult.base = function(n) {\n checkArrayTypes(n);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult_base(q, n);\n return q;\n};\n\nnacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;\nnacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;\n\nnacl.box = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox(msg, nonce, k);\n};\n\nnacl.box.before = function(publicKey, secretKey) {\n checkArrayTypes(publicKey, secretKey);\n checkBoxLengths(publicKey, secretKey);\n var k = new Uint8Array(crypto_box_BEFORENMBYTES);\n crypto_box_beforenm(k, publicKey, secretKey);\n return k;\n};\n\nnacl.box.after = nacl.secretbox;\n\nnacl.box.open = function(msg, nonce, publicKey, secretKey) {\n var k = nacl.box.before(publicKey, secretKey);\n return nacl.secretbox.open(msg, nonce, k);\n};\n\nnacl.box.open.after = nacl.secretbox.open;\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;\nnacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;\nnacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;\nnacl.box.nonceLength = crypto_box_NONCEBYTES;\nnacl.box.overheadLength = nacl.secretbox.overheadLength;\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.open = function(signedMsg, publicKey) {\n checkArrayTypes(signedMsg, publicKey);\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var tmp = new Uint8Array(signedMsg.length);\n var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);\n if (mlen < 0) return null;\n var m = new Uint8Array(mlen);\n for (var i = 0; i < m.length; i++) m[i] = tmp[i];\n return m;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;\nnacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;\nnacl.sign.seedLength = crypto_sign_SEEDBYTES;\nnacl.sign.signatureLength = crypto_sign_BYTES;\n\nnacl.hash = function(msg) {\n checkArrayTypes(msg);\n var h = new Uint8Array(crypto_hash_BYTES);\n crypto_hash(h, msg, msg.length);\n return h;\n};\n\nnacl.hash.hashLength = crypto_hash_BYTES;\n\nnacl.verify = function(x, y) {\n checkArrayTypes(x, y);\n // Zero length arguments are considered not equal.\n if (x.length === 0 || y.length === 0) return false;\n if (x.length !== y.length) return false;\n return (vn(x, 0, y, 0, x.length) === 0) ? true : false;\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n"],"names":["uuid","generateRequest","ClientBrowser","callServer","options","this","reviver","replacer","generator","version","notificationIdNull","module","exports","prototype","request","method","params","id","callback","self","isBatch","Array","isArray","TypeError","undefined","hasCallback","err","message","JSON","stringify","response","_parseResponse","responseText","parse","length","isError","res","error","isNotError","filter","result","globalThis","crypto","isBytes","a","Uint8Array","ArrayBuffer","isView","constructor","name","anumber","n","Number","isSafeInteger","Error","b","lengths","includes","ahash","h","create","outputLen","blockLen","aexists","instance","checkFinished","destroyed","finished","clean","arrays","i","fill","createView","arr","DataView","buffer","byteOffset","byteLength","rotr","word","shift","hasHexBuiltin","from","toHex","fromHex","hexes","_","toString","padStart","bytesToHex","bytes","hex","asciiToBase16","ch","hexToBytes","hl","al","array","ai","hi","n1","charCodeAt","n2","char","str","TextEncoder","encode","toBytes","data","sum","pad","set","Hash","hashCons","hashC","msg","update","digest","tmp","bytesLength","getRandomValues","randomBytes","Chi","c","Maj","HashMD","padOffset","isLE","super","pos","view","len","take","Math","min","dataView","process","subarray","roundClean","digestInto","out","aoutput","value","setBigUint64","_32n","BigInt","_u32_max","wh","wl","l","setUint32","oview","outLen","state","get","slice","destroy","_cloneInto","to","clone","SHA256_IV","Uint32Array","SHA512_IV","U32_MASK64","fromBig","le","shrSH","_l","s","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","add","Ah","Al","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5L","El","add5H","Eh","SHA256_K","SHA256_W","SHA256","A","B","C","D","E","F","G","H","offset","getUint32","W15","W2","s0","s1","T1","T2","K512","lst","map","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","_0n","_1n","_abool2","title","_abytes2","needsLen","numberToHexUnpadded","num","hexToNumber","reverse","numberToBytesLE","expectedLength","e","copyBytes","isPosBig","aInRange","max","bitLen","object","fields","optFields","checkField","fieldName","expectedType","isOpt","val","current","Object","entries","forEach","k","v","notImplemented","memoized","fn","WeakMap","arg","args","computed","_2n","_3n","_4n","_5n","_7n","_8n","_9n","_16n","x","power","modulo","invert","number","y","u","q","r","m","assertIsSquare","Fp","root","eql","sqr","sqrt3mod4","p1div4","ORDER","pow","sqrt5mod8","p5div8","mul","nv","sub","ONE","tonelliShanks","P","Q","S","Z","_Fp","Field","FpLegendre","cc","Q1div2","is0","M","t","R","ZERO","t_tmp","exponent","isNegativeLE","FIELD_FIELDS","nums","passZero","inverted","multipliedAcc","reduce","acc","invertedAcc","inv","reduceRight","p1mod2","powered","yes","zero","no","neg","nBitLength","_nBitLength","nByteLength","ceil","bitLenOrOpts","opts","_nbitLength","_sqrt","allowedLengths","modFromBytes","sqrt","_opts","BITS","BYTES","sqrtP","f","freeze","MASK","isValid","isValidNot0","isOdd","lhs","rhs","p","d","FpPow","div","sqrN","addN","subN","mulN","Fp_","tn","c1","c2","c3","c4","tv1","tv2","tv3","tv4","e1","e2","cmov","e3","sqrt9mod16","fromBytes","skipValidation","padded","scalar","invertBatch","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","negateCt","condition","item","negate","normalizeZ","points","invertedZs","fromAffine","toAffine","validateW","W","bits","calcWOpts","scalarBits","maxNumber","windows","windowSize","mask","shiftBy","calcOffsets","window","wOpts","wbits","nextN","offsetStart","abs","isZero","isNeg","isNegF","offsetF","pointPrecomputes","pointWindowSizes","getW","assert0","wNAF","Point","BASE","Fn","_unsafeLadder","elm","double","precomputeWindow","point","base","push","precomputes","wo","wNAFUnsafe","getPrecomputes","transform","comp","cached","unsafe","prev","createCache","delete","hasCache","pippenger","fieldN","scalars","validateMSMPoints","field","validateMSMScalars","plength","slength","buckets","floor","j","resI","sumI","createField","order","_createCurveFields","type","CURVE","curveOpts","FpFnLE","assign","PrimeEdwardsPoint","ep","_bytes","_hex","clearCofactor","assertValidity","invertedZ","isTorsionFree","isSmallOrder","other","assertSame","init","subtract","multiply","multiplyUnsafe","precompute","isLazy","toRawBytes","hash","eddsaOpts","Gx","Gy","uvRatio","adjustScalarBytes","domain","prehash","mapToCurve","_eddsa_legacy_opts_to_new","extraOpts","validated","cofactor","modP","x2","y2","left","right","isEdValidXY","acoord","banZero","aextpoint","toAffineMemo","iz","X","Y","zz","assertValidMemo","T","X2","Y2","Z2","Z4","aX2","zip215","normed","lastByte","isXOdd","isLastByteOdd","wnaf","equals","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","X3","Y3","T3","Z3","ex","ey","ez","et","msm","_setWindowSize","edwards","eddsa","ExtendedPoint","_eddsa_new_output_to_legacy","cHash","ctx","phflag","modN_LE","getExtendedPublicKey","secretKey","head","prefix","key","hashed","getPrivateScalar","pointBytes","getPublicKey","hashDomainToScalar","context","of","msgs","verifyOpts","_size","publicKey","signature","seed","randomSecretKey","utils","isValidSecretKey","isValidPublicKey","toMontgomery","size","is25519","toMontgomerySecret","randomPrivateKey","keygen","sign","verify","sig","mid","SB","ed25519_CURVE_p","ed25519_CURVE","ED25519_SQRT_M1","v3","v7","_10n","_20n","_40n","_80n","b2","b4","b5","b10","b20","b40","b80","b160","b240","b250","pow_p_5_8","ed25519_pow_2_252_3","vx2","root1","root2","useRoot1","useRoot2","noRoot","ed25519Defaults","ed25519","SQRT_M1","SQRT_AD_MINUS_ONE","INVSQRT_A_MINUS_D","ONE_MINUS_D_SQ","D_MINUS_ONE_SQ","invertSqrt","MAX_255B","bytes255ToNumberLE","calcElligatorRistrettoMap","r0","mod","Ns","Ns_D_is_sq","s_","Nt","s2","W0","W1","W3","_RistrettoPoint","ap","hashToCurve","R1","R2","ristretto255_map","diff","equalBytes","u1","u2","u1_2","u2_2","I","Dx","Dy","u2sq","invsqrt","D1","D2","zInv","_x","_y","one","two","encodeValue","join","encodeURIComponent","String","getPrototypeOf","encodeObjectContextEntry","cause","code","contextAndErrorOptions","errorOptions","contextRest","keys","decodingAdviceMessage","searchParamsString","btoa","encodeContextObject","getErrorMessage","__code","isFixedSize","codec","fixedSize","isLittleEndian","config","endian","numberEncoderFactory","input","encoder","write","range","codecDescription","assertNumberIsBetweenForCodec","arrayBuffer","getSizeFromValue","getEncodedSize","numberDecoderFactory","decoder","read","assertByteArrayIsNotEmptyForCodec","expected","assertByteArrayHasEnoughBytesForCodec","bytesOffset","toArrayBuffer","decode","getU64Encoder","getU64Codec","decoderFixedSize","encoderFixedSize","maxSize","decoderMaxSize","encoderMaxSize","getBigUint64","getU64Decoder","StructError","failure","failures","explanation","rest","path","isObject","isNonArrayObject","print","toFailure","struct","branch","refinement","toFailures","Symbol","iterator","run","coerce","coercer","status","validator","ts","Map","Set","refiner","Struct","props","schema","assert","validate","is","tuples","tuple","done","next","shiftIterator","Element","Class","literal","constant","description","isNaN","optional","record","Key","Value","Structs","Never","union","coerced","first","unknown","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","IOTAS","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","Keccak","suffix","enableXOF","rounds","posOut","state32","keccak","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","keccakP","finish","writeInto","bufferOut","xofInto","xof","keccak_256","gen","HMAC","_key","iHash","oHash","buf","divNearest","den","validateSigFormat","format","validateSigOpts","def","optsn","optName","lowS","DERErr","DER","Err","_tlv","tag","dataLen","lenLen","lengthBytes","_int","parseInt","toSig","int","tlv","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","seq","pprefix","hasEvenY","getWLengths","publicKeyUncompressed","publicKeyHasPrefix","ecdsa","ecdsaOpts","hmac","bits2int","bits2int_modN","CURVE_ORDER","fnBits","getSharedSecret","ecdhOpts","randomBytes_","fieldLen","minLen","reduced","isCompressed","isProbPub","isValidPrivateKey","normPrivateKeyToScalar","secretKeyA","publicKeyB","ecdh","defaultSigOpts","extraEntropy","defaultSigOpts_format","isBiggerThanHalfOrder","validateRS","Signature","recovery","recid","validateSigLength","L","addRecoveryBit","recoverPublicKey","messageHash","FIELD_ORDER","rec","radj","ir","hasHighS","fromCompact","fromDER","normalizeS","toDERRawBytes","toDERHex","toCompactRawBytes","toCompactHex","delta","ORDER_MASK","int2octets","validateMsgAndHash","k2sig","privateKey","some","h1int","seedArgs","kBytes","ik","normS","prepSig","drbg","hashLen","qByteLen","hmacFn","u8n","u8of","byte","reset","reseed","sl","pred","createHmacDrbg","sg","isHex","isObj","derError","tryParsingSig","weierstrass","allowedPrivateKeyLengths","wrapPrivateKey","allowInfinityPoint","endo","_weierstrass_legacy_opts_to_new","_ecdsa_legacy_opts_to_new","_ecdsa","ProjectivePoint","_ecdsa_new_output_to_legacy","beta","basises","assertCompressionIsSupported","encodePoint","_c","bx","decodePoint","uncomp","tail","isValidXY","weierstrassEquation","sqrtError","x3","_4a3","_27b2","aprjpoint","splitEndoScalarN","basis","a1","b1","a2","k1","k2","k1neg","k2neg","MAX_NUM","_splitEndoScalar","finishEndo","endoBeta","k1p","k2p","U1","U2","b3","t0","t1","t2","t3","t4","t5","fake","k1f","k2f","sc","p1","p2","mulEndoUnsafe","multiplyAndAddUnsafe","px","py","pz","fromPrivateKey","weierstrassN","secp256k1_CURVE","secp256k1_ENDO","Fpk1","_6n","_11n","_22n","_23n","_44n","_88n","b6","b9","b11","b22","b44","b88","b176","b220","b223","secp256k1","curveDef","defHash","createCurve","generateKeypair","privateScalar","isOnCurve","toBuffer","Buffer","isBuffer","properties","serialize","SOLANA_SCHEMA","deserialize","decodeUnchecked","deserializeUnchecked","_PublicKey","PUBLIC_KEY_LENGTH","uniquePublicKeyCounter","PublicKey","_bn","isPublicKeyData","decoded","unique","eq","toBase58","toJSON","toArrayLike","zeroPad","alloc","copy","toStringTag","createWithSeed","fromPublicKey","programId","concat","publicKeyBytes","createProgramAddressSync","seeds","createProgramAddress","findProgramAddressSync","address","nonce","seedsWithNonce","findProgramAddress","pubkeyData","default","kind","PACKET_DATA_SIZE","TransactionExpiredBlockheightExceededError","defineProperty","TransactionExpiredTimeoutError","timeoutSeconds","toFixed","TransactionExpiredNonceInvalidError","MessageAccountKeys","staticAccountKeys","accountKeysFromLookups","keySegments","writable","readonly","index","keySegment","flat","compileInstructions","instructions","U8_MAX","keyIndexMap","findKeyIndex","keyIndex","instruction","programIdIndex","accountKeyIndexes","meta","pubkey","property","rustString","rsl","_decode","bind","_encode","rslShim","chars","span","getAlloc","getItemAlloc","elementLayout","layout","decodeLength","elem","encodeLength","rem_len","CompiledKeys","payer","keyMetaMap","compile","getOrInsertDefault","keyMeta","isSigner","isWritable","isInvoked","payerKeyMeta","ix","accountMeta","getMessageComponents","mapEntries","writableSigners","readonlySigners","writableNonSigners","readonlyNonSigners","header","numRequiredSignatures","numReadonlySignedAccounts","numReadonlyUnsignedAccounts","payerAddress","extractTableLookup","lookupTable","writableIndexes","drainedWritableKeys","drainKeysFoundInLookupTable","addresses","readonlyIndexes","drainedReadonlyKeys","accountKey","lookupTableEntries","keyMetaFilter","lookupTableIndexes","drainedKeys","lookupTableIndex","findIndex","entry","END_OF_BUFFER_ERROR_MESSAGE","guardedShift","byteArray","guardedSplice","start","splice","Message","accountKeys","recentBlockhash","indexToProgramIds","account","compiledInstructions","accounts","addressTableLookups","getAccountKeys","compiledKeys","payerKey","isAccountSigner","isAccountWritable","numSignedAccounts","isProgramId","has","programIds","values","nonProgramIds","numKeys","keyCount","keyIndicesCount","dataCount","keyIndices","dataLength","instructionCount","instructionBuffer","instructionBufferLength","signDataLayout","transaction","signData","accountCount","dataSlice","messageArgs","MessageV0","numAccountKeysFromLookups","count","lookup","addressLookupTableAccounts","resolveAddressTableLookups","numStaticAccountKeys","tableLookup","tableAccount","find","lookupTableAccounts","extractResult","addressTableLookup","encodedStaticAccountKeysLength","serializedInstructions","serializeInstructions","encodedInstructionsLength","serializedAddressTableLookups","serializeAddressTableLookups","encodedAddressTableLookupsLength","messageLayout","serializedMessage","serializedMessageLength","staticAccountKeysLength","instructionsLength","addressTableLookupsLength","serializedLength","encodedAccountKeyIndexesLength","encodedDataLength","encodedWritableIndexesLength","encodedReadonlyIndexesLength","maskedPrefix","addressTableLookupsCount","VersionedMessage","deserializeMessageVersion","DEFAULT_SIGNATURE","TransactionInstruction","Transaction","signatures","feePayer","lastValidBlockHeight","nonceInfo","minNonceContextSlot","_message","_json","hasOwnProperty","call","minContextSlot","blockhash","nonceInstruction","signers","items","compileMessage","console","warn","accountMetas","uniqueMetas","pubkeyString","uniqueIndex","sort","localeCompare","localeMatcher","usage","sensitivity","ignorePunctuation","numeric","caseFirst","feePayerIndex","payerMeta","unshift","signedKeys","unsignedKeys","indexOf","_compile","every","pair","serializeMessage","getEstimatedFee","connection","getFeeForMessage","setSigners","seen","uniqueSigners","signer","_partialSign","partialSign","_addSignature","addSignature","sigpair","verifySignatures","requireAllSignatures","_getMessageSignednessErrors","errors","missing","invalid","sigErrors","errorMessage","_serialize","signatureCount","transactionLength","wireTransaction","keyObj","populate","sigPubkeyPair","VersionedTransaction","defaultSignatures","encodedSignaturesLength","transactionLayout","serializedTransaction","serializedTransactionLength","signaturesLength","messageData","signerPubkeys","signerIndex","SYSVAR_CLOCK_PUBKEY","SYSVAR_RECENT_BLOCKHASHES_PUBKEY","SYSVAR_RENT_PUBKEY","SYSVAR_STAKE_HISTORY_PUBKEY","SendTransactionError","action","transactionMessage","logs","maybeLogsOutput","guideText","transactionLogs","transactionError","cachedLogs","getLogs","Promise","resolve","reject","getTransaction","then","tx","logMessages","catch","async","sendAndConfirmTransaction","sendOptions","skipPreflight","preflightCommitment","commitment","maxRetries","sendTransaction","confirmTransaction","abortSignal","nonceAccountPubkey","nonceValue","sleep","ms","setTimeout","encodeData","allocLength","layoutFields","FeeCalculatorLayout","NONCE_ACCOUNT_LENGTH","bigIntLayout","src","bigInt","SYSTEM_INSTRUCTION_LAYOUTS","Create","Assign","Transfer","CreateWithSeed","AdvanceNonceAccount","WithdrawNonceAccount","InitializeNonceAccount","AuthorizeNonceAccount","Allocate","AllocateWithSeed","AssignWithSeed","TransferWithSeed","UpgradeNonceAccount","SystemProgram","createAccount","lamports","space","fromPubkey","newAccountPubkey","transfer","basePubkey","toPubkey","accountPubkey","createAccountWithSeed","createNonceAccount","noncePubkey","initParams","authorizedPubkey","nonceInitialize","authorized","instructionData","nonceAdvance","nonceWithdraw","nonceAuthorize","newAuthorizedPubkey","allocate","Loader","getMinNumSignatures","chunkSize","load","program","balanceNeeded","getMinimumBalanceForRentExemption","programInfo","getAccountInfo","executable","owner","dataLayout","transactions","bytesLengthPadding","_rpcEndpoint","REQUESTS_PER_SECOND","all","deployCommitment","finalizeSignature","getSlot","slot","MS_PER_SLOT","fetch","PublicKeyFromString","RawAccountDataResult","BufferFromRawAccountData","createRpcResult","jsonrpc","UnknownRpcResult","jsonRpcResult","jsonRpcResultAndContext","notificationResultAndContext","GetInflationGovernorResult","foundation","foundationTerm","initial","taper","terminal","GetRecentPrioritizationFeesResult","epoch","effectiveSlot","amount","postBalance","commission","prioritizationFee","GetInflationRateResult","total","GetEpochInfoResult","slotIndex","slotsInEpoch","absoluteSlot","blockHeight","transactionCount","GetEpochScheduleResult","slotsPerEpoch","leaderScheduleSlotOffset","warmup","firstNormalEpoch","firstNormalSlot","GetLeaderScheduleResult","TransactionErrorResult","SignatureStatusResult","SignatureReceivedResult","ParsedInstructionStruct","parsed","PartiallyDecodedInstructionStruct","rentEpoch","unitsConsumed","returnData","innerInstructions","byIdentity","firstSlot","lastSlot","circulating","nonCirculating","nonCirculatingAccounts","TokenAmountResult","uiAmount","decimals","uiAmountString","ParsedAccountDataResult","AccountInfoResult","ParsedOrRawAccountData","ParsedAccountInfoResult","ProgramAccountInfoResult","active","inactive","memo","blockTime","subscription","SlotInfoResult","parent","SlotUpdateResult","timestamp","stats","numTransactionEntries","numSuccessfulTransactions","numFailedTransactions","maxTransactionsPerEntry","VoteAccountInfoResult","gossip","tpu","rpc","votePubkey","nodePubkey","activatedStake","epochVoteAccount","epochCredits","lastVote","rootSlot","ConfirmationStatus","delinquent","SignatureStatusResponse","confirmations","confirmationStatus","AddressTableLookupStruct","ConfirmedTransactionResult","AnnotatedAccountKey","source","ConfirmedTransactionAccountsModeResult","ParsedInstructionResult","RawInstructionResult","ParsedOrRawInstruction","ParsedConfirmedTransactionResult","TokenBalanceResult","accountIndex","mint","uiTokenAmount","LoadedAddressesResult","ConfirmedTransactionMetaResult","fee","preBalances","postBalances","preTokenBalances","postTokenBalances","loadedAddresses","computeUnitsConsumed","costUnits","ParsedConfirmedTransactionMetaResult","TransactionVersionStruct","RewardsResult","rewardType","LogsResult","previousBlockhash","parentSlot","rewards","numTransactions","numSlots","samplePeriodSecs","feeCalculator","lamportsPerSignature","Keypair","keypair","_keypair","generate","fromSecretKey","computedPublicKey","ii","fromSeed","CreateLookupTable","FreezeLookupTable","ExtendLookupTable","DeactivateLookupTable","CloseLookupTable","RequestUnits","RequestHeapFrame","SetComputeUnitLimit","SetComputeUnitPrice","ED25519_INSTRUCTION_LAYOUT","Ed25519Program","createInstructionWithPublicKey","instructionIndex","publicKeyOffset","signatureOffset","messageDataOffset","numSignatures","padding","signatureInstructionIndex","publicKeyInstructionIndex","messageDataSize","messageInstructionIndex","createInstructionWithPrivateKey","publicKeyCreate","SECP256K1_INSTRUCTION_LAYOUT","Secp256k1Program","publicKeyToEthAddress","recoveryId","createInstructionWithEthAddress","ethAddress","rawAddress","startsWith","substr","ethAddressOffset","ethAddressInstructionIndex","pkey","msgHash","privKey","ecdsaSign","_Lockup","STAKE_CONFIG_ID","Lockup","unixTimestamp","custodian","STAKE_INSTRUCTION_LAYOUTS","Initialize","lockup","Authorize","Delegate","Split","Withdraw","Deactivate","Merge","AuthorizeWithSeed","Staker","Withdrawer","StakeProgram","initialize","stakePubkey","maybeLockup","staker","withdrawer","delegate","authorize","stakeAuthorizationType","custodianPubkey","newAuthorized","authorizeWithSeed","authorityBase","authoritySeed","authorityOwner","splitInstruction","splitStakePubkey","split","rentExemptReserve","splitWithSeed","merge","sourceStakePubKey","withdraw","deactivate","VOTE_INSTRUCTION_LAYOUTS","InitializeAccount","voteInit","UpdateValidatorIdentity","voteAuthorizeWithSeedArgs","Voter","VoteProgram","initializeAccount","authorizedVoter","authorizedWithdrawer","voteAuthorizationType","currentAuthorityDerivedKeyBasePubkey","currentAuthorityDerivedKeyOwnerPubkey","currentAuthorityDerivedKeySeed","authorizedWithdrawerPubkey","safeWithdraw","currentVoteAccountBalance","rentExemptMinimum","updateValidatorIdentity","website","details","iconUrl","keybaseUsername","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","Infinity","rt","log","LN2","HpkeError","EncapError","DecapError","ExportError","SealError","OpenError","MessageLimitReachedError","DeriveKeyPairError","dntGlobalThis","baseObj","extObj","Proxy","_target","prop","_receiver","deleteProperty","success","ownKeys","baseKeys","Reflect","extKeys","extKeysSet","desc","getOwnPropertyDescriptor","NativeAlgorithm","enumerable","configurable","_setup","_api","subtle","webcrypto","loadSubtleCrypto","INPUT_LENGTH_LIMIT","w","ret","LABEL_EAE_PRK","LABEL_SHARED_SECRET","Dhkem","prim","kdf","_prim","_kdf","suiteId","serializePublicKey","deserializePublicKey","serializePrivateKey","deserializePrivateKey","importKey","isPublic","generateKeyPair","deriveKeyPair","ikm","encap","ke","ekm","enc","pkrm","recipientPublicKey","dh","kemContext","senderKey","sks","pks","derivePublicKey","pksm","concat3","sharedSecret","_generateSharedSecret","decap","pke","skr","recipientKey","pkr","senderPublicKey","labeledIkm","buildLabeledIkm","labeledInfo","buildLabeledInfo","secretSize","extractAndExpand","KEM_USAGES","Bignum","_num","lessThan","LABEL_CANDIDATE","ORDER_P_256","ORDER_P_384","ORDER_P_521","PKCS8_ALG_ID_P_256","PKCS8_ALG_ID_P_384","PKCS8_ALG_ID_P_521","Ec","kem","hkdf","_hkdf","_alg","namedCurve","_nPk","_nSk","_nDh","_order","_bitmask","_pkcs8AlgId","exportKey","_importRawKey","jwk","base64","replace","byteString","atob","base64UrlToBytes","_importJWK","generateKey","dkpPrk","labeledExtract","bn","counter","labeledExpand","sk","_deserializePkcs8Key","pk","deriveBits","public","crv","pkcs8Key","HPKE_VERSION","HkdfNative","_suiteId","label","_checkInit","info","extract","salt","hashSize","algHash","expand","prk","okm","cur","baseKey","HkdfSha256Native","arguments","AEAD_USAGES","AesGcmContext","_rawKey","seal","iv","aad","_setupKey","alg","additionalData","encrypt","open","decrypt","_importKey","Aes128Gcm","createEncryptionContext","Aes256Gcm","emitNotSupported","_resolve","LABEL_SEC","ExporterContextImpl","api","exporterSecret","_data","_aad","exporterContext","RecipientExporterContextImpl","SenderExporterContextImpl","EncryptionContextImpl","baseNonce","_aead","aead","_nK","keySize","_nN","nonceSize","_nT","tagSize","_ctx","computeNonce","xor","incrementSeq","MAX_SAFE_INTEGER","_Mutex_locked","Mutex","lock","releaseLock","nextLock","previousLock","receiver","__classPrivateFieldGet","__classPrivateFieldSet","_RecipientContextImpl_mutex","RecipientContextImpl","release","pt","_SenderContextImpl_mutex","SenderContextImpl","ct","LABEL_BASE_NONCE","LABEL_EXP","LABEL_INFO_HASH","LABEL_KEY","LABEL_PSK_ID_HASH","LABEL_SECRET","SUITE_ID_HEADER_HPKE","CipherSuiteNative","_kem","createSenderContext","_validateInputLength","mode","psk","_keyScheduleS","createRecipientContext","_keyScheduleR","_keySchedule","pskId","pskIdHash","infoHash","keyScheduleContext","exporterSecretInfo","keyInfo","baseNonceInfo","DhkemP256HkdfSha256Native","CipherSuite","DhkemP256HkdfSha256","HkdfSha256","inRange","ToDictionary","o","Stream","tokens","endOfStream","prepend","token","pop","decoderError","fatal","opt_code_point","DEFAULT_ENCODING","TextDecoder","encoding","toLowerCase","_streaming","_BOMseen","_decoder","_fatal","Boolean","_ignoreBOM","_encoder","_options","UTF8Decoder","utf8_code_point","utf8_bytes_seen","utf8_bytes_needed","utf8_lower_boundary","utf8_upper_boundary","handler","stream","bite","code_point","UTF8Encoder","temp","input_stream","code_points","apply","cp","fromCharCode","codePointsToString","opt_string","string","stringToCodePoints","ieee754","customInspectSymbol","SlowBuffer","INSPECT_MAX_BYTES","K_MAX_LENGTH","createBuffer","RangeError","setPrototypeOf","encodingOrOffset","allocUnsafe","isEncoding","actual","fromString","arrayView","isInstance","fromArrayBuffer","fromArrayLike","fromArrayView","SharedArrayBuffer","valueOf","obj","checked","numberIsNaN","fromObject","toPrimitive","assertSize","mustMatch","loweredCase","utf8ToBytes","base64ToBytes","slowToString","end","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","readUInt16BE","foundIndex","found","hexWrite","remaining","strLen","utf8Write","blitBuffer","asciiWrite","asciiToBytes","base64Write","ucs2Write","units","lo","utf16leToBytes","fromByteArray","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","codePoints","MAX_ARGUMENTS_LENGTH","decodeCodePointsArray","kMaxLength","TYPED_ARRAY_SUPPORT","proto","foo","typedArraySupport","poolSize","allocUnsafeSlow","_isBuffer","compare","list","swap16","swap32","swap64","toLocaleString","inspect","trim","target","thisStart","thisEnd","thisCopy","targetCopy","isFinite","_arr","hexSliceLookupTable","checkOffset","ext","checkInt","wrtBigUInt64LE","checkIntBI","wrtBigUInt64BE","checkIEEE754","writeFloat","littleEndian","noAssert","writeDouble","newBuf","readUintLE","readUIntLE","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readUInt32BE","readBigUInt64LE","defineBigIntMethod","validateNumber","last","boundsError","readBigUInt64BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readBigInt64LE","readBigInt64BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUintLE","writeUIntLE","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeUInt32BE","writeBigUInt64LE","writeBigUInt64BE","writeIntLE","limit","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeBigInt64LE","writeBigInt64BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","sym","getMessage","Base","stack","addNumericalSeparator","ERR_OUT_OF_RANGE","checkBounds","ERR_INVALID_ARG_TYPE","ERR_BUFFER_OUT_OF_BOUNDS","received","isInteger","INVALID_BASE64_RE","leadSurrogate","toByteArray","base64clean","dst","alphabet","table","i16","BufferBigIntNotDefined","rnds8","rng","msCrypto","byteToHex","test","rnds","random","_Buffer","ALPHABET","BASE_MAP","charAt","xc","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","charCode","carry","it3","it4","vch","pbegin","pend","b58","it1","it2","repeat","inherits","ctor","superCtor","super_","TempCtor","BN","isBN","negative","words","red","_init","wordSize","parseHex4Bits","parseHexByte","lowerBound","parseBase","move","dest","cmp","_initNumber","_initArray","_parseHex","_parseBase","toArray","off","_strip","limbLen","limbPow","imuln","_iaddn","_move","_expand","_normSign","for","zeros","groupSizes","groupBases","smallMulTo","ncarry","rword","maxJ","groupSize","groupBase","modrn","idivn","toNumber","ArrayType","reqLength","_toArrayLikeLE","position","_toArrayLikeBE","clz32","_countBits","_zeroBits","zeroBits","toTwos","width","inotn","iaddn","fromTwos","testn","notn","ineg","iuor","ior","or","uor","iuand","iand","and","uand","iuxor","ixor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","iadd","isub","comb10MulTo","a0","al0","ah0","al1","ah1","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","b0","bl0","bh0","bl1","bh1","bl2","bh2","bl3","bh3","bl4","bh4","bl5","bh5","bl6","bh6","b7","bl7","bh7","b8","bl8","bh8","bl9","bh9","w0","imul","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","bigMulTo","hncarry","jumboMulTo","FFTM","mulTo","makeRBT","N","revBin","rb","permute","rbt","rws","iws","rtws","itws","rtwdf","cos","itwdf","sin","rtwdf_","itwdf_","re","ie","ro","io","rx","guessLen13b","odd","conjugate","normalize13b","ws","convert13b","stub","ph","mulp","rwst","iwst","nrws","nrwst","niwst","rmws","mulf","isNegNum","muln","isqr","toBitArray","iushln","carryMask","newCarry","ishln","iushrn","hint","extended","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","subn","iabs","_ishlnsubmul","_wordDiv","bhi","qj","divmod","positive","divn","umod","divRound","dm","half","r2","andln","modn","egcd","g","isEven","yp","xp","im","jm","gcd","_invmp","x1","cmpn","invm","bincn","ucmp","gtn","gt","gten","gte","ltn","lt","lten","lte","eqn","Red","toRed","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","_tmp","K256","P224","P192","P25519","prime","_prime","Mont","imod","rinv","minv","ireduce","rlen","imulK","strip","output","mod3","nOne","lpow","z","wnd","currentLen","mont","b64","lens","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","parts","maxChunkLength","len2","encodeChunk","tripletToBase64","au8","toU8","h2b","isPoint","Gpows","strict","b2n_LE","safe","n2b_32LE","b2h","padh","concatB","arrs","md","pow2","RM1","pow_2_252_3","_shaS","hash2extK","priv","sha512s","cr","etc","concatBytes","sha512Async","messages","sha512Sync","defineProperties","cnd","off1","off2","cnd1","cnd2","u8","buffer_1","checkUint8Array","uint8ArrayToBuffer","Layout","makeDestinationObject","getSpan","replicate","rv","fromArray","nameWithProperty","ExternalLayout","isCount","OffsetLayout","UInt","UIntBE","V2E32","divmodInt64","hi32","lo32","roundedInt64","NearUInt64","NearInt64","Sequence","idx","elo","Structure","decodePrefixes","fd","fsp","firstOffset","lastOffset","lastWrote","fv","layoutFor","offsetOf","Blob","srcBuffer","Events","EE","once","addListener","emitter","event","listener","evt","_events","_eventsCount","clearEvent","EventEmitter","__proto__","eventNames","events","names","getOwnPropertySymbols","listeners","handlers","ee","listenerCount","emit","removeListener","on","removeAllListeners","prefixed","__createBinding","__setModuleDefault","__decorate","decorators","decorate","__importStar","__esModule","__importDefault","BinaryReader","BinaryWriter","BorshError","baseDecode","baseEncode","bn_js_1","bs58_1","textDecoder","INITIAL_LENGTH","fieldPath","originalMessage","addToFieldPath","maybeResize","writeU8","writeU16","writeU32","writeU64","writeBuffer","writeU128","writeU256","writeU512","writeString","writeFixedArray","writeArray","handlingRangeError","propertyKey","propertyDescriptor","originalMethod","readU8","readU16","readU32","readU64","readBuffer","readU128","readU256","readU512","readString","readFixedArray","readArray","capitalizeFirstLetter","toUpperCase","serializeField","fieldType","writer","serializeStruct","borshSerialize","structSchema","deserializeField","reader","deserializeStruct","classType","borshDeserialize","fieldValue","Writer","Reader","basex","exists","SHA2","sha512","copyProps","SafeBuffer","nacl","gf","Float64Array","randombytes","_0","_9","gf0","gf1","_121665","ts64","vn","xi","yi","crypto_verify_16","crypto_verify_32","crypto_core_salsa20","inp","j0","j1","j2","j3","j4","j5","j6","j7","j8","j9","j10","j11","j12","j13","j14","j15","x0","x4","x5","x6","x7","x8","x9","x10","x11","x12","x13","x14","x15","core_salsa20","crypto_core_hsalsa20","core_hsalsa20","sigma","crypto_stream_salsa20_xor","cpos","mpos","crypto_stream_salsa20","crypto_stream","sn","crypto_stream_xor","poly1305","t6","t7","Uint16Array","leftover","fin","crypto_onetimeauth","outpos","crypto_onetimeauth_verify","hpos","crypto_secretbox","crypto_secretbox_open","set25519","car25519","sel25519","pack25519","neq25519","par25519","unpack25519","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b12","b13","b14","b15","inv25519","pow2523","crypto_scalarmult","x32","x16","crypto_scalarmult_base","crypto_box_keypair","crypto_box_beforenm","blocks","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","hibit","h0","h1","h2","h3","h4","h5","h6","h7","h8","h9","r1","r3","r4","r5","r6","r7","r8","r9","mac","macpos","want","crypto_box_afternm","crypto_box_open_afternm","K","crypto_hashblocks_hl","hh","th","tl","Int32Array","crypto_hash","cswap","pack","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","seeded","modL","crypto_sign","sm","smlen","crypto_sign_open","chk","den2","den4","den6","unpackneg","crypto_sign_BYTES","crypto_sign_PUBLICKEYBYTES","crypto_sign_SECRETKEYBYTES","checkLengths","checkArrayTypes","cleanup","lowlevel","crypto_box","crypto_box_open","crypto_secretbox_KEYBYTES","crypto_secretbox_NONCEBYTES","crypto_secretbox_ZEROBYTES","crypto_secretbox_BOXZEROBYTES","crypto_scalarmult_BYTES","crypto_scalarmult_SCALARBYTES","crypto_box_PUBLICKEYBYTES","crypto_box_SECRETKEYBYTES","crypto_box_BEFORENMBYTES","crypto_box_NONCEBYTES","crypto_box_ZEROBYTES","crypto_box_BOXZEROBYTES","crypto_sign_SEEDBYTES","crypto_hash_BYTES","secretbox","box","keyLength","nonceLength","overheadLength","scalarMult","scalarLength","groupElementLength","before","checkBoxLengths","after","keyPair","publicKeyLength","secretKeyLength","sharedKeyLength","signedMsg","mlen","detached","seedLength","signatureLength","hashLength","setPRNG"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/bundle.ecd3017216b8f9e85944.js b/export-and-sign/dist/bundle.ecd3017216b8f9e85944.js new file mode 100644 index 0000000..db5aa11 --- /dev/null +++ b/export-and-sign/dist/bundle.ecd3017216b8f9e85944.js @@ -0,0 +1,3 @@ +/*! For license information please see bundle.ecd3017216b8f9e85944.js.LICENSE.txt */ +(self.webpackChunkexport_and_sign=self.webpackChunkexport_and_sign||[]).push([[96],{22:(t,e,r)=>{"use strict";const n=r(341).v4,i=r(289),s=function(t,e){if(!(this instanceof s))return new s(t,e);e||(e={}),this.options={reviver:void 0!==e.reviver?e.reviver:null,replacer:void 0!==e.replacer?e.replacer:null,generator:void 0!==e.generator?e.generator:function(){return n()},version:void 0!==e.version?e.version:2,notificationIdNull:"boolean"==typeof e.notificationIdNull&&e.notificationIdNull},this.callServer=t};t.exports=s,s.prototype.request=function(t,e,r,n){const s=this;let o=null;const a=Array.isArray(t)&&"function"==typeof e;if(1===this.options.version&&a)throw new TypeError("JSON-RPC 1.0 does not support batching");if(a||!a&&t&&"object"==typeof t&&"function"==typeof e)n=e,o=t;else{"function"==typeof r&&(n=r,r=void 0);const s="function"==typeof n;try{o=i(t,e,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(t){if(s)return n(t);throw t}if(!s)return o}let u;try{u=JSON.stringify(o,this.options.replacer)}catch(t){return n(t)}return this.callServer(u,function(t,e){s._parseResponse(t,e,n)}),o},s.prototype._parseResponse=function(t,e,r){if(t)return void r(t);if(!e)return r();let n;try{n=JSON.parse(e,this.options.reviver)}catch(t){return r(t)}if(3===r.length){if(Array.isArray(n)){const t=function(t){return void 0!==t.error},e=function(e){return!t(e)};return r(null,n.filter(t),n.filter(e))}return r(null,n.error,n.result)}r(null,n)}},112:(t,e,r)=>{"use strict";r.d(e,{AX:()=>bs,Kt:()=>fi});var n=r(287);const i="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function s(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function o(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function a(t,...e){if(!s(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function u(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");o(t.outputLen),o(t.blockLen)}function h(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function c(...t){for(let e=0;e>>e}const d=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),p=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function y(t){if(a(t),d)return t.toHex();let e="";for(let r=0;r=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function m(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);if(d)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let e=0,i=0;et().update(w(e)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function A(t=32){if(i&&"function"==typeof i.getRandomValues)return i.getRandomValues(new Uint8Array(t));if(i&&"function"==typeof i.randomBytes)return Uint8Array.from(i.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function E(t,e,r){return t&e^~t&r}function B(t,e,r){return t&e^t&r^e&r}class I extends k{constructor(t,e,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(t),this.view=l(this.buffer)}update(t){h(this),a(t=w(t));const{view:e,buffer:r,blockLen:n}=this,i=t.length;for(let s=0;sn-s&&(this.process(r,0),s=0);for(let t=s;t>i&s),a=Number(r&s),u=n?4:0,h=n?0:4;t.setUint32(e+u,o,n),t.setUint32(e+h,a,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const o=l(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=u/4,d=this.get();if(f>d.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t>P&_)}:{h:0|Number(t>>P&_),l:0|Number(t&_)}}const O=(t,e,r)=>t>>>r,L=(t,e,r)=>t<<32-r|e>>>r,K=(t,e,r)=>t>>>r|e<<32-r,z=(t,e,r)=>t<<32-r|e>>>r,R=(t,e,r)=>t<<64-r|e>>>r-32,T=(t,e,r)=>t>>>r-32|e<<64-r;function C(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:0|i}}const N=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),j=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,H=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),D=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,W=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),F=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,q=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]),$=new Uint32Array(64);class V extends I{constructor(t=32){super(64,t,8,!1),this.A=0|S[0],this.B=0|S[1],this.C=0|S[2],this.D=0|S[3],this.E=0|S[4],this.F=0|S[5],this.G=0|S[6],this.H=0|S[7]}get(){const{A:t,B:e,C:r,D:n,E:i,F:s,G:o,H:a}=this;return[t,e,r,n,i,s,o,a]}set(t,e,r,n,i,s,o,a){this.A=0|t,this.B=0|e,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(t,e){for(let r=0;r<16;r++,e+=4)$[r]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=$[t-15],r=$[t-2],n=f(e,7)^f(e,18)^e>>>3,i=f(r,17)^f(r,19)^r>>>10;$[t]=i+$[t-7]+n+$[t-16]|0}let{A:r,B:n,C:i,D:s,E:o,F:a,G:u,H:h}=this;for(let t=0;t<64;t++){const e=h+(f(o,6)^f(o,11)^f(o,25))+E(o,a,u)+q[t]+$[t]|0,c=(f(r,2)^f(r,13)^f(r,22))+B(r,n,i)|0;h=u,u=a,a=o,o=s+e|0,s=i,i=n,n=r,r=e+c|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(r,n,i,s,o,a,u,h)}roundClean(){c($)}destroy(){this.set(0,0,0,0,0,0,0,0),c(this.buffer)}}const Z=(()=>function(t,e=!1){const r=t.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;sBigInt(t))))(),G=(()=>Z[0])(),Y=(()=>Z[1])(),X=new Uint32Array(80),J=new Uint32Array(80);class Q extends I{constructor(t=64){super(128,t,16,!1),this.Ah=0|M[0],this.Al=0|M[1],this.Bh=0|M[2],this.Bl=0|M[3],this.Ch=0|M[4],this.Cl=0|M[5],this.Dh=0|M[6],this.Dl=0|M[7],this.Eh=0|M[8],this.El=0|M[9],this.Fh=0|M[10],this.Fl=0|M[11],this.Gh=0|M[12],this.Gl=0|M[13],this.Hh=0|M[14],this.Hl=0|M[15]}get(){const{Ah:t,Al:e,Bh:r,Bl:n,Ch:i,Cl:s,Dh:o,Dl:a,Eh:u,El:h,Fh:c,Fl:l,Gh:f,Gl:d,Hh:p,Hl:y}=this;return[t,e,r,n,i,s,o,a,u,h,c,l,f,d,p,y]}set(t,e,r,n,i,s,o,a,u,h,c,l,f,d,p,y){this.Ah=0|t,this.Al=0|e,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|o,this.Dl=0|a,this.Eh=0|u,this.El=0|h,this.Fh=0|c,this.Fl=0|l,this.Gh=0|f,this.Gl=0|d,this.Hh=0|p,this.Hl=0|y}process(t,e){for(let r=0;r<16;r++,e+=4)X[r]=t.getUint32(e),J[r]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|X[t-15],r=0|J[t-15],n=K(e,r,1)^K(e,r,8)^O(e,0,7),i=z(e,r,1)^z(e,r,8)^L(e,r,7),s=0|X[t-2],o=0|J[t-2],a=K(s,o,19)^R(s,o,61)^O(s,0,6),u=z(s,o,19)^T(s,o,61)^L(s,o,6),h=H(i,u,J[t-7],J[t-16]),c=D(h,n,a,X[t-7],X[t-16]);X[t]=0|c,J[t]=0|h}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:o,Cl:a,Dh:u,Dl:h,Eh:c,El:l,Fh:f,Fl:d,Gh:p,Gl:y,Hh:g,Hl:m}=this;for(let t=0;t<80;t++){const e=K(c,l,14)^K(c,l,18)^R(c,l,41),b=z(c,l,14)^z(c,l,18)^T(c,l,41),w=c&f^~c&p,v=W(m,b,l&d^~l&y,Y[t],J[t]),k=F(v,g,e,w,G[t],X[t]),x=0|v,A=K(r,n,28)^R(r,n,34)^R(r,n,39),E=z(r,n,28)^T(r,n,34)^T(r,n,39),B=r&i^r&o^i&o,I=n&s^n&a^s&a;g=0|p,m=0|y,p=0|f,y=0|d,f=0|c,d=0|l,({h:c,l}=C(0|u,0|h,0|k,0|x)),u=0|o,h=0|a,o=0|i,a=0|s,i=0|r,s=0|n;const S=N(x,E,I);r=j(S,k,A,B),n=0|S}({h:r,l:n}=C(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=C(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=C(0|this.Ch,0|this.Cl,0|o,0|a)),({h:u,l:h}=C(0|this.Dh,0|this.Dl,0|u,0|h)),({h:c,l}=C(0|this.Eh,0|this.El,0|c,0|l)),({h:f,l:d}=C(0|this.Fh,0|this.Fl,0|f,0|d)),({h:p,l:y}=C(0|this.Gh,0|this.Gl,0|p,0|y)),({h:g,l:m}=C(0|this.Hh,0|this.Hl,0|g,0|m)),this.set(r,n,i,s,o,a,u,h,c,l,f,d,p,y,g,m)}roundClean(){c(X,J)}destroy(){c(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const tt=x(()=>new V),et=x(()=>new Q),rt=BigInt(0),nt=BigInt(1);function it(t,e=""){if("boolean"!=typeof t)throw new Error((e&&`"${e}"`)+"expected boolean, got type="+typeof t);return t}function st(t,e,r=""){const n=s(t),i=t?.length,o=void 0!==e;if(!n||o&&i!==e)throw new Error((r&&`"${r}" `)+"expected Uint8Array"+(o?` of length ${e}`:"")+", got "+(n?`length=${i}`:"type="+typeof t));return t}function ot(t){const e=t.toString(16);return 1&e.length?"0"+e:e}function at(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return""===t?rt:BigInt("0x"+t)}function ut(t){return at(y(t))}function ht(t){return a(t),at(y(Uint8Array.from(t).reverse()))}function ct(t,e){return m(t.toString(16).padStart(2*e,"0"))}function lt(t,e){return ct(t,e).reverse()}function ft(t,e,r){let n;if("string"==typeof e)try{n=m(e)}catch(e){throw new Error(t+" must be hex string or Uint8Array, cause: "+e)}else{if(!s(e))throw new Error(t+" must be hex string or Uint8Array");n=Uint8Array.from(e)}const i=n.length;if("number"==typeof r&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function dt(t){return Uint8Array.from(t)}const pt=t=>"bigint"==typeof t&&rt<=t;function yt(t,e,r,n){if(!function(t,e,r){return pt(t)&&pt(e)&&pt(r)&&e<=t&&trt;t>>=nt,e+=1);return e}const mt=t=>(nt<n(t,e,!1)),Object.entries(r).forEach(([t,e])=>n(t,e,!0))}const wt=()=>{throw new Error("not implemented")};function vt(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(void 0!==i)return i;const s=t(r,...n);return e.set(r,s),s}}const kt=BigInt(0),xt=BigInt(1),At=BigInt(2),Et=BigInt(3),Bt=BigInt(4),It=BigInt(5),St=BigInt(7),Mt=BigInt(8),_t=BigInt(9),Pt=BigInt(16);function Ut(t,e){const r=t%e;return r>=kt?r:e+r}function Ot(t,e,r){let n=t;for(;e-- >kt;)n*=n,n%=r;return n}function Lt(t,e){if(t===kt)throw new Error("invert: expected non-zero number");if(e<=kt)throw new Error("invert: expected positive modulus, got "+e);let r=Ut(t,e),n=e,i=kt,s=xt,o=xt,a=kt;for(;r!==kt;){const t=n/r,e=n%r,u=i-o*t,h=s-a*t;n=r,r=e,i=o,s=a,o=u,a=h}if(n!==xt)throw new Error("invert: does not exist");return Ut(i,e)}function Kt(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function zt(t,e){const r=(t.ORDER+xt)/Bt,n=t.pow(e,r);return Kt(t,n,e),n}function Rt(t,e){const r=(t.ORDER-It)/Mt,n=t.mul(e,At),i=t.pow(n,r),s=t.mul(e,i),o=t.mul(t.mul(s,At),i),a=t.mul(s,t.sub(o,t.ONE));return Kt(t,a,e),a}function Tt(t){if(t1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return zt;let s=i.pow(n,e);const o=(e+xt)/At;return function(t,n){if(t.is0(n))return n;if(1!==Ht(t,n))throw new Error("Cannot find square root");let i=r,a=t.mul(t.ONE,s),u=t.pow(n,e),h=t.pow(n,o);for(;!t.eql(u,t.ONE);){if(t.is0(u))return t.ZERO;let e=1,r=t.sqr(u);for(;!t.eql(r,t.ONE);)if(e++,r=t.sqr(r),e===i)throw new Error("Cannot find square root");const n=xt<(Ut(t,e)&xt)===xt,Nt=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jt(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((e,r,i)=>t.is0(r)?e:(n[i]=e,t.mul(e,r)),t.ONE),s=t.inv(i);return e.reduceRight((e,r,i)=>t.is0(r)?e:(n[i]=t.mul(e,n[i]),t.mul(e,r)),s),n}function Ht(t,e){const r=(t.ORDER-xt)/At,n=t.pow(e,r),i=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Dt(t,e){void 0!==e&&o(e);const r=void 0!==e?e:t.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function Wt(t,e,r=!1,n={}){if(t<=kt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o,a=!1;if("object"==typeof e&&null!=e){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const t=e;t.BITS&&(i=t.BITS),t.sqrt&&(s=t.sqrt),"boolean"==typeof t.isLE&&(r=t.isLE),"boolean"==typeof t.modFromBytes&&(a=t.modFromBytes),o=t.allowedLengths}else"number"==typeof e&&(i=e),n.sqrt&&(s=n.sqrt);const{nBitLength:u,nByteLength:h}=Dt(t,i);if(h>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const l=Object.freeze({ORDER:t,isLE:r,BITS:u,BYTES:h,MASK:mt(u),ZERO:kt,ONE:xt,allowedLengths:o,create:e=>Ut(e,t),isValid:e=>{if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return kt<=e&&et===kt,isValidNot0:t=>!l.is0(t)&&l.isValid(t),isOdd:t=>(t&xt)===xt,neg:e=>Ut(-e,t),eql:(t,e)=>t===e,sqr:e=>Ut(e*e,t),add:(e,r)=>Ut(e+r,t),sub:(e,r)=>Ut(e-r,t),mul:(e,r)=>Ut(e*r,t),pow:(t,e)=>function(t,e,r){if(rkt;)r&xt&&(n=t.mul(n,i)),i=t.sqr(i),r>>=xt;return n}(l,t,e),div:(e,r)=>Ut(e*Lt(r,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>Lt(e,t),sqrt:s||(e=>{return c||(c=(r=t)%Bt===Et?zt:r%Mt===It?Rt:r%Pt===_t?function(t){const e=Wt(t),r=Tt(t),n=r(e,e.neg(e.ONE)),i=r(e,n),s=r(e,e.neg(n)),o=(t+St)/Pt;return(t,e)=>{let r=t.pow(e,o),a=t.mul(r,n);const u=t.mul(r,i),h=t.mul(r,s),c=t.eql(t.sqr(a),e),l=t.eql(t.sqr(u),e);r=t.cmov(r,a,c),a=t.cmov(h,u,l);const f=t.eql(t.sqr(a),e),d=t.cmov(r,a,f);return Kt(t,d,e),d}}(r):Tt(r)),c(l,e);var r}),toBytes:t=>r?lt(t,h):ct(t,h),fromBytes:(e,n=!0)=>{if(o){if(!o.includes(e.length)||e.length>h)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);const t=new Uint8Array(h);t.set(e,r?0:t.length-e.length),e=t}if(e.length!==h)throw new Error("Field.fromBytes: expected "+h+" bytes, got "+e.length);let i=r?ht(e):ut(e);if(a&&(i=Ut(i,t)),!n&&!l.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:t=>jt(l,t),cmov:(t,e,r)=>r?e:t});return Object.freeze(l)}function Ft(t){if("bigint"!=typeof t)throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function qt(t){const e=Ft(t);return e+Math.ceil(e/2)}const $t=BigInt(0),Vt=BigInt(1);function Zt(t,e){const r=e.negate();return t?r:e}function Gt(t,e){const r=jt(t.Fp,e.map(t=>t.Z));return e.map((e,n)=>t.fromAffine(e.toAffine(r[n])))}function Yt(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Xt(t,e){Yt(t,e);const r=2**t;return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1),mask:mt(t),maxNumber:r,shiftBy:BigInt(t)}}function Jt(t,e,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(t&i),u=t>>o;a>n&&(a-=s,u+=Vt);const h=e*n;return{nextN:u,offset:h+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:e%2!=0,offsetF:h}}const Qt=new WeakMap,te=new WeakMap;function ee(t){return te.get(t)||1}function re(t){if(t!==$t)throw new Error("invalid wNAF")}class ne{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,r=this.ZERO){let n=t;for(;e>$t;)e&Vt&&(r=r.add(n)),n=n.double(),e>>=Vt;return r}precomputeWindow(t,e){const{windows:r,windowSize:n}=Xt(e,this.bits),i=[];let s=t,o=s;for(let t=0;t{if(!(t instanceof e))throw new Error("invalid point at index "+r)})})(r,t),function(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}(n,e);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=gt(BigInt(i));let u=1;a>12?u=a-3:a>4?u=a-2:a>0&&(u=2);const h=mt(u),c=new Array(Number(h)+1).fill(o);let l=o;for(let t=Math.floor((e.BITS-1)/u)*u;t>=0;t-=u){c.fill(o);for(let e=0;e>BigInt(t)&h);c[s]=c[s].add(r[e])}let e=o;for(let t=c.length-1,r=o;t>0;t--)r=r.add(c[t]),e=e.add(r);if(l=l.add(e),0!==t)for(let t=0;t(t[e]="function",t),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(e),e}return Wt(t,{isLE:r})}function oe(t,e,r={},n){if(void 0===n&&(n="edwards"===t),!e||"object"!=typeof e)throw new Error(`expected valid ${t} CURVE object`);for(const t of["p","n","h"]){const r=e[t];if(!("bigint"==typeof r&&r>$t))throw new Error(`CURVE.${t} must be positive bigint`)}const i=se(e.p,r.Fp,n),s=se(e.n,r.Fn,n),o=["Gx","Gy","a","weierstrass"===t?"b":"d"];for(const t of o)if(!i.isValid(e[t]))throw new Error(`CURVE.${t} must be valid field element of CURVE.Fp`);return{CURVE:e=Object.freeze(Object.assign({},e)),Fp:i,Fn:s}}const ae=BigInt(0),ue=BigInt(1),he=BigInt(2),ce=BigInt(8);class le{constructor(t){this.ep=t}static fromBytes(t){wt()}static fromHex(t){wt()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return y(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}}function fe(t){const{CURVE:e,curveOpts:r,hash:n,eddsaOpts:i}=function(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r={Fp:t.Fp,Fn:Wt(e.n,t.nBitLength,!0),uvRatio:t.uvRatio},n={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:r,hash:t.hash,eddsaOpts:n}}(t),o=function(t,e={}){const r=oe("edwards",t,e,e.FpFnLE),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:o}=s;bt(e,{},{uvRatio:"function"});const a=he<n.create(t),h=e.uvRatio||((t,e)=>{try{return{isValid:!0,value:n.sqrt(n.div(t,e))}}catch(t){return{isValid:!1,value:ae}}});if(!function(t,e,r,n){const i=t.sqr(r),s=t.sqr(n),o=t.add(t.mul(e.a,i),s),a=t.add(t.ONE,t.mul(e.d,t.mul(i,s)));return t.eql(o,a)}(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function c(t,e,r=!1){return yt("coordinate "+t,e,r?ue:ae,a),e}function l(t){if(!(t instanceof p))throw new Error("ExtendedPoint expected")}const f=vt((t,e)=>{const{X:r,Y:i,Z:s}=t,o=t.is0();null==e&&(e=o?ce:n.inv(s));const a=u(r*e),h=u(i*e),c=n.mul(s,e);if(o)return{x:ae,y:ue};if(c!==ue)throw new Error("invZ was invalid");return{x:a,y:h}}),d=vt(t=>{const{a:e,d:r}=s;if(t.is0())throw new Error("bad point: ZERO");const{X:n,Y:i,Z:o,T:a}=t,h=u(n*n),c=u(i*i),l=u(o*o),f=u(l*l),d=u(h*e);if(u(l*u(d+c))!==u(f+u(r*u(h*c))))throw new Error("bad point: equation left != right (1)");if(u(n*i)!==u(o*a))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(t,e,r,n){this.X=c("x",t),this.Y=c("y",e),this.Z=c("z",r,!0),this.T=c("t",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){if(t instanceof p)throw new Error("extended point not allowed");const{x:e,y:r}=t||{};return c("x",e),c("y",r),new p(e,r,ue,u(e*r))}static fromBytes(t,e=!1){const r=n.BYTES,{a:i,d:o}=s;t=dt(st(t,r,"point")),it(e,"zip215");const c=dt(t),l=t[r-1];c[r-1]=-129&l;const f=ht(c),d=e?a:n.ORDER;yt("point.y",f,ae,d);const y=u(f*f),g=u(y-ue),m=u(o*y-i);let{isValid:b,value:w}=h(g,m);if(!b)throw new Error("bad point: invalid y coordinate");const v=(w&ue)===ue,k=!!(128&l);if(!e&&w===ae&&k)throw new Error("bad point: x=0 and x_0=1");return k!==v&&(w=u(-w)),p.fromAffine({x:w,y:f})}static fromHex(t,e=!1){return p.fromBytes(ft("point",t),e)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return g.createCache(this,t),e||this.multiply(he),this}assertValidity(){d(this)}equals(t){l(t);const{X:e,Y:r,Z:n}=this,{X:i,Y:s,Z:o}=t,a=u(e*o),h=u(i*n),c=u(r*o),f=u(s*n);return a===h&&c===f}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.X),this.Y,this.Z,u(-this.T))}double(){const{a:t}=s,{X:e,Y:r,Z:n}=this,i=u(e*e),o=u(r*r),a=u(he*u(n*n)),h=u(t*i),c=e+r,l=u(u(c*c)-i-o),f=h+o,d=f-a,y=h-o,g=u(l*d),m=u(f*y),b=u(l*y),w=u(d*f);return new p(g,m,w,b)}add(t){l(t);const{a:e,d:r}=s,{X:n,Y:i,Z:o,T:a}=this,{X:h,Y:c,Z:f,T:d}=t,y=u(n*h),g=u(i*c),m=u(a*r*d),b=u(o*f),w=u((n+i)*(h+c)-y-g),v=b-m,k=b+m,x=u(g-e*y),A=u(w*v),E=u(k*x),B=u(w*x),I=u(v*k);return new p(A,E,I,B)}subtract(t){return this.add(t.negate())}multiply(t){if(!i.isValidNot0(t))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:e,f:r}=g.cached(this,t,t=>Gt(p,t));return Gt(p,[e,r])[0]}multiplyUnsafe(t,e=p.ZERO){if(!i.isValid(t))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return t===ae?p.ZERO:this.is0()||t===ue?this:g.unsafe(this,t,t=>Gt(p,t),e)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(t){return f(this,t)}clearCofactor(){return o===ue?this:this.multiplyUnsafe(o)}toBytes(){const{x:t,y:e}=this.toAffine(),r=n.toBytes(e);return r[r.length-1]|=t&ue?128:0,r}toHex(){return y(this.toBytes())}toString(){return``}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(t){return Gt(p,t)}static msm(t,e){return ie(p,i,t,e)}_setWindowSize(t){this.precompute(t)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,ue,u(s.Gx*s.Gy)),p.ZERO=new p(ae,ue,ue,ae),p.Fp=n,p.Fn=i;const g=new ne(p,i.BITS);return p.BASE.precompute(8),p}(e,r);return function(t,e){const r=e.Point;return Object.assign({},e,{ExtendedPoint:r,CURVE:t,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(t,function(t,e,r={}){if("function"!=typeof e)throw new Error('"hash" function param is required');bt(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:i,Fp:o,Fn:a}=t,u=r.randomBytes||A,h=r.adjustScalarBytes||(t=>t),c=r.domain||((t,e,r)=>{if(it(r,"phflag"),e.length||r)throw new Error("Contexts/pre-hash are not supported");return t});function l(t){return a.create(ht(t))}function f(t){const{head:r,prefix:n,scalar:s}=function(t){const r=m.secretKey;t=ft("private key",t,r);const n=ft("hashed private key",e(t),2*r),i=h(n.slice(0,r));return{head:i,prefix:n.slice(r,2*r),scalar:l(i)}}(t),o=i.multiply(s),a=o.toBytes();return{head:r,prefix:n,scalar:s,point:o,pointBytes:a}}function d(t){return f(t).pointBytes}function p(t=Uint8Array.of(),...r){const i=v(...r);return l(e(c(i,ft("context",t),!!n)))}const y={zip215:!0},g=o.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function b(t=u(m.seed)){return st(t,m.seed,"seed")}const w={getExtendedPublicKey:f,randomSecretKey:b,isValidSecretKey:function(t){return s(t)&&t.length===a.BYTES},isValidPublicKey:function(e,r){try{return!!t.fromBytes(e,r)}catch(t){return!1}},toMontgomery(e){const{y:r}=t.fromBytes(e),n=m.publicKey,i=32===n;if(!i&&57!==n)throw new Error("only defined for 25519 and 448");const s=i?o.div(ue+r,ue-r):o.div(r-ue,r+ue);return o.toBytes(s)},toMontgomerySecret(t){const r=m.secretKey;st(t,r);const n=e(t.subarray(0,r));return h(n).subarray(0,r)},randomPrivateKey:b,precompute:(e=8,r=t.BASE)=>r.precompute(e,!1)};return Object.freeze({keygen:function(t){const e=w.randomSecretKey(t);return{secretKey:e,publicKey:d(e)}},getPublicKey:d,sign:function(t,e,r={}){t=ft("message",t),n&&(t=n(t));const{prefix:s,scalar:o,pointBytes:u}=f(e),h=p(r.context,s,t),c=i.multiply(h).toBytes(),l=p(r.context,c,u,t),d=a.create(h+l*o);if(!a.isValid(d))throw new Error("sign failed: invalid s");return st(v(c,a.toBytes(d)),m.signature,"result")},verify:function(e,r,s,o=y){const{context:a,zip215:u}=o,h=m.signature;e=ft("signature",e,h),r=ft("message",r),s=ft("publicKey",s,m.publicKey),void 0!==u&&it(u,"zip215"),n&&(r=n(r));const c=h/2,l=e.subarray(0,c),f=ht(e.subarray(c,h));let d,g,b;try{d=t.fromBytes(s,u),g=t.fromBytes(l,u),b=i.multiplyUnsafe(f)}catch(t){return!1}if(!u&&d.isSmallOrder())return!1;const w=p(a,g.toBytes(),d.toBytes(),r);return g.add(d.multiplyUnsafe(w)).subtract(b).clearCofactor().is0()},utils:w,Point:t,lengths:m})}(o,n,i))}b("HashToScalar-");const de=BigInt(0),pe=BigInt(1),ye=BigInt(2),ge=(BigInt(3),BigInt(5)),me=BigInt(8),be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),we=(()=>({p:be,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:me,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function ve(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const ke=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function xe(t,e){const r=be,n=Ut(e*e*e,r),i=Ut(n*n*e,r);let s=Ut(t*n*function(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=be,o=t*t%s*t%s,a=Ot(o,ye,s)*o%s,u=Ot(a,pe,s)*t%s,h=Ot(u,ge,s)*u%s,c=Ot(h,e,s)*h%s,l=Ot(c,r,s)*c%s,f=Ot(l,n,s)*l%s,d=Ot(f,i,s)*f%s,p=Ot(d,i,s)*f%s,y=Ot(p,e,s)*h%s;return{pow_p_5_8:Ot(y,ye,s)*t%s,b2:o}}(t*i).pow_p_5_8,r);const o=Ut(e*s*s,r),a=s,u=Ut(s*ke,r),h=o===t,c=o===Ut(-t,r),l=o===Ut(-t*ke,r);return h&&(s=a),(c||l)&&(s=u),Ct(s,r)&&(s=Ut(-s,r)),{isValid:h||c,value:s}}const Ae=(()=>Wt(we.p,{isLE:!0}))(),Ee=(()=>Wt(we.n,{isLE:!0}))(),Be=(()=>({...we,Fp:Ae,hash:et,adjustScalarBytes:ve,uvRatio:xe}))(),Ie=(()=>fe(Be))(),Se=ke,Me=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),_e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Pe=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Ue=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Oe=t=>xe(pe,t),Le=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ke=t=>Ie.Point.Fp.create(ht(t)&Le);function ze(t){const{d:e}=we,r=be,n=t=>Ae.create(t),i=n(Se*t*t),s=n((i+pe)*Pe);let o=BigInt(-1);const a=n((o-e*i)*n(i+e));let{isValid:u,value:h}=xe(s,a),c=n(h*t);Ct(c,r)||(c=n(-c)),u||(h=c),u||(o=i);const l=n(o*(i-pe)*Ue-a),f=h*h,d=n((h+h)*a),p=n(l*Me),y=n(pe-f),g=n(pe+f);return new Ie.Point(n(d*g),n(y*p),n(p*g),n(d*y))}class Re extends le{constructor(t){super(t)}static fromAffine(t){return new Re(Ie.Point.fromAffine(t))}assertSame(t){if(!(t instanceof Re))throw new Error("RistrettoPoint expected")}init(t){return new Re(t)}static hashToCurve(t){return function(t){a(t,64);const e=ze(Ke(t.subarray(0,32))),r=ze(Ke(t.subarray(32,64)));return new Re(e.add(r))}(ft("ristrettoHash",t,64))}static fromBytes(t){a(t,32);const{a:e,d:r}=we,n=be,i=t=>Ae.create(t),s=Ke(t);if(!function(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;nAe.create(t),o=s(s(r+e)*s(r-e)),a=s(t*e),u=s(a*a),{value:h}=Oe(s(o*u)),c=s(h*o),l=s(h*a),f=s(c*l*n);let d;if(Ct(n*f,i)){let r=s(e*Se),n=s(t*Se);t=r,e=n,d=s(c*_e)}else d=l;Ct(t*f,i)&&(e=s(-e));let p=s((r-e)*d);return Ct(p,i)&&(p=s(-p)),Ae.toBytes(p)}equals(t){this.assertSame(t);const{X:e,Y:r}=this.ep,{X:n,Y:i}=t.ep,s=t=>Ae.create(t),o=s(e*i)===s(r*n),a=s(r*i)===s(e*n);return o||a}is0(){return this.equals(Re.ZERO)}}Re.BASE=(()=>new Re(Ie.Point.BASE))(),Re.ZERO=(()=>new Re(Ie.Point.ZERO))(),Re.Fp=(()=>Ae)(),Re.Fn=(()=>Ee)();var Te=r(404),Ce=r.n(Te),Ne=r(763),je=r.n(Ne);function He(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function De(t,...e){if(!((r=t)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function We(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Fe(t,e){De(t);const r=e.outputLen;if(t.length>>e}function Ze(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Ge=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?t=>t:function(t){for(let e=0;et().update(Ye(e)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Qe(t,e,r){return t&e^~t&r}function tr(t,e,r){return t&e^t&r^e&r}class er extends Xe{constructor(t,e,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(t),this.view=$e(this.buffer)}update(t){We(this),De(t=Ye(t));const{view:e,buffer:r,blockLen:n}=this,i=t.length;for(let s=0;sn-s&&(this.process(r,0),s=0);for(let t=s;t>i&s),a=Number(r&s),u=n?4:0,h=n?0:4;t.setUint32(e+u,o,n),t.setUint32(e+h,a,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const o=$e(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t>ir&nr)}:{h:0|Number(t>>ir&nr),l:0|Number(t&nr)}}const or=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]),ar=new Uint32Array(64);class ur extends er{constructor(t=32){super(64,t,8,!1),this.A=0|rr[0],this.B=0|rr[1],this.C=0|rr[2],this.D=0|rr[3],this.E=0|rr[4],this.F=0|rr[5],this.G=0|rr[6],this.H=0|rr[7]}get(){const{A:t,B:e,C:r,D:n,E:i,F:s,G:o,H:a}=this;return[t,e,r,n,i,s,o,a]}set(t,e,r,n,i,s,o,a){this.A=0|t,this.B=0|e,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(t,e){for(let r=0;r<16;r++,e+=4)ar[r]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=ar[t-15],r=ar[t-2],n=Ve(e,7)^Ve(e,18)^e>>>3,i=Ve(r,17)^Ve(r,19)^r>>>10;ar[t]=i+ar[t-7]+n+ar[t-16]|0}let{A:r,B:n,C:i,D:s,E:o,F:a,G:u,H:h}=this;for(let t=0;t<64;t++){const e=h+(Ve(o,6)^Ve(o,11)^Ve(o,25))+Qe(o,a,u)+or[t]+ar[t]|0,c=(Ve(r,2)^Ve(r,13)^Ve(r,22))+tr(r,n,i)|0;h=u,u=a,a=o,o=s+e|0,s=i,i=n,n=r,r=e+c|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(r,n,i,s,o,a,u,h)}roundClean(){qe(ar)}destroy(){this.set(0,0,0,0,0,0,0,0),qe(this.buffer)}}const hr=Je(()=>new ur);var cr=r(755),lr=r(601);function fr(t){return Array.isArray(t)?"%5B"+t.map(fr).join("%2C%20")+"%5D":"bigint"==typeof t?`${t}n`:encodeURIComponent(String(null!=t&&null===Object.getPrototypeOf(t)?{...t}:t))}function dr([t,e]){return`${t}=${fr(e)}`}var pr=class extends Error{cause=this.cause;context;constructor(...[t,e]){let r,n;if(e){const{cause:t,...i}=e;t&&(n={cause:t}),Object.keys(i).length>0&&(r=i)}super(function(t,e={}){{let r=`Solana error #${t}; Decode this error by running \`npx @solana/errors decode -- ${t}`;return Object.keys(e).length&&(r+=` '${function(t){const e=Object.entries(t).map(dr).join("&");return btoa(e)}(e)}'`),`${r}\``}}(t,r),n),this.context={__code:t,...r},this.name="SolanaError"}};function yr(t){return"fixedSize"in t&&"number"==typeof t.fixedSize}function gr(t){return 1!==t?.endian}function mr(t){return e={fixedSize:t.size,write(e,r,n){t.range&&function(t,e,r,n){if(nr)throw new pr(8078011,{codecDescription:t,max:r,min:e,value:n})}(t.name,t.range[0],t.range[1],e);const i=new ArrayBuffer(t.size);return t.set(new DataView(i),e,gr(t.config)),r.set(new Uint8Array(i),n),n+t.size}},Object.freeze({...e,encode:t=>{const r=new Uint8Array(function(t,e){return"fixedSize"in e?e.fixedSize:e.getSizeFromValue(t)}(t,e));return e.write(t,r,0),r}});var e}function br(t){return e={fixedSize:t.size,read(e,r=0){!function(t,e,r=0){if(e.length-r<=0)throw new pr(8078e3,{codecDescription:t})}(t.name,e,r),function(t,e,r,n=0){const i=r.length-n;if(ie.read(t,r)[0]});var e}var wr=(t={})=>mr({config:t,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(t,e,r)=>t.setBigUint64(0,BigInt(e),r),size:8}),vr=(t={})=>function(t,e){if(yr(t)!==yr(e))throw new pr(8078004);if(yr(t)&&yr(e)&&t.fixedSize!==e.fixedSize)throw new pr(8078005,{decoderFixedSize:e.fixedSize,encoderFixedSize:t.fixedSize});if(!yr(t)&&!yr(e)&&t.maxSize!==e.maxSize)throw new pr(8078006,{decoderMaxSize:e.maxSize,encoderMaxSize:t.maxSize});return{...e,...t,decode:e.decode,encode:t.encode,read:e.read,write:t.write}}(wr(t),((t={})=>br({config:t,get:(t,e)=>t.getBigUint64(0,e),name:"u64",size:8}))(t));class kr extends TypeError{constructor(t,e){let r;const{message:n,explanation:i,...s}=t,{path:o}=t,a=0===o.length?n:`At path: ${o.join(".")} -- ${n}`;super(i??a),null!=i&&(this.cause=a),Object.assign(this,s),this.name=this.constructor.name,this.failures=()=>r??(r=[t,...e()])}}function xr(t){return"object"==typeof t&&null!=t}function Ar(t){return xr(t)&&!Array.isArray(t)}function Er(t){return"symbol"==typeof t?t.toString():"string"==typeof t?JSON.stringify(t):`${t}`}function Br(t,e,r,n){if(!0===t)return;!1===t?t={}:"string"==typeof t&&(t={message:t});const{path:i,branch:s}=e,{type:o}=r,{refinement:a,message:u=`Expected a value of type \`${o}\`${a?` with refinement \`${a}\``:""}, but received: \`${Er(n)}\``}=t;return{value:n,type:o,refinement:a,key:i[i.length-1],path:i,branch:s,...t,message:u}}function*Ir(t,e,r,n){var i;xr(i=t)&&"function"==typeof i[Symbol.iterator]||(t=[t]);for(const i of t){const t=Br(i,e,r,n);t&&(yield t)}}function*Sr(t,e,r={}){const{path:n=[],branch:i=[t],coerce:s=!1,mask:o=!1}=r,a={path:n,branch:i,mask:o};s&&(t=e.coercer(t,a));let u="valid";for(const n of e.validator(t,a))n.explanation=r.message,u="not_valid",yield[n,void 0];for(let[h,c,l]of e.entries(t,a)){const e=Sr(c,l,{path:void 0===h?n:[...n,h],branch:void 0===h?i:[...i,c],coerce:s,mask:o,message:r.message});for(const r of e)r[0]?(u=null!=r[0].refinement?"not_refined":"not_valid",yield[r[0],void 0]):s&&(c=r[1],void 0===h?t=c:t instanceof Map?t.set(h,c):t instanceof Set?t.add(c):xr(t)&&(void 0!==c||h in t)&&(t[h]=c))}if("not_valid"!==u)for(const n of e.refiner(t,a))n.explanation=r.message,u="not_refined",yield[n,void 0];"valid"===u&&(yield[void 0,t])}class Mr{constructor(t){const{type:e,schema:r,validator:n,refiner:i,coercer:s=t=>t,entries:o=function*(){}}=t;this.type=e,this.schema=r,this.entries=o,this.coercer=s,this.validator=n?(t,e)=>Ir(n(t,e),e,this,t):()=>[],this.refiner=i?(t,e)=>Ir(i(t,e),e,this,t):()=>[]}assert(t,e){return function(t,e,r){const n=Ur(t,e,{message:r});if(n[0])throw n[0]}(t,this,e)}create(t,e){return _r(t,this,e)}is(t){return Pr(t,this)}mask(t,e){return function(t,e,r){const n=Ur(t,e,{coerce:!0,mask:!0,message:r});if(n[0])throw n[0];return n[1]}(t,this,e)}validate(t,e={}){return Ur(t,this,e)}}function _r(t,e,r){const n=Ur(t,e,{coerce:!0,message:r});if(n[0])throw n[0];return n[1]}function Pr(t,e){return!Ur(t,e)[0]}function Ur(t,e,r={}){const n=Sr(t,e,r),i=function(t){const{done:e,value:r}=t.next();return e?void 0:r}(n);return i[0]?[new kr(i[0],function*(){for(const t of n)t[0]&&(yield t[0])}),void 0]:[void 0,i[1]]}function Or(t,e){return new Mr({type:t,schema:null,validator:e})}function Lr(t){return new Mr({type:"array",schema:t,*entries(e){if(t&&Array.isArray(e))for(const[r,n]of e.entries())yield[r,n,t]},coercer:t=>Array.isArray(t)?t.slice():t,validator:t=>Array.isArray(t)||`Expected an array value, but received: ${Er(t)}`})}function Kr(){return Or("boolean",t=>"boolean"==typeof t)}function zr(t){return Or("instance",e=>e instanceof t||`Expected a \`${t.name}\` instance, but received: ${Er(e)}`)}function Rr(t){const e=Er(t),r=typeof t;return new Mr({type:"literal",schema:"string"===r||"number"===r||"boolean"===r?t:null,validator:r=>r===t||`Expected the literal \`${e}\`, but received: ${Er(r)}`})}function Tr(t){return new Mr({...t,validator:(e,r)=>null===e||t.validator(e,r),refiner:(e,r)=>null===e||t.refiner(e,r)})}function Cr(){return Or("number",t=>"number"==typeof t&&!isNaN(t)||`Expected a number, but received: ${Er(t)}`)}function Nr(t){return new Mr({...t,validator:(e,r)=>void 0===e||t.validator(e,r),refiner:(e,r)=>void 0===e||t.refiner(e,r)})}function jr(t,e){return new Mr({type:"record",schema:null,*entries(r){if(xr(r))for(const n in r){const i=r[n];yield[n,n,t],yield[n,i,e]}},validator:t=>Ar(t)||`Expected an object, but received: ${Er(t)}`,coercer:t=>Ar(t)?{...t}:t})}function Hr(){return Or("string",t=>"string"==typeof t||`Expected a string, but received: ${Er(t)}`)}function Dr(t){const e=Or("never",()=>!1);return new Mr({type:"tuple",schema:null,*entries(r){if(Array.isArray(r)){const n=Math.max(t.length,r.length);for(let i=0;iArray.isArray(t)||`Expected an array, but received: ${Er(t)}`,coercer:t=>Array.isArray(t)?t.slice():t})}function Wr(t){const e=Object.keys(t);return new Mr({type:"type",schema:t,*entries(r){if(xr(r))for(const n of e)yield[n,r[n],t[n]]},validator:t=>Ar(t)||`Expected an object, but received: ${Er(t)}`,coercer:t=>Ar(t)?{...t}:t})}function Fr(t){const e=t.map(t=>t.type).join(" | ");return new Mr({type:"union",schema:null,coercer(e,r){for(const n of t){const[t,i]=n.validate(e,{coerce:!0,mask:r.mask});if(!t)return i}return e},validator(r,n){const i=[];for(const e of t){const[...t]=Sr(r,e,n),[s]=t;if(!s[0])return[];for(const[e]of t)e&&i.push(e)}return[`Expected the value to satisfy a union of \`${e}\`, but received: ${Er(r)}`,...i]}})}function qr(){return Or("unknown",()=>!0)}function $r(t,e,r){return new Mr({...t,coercer:(n,i)=>Pr(n,e)?t.coercer(r(n,i),i):t.coercer(n,i)})}r(22),r(678);const Vr=BigInt(0),Zr=BigInt(1),Gr=BigInt(2),Yr=BigInt(7),Xr=BigInt(256),Jr=BigInt(113),Qr=[],tn=[],en=[];for(let t=0,e=Zr,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Qr.push(2*(5*n+r)),tn.push((t+1)*(t+2)/2%64);let i=Vr;for(let t=0;t<7;t++)e=(e<>Yr)*Jr)%Xr,e&Gr&&(i^=Zr<<(Zr<r>32?((t,e,r)=>e<>>64-r)(t,e,r):((t,e,r)=>t<>>32-r)(t,e,r),an=(t,e,r)=>r>32?((t,e,r)=>t<>>64-r)(t,e,r):((t,e,r)=>e<>>32-r)(t,e,r);class un extends Xe{constructor(t,e,r,n=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=e,this.outputLen=r,this.enableXOF=n,this.rounds=i,He(r),!(0=r&&this.keccak();const s=Math.min(r-this.posOut,i-n);t.set(e.subarray(this.posOut,this.posOut+s),n),this.posOut+=s,n+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return He(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Fe(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,qe(this.state)}_cloneInto(t){const{blockLen:e,suffix:r,outputLen:n,rounds:i,enableXOF:s}=this;return t||(t=new un(e,r,n,s,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=r,t.outputLen=n,t.enableXOF=s,t.destroyed=this.destroyed,t}}const hn=(()=>{return t=1,e=136,r=32,Je(()=>new un(e,t,r));var t,e,r})();class cn extends k{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,u(t);const r=w(e);if(this.iHash=t.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 n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?t.create().update(r).digest():r);for(let t=0;tnew cn(t,e).update(r).digest();ln.create=(t,e)=>new cn(t,e);const fn=(t,e)=>(t+(t>=0?e:-e)/wn)/e;function dn(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function pn(t,e){const r={};for(let n of Object.keys(e))r[n]=void 0===t[n]?e[n]:t[n];return it(r.lowS,"lowS"),it(r.prehash,"prehash"),void 0!==r.format&&dn(r.format),r}class yn extends Error{constructor(t=""){super(t)}}const gn={Err:yn,_tlv:{encode:(t,e)=>{const{Err:r}=gn;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(1&e.length)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=ot(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?ot(i.length/2|128):"";return ot(t)+s+i+e},decode(t,e){const{Err:r}=gn;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++];let s=0;if(128&i){const t=127&i;if(!t)throw new r("tlv.decode(long): indefinite length not supported");if(t>4)throw new r("tlv.decode(long): byte length is too big");const o=e.subarray(n,n+t);if(o.length!==t)throw new r("tlv.decode: length bytes not complete");if(0===o[0])throw new r("tlv.decode(long): zero leftmost byte");for(const t of o)s=s<<8|t;if(n+=t,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=i;const o=e.subarray(n,n+s);if(o.length!==s)throw new r("tlv.decode: wrong value length");return{v:o,l:e.subarray(n+s)}}},_int:{encode(t){const{Err:e}=gn;if(tln(e,t,v(...r))),{Fp:o,Fn:a}=t,{ORDER:h,BITS:c}=a,{keygen:l,getPublicKey:f,getSharedSecret:d,utils:p,lengths:g}=function(t,e={}){const{Fn:r}=t,n=e.randomBytes||A,i=Object.assign(En(t.Fp,r),{seed:qt(r.ORDER)});function s(t){try{return!!xn(r,t)}catch(t){return!1}}function o(t=n(i.seed)){return function(t,e,r=!1){const n=t.length,i=Ft(e),s=qt(e);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=Ut(r?ht(t):ut(t),e-xt)+xt;return r?lt(o,i):ct(o,i)}(st(t,i.seed,"seed"),r.ORDER)}function a(e,n=!0){return t.BASE.multiply(xn(r,e)).toBytes(n)}function u(e){if("bigint"==typeof e)return!1;if(e instanceof t)return!0;const{secretKey:n,publicKey:s,publicKeyUncompressed:o}=i;if(r.allowedLengths||n===s)return;const a=ft("key",e).length;return a===s||a===o}const h={isValidSecretKey:s,isValidPublicKey:function(e,r){const{publicKey:n,publicKeyUncompressed:s}=i;try{const i=e.length;return!(!0===r&&i!==n||!1===r&&i!==s||!t.fromBytes(e))}catch(t){return!1}},randomSecretKey:o,isValidPrivateKey:s,randomPrivateKey:o,normPrivateKeyToScalar:t=>xn(r,t),precompute:(e=8,r=t.BASE)=>r.precompute(e,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(e,n,i=!0){if(!0===u(e))throw new Error("first arg must be private key");if(!1===u(n))throw new Error("second arg must be public key");const s=xn(r,e);return t.fromHex(n).multiply(s).toBytes(i)},keygen:function(t){const e=o(t);return{secretKey:e,publicKey:a(e)}},Point:t,utils:h,lengths:i})}(t,r),b={prehash:!1,lowS:"boolean"==typeof r.lowS&&r.lowS,format:void 0,extraEntropy:!1},w="compact";function k(t){return t>h>>bn}function x(t,e){if(!a.isValidNot0(e))throw new Error(`invalid signature ${t}: out of range 1..Point.Fn.ORDER`);return e}class E{constructor(t,e,r){this.r=x("r",t),this.s=x("s",e),null!=r&&(this.recovery=r),Object.freeze(this)}static fromBytes(t,e=w){let r;if(function(t,e){dn(e);const r=g.signature;st(t,"compact"===e?r:"recovered"===e?r+1:void 0,`${e} signature`)}(t,e),"der"===e){const{r:e,s:r}=gn.toSig(st(t));return new E(e,r)}"recovered"===e&&(r=t[0],e="compact",t=t.subarray(1));const n=a.BYTES,i=t.subarray(0,n),s=t.subarray(n,2*n);return new E(a.fromBytes(i),a.fromBytes(s),r)}static fromHex(t,e){return this.fromBytes(m(t),e)}addRecoveryBit(t){return new E(this.r,this.s,t)}recoverPublicKey(e){const r=o.ORDER,{r:n,s:i,recovery:s}=this;if(null==s||![0,1,2,3].includes(s))throw new Error("recovery id invalid");if(h*wn1)throw new Error("recovery id is ambiguous for h>1 curve");const u=2===s||3===s?n+h:n;if(!o.isValid(u))throw new Error("recovery id 2 or 3 invalid");const c=o.toBytes(u),l=t.fromBytes(v(An(!(1&s)),c)),f=a.inv(u),d=I(ft("msgHash",e)),p=a.create(-d*f),y=a.create(i*f),g=t.BASE.multiplyUnsafe(p).add(l.multiplyUnsafe(y));if(g.is0())throw new Error("point at infinify");return g.assertValidity(),g}hasHighS(){return k(this.s)}toBytes(t=w){if(dn(t),"der"===t)return m(gn.hexFromSig(this));const e=a.toBytes(this.r),r=a.toBytes(this.s);if("recovered"===t){if(null==this.recovery)throw new Error("recovery bit must be present");return v(Uint8Array.of(this.recovery),e,r)}return v(e,r)}toHex(t){return y(this.toBytes(t))}assertValidity(){}static fromCompact(t){return E.fromBytes(ft("sig",t),"compact")}static fromDER(t){return E.fromBytes(ft("sig",t),"der")}normalizeS(){return this.hasHighS()?new E(this.r,a.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return y(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return y(this.toBytes("compact"))}}const B=r.bits2int||function(t){if(t.length>8192)throw new Error("input is too large");const e=ut(t),r=8*t.length-c;return r>0?e>>BigInt(r):e},I=r.bits2int_modN||function(t){return a.create(B(t))},S=mt(c);function M(t){return yt("num < 2^"+c,t,mn,S),a.toBytes(t)}function _(t,r){return st(t,void 0,"message"),r?st(e(t),void 0,"prehashed message"):t}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:d,utils:p,lengths:g,Point:t,sign:function(r,s,o={}){r=ft("message",r);const{seed:u,k2sig:h}=function(e,r,i){if(["recovered","canonical"].some(t=>t in i))throw new Error("sign() legacy options not supported");const{lowS:s,prehash:o,extraEntropy:u}=pn(i,b);e=_(e,o);const h=I(e),c=xn(a,r),l=[M(c),M(h)];if(null!=u&&!1!==u){const t=!0===u?n(g.secretKey):u;l.push(ft("extraEntropy",t))}const f=v(...l),d=h;return{seed:f,k2sig:function(e){const r=B(e);if(!a.isValidNot0(r))return;const n=a.inv(r),i=t.BASE.multiply(r).toAffine(),o=a.create(i.x);if(o===mn)return;const u=a.create(n*a.create(d+o*c));if(u===mn)return;let h=(i.x===o?0:2)|Number(i.y&bn),l=u;return s&&k(u)&&(l=a.neg(u),h^=1),new E(o,l,h)}}}(r,s,o),c=function(t,e,r){if("number"!=typeof t||t<2)throw new Error("hashLen must be a number");if("number"!=typeof e||e<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");const n=t=>new Uint8Array(t),i=t=>Uint8Array.of(t);let s=n(t),o=n(t),a=0;const u=()=>{s.fill(1),o.fill(0),a=0},h=(...t)=>r(o,s,...t),c=(t=n(0))=>{o=h(i(0),t),s=h(),0!==t.length&&(o=h(i(1),t),s=h())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let t=0;const r=[];for(;t{let r;for(u(),c(t);!(r=e(l()));)c();return u(),r}}(e.outputLen,a.BYTES,i);return c(u,h)},verify:function(e,r,n,i={}){const{lowS:o,prehash:u,format:h}=pn(i,b);if(n=ft("publicKey",n),r=_(ft("message",r),u),"strict"in i)throw new Error("options.strict was renamed to lowS");const c=void 0===h?function(t){let e;const r="string"==typeof t||s(t),n=!r&&null!==t&&"object"==typeof t&&"bigint"==typeof t.r&&"bigint"==typeof t.s;if(!r&&!n)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)e=new E(t.r,t.s);else if(r){try{e=E.fromBytes(ft("sig",t),"der")}catch(t){if(!(t instanceof gn.Err))throw t}if(!e)try{e=E.fromBytes(ft("sig",t),"compact")}catch(t){return!1}}return e||!1}(e):E.fromBytes(ft("sig",e),h);if(!1===c)return!1;try{const e=t.fromBytes(n);if(o&&c.hasHighS())return!1;const{r:i,s}=c,u=I(r),h=a.inv(s),l=a.create(u*h),f=a.create(i*h),d=t.BASE.multiplyUnsafe(l).add(e.multiplyUnsafe(f));return!d.is0()&&a.create(d.x)===i}catch(t){return!1}},recoverPublicKey:function(t,e,r={}){const{prehash:n}=pn(r,b);return e=_(e,n),E.fromBytes(t,"recovered").recoverPublicKey(e).toBytes()},Signature:E,hash:e})}function In(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=function(t){const{CURVE:e,curveOpts:r}=function(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(t=>Math.ceil(t/2)))):void 0;return{CURVE:e,curveOpts:{Fp:r,Fn:Wt(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes}}}(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}(t);return function(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Dt(r.Fn.ORDER,r.Fn.BITS))})}(t,Bn(function(t,e={}){const r=oe("weierstrass",t,e),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:o,n:a}=s;bt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:u}=e;if(u&&(!n.is0(s.a)||"bigint"!=typeof u.beta||!Array.isArray(u.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const h=En(n,i);function c(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const l=e.toBytes||function(t,e,r){const{x:i,y:s}=e.toAffine(),o=n.toBytes(i);return it(r,"isCompressed"),r?(c(),v(An(!n.isOdd(s)),o)):v(Uint8Array.of(4),o,n.toBytes(s))},f=e.fromBytes||function(t){st(t,void 0,"Point");const{publicKey:e,publicKeyUncompressed:r}=h,i=t.length,s=t[0],o=t.subarray(1);if(i!==e||2!==s&&3!==s){if(i===r&&4===s){const t=n.BYTES,e=n.fromBytes(o.subarray(0,t)),r=n.fromBytes(o.subarray(t,2*t));if(!p(e,r))throw new Error("bad point: is not on curve");return{x:e,y:r}}throw new Error(`bad point: got length ${i}, expected compressed=${e} or uncompressed=${r}`)}{const t=n.fromBytes(o);if(!n.isValid(t))throw new Error("bad point: is not on curve, wrong x");const e=d(t);let r;try{r=n.sqrt(e)}catch(t){const e=t instanceof Error?": "+t.message:"";throw new Error("bad point: is not on curve, sqrt error"+e)}return c(),!(1&~s)!==n.isOdd(r)&&(r=n.neg(r)),{x:t,y:r}}};function d(t){const e=n.sqr(t),r=n.mul(e,t);return n.add(n.add(r,n.mul(t,s.a)),s.b)}function p(t,e){const r=n.sqr(e),i=d(t);return n.eql(r,i)}if(!p(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const g=n.mul(n.pow(s.a,vn),kn),m=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,m)))throw new Error("bad curve params: a or b");function b(t,e,r=!1){if(!n.isValid(e)||r&&n.is0(e))throw new Error(`bad point coordinate ${t}`);return e}function w(t){if(!(t instanceof B))throw new Error("ProjectivePoint expected")}function k(t){if(!u||!u.basises)throw new Error("no endo");return function(t,e,r){const[[n,i],[s,o]]=e,a=fn(o*t,r),u=fn(-i*t,r);let h=t-a*n-u*s,c=-a*i-u*o;const l=h=d||c=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:l,k1:h,k2neg:f,k2:c}}(t,u.basises,i.ORDER)}const x=vt((t,e)=>{const{X:r,Y:i,Z:s}=t;if(n.eql(s,n.ONE))return{x:r,y:i};const o=t.is0();null==e&&(e=o?n.ONE:n.inv(s));const a=n.mul(r,e),u=n.mul(i,e),h=n.mul(s,e);if(o)return{x:n.ZERO,y:n.ZERO};if(!n.eql(h,n.ONE))throw new Error("invZ was invalid");return{x:a,y:u}}),A=vt(t=>{if(t.is0()){if(e.allowInfinityPoint&&!n.is0(t.Y))return;throw new Error("bad point: ZERO")}const{x:r,y:i}=t.toAffine();if(!n.isValid(r)||!n.isValid(i))throw new Error("bad point: x or y not field elements");if(!p(r,i))throw new Error("bad point: equation left != right");if(!t.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(t,e,r,i,s){return r=new B(n.mul(r.X,t),r.Y,r.Z),e=Zt(i,e),r=Zt(s,r),e.add(r)}class B{constructor(t,e,r){this.X=b("x",t),this.Y=b("y",e,!0),this.Z=b("z",r),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){const{x:e,y:r}=t||{};if(!t||!n.isValid(e)||!n.isValid(r))throw new Error("invalid affine point");if(t instanceof B)throw new Error("projective point not allowed");return n.is0(e)&&n.is0(r)?B.ZERO:new B(e,r,n.ONE)}static fromBytes(t){const e=B.fromAffine(f(st(t,void 0,"point")));return e.assertValidity(),e}static fromHex(t){return B.fromBytes(ft("pointHex",t))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return S.createCache(this,t),e||this.multiply(vn),this}assertValidity(){A(this)}hasEvenY(){const{y:t}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(t)}equals(t){w(t);const{X:e,Y:r,Z:i}=this,{X:s,Y:o,Z:a}=t,u=n.eql(n.mul(e,a),n.mul(s,i)),h=n.eql(n.mul(r,a),n.mul(o,i));return u&&h}negate(){return new B(this.X,n.neg(this.Y),this.Z)}double(){const{a:t,b:e}=s,r=n.mul(e,vn),{X:i,Y:o,Z:a}=this;let u=n.ZERO,h=n.ZERO,c=n.ZERO,l=n.mul(i,i),f=n.mul(o,o),d=n.mul(a,a),p=n.mul(i,o);return p=n.add(p,p),c=n.mul(i,a),c=n.add(c,c),u=n.mul(t,c),h=n.mul(r,d),h=n.add(u,h),u=n.sub(f,h),h=n.add(f,h),h=n.mul(u,h),u=n.mul(p,u),c=n.mul(r,c),d=n.mul(t,d),p=n.sub(l,d),p=n.mul(t,p),p=n.add(p,c),c=n.add(l,l),l=n.add(c,l),l=n.add(l,d),l=n.mul(l,p),h=n.add(h,l),d=n.mul(o,a),d=n.add(d,d),l=n.mul(d,p),u=n.sub(u,l),c=n.mul(d,f),c=n.add(c,c),c=n.add(c,c),new B(u,h,c)}add(t){w(t);const{X:e,Y:r,Z:i}=this,{X:o,Y:a,Z:u}=t;let h=n.ZERO,c=n.ZERO,l=n.ZERO;const f=s.a,d=n.mul(s.b,vn);let p=n.mul(e,o),y=n.mul(r,a),g=n.mul(i,u),m=n.add(e,r),b=n.add(o,a);m=n.mul(m,b),b=n.add(p,y),m=n.sub(m,b),b=n.add(e,i);let v=n.add(o,u);return b=n.mul(b,v),v=n.add(p,g),b=n.sub(b,v),v=n.add(r,i),h=n.add(a,u),v=n.mul(v,h),h=n.add(y,g),v=n.sub(v,h),l=n.mul(f,b),h=n.mul(d,g),l=n.add(h,l),h=n.sub(y,l),l=n.add(y,l),c=n.mul(h,l),y=n.add(p,p),y=n.add(y,p),g=n.mul(f,g),b=n.mul(d,b),y=n.add(y,g),g=n.sub(p,g),g=n.mul(f,g),b=n.add(b,g),p=n.mul(y,b),c=n.add(c,p),p=n.mul(v,b),h=n.mul(m,h),h=n.sub(h,p),p=n.mul(m,y),l=n.mul(v,l),l=n.add(l,p),new B(h,c,l)}subtract(t){return this.add(t.negate())}is0(){return this.equals(B.ZERO)}multiply(t){const{endo:r}=e;if(!i.isValidNot0(t))throw new Error("invalid scalar: out of range");let n,s;const o=t=>S.cached(this,t,t=>Gt(B,t));if(r){const{k1neg:e,k1:i,k2neg:a,k2:u}=k(t),{p:h,f:c}=o(i),{p:l,f}=o(u);s=c.add(f),n=E(r.beta,h,l,e,a)}else{const{p:e,f:r}=o(t);n=e,s=r}return Gt(B,[n,s])[0]}multiplyUnsafe(t){const{endo:r}=e,n=this;if(!i.isValid(t))throw new Error("invalid scalar: out of range");if(t===mn||n.is0())return B.ZERO;if(t===bn)return n;if(S.hasCache(this))return this.multiply(t);if(r){const{k1neg:e,k1:i,k2neg:s,k2:o}=k(t),{p1:a,p2:u}=function(t,e,r,n){let i=e,s=t.ZERO,o=t.ZERO;for(;r>$t||n>$t;)r&Vt&&(s=s.add(i)),n&Vt&&(o=o.add(i)),i=i.double(),r>>=Vt,n>>=Vt;return{p1:s,p2:o}}(B,n,i,o);return E(r.beta,a,u,e,s)}return S.unsafe(n,t)}multiplyAndAddUnsafe(t,e,r){const n=this.multiplyUnsafe(e).add(t.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(t){return x(this,t)}isTorsionFree(){const{isTorsionFree:t}=e;return o===bn||(t?t(B,this):S.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:t}=e;return o===bn?this:t?t(B,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(t=!0){return it(t,"isCompressed"),this.assertValidity(),l(B,this,t)}toHex(t=!0){return y(this.toBytes(t))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(t=!0){return this.toBytes(t)}_setWindowSize(t){this.precompute(t)}static normalizeZ(t){return Gt(B,t)}static msm(t,e){return ie(B,i,t,e)}static fromPrivateKey(t){return B.BASE.multiply(xn(i,t))}}B.BASE=new B(s.Gx,s.Gy,n.ONE),B.ZERO=new B(n.ZERO,n.ONE,n.ZERO),B.Fp=n,B.Fn=i;const I=i.BITS,S=new ne(B,e.endo?Math.ceil(I/2):I);return B.BASE.precompute(8),B}(e,r),n,i))}const Sn={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Mn={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},_n=BigInt(2),Pn=Wt(Sn.p,{sqrt:function(t){const e=Sn.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),u=BigInt(88),h=t*t*t%e,c=h*h*t%e,l=Ot(c,r,e)*c%e,f=Ot(l,r,e)*c%e,d=Ot(f,_n,e)*h%e,p=Ot(d,i,e)*d%e,y=Ot(p,s,e)*p%e,g=Ot(y,a,e)*y%e,m=Ot(g,u,e)*g%e,b=Ot(m,a,e)*y%e,w=Ot(b,r,e)*c%e,v=Ot(w,o,e)*p%e,k=Ot(v,n,e)*h%e,x=Ot(k,_n,e);if(!Pn.eql(Pn.sqr(x),t))throw new Error("Cannot find square root");return x}}),Un=function(t,e){const r=e=>In({...t,hash:e});return{...r(e),create:r}}({...Sn,Fp:Pn,lowS:!0,endo:Mn},tt);Ie.utils.randomPrivateKey;const On=()=>{const t=Ie.utils.randomPrivateKey(),e=Ln(t),r=new Uint8Array(64);return r.set(t),r.set(e,32),{publicKey:e,secretKey:r}},Ln=Ie.getPublicKey;function Kn(t){try{return Ie.ExtendedPoint.fromHex(t),!0}catch{return!1}}const zn=(t,e)=>Ie.sign(t,e.slice(0,32)),Rn=Ie.verify,Tn=t=>n.Buffer.isBuffer(t)?t:t instanceof Uint8Array?n.Buffer.from(t.buffer,t.byteOffset,t.byteLength):n.Buffer.from(t);class Cn{constructor(t){Object.assign(this,t)}encode(){return n.Buffer.from((0,cr.serialize)(Nn,this))}static decode(t){return(0,cr.deserialize)(Nn,this,t)}static decodeUnchecked(t){return(0,cr.deserializeUnchecked)(Nn,this,t)}}const Nn=new Map;var jn;const Hn=32;let Dn=1;class Wn extends Cn{constructor(t){if(super({}),this._bn=void 0,function(t){return void 0!==t._bn}(t))this._bn=t._bn;else{if("string"==typeof t){const e=je().decode(t);if(e.length!=Hn)throw new Error("Invalid public key input");this._bn=new(Ce())(e)}else this._bn=new(Ce())(t);if(this._bn.byteLength()>Hn)throw new Error("Invalid public key input")}}static unique(){const t=new Wn(Dn);return Dn+=1,new Wn(t.toBuffer())}equals(t){return this._bn.eq(t._bn)}toBase58(){return je().encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const t=this.toBuffer();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}toBuffer(){const t=this._bn.toArrayLike(n.Buffer);if(t.length===Hn)return t;const e=n.Buffer.alloc(32);return t.copy(e,32-t.length),e}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(t,e,r){const i=n.Buffer.concat([t.toBuffer(),n.Buffer.from(e),r.toBuffer()]),s=hr(i);return new Wn(s)}static createProgramAddressSync(t,e){let r=n.Buffer.alloc(0);t.forEach(function(t){if(t.length>32)throw new TypeError("Max seed length exceeded");r=n.Buffer.concat([r,Tn(t)])}),r=n.Buffer.concat([r,e.toBuffer(),n.Buffer.from("ProgramDerivedAddress")]);const i=hr(r);if(Kn(i))throw new Error("Invalid seeds, address must fall off the curve");return new Wn(i)}static async createProgramAddress(t,e){return this.createProgramAddressSync(t,e)}static findProgramAddressSync(t,e){let r,i=255;for(;0!=i;){try{const s=t.concat(n.Buffer.from([i]));r=this.createProgramAddressSync(s,e)}catch(t){if(t instanceof TypeError)throw t;i--;continue}return[r,i]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(t,e){return this.findProgramAddressSync(t,e)}static isOnCurve(t){return Kn(new Wn(t).toBytes())}}jn=Wn,Wn.default=new jn("11111111111111111111111111111111"),Nn.set(Wn,{kind:"struct",fields:[["_bn","u256"]]}),new Wn("BPFLoader1111111111111111111111111111111111");const Fn=1232;class qn extends Error{constructor(t){super(`Signature ${t} has expired: block height exceeded.`),this.signature=void 0,this.signature=t}}Object.defineProperty(qn.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class $n extends Error{constructor(t,e){super(`Transaction was not confirmed in ${e.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${t} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=t}}Object.defineProperty($n.prototype,"name",{value:"TransactionExpiredTimeoutError"});class Vn extends Error{constructor(t){super(`Signature ${t} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=t}}Object.defineProperty(Vn.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class Zn{constructor(t,e){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=t,this.accountKeysFromLookups=e}keySegments(){const t=[this.staticAccountKeys];return this.accountKeysFromLookups&&(t.push(this.accountKeysFromLookups.writable),t.push(this.accountKeysFromLookups.readonly)),t}get(t){for(const e of this.keySegments()){if(t256)throw new Error("Account index overflow encountered during compilation");const e=new Map;this.keySegments().flat().forEach((t,r)=>{e.set(t.toBase58(),r)});const r=t=>{const r=e.get(t.toBase58());if(void 0===r)throw new Error("Encountered an unknown instruction account key during compilation");return r};return t.map(t=>({programIdIndex:r(t.programId),accountKeyIndexes:t.keys.map(t=>r(t.pubkey)),data:t.data}))}}const Gn=(t="publicKey")=>lr.av(32,t),Yn=(t="signature")=>lr.av(64,t),Xn=(t="string")=>{const e=lr.w3([lr.DH("length"),lr.DH("lengthPadding"),lr.av(lr.cY(lr.DH(),-8),"chars")],t),r=e.decode.bind(e),i=e.encode.bind(e),s=e;return s.decode=(t,e)=>r(t,e).chars.toString(),s.encode=(t,e,r)=>{const s={chars:n.Buffer.from(t,"utf8")};return i(s,e,r)},s.alloc=t=>lr.DH().span+lr.DH().span+n.Buffer.from(t,"utf8").length,s};function Jn(t,e){const r=t=>{if(t.span>=0)return t.span;if("function"==typeof t.alloc)return t.alloc(e[t.property]);if("count"in t&&"elementLayout"in t){const n=e[t.property];if(Array.isArray(n))return n.length*r(t.elementLayout)}else if("fields"in t)return Jn({layout:t},e[t.property]);return 0};let n=0;return t.layout.fields.forEach(t=>{n+=r(t)}),n}function Qn(t){let e=0,r=0;for(;;){let n=t.shift();if(e|=(127&n)<<7*r,r+=1,!(128&n))break}return e}function ti(t,e){let r=e;for(;;){let e=127&r;if(r>>=7,0==r){t.push(e);break}e|=128,t.push(e)}}function ei(t,e){if(!t)throw new Error(e||"Assertion failed")}class ri{constructor(t,e){this.payer=void 0,this.keyMetaMap=void 0,this.payer=t,this.keyMetaMap=e}static compile(t,e){const r=new Map,n=t=>{const e=t.toBase58();let n=r.get(e);return void 0===n&&(n={isSigner:!1,isWritable:!1,isInvoked:!1},r.set(e,n)),n},i=n(e);i.isSigner=!0,i.isWritable=!0;for(const e of t){n(e.programId).isInvoked=!0;for(const t of e.keys){const e=n(t.pubkey);e.isSigner||=t.isSigner,e.isWritable||=t.isWritable}}return new ri(e,r)}getMessageComponents(){const t=[...this.keyMetaMap.entries()];ei(t.length<=256,"Max static account keys length exceeded");const e=t.filter(([,t])=>t.isSigner&&t.isWritable),r=t.filter(([,t])=>t.isSigner&&!t.isWritable),n=t.filter(([,t])=>!t.isSigner&&t.isWritable),i=t.filter(([,t])=>!t.isSigner&&!t.isWritable),s={numRequiredSignatures:e.length+r.length,numReadonlySignedAccounts:r.length,numReadonlyUnsignedAccounts:i.length};{ei(e.length>0,"Expected at least one writable signer key");const[t]=e[0];ei(t===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[s,[...e.map(([t])=>new Wn(t)),...r.map(([t])=>new Wn(t)),...n.map(([t])=>new Wn(t)),...i.map(([t])=>new Wn(t))]]}extractTableLookup(t){const[e,r]=this.drainKeysFoundInLookupTable(t.state.addresses,t=>!t.isSigner&&!t.isInvoked&&t.isWritable),[n,i]=this.drainKeysFoundInLookupTable(t.state.addresses,t=>!t.isSigner&&!t.isInvoked&&!t.isWritable);if(0!==e.length||0!==n.length)return[{accountKey:t.key,writableIndexes:e,readonlyIndexes:n},{writable:r,readonly:i}]}drainKeysFoundInLookupTable(t,e){const r=new Array,n=new Array;for(const[i,s]of this.keyMetaMap.entries())if(e(s)){const e=new Wn(i),s=t.findIndex(t=>t.equals(e));s>=0&&(ei(s<256,"Max lookup table index exceeded"),r.push(s),n.push(e),this.keyMetaMap.delete(i))}return[r,n]}}const ni="Reached end of buffer unexpectedly";function ii(t){if(0===t.length)throw new Error(ni);return t.shift()}function si(t,...e){const[r]=e;if(2===e.length?r+(e[1]??0)>t.length:r>=t.length)throw new Error(ni);return t.splice(...e)}class oi{constructor(t){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=t.header,this.accountKeys=t.accountKeys.map(t=>new Wn(t)),this.recentBlockhash=t.recentBlockhash,this.instructions=t.instructions,this.instructions.forEach(t=>this.indexToProgramIds.set(t.programIdIndex,this.accountKeys[t.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(t=>({programIdIndex:t.programIdIndex,accountKeyIndexes:t.accounts,data:je().decode(t.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new Zn(this.staticAccountKeys)}static compile(t){const e=ri.compile(t.instructions,t.payerKey),[r,n]=e.getMessageComponents(),i=new Zn(n).compileInstructions(t.instructions).map(t=>({programIdIndex:t.programIdIndex,accounts:t.accountKeyIndexes,data:je().encode(t.data)}));return new oi({header:r,accountKeys:n,recentBlockhash:t.recentBlockhash,instructions:i})}isAccountSigner(t){return t=this.header.numRequiredSignatures?t-e!this.isProgramId(e))}serialize(){const t=this.accountKeys.length;let e=[];ti(e,t);const r=this.instructions.map(t=>{const{accounts:e,programIdIndex:r}=t,i=Array.from(je().decode(t.data));let s=[];ti(s,e.length);let o=[];return ti(o,i.length),{programIdIndex:r,keyIndicesCount:n.Buffer.from(s),keyIndices:e,dataLength:n.Buffer.from(o),data:i}});let i=[];ti(i,r.length);let s=n.Buffer.alloc(Fn);n.Buffer.from(i).copy(s);let o=i.length;r.forEach(t=>{const e=lr.w3([lr.u8("programIdIndex"),lr.av(t.keyIndicesCount.length,"keyIndicesCount"),lr.O6(lr.u8("keyIndex"),t.keyIndices.length,"keyIndices"),lr.av(t.dataLength.length,"dataLength"),lr.O6(lr.u8("userdatum"),t.data.length,"data")]).encode(t,s,o);o+=e}),s=s.slice(0,o);const a=lr.w3([lr.av(1,"numRequiredSignatures"),lr.av(1,"numReadonlySignedAccounts"),lr.av(1,"numReadonlyUnsignedAccounts"),lr.av(e.length,"keyCount"),lr.O6(Gn("key"),t,"keys"),Gn("recentBlockhash")]),u={numRequiredSignatures:n.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:n.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:n.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:n.Buffer.from(e),keys:this.accountKeys.map(t=>Tn(t.toBytes())),recentBlockhash:je().decode(this.recentBlockhash)};let h=n.Buffer.alloc(2048);const c=a.encode(u,h);return s.copy(h,c),h.slice(0,c+s.length)}static from(t){let e=[...t];const r=ii(e);if(r!==(127&r))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const i=ii(e),s=ii(e),o=Qn(e);let a=[];for(let t=0;t0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new Zn(this.staticAccountKeys,e)}isAccountSigner(t){return t=r?t-rt+e.writableIndexes.length,0):t>=this.header.numRequiredSignatures?t-et.key.equals(r.accountKey));if(!n)throw new Error(`Failed to find address lookup table account for table key ${r.accountKey.toBase58()}`);for(const t of r.writableIndexes){if(!(tt.toBytes()),recentBlockhash:je().decode(this.recentBlockhash),instructionsLength:new Uint8Array(r),serializedInstructions:e,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:n},o);return o.slice(0,a)}serializeInstructions(){let t=0;const e=new Uint8Array(Fn);for(const r of this.compiledInstructions){const n=Array();ti(n,r.accountKeyIndexes.length);const i=Array();ti(i,r.data.length),t+=lr.w3([lr.u8("programIdIndex"),lr.av(n.length,"encodedAccountKeyIndexesLength"),lr.O6(lr.u8(),r.accountKeyIndexes.length,"accountKeyIndexes"),lr.av(i.length,"encodedDataLength"),lr.av(r.data.length,"data")]).encode({programIdIndex:r.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(n),accountKeyIndexes:r.accountKeyIndexes,encodedDataLength:new Uint8Array(i),data:r.data},e,t)}return e.slice(0,t)}serializeAddressTableLookups(){let t=0;const e=new Uint8Array(Fn);for(const r of this.addressTableLookups){const n=Array();ti(n,r.writableIndexes.length);const i=Array();ti(i,r.readonlyIndexes.length),t+=lr.w3([Gn("accountKey"),lr.av(n.length,"encodedWritableIndexesLength"),lr.O6(lr.u8(),r.writableIndexes.length,"writableIndexes"),lr.av(i.length,"encodedReadonlyIndexesLength"),lr.O6(lr.u8(),r.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:r.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(n),writableIndexes:r.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(i),readonlyIndexes:r.readonlyIndexes},e,t)}return e.slice(0,t)}static deserialize(t){let e=[...t];const r=ii(e),n=127&r;ei(r!==n,"Expected versioned message but received legacy message"),ei(0===n,`Expected versioned message with version 0 but found version ${n}`);const i={numRequiredSignatures:ii(e),numReadonlySignedAccounts:ii(e),numReadonlyUnsignedAccounts:ii(e)},s=[],o=Qn(e);for(let t=0;t{const e=ui.deserializeMessageVersion(t);if("legacy"===e)return oi.from(t);if(0===e)return ai.deserialize(t);throw new Error(`Transaction message version ${e} deserialization is not supported`)}},hi=n.Buffer.alloc(64).fill(0);class ci{constructor(t){this.keys=void 0,this.programId=void 0,this.data=n.Buffer.alloc(0),this.programId=t.programId,this.keys=t.keys,t.data&&(this.data=t.data)}toJSON(){return{keys:this.keys.map(({pubkey:t,isSigner:e,isWritable:r})=>({pubkey:t.toJSON(),isSigner:e,isWritable:r})),programId:this.programId.toJSON(),data:[...this.data]}}}class li{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(t){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,t)if(t.feePayer&&(this.feePayer=t.feePayer),t.signatures&&(this.signatures=t.signatures),Object.prototype.hasOwnProperty.call(t,"nonceInfo")){const{minContextSlot:e,nonceInfo:r}=t;this.minNonceContextSlot=e,this.nonceInfo=r}else if(Object.prototype.hasOwnProperty.call(t,"lastValidBlockHeight")){const{blockhash:e,lastValidBlockHeight:r}=t;this.recentBlockhash=e,this.lastValidBlockHeight=r}else{const{recentBlockhash:e,nonceInfo:r}=t;r&&(this.nonceInfo=r),this.recentBlockhash=e}}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(t=>t.toJSON()),signers:this.signatures.map(({publicKey:t})=>t.toJSON())}}add(...t){if(0===t.length)throw new Error("No instructions");return t.forEach(t=>{"instructions"in t?this.instructions=this.instructions.concat(t.instructions):"data"in t&&"programId"in t&&"keys"in t?this.instructions.push(t):this.instructions.push(new ci(t))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let t,e,r;if(this.nonceInfo?(t=this.nonceInfo.nonce,e=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(t=this.recentBlockhash,e=this.instructions),!t)throw new Error("Transaction recentBlockhash required");if(e.length<1&&console.warn("No instructions provided"),this.feePayer)r=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");r=this.signatures[0].publicKey}for(let t=0;t{t.keys.forEach(t=>{i.push({...t})});const e=t.programId.toString();n.includes(e)||n.push(e)}),n.forEach(t=>{i.push({pubkey:new Wn(t),isSigner:!1,isWritable:!1})});const s=[];i.forEach(t=>{const e=t.pubkey.toString(),r=s.findIndex(t=>t.pubkey.toString()===e);r>-1?(s[r].isWritable=s[r].isWritable||t.isWritable,s[r].isSigner=s[r].isSigner||t.isSigner):s.push(t)}),s.sort(function(t,e){return t.isSigner!==e.isSigner?t.isSigner?-1:1:t.isWritable!==e.isWritable?t.isWritable?-1:1:t.pubkey.toBase58().localeCompare(e.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const o=s.findIndex(t=>t.pubkey.equals(r));if(o>-1){const[t]=s.splice(o,1);t.isSigner=!0,t.isWritable=!0,s.unshift(t)}else s.unshift({pubkey:r,isSigner:!0,isWritable:!0});for(const t of this.signatures){const e=s.findIndex(e=>e.pubkey.equals(t.publicKey));if(!(e>-1))throw new Error(`unknown signer: ${t.publicKey.toString()}`);s[e].isSigner||(s[e].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 a=0,u=0,h=0;const c=[],l=[];s.forEach(({pubkey:t,isSigner:e,isWritable:r})=>{e?(c.push(t.toString()),a+=1,r||(u+=1)):(l.push(t.toString()),r||(h+=1))});const f=c.concat(l),d=e.map(t=>{const{data:e,programId:r}=t;return{programIdIndex:f.indexOf(r.toString()),accounts:t.keys.map(t=>f.indexOf(t.pubkey.toString())),data:je().encode(e)}});return d.forEach(t=>{ei(t.programIdIndex>=0),t.accounts.forEach(t=>ei(t>=0))}),new oi({header:{numRequiredSignatures:a,numReadonlySignedAccounts:u,numReadonlyUnsignedAccounts:h},accountKeys:f,recentBlockhash:t,instructions:d})}_compile(){const t=this.compileMessage(),e=t.accountKeys.slice(0,t.header.numRequiredSignatures);return this.signatures.length===e.length&&this.signatures.every((t,r)=>e[r].equals(t.publicKey))||(this.signatures=e.map(t=>({signature:null,publicKey:t}))),t}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(t){return(await t.getFeeForMessage(this.compileMessage())).value}setSigners(...t){if(0===t.length)throw new Error("No signers");const e=new Set;this.signatures=t.filter(t=>{const r=t.toString();return!e.has(r)&&(e.add(r),!0)}).map(t=>({signature:null,publicKey:t}))}sign(...t){if(0===t.length)throw new Error("No signers");const e=new Set,r=[];for(const n of t){const t=n.publicKey.toString();e.has(t)||(e.add(t),r.push(n))}this.signatures=r.map(t=>({signature:null,publicKey:t.publicKey}));const n=this._compile();this._partialSign(n,...r)}partialSign(...t){if(0===t.length)throw new Error("No signers");const e=new Set,r=[];for(const n of t){const t=n.publicKey.toString();e.has(t)||(e.add(t),r.push(n))}const n=this._compile();this._partialSign(n,...r)}_partialSign(t,...e){const r=t.serialize();e.forEach(t=>{const e=zn(r,t.secretKey);this._addSignature(t.publicKey,Tn(e))})}addSignature(t,e){this._compile(),this._addSignature(t,e)}_addSignature(t,e){ei(64===e.length);const r=this.signatures.findIndex(e=>t.equals(e.publicKey));if(r<0)throw new Error(`unknown signer: ${t.toString()}`);this.signatures[r].signature=n.Buffer.from(e)}verifySignatures(t=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),t)}_getMessageSignednessErrors(t,e){const r={};for(const{signature:n,publicKey:i}of this.signatures)null===n?e&&(r.missing||=[]).push(i):Rn(n,t,i.toBytes())||(r.invalid||=[]).push(i);return r.invalid||r.missing?r:void 0}serialize(t){const{requireAllSignatures:e,verifySignatures:r}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},t),n=this.serializeMessage();if(r){const t=this._getMessageSignednessErrors(n,e);if(t){let e="Signature verification failed.";throw t.invalid&&(e+=`\nInvalid signature for public key${1===t.invalid.length?"":"(s)"} [\`${t.invalid.map(t=>t.toBase58()).join("`, `")}\`].`),t.missing&&(e+=`\nMissing signature for public key${1===t.missing.length?"":"(s)"} [\`${t.missing.map(t=>t.toBase58()).join("`, `")}\`].`),new Error(e)}}return this._serialize(n)}_serialize(t){const{signatures:e}=this,r=[];ti(r,e.length);const i=r.length+64*e.length+t.length,s=n.Buffer.alloc(i);return ei(e.length<256),n.Buffer.from(r).copy(s,0),e.forEach(({signature:t},e)=>{null!==t&&(ei(64===t.length,"signature has invalid length"),n.Buffer.from(t).copy(s,r.length+64*e))}),t.copy(s,r.length+64*e.length),ei(s.length<=Fn,`Transaction too large: ${s.length} > 1232`),s}get keys(){return ei(1===this.instructions.length),this.instructions[0].keys.map(t=>t.pubkey)}get programId(){return ei(1===this.instructions.length),this.instructions[0].programId}get data(){return ei(1===this.instructions.length),this.instructions[0].data}static from(t){let e=[...t];const r=Qn(e);let i=[];for(let t=0;t0&&(r.feePayer=t.accountKeys[0]),e.forEach((e,n)=>{const i={signature:e==je().encode(hi)?null:je().decode(e),publicKey:t.accountKeys[n]};r.signatures.push(i)}),t.instructions.forEach(e=>{const n=e.accounts.map(e=>{const n=t.accountKeys[e];return{pubkey:n,isSigner:r.signatures.some(t=>t.publicKey.toString()===n.toString())||t.isAccountSigner(e),isWritable:t.isAccountWritable(e)}});r.instructions.push(new ci({keys:n,programId:t.accountKeys[e.programIdIndex],data:je().decode(e.data)}))}),r._message=t,r._json=r.toJSON(),r}}class fi{get version(){return this.message.version}constructor(t,e){if(this.signatures=void 0,this.message=void 0,void 0!==e)ei(e.length===t.header.numRequiredSignatures,"Expected signatures length to be equal to the number of required signatures"),this.signatures=e;else{const e=[];for(let r=0;rt.equals(n.publicKey));ei(t>=0,`Cannot sign with non signer key ${n.publicKey.toBase58()}`),this.signatures[t]=zn(e,n.secretKey)}}addSignature(t,e){ei(64===e.byteLength,"Signature must be 64 bytes long");const r=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures).findIndex(e=>e.equals(t));ei(r>=0,`Can not add signature; \`${t.toBase58()}\` is not required to sign this transaction`),this.signatures[r]=e}}const di=new Wn("SysvarC1ock11111111111111111111111111111111"),pi=(new Wn("SysvarEpochSchedu1e111111111111111111111111"),new Wn("Sysvar1nstructions1111111111111111111111111"),new Wn("SysvarRecentB1ockHashes11111111111111111111")),yi=new Wn("SysvarRent111111111111111111111111111111111"),gi=(new Wn("SysvarRewards111111111111111111111111111111"),new Wn("SysvarS1otHashes111111111111111111111111111"),new Wn("SysvarS1otHistory11111111111111111111111111"),new Wn("SysvarStakeHistory1111111111111111111111111"));class mi extends Error{constructor({action:t,signature:e,transactionMessage:r,logs:n}){const i=n?`Logs: \n${JSON.stringify(n.slice(-10),null,2)}. `:"",s="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let o;switch(t){case"send":o=`Transaction ${e} resulted in an error. \n${r}. `+i+s;break;case"simulate":o=`Simulation failed. \nMessage: ${r}. \n`+i+s;break;default:o=`Unknown action '${t}'`}super(o),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=e,this.transactionMessage=r,this.transactionLogs=n||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const t=this.transactionLogs;if(null==t||"object"!=typeof t||!("then"in t))return t}async getLogs(t){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((e,r)=>{t.getTransaction(this.signature).then(t=>{if(t&&t.meta&&t.meta.logMessages){const r=t.meta.logMessages;this.transactionLogs=r,e(r)}else r(new Error("Log messages not found"))}).catch(r)})),await this.transactionLogs}}async function bi(t,e,r,n){const i=n&&{skipPreflight:n.skipPreflight,preflightCommitment:n.preflightCommitment||n.commitment,maxRetries:n.maxRetries,minContextSlot:n.minContextSlot},s=await t.sendTransaction(e,r,i);let o;if(null!=e.recentBlockhash&&null!=e.lastValidBlockHeight)o=(await t.confirmTransaction({abortSignal:n?.abortSignal,signature:s,blockhash:e.recentBlockhash,lastValidBlockHeight:e.lastValidBlockHeight},n&&n.commitment)).value;else if(null!=e.minNonceContextSlot&&null!=e.nonceInfo){const{nonceInstruction:r}=e.nonceInfo,i=r.keys[0].pubkey;o=(await t.confirmTransaction({abortSignal:n?.abortSignal,minContextSlot:e.minNonceContextSlot,nonceAccountPubkey:i,nonceValue:e.nonceInfo.nonce,signature:s},n&&n.commitment)).value}else null!=n?.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."),o=(await t.confirmTransaction(s,n&&n.commitment)).value;if(o.err){if(null!=s)throw new mi({action:"send",signature:s,transactionMessage:`Status: (${JSON.stringify(o)})`});throw new Error(`Transaction ${s} failed (${JSON.stringify(o)})`)}return s}function wi(t){return new Promise(e=>setTimeout(e,t))}function vi(t,e){const r=t.layout.span>=0?t.layout.span:Jn(t,e),i=n.Buffer.alloc(r),s=Object.assign({instruction:t.index},e);return t.layout.encode(s,i),i}Error;const ki=lr.I0("lamportsPerSignature"),xi=lr.w3([lr.DH("version"),lr.DH("state"),Gn("authorizedPubkey"),Gn("nonce"),lr.w3([ki],"feeCalculator")]).span;function Ai(t){const e=(0,lr.av)(8,t),r=e.decode.bind(e),n=e.encode.bind(e),i=e,s=vr();return i.decode=(t,e)=>{const n=r(t,e);return s.decode(n)},i.encode=(t,e,r)=>{const i=s.encode(t);return n(i,e,r)},i}const Ei=Object.freeze({Create:{index:0,layout:lr.w3([lr.DH("instruction"),lr.Wg("lamports"),lr.Wg("space"),Gn("programId")])},Assign:{index:1,layout:lr.w3([lr.DH("instruction"),Gn("programId")])},Transfer:{index:2,layout:lr.w3([lr.DH("instruction"),Ai("lamports")])},CreateWithSeed:{index:3,layout:lr.w3([lr.DH("instruction"),Gn("base"),Xn("seed"),lr.Wg("lamports"),lr.Wg("space"),Gn("programId")])},AdvanceNonceAccount:{index:4,layout:lr.w3([lr.DH("instruction")])},WithdrawNonceAccount:{index:5,layout:lr.w3([lr.DH("instruction"),lr.Wg("lamports")])},InitializeNonceAccount:{index:6,layout:lr.w3([lr.DH("instruction"),Gn("authorized")])},AuthorizeNonceAccount:{index:7,layout:lr.w3([lr.DH("instruction"),Gn("authorized")])},Allocate:{index:8,layout:lr.w3([lr.DH("instruction"),lr.Wg("space")])},AllocateWithSeed:{index:9,layout:lr.w3([lr.DH("instruction"),Gn("base"),Xn("seed"),lr.Wg("space"),Gn("programId")])},AssignWithSeed:{index:10,layout:lr.w3([lr.DH("instruction"),Gn("base"),Xn("seed"),Gn("programId")])},TransferWithSeed:{index:11,layout:lr.w3([lr.DH("instruction"),Ai("lamports"),Xn("seed"),Gn("programId")])},UpgradeNonceAccount:{index:12,layout:lr.w3([lr.DH("instruction")])}});class Bi{constructor(){}static createAccount(t){const e=vi(Ei.Create,{lamports:t.lamports,space:t.space,programId:Tn(t.programId.toBuffer())});return new ci({keys:[{pubkey:t.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:t.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:e})}static transfer(t){let e,r;return"basePubkey"in t?(e=vi(Ei.TransferWithSeed,{lamports:BigInt(t.lamports),seed:t.seed,programId:Tn(t.programId.toBuffer())}),r=[{pubkey:t.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:t.basePubkey,isSigner:!0,isWritable:!1},{pubkey:t.toPubkey,isSigner:!1,isWritable:!0}]):(e=vi(Ei.Transfer,{lamports:BigInt(t.lamports)}),r=[{pubkey:t.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:t.toPubkey,isSigner:!1,isWritable:!0}]),new ci({keys:r,programId:this.programId,data:e})}static assign(t){let e,r;return"basePubkey"in t?(e=vi(Ei.AssignWithSeed,{base:Tn(t.basePubkey.toBuffer()),seed:t.seed,programId:Tn(t.programId.toBuffer())}),r=[{pubkey:t.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:t.basePubkey,isSigner:!0,isWritable:!1}]):(e=vi(Ei.Assign,{programId:Tn(t.programId.toBuffer())}),r=[{pubkey:t.accountPubkey,isSigner:!0,isWritable:!0}]),new ci({keys:r,programId:this.programId,data:e})}static createAccountWithSeed(t){const e=vi(Ei.CreateWithSeed,{base:Tn(t.basePubkey.toBuffer()),seed:t.seed,lamports:t.lamports,space:t.space,programId:Tn(t.programId.toBuffer())});let r=[{pubkey:t.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:t.newAccountPubkey,isSigner:!1,isWritable:!0}];return t.basePubkey.equals(t.fromPubkey)||r.push({pubkey:t.basePubkey,isSigner:!0,isWritable:!1}),new ci({keys:r,programId:this.programId,data:e})}static createNonceAccount(t){const e=new li;"basePubkey"in t&&"seed"in t?e.add(Bi.createAccountWithSeed({fromPubkey:t.fromPubkey,newAccountPubkey:t.noncePubkey,basePubkey:t.basePubkey,seed:t.seed,lamports:t.lamports,space:xi,programId:this.programId})):e.add(Bi.createAccount({fromPubkey:t.fromPubkey,newAccountPubkey:t.noncePubkey,lamports:t.lamports,space:xi,programId:this.programId}));const r={noncePubkey:t.noncePubkey,authorizedPubkey:t.authorizedPubkey};return e.add(this.nonceInitialize(r)),e}static nonceInitialize(t){const e=vi(Ei.InitializeNonceAccount,{authorized:Tn(t.authorizedPubkey.toBuffer())}),r={keys:[{pubkey:t.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:pi,isSigner:!1,isWritable:!1},{pubkey:yi,isSigner:!1,isWritable:!1}],programId:this.programId,data:e};return new ci(r)}static nonceAdvance(t){const e=vi(Ei.AdvanceNonceAccount),r={keys:[{pubkey:t.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:pi,isSigner:!1,isWritable:!1},{pubkey:t.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:e};return new ci(r)}static nonceWithdraw(t){const e=vi(Ei.WithdrawNonceAccount,{lamports:t.lamports});return new ci({keys:[{pubkey:t.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:t.toPubkey,isSigner:!1,isWritable:!0},{pubkey:pi,isSigner:!1,isWritable:!1},{pubkey:yi,isSigner:!1,isWritable:!1},{pubkey:t.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:e})}static nonceAuthorize(t){const e=vi(Ei.AuthorizeNonceAccount,{authorized:Tn(t.newAuthorizedPubkey.toBuffer())});return new ci({keys:[{pubkey:t.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:t.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:e})}static allocate(t){let e,r;return"basePubkey"in t?(e=vi(Ei.AllocateWithSeed,{base:Tn(t.basePubkey.toBuffer()),seed:t.seed,space:t.space,programId:Tn(t.programId.toBuffer())}),r=[{pubkey:t.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:t.basePubkey,isSigner:!0,isWritable:!1}]):(e=vi(Ei.Allocate,{space:t.space}),r=[{pubkey:t.accountPubkey,isSigner:!0,isWritable:!0}]),new ci({keys:r,programId:this.programId,data:e})}}Bi.programId=new Wn("11111111111111111111111111111111");class Ii{constructor(){}static getMinNumSignatures(t){return 2*(Math.ceil(t/Ii.chunkSize)+1+1)}static async load(t,e,r,i,s){{const n=await t.getMinimumBalanceForRentExemption(s.length),o=await t.getAccountInfo(r.publicKey,"confirmed");let a=null;if(null!==o){if(o.executable)return console.error("Program load failed, account is already executable"),!1;o.data.length!==s.length&&(a=a||new li,a.add(Bi.allocate({accountPubkey:r.publicKey,space:s.length}))),o.owner.equals(i)||(a=a||new li,a.add(Bi.assign({accountPubkey:r.publicKey,programId:i}))),o.lamports0?n:1,space:s.length,programId:i}));null!==a&&await bi(t,a,[e,r],{commitment:"confirmed"})}const o=lr.w3([lr.DH("instruction"),lr.DH("offset"),lr.DH("bytesLength"),lr.DH("bytesLengthPadding"),lr.O6(lr.u8("byte"),lr.cY(lr.DH(),-8),"bytes")]),a=Ii.chunkSize;let u=0,h=s,c=[];for(;h.length>0;){const s=h.slice(0,a),l=n.Buffer.alloc(a+16);o.encode({instruction:0,offset:u,bytes:s,bytesLength:0,bytesLengthPadding:0},l);const f=(new li).add({keys:[{pubkey:r.publicKey,isSigner:!0,isWritable:!0}],programId:i,data:l});if(c.push(bi(t,f,[e,r],{commitment:"confirmed"})),t._rpcEndpoint.includes("solana.com")){const t=4;await wi(1e3/t)}u+=a,h=h.slice(a)}await Promise.all(c);{const s=lr.w3([lr.DH("instruction")]),o=n.Buffer.alloc(s.span);s.encode({instruction:1},o);const a=(new li).add({keys:[{pubkey:r.publicKey,isSigner:!0,isWritable:!0},{pubkey:yi,isSigner:!1,isWritable:!1}],programId:i,data:o}),u="processed",h=await t.sendTransaction(a,[e,r],{preflightCommitment:u}),{context:c,value:l}=await t.confirmTransaction({signature:h,lastValidBlockHeight:a.lastValidBlockHeight,blockhash:a.recentBlockhash},u);if(l.err)throw new Error(`Transaction ${h} failed (${JSON.stringify(l)})`);for(;;){try{if(await t.getSlot({commitment:u})>c.slot)break}catch{}await new Promise(t=>setTimeout(t,Math.round(200)))}}return!0}}Ii.chunkSize=932,new Wn("BPFLoader2111111111111111111111111111111111"),globalThis.fetch,lr.w3([lr.DH("typeIndex"),Ai("deactivationSlot"),lr.I0("lastExtendedSlot"),lr.u8("lastExtendedStartIndex"),lr.u8(),lr.O6(Gn(),lr.cY(lr.u8(),-1),"authority")]);const Si=$r(zr(Wn),Hr(),t=>new Wn(t)),Mi=Dr([Hr(),Rr("base64")]),_i=$r(zr(n.Buffer),Mi,t=>n.Buffer.from(t[0],"base64"));function Pi(t){return Fr([Wr({jsonrpc:Rr("2.0"),id:Hr(),result:t}),Wr({jsonrpc:Rr("2.0"),id:Hr(),error:Wr({code:qr(),message:Hr(),data:Nr(Or("any",()=>!0))})})])}const Ui=Pi(qr());function Oi(t){return $r(Pi(t),Ui,e=>"error"in e?e:{...e,result:_r(e.result,t)})}function Li(t){return Oi(Wr({context:Wr({slot:Cr()}),value:t}))}function Ki(t){return Wr({context:Wr({slot:Cr()}),value:t})}const zi=Wr({foundation:Cr(),foundationTerm:Cr(),initial:Cr(),taper:Cr(),terminal:Cr()}),Ri=(Oi(Lr(Tr(Wr({epoch:Cr(),effectiveSlot:Cr(),amount:Cr(),postBalance:Cr(),commission:Nr(Tr(Cr()))})))),Lr(Wr({slot:Cr(),prioritizationFee:Cr()}))),Ti=Wr({total:Cr(),validator:Cr(),foundation:Cr(),epoch:Cr()}),Ci=Wr({epoch:Cr(),slotIndex:Cr(),slotsInEpoch:Cr(),absoluteSlot:Cr(),blockHeight:Nr(Cr()),transactionCount:Nr(Cr())}),Ni=Wr({slotsPerEpoch:Cr(),leaderScheduleSlotOffset:Cr(),warmup:Kr(),firstNormalEpoch:Cr(),firstNormalSlot:Cr()}),ji=jr(Hr(),Lr(Cr())),Hi=Tr(Fr([Wr({}),Hr()])),Di=Wr({err:Hi}),Wi=Rr("receivedSignature"),Fi=(Wr({"solana-core":Hr(),"feature-set":Nr(Cr())}),Wr({program:Hr(),programId:Si,parsed:qr()})),qi=Wr({programId:Si,accounts:Lr(Si),data:Hr()});Li(Wr({err:Tr(Fr([Wr({}),Hr()])),logs:Tr(Lr(Hr())),accounts:Nr(Tr(Lr(Tr(Wr({executable:Kr(),owner:Hr(),lamports:Cr(),data:Lr(Hr()),rentEpoch:Nr(Cr())}))))),unitsConsumed:Nr(Cr()),returnData:Nr(Tr(Wr({programId:Hr(),data:Dr([Hr(),Rr("base64")])}))),innerInstructions:Nr(Tr(Lr(Wr({index:Cr(),instructions:Lr(Fr([Fi,qi]))}))))})),Li(Wr({byIdentity:jr(Hr(),Lr(Cr())),range:Wr({firstSlot:Cr(),lastSlot:Cr()})})),Oi(zi),Oi(Ti),Oi(Ri),Oi(Ci),Oi(Ni),Oi(ji),Oi(Cr()),Li(Wr({total:Cr(),circulating:Cr(),nonCirculating:Cr(),nonCirculatingAccounts:Lr(Si)}));const $i=Wr({amount:Hr(),uiAmount:Tr(Cr()),decimals:Cr(),uiAmountString:Nr(Hr())}),Vi=(Li(Lr(Wr({address:Si,amount:Hr(),uiAmount:Tr(Cr()),decimals:Cr(),uiAmountString:Nr(Hr())}))),Li(Lr(Wr({pubkey:Si,account:Wr({executable:Kr(),owner:Si,lamports:Cr(),data:_i,rentEpoch:Cr()})}))),Wr({program:Hr(),parsed:qr(),space:Cr()})),Zi=(Li(Lr(Wr({pubkey:Si,account:Wr({executable:Kr(),owner:Si,lamports:Cr(),data:Vi,rentEpoch:Cr()})}))),Li(Lr(Wr({lamports:Cr(),address:Si}))),Wr({executable:Kr(),owner:Si,lamports:Cr(),data:_i,rentEpoch:Cr()})),Gi=(Wr({pubkey:Si,account:Zi}),$r(Fr([zr(n.Buffer),Vi]),Fr([Mi,Vi]),t=>Array.isArray(t)?_r(t,_i):t)),Yi=Wr({executable:Kr(),owner:Si,lamports:Cr(),data:Gi,rentEpoch:Cr()}),Xi=(Wr({pubkey:Si,account:Yi}),Wr({state:Fr([Rr("active"),Rr("inactive"),Rr("activating"),Rr("deactivating")]),active:Cr(),inactive:Cr()}),Oi(Lr(Wr({signature:Hr(),slot:Cr(),err:Hi,memo:Tr(Hr()),blockTime:Nr(Tr(Cr()))}))),Oi(Lr(Wr({signature:Hr(),slot:Cr(),err:Hi,memo:Tr(Hr()),blockTime:Nr(Tr(Cr()))}))),Wr({subscription:Cr(),result:Ki(Zi)}),Wr({pubkey:Si,account:Zi})),Ji=(Wr({subscription:Cr(),result:Ki(Xi)}),Wr({parent:Cr(),slot:Cr(),root:Cr()})),Qi=(Wr({subscription:Cr(),result:Ji}),Fr([Wr({type:Fr([Rr("firstShredReceived"),Rr("completed"),Rr("optimisticConfirmation"),Rr("root")]),slot:Cr(),timestamp:Cr()}),Wr({type:Rr("createdBank"),parent:Cr(),slot:Cr(),timestamp:Cr()}),Wr({type:Rr("frozen"),slot:Cr(),timestamp:Cr(),stats:Wr({numTransactionEntries:Cr(),numSuccessfulTransactions:Cr(),numFailedTransactions:Cr(),maxTransactionsPerEntry:Cr()})}),Wr({type:Rr("dead"),slot:Cr(),timestamp:Cr(),err:Hr()})])),ts=(Wr({subscription:Cr(),result:Qi}),Wr({subscription:Cr(),result:Ki(Fr([Di,Wi]))}),Wr({subscription:Cr(),result:Cr()}),Wr({pubkey:Hr(),gossip:Tr(Hr()),tpu:Tr(Hr()),rpc:Tr(Hr()),version:Tr(Hr())}),Wr({votePubkey:Hr(),nodePubkey:Hr(),activatedStake:Cr(),epochVoteAccount:Kr(),epochCredits:Lr(Dr([Cr(),Cr(),Cr()])),commission:Cr(),lastVote:Cr(),rootSlot:Tr(Cr())})),es=(Oi(Wr({current:Lr(ts),delinquent:Lr(ts)})),Fr([Rr("processed"),Rr("confirmed"),Rr("finalized")])),rs=Wr({slot:Cr(),confirmations:Tr(Cr()),err:Hi,confirmationStatus:Nr(es)}),ns=(Li(Lr(Tr(rs))),Oi(Cr()),Wr({accountKey:Si,writableIndexes:Lr(Cr()),readonlyIndexes:Lr(Cr())})),is=Wr({signatures:Lr(Hr()),message:Wr({accountKeys:Lr(Hr()),header:Wr({numRequiredSignatures:Cr(),numReadonlySignedAccounts:Cr(),numReadonlyUnsignedAccounts:Cr()}),instructions:Lr(Wr({accounts:Lr(Cr()),data:Hr(),programIdIndex:Cr()})),recentBlockhash:Hr(),addressTableLookups:Nr(Lr(ns))})}),ss=Wr({pubkey:Si,signer:Kr(),writable:Kr(),source:Nr(Fr([Rr("transaction"),Rr("lookupTable")]))}),os=Wr({accountKeys:Lr(ss),signatures:Lr(Hr())}),as=Wr({parsed:qr(),program:Hr(),programId:Si}),us=Wr({accounts:Lr(Si),data:Hr(),programId:Si}),hs=$r(Fr([us,as]),Fr([Wr({parsed:qr(),program:Hr(),programId:Hr()}),Wr({accounts:Lr(Hr()),data:Hr(),programId:Hr()})]),t=>_r(t,"accounts"in t?us:as)),cs=Wr({signatures:Lr(Hr()),message:Wr({accountKeys:Lr(ss),instructions:Lr(hs),recentBlockhash:Hr(),addressTableLookups:Nr(Tr(Lr(ns)))})}),ls=Wr({accountIndex:Cr(),mint:Hr(),owner:Nr(Hr()),programId:Nr(Hr()),uiTokenAmount:$i}),fs=Wr({writable:Lr(Si),readonly:Lr(Si)}),ds=Wr({err:Hi,fee:Cr(),innerInstructions:Nr(Tr(Lr(Wr({index:Cr(),instructions:Lr(Wr({accounts:Lr(Cr()),data:Hr(),programIdIndex:Cr()}))})))),preBalances:Lr(Cr()),postBalances:Lr(Cr()),logMessages:Nr(Tr(Lr(Hr()))),preTokenBalances:Nr(Tr(Lr(ls))),postTokenBalances:Nr(Tr(Lr(ls))),loadedAddresses:Nr(fs),computeUnitsConsumed:Nr(Cr()),costUnits:Nr(Cr())}),ps=Wr({err:Hi,fee:Cr(),innerInstructions:Nr(Tr(Lr(Wr({index:Cr(),instructions:Lr(hs)})))),preBalances:Lr(Cr()),postBalances:Lr(Cr()),logMessages:Nr(Tr(Lr(Hr()))),preTokenBalances:Nr(Tr(Lr(ls))),postTokenBalances:Nr(Tr(Lr(ls))),loadedAddresses:Nr(fs),computeUnitsConsumed:Nr(Cr()),costUnits:Nr(Cr())}),ys=Fr([Rr(0),Rr("legacy")]),gs=Wr({pubkey:Hr(),lamports:Cr(),postBalance:Tr(Cr()),rewardType:Tr(Hr()),commission:Nr(Tr(Cr()))}),ms=(Oi(Tr(Wr({blockhash:Hr(),previousBlockhash:Hr(),parentSlot:Cr(),transactions:Lr(Wr({transaction:is,meta:Tr(ds),version:Nr(ys)})),rewards:Nr(Lr(gs)),blockTime:Tr(Cr()),blockHeight:Tr(Cr())}))),Oi(Tr(Wr({blockhash:Hr(),previousBlockhash:Hr(),parentSlot:Cr(),rewards:Nr(Lr(gs)),blockTime:Tr(Cr()),blockHeight:Tr(Cr())}))),Oi(Tr(Wr({blockhash:Hr(),previousBlockhash:Hr(),parentSlot:Cr(),transactions:Lr(Wr({transaction:os,meta:Tr(ds),version:Nr(ys)})),rewards:Nr(Lr(gs)),blockTime:Tr(Cr()),blockHeight:Tr(Cr())}))),Oi(Tr(Wr({blockhash:Hr(),previousBlockhash:Hr(),parentSlot:Cr(),transactions:Lr(Wr({transaction:cs,meta:Tr(ps),version:Nr(ys)})),rewards:Nr(Lr(gs)),blockTime:Tr(Cr()),blockHeight:Tr(Cr())}))),Oi(Tr(Wr({blockhash:Hr(),previousBlockhash:Hr(),parentSlot:Cr(),transactions:Lr(Wr({transaction:os,meta:Tr(ps),version:Nr(ys)})),rewards:Nr(Lr(gs)),blockTime:Tr(Cr()),blockHeight:Tr(Cr())}))),Oi(Tr(Wr({blockhash:Hr(),previousBlockhash:Hr(),parentSlot:Cr(),rewards:Nr(Lr(gs)),blockTime:Tr(Cr()),blockHeight:Tr(Cr())}))),Oi(Tr(Wr({blockhash:Hr(),previousBlockhash:Hr(),parentSlot:Cr(),transactions:Lr(Wr({transaction:is,meta:Tr(ds)})),rewards:Nr(Lr(gs)),blockTime:Tr(Cr())}))),Oi(Tr(Wr({blockhash:Hr(),previousBlockhash:Hr(),parentSlot:Cr(),signatures:Lr(Hr()),blockTime:Tr(Cr())}))),Oi(Tr(Wr({slot:Cr(),meta:Tr(ds),blockTime:Nr(Tr(Cr())),transaction:is,version:Nr(ys)}))),Oi(Tr(Wr({slot:Cr(),transaction:cs,meta:Tr(ps),blockTime:Nr(Tr(Cr())),version:Nr(ys)}))),Li(Wr({blockhash:Hr(),lastValidBlockHeight:Cr()})),Li(Kr()),Oi(Lr(Wr({slot:Cr(),numTransactions:Cr(),numSlots:Cr(),samplePeriodSecs:Cr()}))),Li(Tr(Wr({feeCalculator:Wr({lamportsPerSignature:Cr()})}))),Oi(Hr()),Oi(Hr()),Wr({err:Hi,logs:Lr(Hr()),signature:Hr()}));Wr({result:Ki(ms),subscription:Cr()});class bs{constructor(t){this._keypair=void 0,this._keypair=t??On()}static generate(){return new bs(On())}static fromSecretKey(t,e){if(64!==t.byteLength)throw new Error("bad secret key size");const r=t.slice(32,64);if(!e||!e.skipValidation){const e=t.slice(0,32),n=Ln(e);for(let t=0;t<32;t++)if(r[t]!==n[t])throw new Error("provided secretKey is invalid")}return new bs({publicKey:r,secretKey:t})}static fromSeed(t){const e=Ln(t),r=new Uint8Array(64);return r.set(t),r.set(e,32),new bs({publicKey:e,secretKey:r})}get publicKey(){return new Wn(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:lr.w3([lr.DH("instruction"),Ai("recentSlot"),lr.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:lr.w3([lr.DH("instruction")])},ExtendLookupTable:{index:2,layout:lr.w3([lr.DH("instruction"),Ai(),lr.O6(Gn(),lr.cY(lr.DH(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:lr.w3([lr.DH("instruction")])},CloseLookupTable:{index:4,layout:lr.w3([lr.DH("instruction")])}});new Wn("AddressLookupTab1e1111111111111111111111111");Object.freeze({RequestUnits:{index:0,layout:lr.w3([lr.u8("instruction"),lr.DH("units"),lr.DH("additionalFee")])},RequestHeapFrame:{index:1,layout:lr.w3([lr.u8("instruction"),lr.DH("bytes")])},SetComputeUnitLimit:{index:2,layout:lr.w3([lr.u8("instruction"),lr.DH("units")])},SetComputeUnitPrice:{index:3,layout:lr.w3([lr.u8("instruction"),Ai("microLamports")])}});new Wn("ComputeBudget111111111111111111111111111111");const ws=lr.w3([lr.u8("numSignatures"),lr.u8("padding"),lr.NX("signatureOffset"),lr.NX("signatureInstructionIndex"),lr.NX("publicKeyOffset"),lr.NX("publicKeyInstructionIndex"),lr.NX("messageDataOffset"),lr.NX("messageDataSize"),lr.NX("messageInstructionIndex")]);class vs{constructor(){}static createInstructionWithPublicKey(t){const{publicKey:e,message:r,signature:i,instructionIndex:s}=t;ei(32===e.length,`Public Key must be 32 bytes but received ${e.length} bytes`),ei(64===i.length,`Signature must be 64 bytes but received ${i.length} bytes`);const o=ws.span,a=o+e.length,u=a+i.length,h=n.Buffer.alloc(u+r.length),c=null==s?65535:s;return ws.encode({numSignatures:1,padding:0,signatureOffset:a,signatureInstructionIndex:c,publicKeyOffset:o,publicKeyInstructionIndex:c,messageDataOffset:u,messageDataSize:r.length,messageInstructionIndex:c},h),h.fill(e,o),h.fill(i,a),h.fill(r,u),new ci({keys:[],programId:vs.programId,data:h})}static createInstructionWithPrivateKey(t){const{privateKey:e,message:r,instructionIndex:n}=t;ei(64===e.length,`Private key must be 64 bytes but received ${e.length} bytes`);try{const t=bs.fromSecretKey(e),i=t.publicKey.toBytes(),s=zn(r,t.secretKey);return this.createInstructionWithPublicKey({publicKey:i,message:r,signature:s,instructionIndex:n})}catch(t){throw new Error(`Error creating instruction; ${t}`)}}}vs.programId=new Wn("Ed25519SigVerify111111111111111111111111111"),Un.utils.isValidPrivateKey;const ks=Un.getPublicKey,xs=lr.w3([lr.u8("numSignatures"),lr.NX("signatureOffset"),lr.u8("signatureInstructionIndex"),lr.NX("ethAddressOffset"),lr.u8("ethAddressInstructionIndex"),lr.NX("messageDataOffset"),lr.NX("messageDataSize"),lr.u8("messageInstructionIndex"),lr.av(20,"ethAddress"),lr.av(64,"signature"),lr.u8("recoveryId")]);class As{constructor(){}static publicKeyToEthAddress(t){ei(64===t.length,`Public key must be 64 bytes but received ${t.length} bytes`);try{return n.Buffer.from(hn(Tn(t))).slice(-20)}catch(t){throw new Error(`Error constructing Ethereum address: ${t}`)}}static createInstructionWithPublicKey(t){const{publicKey:e,message:r,signature:n,recoveryId:i,instructionIndex:s}=t;return As.createInstructionWithEthAddress({ethAddress:As.publicKeyToEthAddress(e),message:r,signature:n,recoveryId:i,instructionIndex:s})}static createInstructionWithEthAddress(t){const{ethAddress:e,message:r,signature:i,recoveryId:s,instructionIndex:o=0}=t;let a;a="string"==typeof e?e.startsWith("0x")?n.Buffer.from(e.substr(2),"hex"):n.Buffer.from(e,"hex"):e,ei(20===a.length,`Address must be 20 bytes but received ${a.length} bytes`);const u=12+a.length,h=u+i.length+1,c=n.Buffer.alloc(xs.span+r.length);return xs.encode({numSignatures:1,signatureOffset:u,signatureInstructionIndex:o,ethAddressOffset:12,ethAddressInstructionIndex:o,messageDataOffset:h,messageDataSize:r.length,messageInstructionIndex:o,signature:Tn(i),ethAddress:Tn(a),recoveryId:s},c),c.fill(Tn(r),xs.span),new ci({keys:[],programId:As.programId,data:c})}static createInstructionWithPrivateKey(t){const{privateKey:e,message:r,instructionIndex:i}=t;ei(32===e.length,`Private key must be 32 bytes but received ${e.length} bytes`);try{const t=Tn(e),s=ks(t,!1).slice(1),o=n.Buffer.from(hn(Tn(r))),[a,u]=((t,e)=>{const r=Un.sign(t,e);return[r.toCompactRawBytes(),r.recovery]})(o,t);return this.createInstructionWithPublicKey({publicKey:s,message:r,signature:a,recoveryId:u,instructionIndex:i})}catch(t){throw new Error(`Error creating instruction; ${t}`)}}}var Es;As.programId=new Wn("KeccakSecp256k11111111111111111111111111111");const Bs=new Wn("StakeConfig11111111111111111111111111111111");class Is{constructor(t,e,r){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=t,this.epoch=e,this.custodian=r}}Es=Is,Is.default=new Es(0,0,Wn.default);const Ss=Object.freeze({Initialize:{index:0,layout:lr.w3([lr.DH("instruction"),((t="authorized")=>lr.w3([Gn("staker"),Gn("withdrawer")],t))(),((t="lockup")=>lr.w3([lr.Wg("unixTimestamp"),lr.Wg("epoch"),Gn("custodian")],t))()])},Authorize:{index:1,layout:lr.w3([lr.DH("instruction"),Gn("newAuthorized"),lr.DH("stakeAuthorizationType")])},Delegate:{index:2,layout:lr.w3([lr.DH("instruction")])},Split:{index:3,layout:lr.w3([lr.DH("instruction"),lr.Wg("lamports")])},Withdraw:{index:4,layout:lr.w3([lr.DH("instruction"),lr.Wg("lamports")])},Deactivate:{index:5,layout:lr.w3([lr.DH("instruction")])},Merge:{index:7,layout:lr.w3([lr.DH("instruction")])},AuthorizeWithSeed:{index:8,layout:lr.w3([lr.DH("instruction"),Gn("newAuthorized"),lr.DH("stakeAuthorizationType"),Xn("authoritySeed"),Gn("authorityOwner")])}});Object.freeze({Staker:{index:0},Withdrawer:{index:1}});class Ms{constructor(){}static initialize(t){const{stakePubkey:e,authorized:r,lockup:n}=t,i=n||Is.default,s=vi(Ss.Initialize,{authorized:{staker:Tn(r.staker.toBuffer()),withdrawer:Tn(r.withdrawer.toBuffer())},lockup:{unixTimestamp:i.unixTimestamp,epoch:i.epoch,custodian:Tn(i.custodian.toBuffer())}}),o={keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:yi,isSigner:!1,isWritable:!1}],programId:this.programId,data:s};return new ci(o)}static createAccountWithSeed(t){const e=new li;e.add(Bi.createAccountWithSeed({fromPubkey:t.fromPubkey,newAccountPubkey:t.stakePubkey,basePubkey:t.basePubkey,seed:t.seed,lamports:t.lamports,space:this.space,programId:this.programId}));const{stakePubkey:r,authorized:n,lockup:i}=t;return e.add(this.initialize({stakePubkey:r,authorized:n,lockup:i}))}static createAccount(t){const e=new li;e.add(Bi.createAccount({fromPubkey:t.fromPubkey,newAccountPubkey:t.stakePubkey,lamports:t.lamports,space:this.space,programId:this.programId}));const{stakePubkey:r,authorized:n,lockup:i}=t;return e.add(this.initialize({stakePubkey:r,authorized:n,lockup:i}))}static delegate(t){const{stakePubkey:e,authorizedPubkey:r,votePubkey:n}=t,i=vi(Ss.Delegate);return(new li).add({keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:gi,isSigner:!1,isWritable:!1},{pubkey:Bs,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}],programId:this.programId,data:i})}static authorize(t){const{stakePubkey:e,authorizedPubkey:r,newAuthorizedPubkey:n,stakeAuthorizationType:i,custodianPubkey:s}=t,o=vi(Ss.Authorize,{newAuthorized:Tn(n.toBuffer()),stakeAuthorizationType:i.index}),a=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1}];return s&&a.push({pubkey:s,isSigner:!0,isWritable:!1}),(new li).add({keys:a,programId:this.programId,data:o})}static authorizeWithSeed(t){const{stakePubkey:e,authorityBase:r,authoritySeed:n,authorityOwner:i,newAuthorizedPubkey:s,stakeAuthorizationType:o,custodianPubkey:a}=t,u=vi(Ss.AuthorizeWithSeed,{newAuthorized:Tn(s.toBuffer()),stakeAuthorizationType:o.index,authoritySeed:n,authorityOwner:Tn(i.toBuffer())}),h=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1},{pubkey:di,isSigner:!1,isWritable:!1}];return a&&h.push({pubkey:a,isSigner:!0,isWritable:!1}),(new li).add({keys:h,programId:this.programId,data:u})}static splitInstruction(t){const{stakePubkey:e,authorizedPubkey:r,splitStakePubkey:n,lamports:i}=t,s=vi(Ss.Split,{lamports:i});return new ci({keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1}],programId:this.programId,data:s})}static split(t,e){const r=new li;return r.add(Bi.createAccount({fromPubkey:t.authorizedPubkey,newAccountPubkey:t.splitStakePubkey,lamports:e,space:this.space,programId:this.programId})),r.add(this.splitInstruction(t))}static splitWithSeed(t,e){const{stakePubkey:r,authorizedPubkey:n,splitStakePubkey:i,basePubkey:s,seed:o,lamports:a}=t,u=new li;return u.add(Bi.allocate({accountPubkey:i,basePubkey:s,seed:o,space:this.space,programId:this.programId})),e&&e>0&&u.add(Bi.transfer({fromPubkey:t.authorizedPubkey,toPubkey:i,lamports:e})),u.add(this.splitInstruction({stakePubkey:r,authorizedPubkey:n,splitStakePubkey:i,lamports:a}))}static merge(t){const{stakePubkey:e,sourceStakePubKey:r,authorizedPubkey:n}=t,i=vi(Ss.Merge);return(new li).add({keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:gi,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:i})}static withdraw(t){const{stakePubkey:e,authorizedPubkey:r,toPubkey:n,lamports:i,custodianPubkey:s}=t,o=vi(Ss.Withdraw,{lamports:i}),a=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:gi,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}];return s&&a.push({pubkey:s,isSigner:!0,isWritable:!1}),(new li).add({keys:a,programId:this.programId,data:o})}static deactivate(t){const{stakePubkey:e,authorizedPubkey:r}=t,n=vi(Ss.Deactivate);return(new li).add({keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}],programId:this.programId,data:n})}}Ms.programId=new Wn("Stake11111111111111111111111111111111111111"),Ms.space=200;const _s=Object.freeze({InitializeAccount:{index:0,layout:lr.w3([lr.DH("instruction"),((t="voteInit")=>lr.w3([Gn("nodePubkey"),Gn("authorizedVoter"),Gn("authorizedWithdrawer"),lr.u8("commission")],t))()])},Authorize:{index:1,layout:lr.w3([lr.DH("instruction"),Gn("newAuthorized"),lr.DH("voteAuthorizationType")])},Withdraw:{index:3,layout:lr.w3([lr.DH("instruction"),lr.Wg("lamports")])},UpdateValidatorIdentity:{index:4,layout:lr.w3([lr.DH("instruction")])},AuthorizeWithSeed:{index:10,layout:lr.w3([lr.DH("instruction"),((t="voteAuthorizeWithSeedArgs")=>lr.w3([lr.DH("voteAuthorizationType"),Gn("currentAuthorityDerivedKeyOwnerPubkey"),Xn("currentAuthorityDerivedKeySeed"),Gn("newAuthorized")],t))()])}});Object.freeze({Voter:{index:0},Withdrawer:{index:1}});class Ps{constructor(){}static initializeAccount(t){const{votePubkey:e,nodePubkey:r,voteInit:n}=t,i=vi(_s.InitializeAccount,{voteInit:{nodePubkey:Tn(n.nodePubkey.toBuffer()),authorizedVoter:Tn(n.authorizedVoter.toBuffer()),authorizedWithdrawer:Tn(n.authorizedWithdrawer.toBuffer()),commission:n.commission}}),s={keys:[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:yi,isSigner:!1,isWritable:!1},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}],programId:this.programId,data:i};return new ci(s)}static createAccount(t){const e=new li;return e.add(Bi.createAccount({fromPubkey:t.fromPubkey,newAccountPubkey:t.votePubkey,lamports:t.lamports,space:this.space,programId:this.programId})),e.add(this.initializeAccount({votePubkey:t.votePubkey,nodePubkey:t.voteInit.nodePubkey,voteInit:t.voteInit}))}static authorize(t){const{votePubkey:e,authorizedPubkey:r,newAuthorizedPubkey:n,voteAuthorizationType:i}=t,s=vi(_s.Authorize,{newAuthorized:Tn(n.toBuffer()),voteAuthorizationType:i.index}),o=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}];return(new li).add({keys:o,programId:this.programId,data:s})}static authorizeWithSeed(t){const{currentAuthorityDerivedKeyBasePubkey:e,currentAuthorityDerivedKeyOwnerPubkey:r,currentAuthorityDerivedKeySeed:n,newAuthorizedPubkey:i,voteAuthorizationType:s,votePubkey:o}=t,a=vi(_s.AuthorizeWithSeed,{voteAuthorizeWithSeedArgs:{currentAuthorityDerivedKeyOwnerPubkey:Tn(r.toBuffer()),currentAuthorityDerivedKeySeed:n,newAuthorized:Tn(i.toBuffer()),voteAuthorizationType:s.index}}),u=[{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:di,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!0,isWritable:!1}];return(new li).add({keys:u,programId:this.programId,data:a})}static withdraw(t){const{votePubkey:e,authorizedWithdrawerPubkey:r,lamports:n,toPubkey:i}=t,s=vi(_s.Withdraw,{lamports:n}),o=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1}];return(new li).add({keys:o,programId:this.programId,data:s})}static safeWithdraw(t,e,r){if(t.lamports>e-r)throw new Error("Withdraw will leave vote account with insufficient funds.");return Ps.withdraw(t)}static updateValidatorIdentity(t){const{votePubkey:e,authorizedWithdrawerPubkey:r,nodePubkey:n}=t,i=vi(_s.UpdateValidatorIdentity),s=[{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}];return(new li).add({keys:s,programId:this.programId,data:i})}}Ps.programId=new Wn("Vote111111111111111111111111111111111111111"),Ps.space=3762,new Wn("Va1idator1nfo111111111111111111111111111111"),Wr({name:Hr(),website:Nr(Hr()),details:Nr(Hr()),iconUrl:Nr(Hr()),keybaseUsername:Nr(Hr())}),new Wn("Vote111111111111111111111111111111111111111"),lr.w3([Gn("nodePubkey"),Gn("authorizedWithdrawer"),lr.u8("commission"),lr.I0(),lr.O6(lr.w3([lr.I0("slot"),lr.DH("confirmationCount")]),lr.cY(lr.DH(),-8),"votes"),lr.u8("rootSlotValid"),lr.I0("rootSlot"),lr.I0(),lr.O6(lr.w3([lr.I0("epoch"),Gn("authorizedVoter")]),lr.cY(lr.DH(),-8),"authorizedVoters"),lr.w3([lr.O6(lr.w3([Gn("authorizedPubkey"),lr.I0("epochOfLastAuthorizedSwitch"),lr.I0("targetEpoch")]),32,"buf"),lr.I0("idx"),lr.u8("isEmpty")],"priorVoters"),lr.I0(),lr.O6(lr.w3([lr.I0("epoch"),lr.I0("credits"),lr.I0("prevCredits")]),lr.cY(lr.DH(),-8),"epochCredits"),lr.w3([lr.I0("slot"),lr.I0("timestamp")],"lastTimestamp")])},251:(t,e)=>{e.read=function(t,e,r,n,i){var s,o,a=8*i-n-1,u=(1<>1,c=-7,l=r?i-1:0,f=r?-1:1,d=t[e+l];for(l+=f,s=d&(1<<-c)-1,d>>=-c,c+=a;c>0;s=256*s+t[e+l],l+=f,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=n;c>0;o=256*o+t[e+l],l+=f,c-=8);if(0===s)s=1-h;else{if(s===u)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,n),s-=h}return(d?-1:1)*o*Math.pow(2,s-n)},e.write=function(t,e,r,n,i,s){var o,a,u,h=8*s-i-1,c=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:s-1,p=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),(e+=o+l>=1?f/u:f*Math.pow(2,1-l))*u>=2&&(o++,u/=2),o+l>=c?(a=0,o=c):o+l>=1?(a=(e*u-1)*Math.pow(2,i),o+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;t[r+d]=255&a,d+=p,a/=256,i-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,h-=8);t[r+d-p]|=128*y}},255:(t,e,r)=>{"use strict";r.d(e,{ws:()=>q,GR:()=>yt,RG:()=>gt,v7:()=>mt});class n extends Error{constructor(t){let e;e=t instanceof Error?t.message:"string"==typeof t?t:"",super(e),this.name=this.constructor.name}}class i extends n{}class s extends n{}class o extends n{}class a extends n{}class u extends n{}class h extends n{}class c extends n{}class l extends n{}class f extends n{}class d extends n{}class p extends n{}const y=(g=globalThis,m={},new Proxy(g,{get:(t,e,r)=>e in m?m[e]:g[e],set:(t,e,r)=>(e in m&&delete m[e],g[e]=r,!0),deleteProperty(t,e){let r=!1;return e in m&&(delete m[e],r=!0),e in g&&(delete g[e],r=!0),r},ownKeys(t){const e=Reflect.ownKeys(g),r=Reflect.ownKeys(m),n=new Set(r);return[...e.filter(t=>!n.has(t)),...r]},defineProperty:(t,e,r)=>(e in m&&delete m[e],Reflect.defineProperty(g,e,r),!0),getOwnPropertyDescriptor:(t,e)=>e in m?Reflect.getOwnPropertyDescriptor(m,e):Reflect.getOwnPropertyDescriptor(g,e),has:(t,e)=>e in m||e in g}));var g,m;class b{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){void 0===this._api&&(this._api=await async function(){if(void 0!==y&&void 0!==globalThis.crypto)return globalThis.crypto.subtle;try{const{webcrypto:t}=await r.e(825).then(r.t.bind(r,825,19));return t.subtle}catch(t){throw new p(t)}}())}}const w=8192,v=new Uint8Array(0),k=new Uint8Array([75,69,77,0,0]),x=t=>"object"==typeof t&&null!==t&&"object"==typeof t.privateKey&&"object"==typeof t.publicKey;function A(t,e){if(e<=0)throw new Error("i2Osp: too small size");if(t>=256**e)throw new Error("i2Osp: too large integer");const r=new Uint8Array(e);for(let n=0;n>=8;return r}function E(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t,0),r.set(e,t.length),r}const B=new Uint8Array([101,97,101,95,112,114,107]),I=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);class S{constructor(t,e,r){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_prim",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=t,this._prim=e,this._kdf=r;const n=new Uint8Array(k);n.set(A(this.id,2),3),this._kdf.init(n)}async serializePublicKey(t){return await this._prim.serializePublicKey(t)}async deserializePublicKey(t){return await this._prim.deserializePublicKey(t)}async serializePrivateKey(t){return await this._prim.serializePrivateKey(t)}async deserializePrivateKey(t){return await this._prim.deserializePrivateKey(t)}async importKey(t,e,r=!0){return await this._prim.importKey(t,e,r)}async generateKeyPair(){return await this._prim.generateKeyPair()}async deriveKeyPair(t){if(t.byteLength>w)throw new i("Too long ikm");return await this._prim.deriveKeyPair(t)}async encap(t){let e;e=void 0===t.ekm?await this.generateKeyPair():x(t.ekm)?t.ekm:await this.deriveKeyPair(t.ekm);const r=await this._prim.serializePublicKey(e.publicKey),n=await this._prim.serializePublicKey(t.recipientPublicKey);try{let i,s;if(void 0===t.senderKey)i=new Uint8Array(await this._prim.dh(e.privateKey,t.recipientPublicKey));else{const r=x(t.senderKey)?t.senderKey.privateKey:t.senderKey;i=E(new Uint8Array(await this._prim.dh(e.privateKey,t.recipientPublicKey)),new Uint8Array(await this._prim.dh(r,t.recipientPublicKey)))}if(void 0===t.senderKey)s=E(new Uint8Array(r),new Uint8Array(n));else{const e=x(t.senderKey)?t.senderKey.publicKey:await this._prim.derivePublicKey(t.senderKey),i=await this._prim.serializePublicKey(e);s=function(t,e,r){const n=new Uint8Array(t.length+e.length+r.length);return n.set(t,0),n.set(e,t.length),n.set(r,t.length+e.length),n}(new Uint8Array(r),new Uint8Array(n),new Uint8Array(i))}return{enc:r,sharedSecret:await this._generateSharedSecret(i,s)}}catch(t){throw new a(t)}}async decap(t){const e=await this._prim.deserializePublicKey(t.enc),r=x(t.recipientKey)?t.recipientKey.privateKey:t.recipientKey,n=x(t.recipientKey)?t.recipientKey.publicKey:await this._prim.derivePublicKey(t.recipientKey),i=await this._prim.serializePublicKey(n);try{let n,s;if(void 0===t.senderPublicKey)n=new Uint8Array(await this._prim.dh(r,e));else{n=E(new Uint8Array(await this._prim.dh(r,e)),new Uint8Array(await this._prim.dh(r,t.senderPublicKey)))}if(void 0===t.senderPublicKey)s=E(new Uint8Array(t.enc),new Uint8Array(i));else{const e=await this._prim.serializePublicKey(t.senderPublicKey);s=new Uint8Array(t.enc.byteLength+i.byteLength+e.byteLength),s.set(new Uint8Array(t.enc),0),s.set(new Uint8Array(i),t.enc.byteLength),s.set(new Uint8Array(e),t.enc.byteLength+i.byteLength)}return await this._generateSharedSecret(n,s)}catch(t){throw new u(t)}}async _generateSharedSecret(t,e){const r=this._kdf.buildLabeledIkm(B,t),n=this._kdf.buildLabeledInfo(I,e,this.secretSize);return await this._kdf.extractAndExpand(v.buffer,r.buffer,n.buffer,this.secretSize)}}const M=["deriveBits"],_=new Uint8Array([100,107,112,95,112,114,107]);new Uint8Array([115,107]);class P{constructor(t){Object.defineProperty(this,"_num",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._num=new Uint8Array(t)}val(){return this._num}reset(){this._num.fill(0)}set(t){if(t.length!==this._num.length)throw new Error("Bignum.set: invalid argument");this._num.set(t)}isZero(){for(let t=0;tt[e])return!1}return!1}}const U=new Uint8Array([99,97,110,100,105,100,97,116,101]),O=new Uint8Array([255,255,255,255,0,0,0,0,255,255,255,255,255,255,255,255,188,230,250,173,167,23,158,132,243,185,202,194,252,99,37,81]),L=new Uint8Array([255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,199,99,77,129,244,55,45,223,88,26,13,178,72,176,167,122,236,236,25,106,204,197,41,115]),K=new Uint8Array([1,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,250,81,134,135,131,191,47,150,107,127,204,1,72,247,9,165,208,59,181,201,184,137,156,71,174,187,111,183,30,145,56,100,9]),z=new Uint8Array([48,65,2,1,0,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,4,39,48,37,2,1,1,4,32]),R=new Uint8Array([48,78,2,1,0,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,34,4,55,48,53,2,1,1,4,48]),T=new Uint8Array([48,96,2,1,0,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,35,4,73,48,71,2,1,1,4,66]);class C extends b{constructor(t,e){switch(super(),Object.defineProperty(this,"_hkdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_alg",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nPk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nSk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nDh",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_bitmask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pkcs8AlgId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._hkdf=e,t){case 16:this._alg={name:"ECDH",namedCurve:"P-256"},this._nPk=65,this._nSk=32,this._nDh=32,this._order=O,this._bitmask=255,this._pkcs8AlgId=z;break;case 17:this._alg={name:"ECDH",namedCurve:"P-384"},this._nPk=97,this._nSk=48,this._nDh=48,this._order=L,this._bitmask=255,this._pkcs8AlgId=R;break;default:this._alg={name:"ECDH",namedCurve:"P-521"},this._nPk=133,this._nSk=66,this._nDh=66,this._order=K,this._bitmask=1,this._pkcs8AlgId=T}}async serializePublicKey(t){await this._setup();try{return await this._api.exportKey("raw",t)}catch(t){throw new s(t)}}async deserializePublicKey(t){await this._setup();try{return await this._importRawKey(t,!0)}catch(t){throw new o(t)}}async serializePrivateKey(t){await this._setup();try{const e=await this._api.exportKey("jwk",t);if(!("d"in e))throw new Error("Not private key");return function(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e),n=new Uint8Array(r.length);for(let t=0;t255)throw new Error("Faild to derive a key pair");const n=new Uint8Array(await this._hkdf.labeledExpand(e,U,A(t,1),this._nSk));n[0]=n[0]&this._bitmask,r.set(n)}const n=await this._deserializePkcs8Key(r.val());return r.reset(),{privateKey:n,publicKey:await this.derivePublicKey(n)}}catch(t){throw new d(t)}}async derivePublicKey(t){await this._setup();try{const e=await this._api.exportKey("jwk",t);return delete e.d,delete e.key_ops,await this._api.importKey("jwk",e,this._alg,!0,[])}catch(t){throw new o(t)}}async dh(t,e){try{return await this._setup(),await this._api.deriveBits({name:"ECDH",public:e},t,8*this._nDh)}catch(t){throw new s(t)}}async _importRawKey(t,e){if(e&&t.byteLength!==this._nPk)throw new Error("Invalid public key for the ciphersuite");if(!e&&t.byteLength!==this._nSk)throw new Error("Invalid private key for the ciphersuite");return e?await this._api.importKey("raw",t,this._alg,!0,[]):await this._deserializePkcs8Key(new Uint8Array(t))}async _importJWK(t,e){if(void 0===t.crv||t.crv!==this._alg.namedCurve)throw new Error(`Invalid crv: ${t.crv}`);if(e){if(void 0!==t.d)throw new Error("Invalid key: `d` should not be set");return await this._api.importKey("jwk",t,this._alg,!0,[])}if(void 0===t.d)throw new Error("Invalid key: `d` not found");return await this._api.importKey("jwk",t,this._alg,!0,M)}async _deserializePkcs8Key(t){const e=new Uint8Array(this._pkcs8AlgId.length+t.length);return e.set(this._pkcs8AlgId,0),e.set(t,this._pkcs8AlgId.length),await this._api.importKey("pkcs8",e,this._alg,!0,M)}}const N=new Uint8Array([72,80,75,69,45,118,49]);class j extends b{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:v}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:"HMAC",hash:"SHA-256",length:256}})}init(t){this._suiteId=t}buildLabeledIkm(t,e){this._checkInit();const r=new Uint8Array(7+this._suiteId.byteLength+t.byteLength+e.byteLength);return r.set(N,0),r.set(this._suiteId,7),r.set(t,7+this._suiteId.byteLength),r.set(e,7+this._suiteId.byteLength+t.byteLength),r}buildLabeledInfo(t,e,r){this._checkInit();const n=new Uint8Array(9+this._suiteId.byteLength+t.byteLength+e.byteLength);return n.set(new Uint8Array([0,r]),0),n.set(N,2),n.set(this._suiteId,9),n.set(t,9+this._suiteId.byteLength),n.set(e,9+this._suiteId.byteLength+t.byteLength),n}async extract(t,e){if(await this._setup(),0===t.byteLength&&(t=new ArrayBuffer(this.hashSize)),t.byteLength!==this.hashSize)throw new i("The salt length must be the same as the hashSize");const r=await this._api.importKey("raw",t,this.algHash,!1,["sign"]);return await this._api.sign("HMAC",r,e)}async expand(t,e,r){await this._setup();const n=await this._api.importKey("raw",t,this.algHash,!1,["sign"]),i=new ArrayBuffer(r),s=new Uint8Array(i);let o=v;const a=new Uint8Array(e),u=new Uint8Array(1);if(r>255*this.hashSize)throw new Error("Entropy limit reached");const h=new Uint8Array(this.hashSize+a.length+1);for(let t=1,e=0;e=o.length?(s.set(o,e),e+=o.length):(s.set(o.slice(0,s.length-e),e),e+=s.length-e);return i}async extractAndExpand(t,e,r,n){await this._setup();const i=await this._api.importKey("raw",e,"HKDF",!1,["deriveBits"]);return await this._api.deriveBits({name:"HKDF",hash:this.algHash.hash,salt:t,info:r},i,8*n)}async labeledExtract(t,e,r){return await this.extract(t,this.buildLabeledIkm(e,r).buffer)}async labeledExpand(t,e,r,n){return await this.expand(t,this.buildLabeledInfo(e,r,n).buffer,n)}_checkInit(){if(this._suiteId===v)throw new Error("Not initialized. Call init()")}}class H extends j{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:"HMAC",hash:"SHA-256",length:256}})}}const D=["encrypt","decrypt"];BigInt(0),BigInt(1),BigInt(2);class W extends b{constructor(t){super(),Object.defineProperty(this,"_rawKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._rawKey=t}async seal(t,e,r){await this._setupKey();const n={name:"AES-GCM",iv:t,additionalData:r};return await this._api.encrypt(n,this._key,e)}async open(t,e,r){await this._setupKey();const n={name:"AES-GCM",iv:t,additionalData:r};return await this._api.decrypt(n,this._key,e)}async _setupKey(){if(void 0!==this._key)return;await this._setup();const t=await this._importKey(this._rawKey);new Uint8Array(this._rawKey).fill(0),this._key=t}async _importKey(t){return await this._api.importKey("raw",t,{name:"AES-GCM"},!0,D)}}class F{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"keySize",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"nonceSize",{enumerable:!0,configurable:!0,writable:!0,value:12}),Object.defineProperty(this,"tagSize",{enumerable:!0,configurable:!0,writable:!0,value:16})}createEncryptionContext(t){return new W(t)}}class q extends F{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:2}),Object.defineProperty(this,"keySize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"nonceSize",{enumerable:!0,configurable:!0,writable:!0,value:12}),Object.defineProperty(this,"tagSize",{enumerable:!0,configurable:!0,writable:!0,value:16})}}function $(){return new Promise((t,e)=>{e(new p("Not supported"))})}const V=new Uint8Array([115,101,99]);class Z{constructor(t,e,r){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exporterSecret",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._api=t,this._kdf=e,this.exporterSecret=r}async seal(t,e){return await $()}async open(t,e){return await $()}async export(t,e){if(t.byteLength>w)throw new i("Too long exporter context");try{return await this._kdf.labeledExpand(this.exporterSecret,V,new Uint8Array(t),e)}catch(t){throw new h(t)}}}class G extends Z{}class Y extends Z{constructor(t,e,r,n){super(t,e,r),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.enc=n}}class X extends Z{constructor(t,e,r){if(super(t,e,r.exporterSecret),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nT",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),void 0===r.key||void 0===r.baseNonce||void 0===r.seq)throw new Error("Required parameters are missing");this._aead=r.aead,this._nK=this._aead.keySize,this._nN=this._aead.nonceSize,this._nT=this._aead.tagSize;const n=this._aead.createEncryptionContext(r.key);this._ctx={key:n,baseNonce:r.baseNonce,seq:r.seq}}computeNonce(t){const e=A(t.seq,t.baseNonce.byteLength);return function(t,e){if(t.byteLength!==e.byteLength)throw new Error("xor: different length inputs");const r=new Uint8Array(t.byteLength);for(let n=0;nNumber.MAX_SAFE_INTEGER)throw new f("Message limit reached");t.seq+=1}}var J;class Q{constructor(){J.set(this,Promise.resolve())}async lock(){let t;const e=new Promise(e=>{t=e}),r=function(t,e,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(t):n?n.value:e.get(t)}(this,J,"f");return function(t,e,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===n?i.call(t,r):i?i.value=r:e.set(t,r)}(this,J,e,"f"),await r,t}}J=new WeakMap;var tt,et=function(t,e,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(t):n?n.value:e.get(t)};class rt extends X{constructor(){super(...arguments),tt.set(this,void 0)}async open(t,e=v.buffer){!function(t,e,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===n?i.call(t,r):i?i.value=r:e.set(t,r)}(this,tt,et(this,tt,"f")??new Q,"f");const r=await et(this,tt,"f").lock();let n;try{n=await this._ctx.key.open(this.computeNonce(this._ctx),t,e)}catch(t){throw new l(t)}finally{r()}return this.incrementSeq(this._ctx),n}}tt=new WeakMap;var nt,it=function(t,e,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(t):n?n.value:e.get(t)};class st extends X{constructor(t,e,r,n){super(t,e,r),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),nt.set(this,void 0),this.enc=n}async seal(t,e=v.buffer){!function(t,e,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===n?i.call(t,r):i?i.value=r:e.set(t,r)}(this,nt,it(this,nt,"f")??new Q,"f");const r=await it(this,nt,"f").lock();let n;try{n=await this._ctx.key.seal(this.computeNonce(this._ctx),t,e)}catch(t){throw new c(t)}finally{r()}return this.incrementSeq(this._ctx),n}}nt=new WeakMap;const ot=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),at=new Uint8Array([101,120,112]),ut=new Uint8Array([105,110,102,111,95,104,97,115,104]),ht=new Uint8Array([107,101,121]),ct=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),lt=new Uint8Array([115,101,99,114,101,116]),ft=new Uint8Array([72,80,75,69,0,0,0,0,0,0]);class dt extends b{constructor(t){if(super(),Object.defineProperty(this,"_kem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"number"==typeof t.kem)throw new i("KemId cannot be used");if(this._kem=t.kem,"number"==typeof t.kdf)throw new i("KdfId cannot be used");if(this._kdf=t.kdf,"number"==typeof t.aead)throw new i("AeadId cannot be used");this._aead=t.aead,this._suiteId=new Uint8Array(ft),this._suiteId.set(A(this._kem.id,2),4),this._suiteId.set(A(this._kdf.id,2),6),this._suiteId.set(A(this._aead.id,2),8),this._kdf.init(this._suiteId)}get kem(){return this._kem}get kdf(){return this._kdf}get aead(){return this._aead}async createSenderContext(t){this._validateInputLength(t),await this._setup();const e=await this._kem.encap(t);let r;return r=void 0!==t.psk?void 0!==t.senderKey?3:1:void 0!==t.senderKey?2:0,await this._keyScheduleS(r,e.sharedSecret,e.enc,t)}async createRecipientContext(t){this._validateInputLength(t),await this._setup();const e=await this._kem.decap(t);let r;return r=void 0!==t.psk?void 0!==t.senderPublicKey?3:1:void 0!==t.senderPublicKey?2:0,await this._keyScheduleR(r,e,t)}async seal(t,e,r=v.buffer){const n=await this.createSenderContext(t);return{ct:await n.seal(e,r),enc:n.enc}}async open(t,e,r=v.buffer){const n=await this.createRecipientContext(t);return await n.open(e,r)}async _keySchedule(t,e,r){const n=void 0===r.psk?v:new Uint8Array(r.psk.id),i=await this._kdf.labeledExtract(v.buffer,ct,n),s=void 0===r.info?v:new Uint8Array(r.info),o=await this._kdf.labeledExtract(v.buffer,ut,s),a=new Uint8Array(1+i.byteLength+o.byteLength);a.set(new Uint8Array([t]),0),a.set(new Uint8Array(i),1),a.set(new Uint8Array(o),1+i.byteLength);const u=void 0===r.psk?v:new Uint8Array(r.psk.key),h=this._kdf.buildLabeledIkm(lt,u).buffer,c=this._kdf.buildLabeledInfo(at,a,this._kdf.hashSize).buffer,l=await this._kdf.extractAndExpand(e,h,c,this._kdf.hashSize);if(65535===this._aead.id)return{aead:this._aead,exporterSecret:l};const f=this._kdf.buildLabeledInfo(ht,a,this._aead.keySize).buffer,d=await this._kdf.extractAndExpand(e,h,f,this._aead.keySize),p=this._kdf.buildLabeledInfo(ot,a,this._aead.nonceSize).buffer,y=await this._kdf.extractAndExpand(e,h,p,this._aead.nonceSize);return{aead:this._aead,exporterSecret:l,key:d,baseNonce:new Uint8Array(y),seq:0}}async _keyScheduleS(t,e,r,n){const i=await this._keySchedule(t,e,n);return void 0===i.key?new Y(this._api,this._kdf,i.exporterSecret,r):new st(this._api,this._kdf,i,r)}async _keyScheduleR(t,e,r){const n=await this._keySchedule(t,e,r);return void 0===n.key?new G(this._api,this._kdf,n.exporterSecret):new rt(this._api,this._kdf,n)}_validateInputLength(t){if(void 0!==t.info&&t.info.byteLength>65536)throw new i("Too long info");if(void 0!==t.psk){if(t.psk.key.byteLength<32)throw new i("PSK must have at least 32 bytes");if(t.psk.key.byteLength>w)throw new i("Too long psk.key");if(t.psk.id.byteLength>w)throw new i("Too long psk.id")}}}class pt extends S{constructor(){const t=new H;super(16,new C(16,t),t),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:65}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:65}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:32})}}class yt extends dt{}class gt extends pt{}class mt extends H{}new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),new Uint8Array([48,70,2,1,0,48,5,6,3,43,101,111,4,58,4,56])},281:(t,e)=>{"use strict";function r(t,e,r){return e<=t&&t<=r}function n(t){if(void 0===t)return{};if(t===Object(t))return t;throw TypeError("Could not convert argument to dictionary")}function i(t){this.tokens=[].slice.call(t)}i.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():-1},prepend:function(t){if(Array.isArray(t))for(var e=t;e.length;)this.tokens.unshift(e.pop());else this.tokens.unshift(t)},push:function(t){if(Array.isArray(t))for(var e=t;e.length;)this.tokens.push(e.shift());else this.tokens.push(t)}};var s=-1;function o(t,e){if(t)throw TypeError("Decoder error");return e||65533}var a="utf-8";function u(t,e){if(!(this instanceof u))return new u(t,e);if((t=void 0!==t?String(t).toLowerCase():a)!==a)throw new Error("Encoding not supported. Only utf-8 is supported");e=n(e),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=Boolean(e.fatal),this._ignoreBOM=Boolean(e.ignoreBOM),Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}function h(t,e){if(!(this instanceof h))return new h(t,e);if((t=void 0!==t?String(t).toLowerCase():a)!==a)throw new Error("Encoding not supported. Only utf-8 is supported");e=n(e),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(e.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function c(t){var e=t.fatal,n=0,i=0,a=0,u=128,h=191;this.handler=function(t,c){if(-1===c&&0!==a)return a=0,o(e);if(-1===c)return s;if(0===a){if(r(c,0,127))return c;if(r(c,194,223))a=1,n=c-192;else if(r(c,224,239))224===c&&(u=160),237===c&&(h=159),a=2,n=c-224;else{if(!r(c,240,244))return o(e);240===c&&(u=144),244===c&&(h=143),a=3,n=c-240}return n<<=6*a,null}if(!r(c,u,h))return n=a=i=0,u=128,h=191,t.prepend(c),o(e);if(u=128,h=191,n+=c-128<<6*(a-(i+=1)),i!==a)return null;var l=n;return n=a=i=0,l}}function l(t){t.fatal,this.handler=function(t,e){if(-1===e)return s;if(r(e,0,127))return e;var n,i;r(e,128,2047)?(n=1,i=192):r(e,2048,65535)?(n=2,i=224):r(e,65536,1114111)&&(n=3,i=240);for(var o=[(e>>6*n)+i];n>0;){var a=e>>6*(n-1);o.push(128|63&a),n-=1}return o}}u.prototype={decode:function(t,e){var r;r="object"==typeof t&&t instanceof ArrayBuffer?new Uint8Array(t):"object"==typeof t&&"buffer"in t&&t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(0),e=n(e),this._streaming||(this._decoder=new c({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(e.stream);for(var o,a=new i(r),u=[];!a.endOfStream()&&(o=this._decoder.handler(a,a.read()))!==s;)null!==o&&(Array.isArray(o)?u.push.apply(u,o):u.push(o));if(!this._streaming){do{if((o=this._decoder.handler(a,a.read()))===s)break;null!==o&&(Array.isArray(o)?u.push.apply(u,o):u.push(o))}while(!a.endOfStream());this._decoder=null}return u.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===u[0]?(this._BOMseen=!0,u.shift()):this._BOMseen=!0)),function(t){for(var e="",r=0;r>10),56320+(1023&n)))}return e}(u)}},h.prototype={encode:function(t,e){t=t?String(t):"",e=n(e),this._streaming||(this._encoder=new l(this._options)),this._streaming=Boolean(e.stream);for(var r,o=[],a=new i(function(t){for(var e=String(t),r=e.length,n=0,i=[];n57343)i.push(s);else if(56320<=s&&s<=57343)i.push(65533);else if(55296<=s&&s<=56319)if(n===r-1)i.push(65533);else{var o=t.charCodeAt(n+1);if(56320<=o&&o<=57343){var a=1023&s,u=1023&o;i.push(65536+(a<<10)+u),n+=1}else i.push(65533)}n+=1}return i}(t));!a.endOfStream()&&(r=this._encoder.handler(a,a.read()))!==s;)Array.isArray(r)?o.push.apply(o,r):o.push(r);if(!this._streaming){for(;(r=this._encoder.handler(a,a.read()))!==s;)Array.isArray(r)?o.push.apply(o,r):o.push(r);this._encoder=null}return new Uint8Array(o)}},e.TextEncoder=h,e.TextDecoder=u},287:(t,e,r)=>{"use strict";const n=r(526),i=r(251),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=u,e.SlowBuffer=function(t){return+t!=t&&(t=0),u.alloc(+t)},e.INSPECT_MAX_BYTES=50;const o=2147483647;function a(t){if(t>o)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,u.prototype),e}function u(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return l(t)}return h(t,e,r)}function h(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!u.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|y(t,e);let n=a(r);const i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(G(t,Uint8Array)){const e=new Uint8Array(t);return d(e.buffer,e.byteOffset,e.byteLength)}return f(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(G(t,ArrayBuffer)||t&&G(t.buffer,ArrayBuffer))return d(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(G(t,SharedArrayBuffer)||t&&G(t.buffer,SharedArrayBuffer)))return d(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return u.from(n,e,r);const i=function(t){if(u.isBuffer(t)){const e=0|p(t.length),r=a(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||Y(t.length)?a(0):f(t):"Buffer"===t.type&&Array.isArray(t.data)?f(t.data):void 0}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return u.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function c(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function l(t){return c(t),a(t<0?0:0|p(t))}function f(t){const e=t.length<0?0:0|p(t.length),r=a(e);for(let n=0;n=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|t}function y(t,e){if(u.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||G(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return $(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return V(t).length;default:if(i)return n?-1:$(t).length;e=(""+e).toLowerCase(),i=!0}}function g(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return P(this,e,r);case"utf8":case"utf-8":return I(this,e,r);case"ascii":return M(this,e,r);case"latin1":case"binary":return _(this,e,r);case"base64":return B(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function m(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function b(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Y(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=u.from(e,n)),u.isBuffer(e))return 0===e.length?-1:w(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):w(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function w(t,e,r,n,i){let s,o=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,a/=2,u/=2,r/=2}function h(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){let n=-1;for(s=r;sa&&(r=a-u),s=r;s>=0;s--){let r=!0;for(let n=0;ni&&(n=i):n=i;const s=e.length;let o;for(n>s/2&&(n=s/2),o=0;o>8,i=r%256,s.push(i),s.push(n);return s}(e,t.length-r),t,r,n)}function B(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function I(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+o<=r){let r,n,a,u;switch(o){case 1:e<128&&(s=e);break;case 2:r=t[i+1],128==(192&r)&&(u=(31&e)<<6|63&r,u>127&&(s=u));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(u=(15&e)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:r=t[i+1],n=t[i+2],a=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(u=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&a,u>65535&&u<1114112&&(s=u))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(t){const e=t.length;if(e<=S)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn.length?(u.isBuffer(e)||(e=u.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!u.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},u.byteLength=y,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;er&&(t+=" ... "),""},s&&(u.prototype[s]=u.prototype.inspect),u.prototype.compare=function(t,e,r,n,i){if(G(t,Uint8Array)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let s=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(e>>>=0);const a=Math.min(s,o),h=this.slice(n,i),c=t.slice(e,r);for(let t=0;t>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return v(this,t,e,r);case"utf8":case"utf-8":return k(this,t,e,r);case"ascii":case"latin1":case"binary":return x(this,t,e,r);case"base64":return A(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const S=4096;function M(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;in)&&(r=n);let i="";for(let n=e;nr)throw new RangeError("Trying to access beyond buffer length")}function L(t,e,r,n,i,s){if(!u.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function K(t,e,r,n,i){D(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,r}function z(t,e,r,n,i){D(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s>>=8,t[r+6]=s,s>>=8,t[r+5]=s,s>>=8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o>>=8,t[r+2]=o,o>>=8,t[r+1]=o,o>>=8,t[r]=o,r+8}function R(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function T(t,e,r,n,s){return e=+e,r>>>=0,s||R(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function C(t,e,r,n,s){return e=+e,r>>>=0,s||R(t,0,r,8),i.write(t,e,r,n,52,8),r+8}u.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||O(t,e,this.length);let n=this[t],i=1,s=0;for(;++s>>=0,e>>>=0,r||O(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},u.prototype.readUint8=u.prototype.readUInt8=function(t,e){return t>>>=0,e||O(t,1,this.length),this[t]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(t,e){return t>>>=0,e||O(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(t,e){return t>>>=0,e||O(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(t,e){return t>>>=0,e||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(t,e){return t>>>=0,e||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readBigUInt64LE=J(function(t){W(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<>>=0,e>>>=0,r||O(t,e,this.length);let n=this[t],i=1,s=0;for(;++s=i&&(n-=Math.pow(2,8*e)),n},u.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||O(t,e,this.length);let n=e,i=1,s=this[t+--n];for(;n>0&&(i*=256);)s+=this[t+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*e)),s},u.prototype.readInt8=function(t,e){return t>>>=0,e||O(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u.prototype.readInt16LE=function(t,e){t>>>=0,e||O(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(t,e){t>>>=0,e||O(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(t,e){return t>>>=0,e||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,e){return t>>>=0,e||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readBigInt64LE=J(function(t){W(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<>>=0,e||O(t,4,this.length),i.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,e){return t>>>=0,e||O(t,4,this.length),i.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,e){return t>>>=0,e||O(t,8,this.length),i.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,e){return t>>>=0,e||O(t,8,this.length),i.read(this,t,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||L(this,t,e,r,Math.pow(2,8*r)-1,0);let i=1,s=0;for(this[e]=255&t;++s>>=0,r>>>=0,n||L(this,t,e,r,Math.pow(2,8*r)-1,0);let i=r-1,s=1;for(this[e+i]=255&t;--i>=0&&(s*=256);)this[e+i]=t/s&255;return e+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,1,255,0),this[e]=255&t,e+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},u.prototype.writeBigUInt64LE=J(function(t,e=0){return K(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=J(function(t,e=0){return z(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);L(this,t,e,r,n-1,-n)}let i=0,s=1,o=0;for(this[e]=255&t;++i>>=0,!n){const n=Math.pow(2,8*r-1);L(this,t,e,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[e+i]=255&t;--i>=0&&(s*=256);)t<0&&0===o&&0!==this[e+i+1]&&(o=1),this[e+i]=(t/s|0)-o&255;return e+r},u.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},u.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},u.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},u.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},u.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||L(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},u.prototype.writeBigInt64LE=J(function(t,e=0){return K(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=J(function(t,e=0){return z(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeFloatLE=function(t,e,r){return T(this,t,e,!0,r)},u.prototype.writeFloatBE=function(t,e,r){return T(this,t,e,!1,r)},u.prototype.writeDoubleLE=function(t,e,r){return C(this,t,e,!0,r)},u.prototype.writeDoubleBE=function(t,e,r){return C(this,t,e,!1,r)},u.prototype.copy=function(t,e,r,n){if(!u.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function D(t,e,r,n,i,s){if(t>r||t3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new N.ERR_OUT_OF_RANGE("value",i,t)}!function(t,e,r){W(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||F(e,t.length-(r+1))}(n,i,s)}function W(t,e){if("number"!=typeof t)throw new N.ERR_INVALID_ARG_TYPE(e,"number",t)}function F(t,e,r){if(Math.floor(t)!==t)throw W(t,r),new N.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new N.ERR_BUFFER_OUT_OF_BOUNDS;throw new N.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}j("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError),j("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);const q=/[^+/0-9A-Za-z-_]/g;function $(t,e){let r;e=e||1/0;const n=t.length;let i=null;const s=[];for(let o=0;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function V(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Z(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function G(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function Y(t){return t!=t}const X=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function J(t){return"undefined"==typeof BigInt?Q:t}function Q(){throw new Error("BigInt not supported")}},289:(t,e,r)=>{"use strict";const n=r(341).v4;t.exports=function(t,e,r,i){if("string"!=typeof t)throw new TypeError(t+" must be a string");const s="number"==typeof(i=i||{}).version?i.version:2;if(1!==s&&2!==s)throw new TypeError(s+" must be 1 or 2");const o={method:t};if(2===s&&(o.jsonrpc="2.0"),e){if("object"!=typeof e&&!Array.isArray(e))throw new TypeError(e+" must be an object, array or omitted");o.params=e}if(void 0===r){const t="function"==typeof i.generator?i.generator:function(){return n()};o.id=t(o,i)}else 2===s&&null===r?i.notificationIdNull&&(o.id=null):o.id=r;return o}},341:(t,e,r)=>{"use strict";var n;r.d(e,{v4:()=>c});var i=new Uint8Array(16);function s(){if(!n&&!(n="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 n(i)}const o=/^(?:[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;for(var a=[],u=0;u<256;++u)a.push((u+256).toString(16).substr(1));const h=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(a[t[e+0]]+a[t[e+1]]+a[t[e+2]]+a[t[e+3]]+"-"+a[t[e+4]]+a[t[e+5]]+"-"+a[t[e+6]]+a[t[e+7]]+"-"+a[t[e+8]]+a[t[e+9]]+"-"+a[t[e+10]]+a[t[e+11]]+a[t[e+12]]+a[t[e+13]]+a[t[e+14]]+a[t[e+15]]).toLowerCase();if(!function(t){return"string"==typeof t&&o.test(t)}(r))throw TypeError("Stringified UUID is invalid");return r},c=function(t,e,r){var n=(t=t||{}).random||(t.rng||s)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(var i=0;i<16;++i)e[r+i]=n[i];return e}return h(n)}},364:(t,e,r)=>{"use strict";var n=r(861).Buffer;t.exports=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,c=new Uint8Array(o);r255)return;var f=e[l];if(255===f)return;for(var d=0,p=o-1;(0!==f||d>>0,c[p]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");s=d,r++}for(var y=o-s;y!==o&&0===c[y];)y++;var g=n.allocUnsafe(i+(o-y));g.fill(0,0,i);for(var m=i;y!==o;)g[m++]=c[y++];return g}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=n.from(e)),!n.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,i=0,s=0,o=e.length;s!==o&&0===e[s];)s++,r++;for(var h=(o-s)*c+1>>>0,l=new Uint8Array(h);s!==o;){for(var f=e[s],d=0,p=h-1;(0!==f||d>>0,l[p]=f%a>>>0,f=f/a>>>0;if(0!==f)throw new Error("Non-zero carry");i=d,s++}for(var y=h-i;y!==h&&0===l[y];)y++;for(var g=u.repeat(r);y=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+t)}function u(t,e,r){var n=a(t,r);return r-1>=e&&(n|=a(t,r-1)<<4),n}function h(t,e,r,i){for(var s=0,o=0,a=Math.min(t.length,r),u=e;u=49?h-49+10:h>=17?h-17+10:h,n(h>=0&&o0?t:e},s.min=function(t,e){return t.cmp(e)<0?t:e},s.prototype._init=function(t,e,r){if("number"==typeof t)return this._initNumber(t,e,r);if("object"==typeof t)return this._initArray(t,e,r);"hex"===e&&(e=16),n(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)o=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[s]|=o<>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);else if("le"===r)for(i=0,s=0;i>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);return this._strip()},s.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;this._strip()},s.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var s=t.length-r,o=s%n,a=Math.min(s,s-o)+r,u=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=l}catch(t){s.prototype.inspect=l}else s.prototype.inspect=l;function l(){return(this.red?""}var f=["","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"],d=[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],p=[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];function y(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],s=0|e.words[0],o=i*s,a=67108863&o,u=o/67108864|0;r.words[0]=a;for(var h=1;h>>26,l=67108863&u,f=Math.min(h,e.length-1),d=Math.max(0,h-t.length+1);d<=f;d++){var p=h-d|0;c+=(o=(i=0|t.words[p])*(s=0|e.words[d])+l)/67108864|0,l=67108863&o}r.words[h]=0|l,u=0|c}return 0!==u?r.words[h]=0|u:r.length--,r._strip()}s.prototype.toString=function(t,e){var r;if(e=0|e||1,16===(t=t||10)||"hex"===t){r="";for(var i=0,s=0,o=0;o>>24-i&16777215,(i+=2)>=26&&(i-=26,o--),r=0!==s||o!==this.length-1?f[6-u.length]+u+r:u+r}for(0!==s&&(r=s.toString(16)+r);r.length%e!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(t===(0|t)&&t>=2&&t<=36){var h=d[t],c=p[t];r="";var l=this.clone();for(l.negative=0;!l.isZero();){var y=l.modrn(c).toString(t);r=(l=l.idivn(c)).isZero()?y+r:f[h-y.length]+y+r}for(this.isZero()&&(r="0"+r);r.length%e!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(t,e){return this.toArrayLike(o,t,e)}),s.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},s.prototype.toArrayLike=function(t,e,r){this._strip();var i=this.byteLength(),s=r||Math.max(1,i);n(i<=s,"byte array longer than desired length"),n(s>0,"Requested array length <= 0");var o=function(t,e){return t.allocUnsafe?t.allocUnsafe(e):new t(e)}(t,s);return this["_toArrayLike"+("le"===e?"LE":"BE")](o,i),o},s.prototype._toArrayLikeLE=function(t,e){for(var r=0,n=0,i=0,s=0;i>8&255),r>16&255),6===s?(r>24&255),n=0,s=0):(n=o>>>24,s+=2)}if(r=0&&(t[r--]=o>>8&255),r>=0&&(t[r--]=o>>16&255),6===s?(r>=0&&(t[r--]=o>>24&255),n=0,s=0):(n=o>>>24,s+=2)}if(r>=0)for(t[r--]=n;r>=0;)t[r--]=0},Math.clz32?s.prototype._countBits=function(t){return 32-Math.clz32(t)}:s.prototype._countBits=function(t){var e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},s.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 8191&e||(r+=13,e>>>=13),127&e||(r+=7,e>>>=7),15&e||(r+=4,e>>>=4),3&e||(r+=2,e>>>=2),1&e||r++,r},s.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},s.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},s.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},s.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},s.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},s.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},s.prototype.inotn=function(t){n("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),r=t%26;this._expand(e),r>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this._strip()},s.prototype.notn=function(t){return this.clone().inotn(t)},s.prototype.setn=function(t,e){n("number"==typeof t&&t>=0);var r=t/26|0,i=t%26;return this._expand(r+1),this.words[r]=e?this.words[r]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,s=0;s>>26;for(;0!==i&&s>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;st.length?this.clone().iadd(t):t.clone().iadd(this)},s.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var s=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==s&&o>26,this.words[o]=67108863&e;if(0===s&&o>>13,d=0|o[1],p=8191&d,y=d>>>13,g=0|o[2],m=8191&g,b=g>>>13,w=0|o[3],v=8191&w,k=w>>>13,x=0|o[4],A=8191&x,E=x>>>13,B=0|o[5],I=8191&B,S=B>>>13,M=0|o[6],_=8191&M,P=M>>>13,U=0|o[7],O=8191&U,L=U>>>13,K=0|o[8],z=8191&K,R=K>>>13,T=0|o[9],C=8191&T,N=T>>>13,j=0|a[0],H=8191&j,D=j>>>13,W=0|a[1],F=8191&W,q=W>>>13,$=0|a[2],V=8191&$,Z=$>>>13,G=0|a[3],Y=8191&G,X=G>>>13,J=0|a[4],Q=8191&J,tt=J>>>13,et=0|a[5],rt=8191&et,nt=et>>>13,it=0|a[6],st=8191&it,ot=it>>>13,at=0|a[7],ut=8191&at,ht=at>>>13,ct=0|a[8],lt=8191&ct,ft=ct>>>13,dt=0|a[9],pt=8191&dt,yt=dt>>>13;r.negative=t.negative^e.negative,r.length=19;var gt=(h+(n=Math.imul(l,H))|0)+((8191&(i=(i=Math.imul(l,D))+Math.imul(f,H)|0))<<13)|0;h=((s=Math.imul(f,D))+(i>>>13)|0)+(gt>>>26)|0,gt&=67108863,n=Math.imul(p,H),i=(i=Math.imul(p,D))+Math.imul(y,H)|0,s=Math.imul(y,D);var mt=(h+(n=n+Math.imul(l,F)|0)|0)+((8191&(i=(i=i+Math.imul(l,q)|0)+Math.imul(f,F)|0))<<13)|0;h=((s=s+Math.imul(f,q)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(m,H),i=(i=Math.imul(m,D))+Math.imul(b,H)|0,s=Math.imul(b,D),n=n+Math.imul(p,F)|0,i=(i=i+Math.imul(p,q)|0)+Math.imul(y,F)|0,s=s+Math.imul(y,q)|0;var bt=(h+(n=n+Math.imul(l,V)|0)|0)+((8191&(i=(i=i+Math.imul(l,Z)|0)+Math.imul(f,V)|0))<<13)|0;h=((s=s+Math.imul(f,Z)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(v,H),i=(i=Math.imul(v,D))+Math.imul(k,H)|0,s=Math.imul(k,D),n=n+Math.imul(m,F)|0,i=(i=i+Math.imul(m,q)|0)+Math.imul(b,F)|0,s=s+Math.imul(b,q)|0,n=n+Math.imul(p,V)|0,i=(i=i+Math.imul(p,Z)|0)+Math.imul(y,V)|0,s=s+Math.imul(y,Z)|0;var wt=(h+(n=n+Math.imul(l,Y)|0)|0)+((8191&(i=(i=i+Math.imul(l,X)|0)+Math.imul(f,Y)|0))<<13)|0;h=((s=s+Math.imul(f,X)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(A,H),i=(i=Math.imul(A,D))+Math.imul(E,H)|0,s=Math.imul(E,D),n=n+Math.imul(v,F)|0,i=(i=i+Math.imul(v,q)|0)+Math.imul(k,F)|0,s=s+Math.imul(k,q)|0,n=n+Math.imul(m,V)|0,i=(i=i+Math.imul(m,Z)|0)+Math.imul(b,V)|0,s=s+Math.imul(b,Z)|0,n=n+Math.imul(p,Y)|0,i=(i=i+Math.imul(p,X)|0)+Math.imul(y,Y)|0,s=s+Math.imul(y,X)|0;var vt=(h+(n=n+Math.imul(l,Q)|0)|0)+((8191&(i=(i=i+Math.imul(l,tt)|0)+Math.imul(f,Q)|0))<<13)|0;h=((s=s+Math.imul(f,tt)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(I,H),i=(i=Math.imul(I,D))+Math.imul(S,H)|0,s=Math.imul(S,D),n=n+Math.imul(A,F)|0,i=(i=i+Math.imul(A,q)|0)+Math.imul(E,F)|0,s=s+Math.imul(E,q)|0,n=n+Math.imul(v,V)|0,i=(i=i+Math.imul(v,Z)|0)+Math.imul(k,V)|0,s=s+Math.imul(k,Z)|0,n=n+Math.imul(m,Y)|0,i=(i=i+Math.imul(m,X)|0)+Math.imul(b,Y)|0,s=s+Math.imul(b,X)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,tt)|0)+Math.imul(y,Q)|0,s=s+Math.imul(y,tt)|0;var kt=(h+(n=n+Math.imul(l,rt)|0)|0)+((8191&(i=(i=i+Math.imul(l,nt)|0)+Math.imul(f,rt)|0))<<13)|0;h=((s=s+Math.imul(f,nt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(_,H),i=(i=Math.imul(_,D))+Math.imul(P,H)|0,s=Math.imul(P,D),n=n+Math.imul(I,F)|0,i=(i=i+Math.imul(I,q)|0)+Math.imul(S,F)|0,s=s+Math.imul(S,q)|0,n=n+Math.imul(A,V)|0,i=(i=i+Math.imul(A,Z)|0)+Math.imul(E,V)|0,s=s+Math.imul(E,Z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,X)|0)+Math.imul(k,Y)|0,s=s+Math.imul(k,X)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,tt)|0)+Math.imul(b,Q)|0,s=s+Math.imul(b,tt)|0,n=n+Math.imul(p,rt)|0,i=(i=i+Math.imul(p,nt)|0)+Math.imul(y,rt)|0,s=s+Math.imul(y,nt)|0;var xt=(h+(n=n+Math.imul(l,st)|0)|0)+((8191&(i=(i=i+Math.imul(l,ot)|0)+Math.imul(f,st)|0))<<13)|0;h=((s=s+Math.imul(f,ot)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(O,H),i=(i=Math.imul(O,D))+Math.imul(L,H)|0,s=Math.imul(L,D),n=n+Math.imul(_,F)|0,i=(i=i+Math.imul(_,q)|0)+Math.imul(P,F)|0,s=s+Math.imul(P,q)|0,n=n+Math.imul(I,V)|0,i=(i=i+Math.imul(I,Z)|0)+Math.imul(S,V)|0,s=s+Math.imul(S,Z)|0,n=n+Math.imul(A,Y)|0,i=(i=i+Math.imul(A,X)|0)+Math.imul(E,Y)|0,s=s+Math.imul(E,X)|0,n=n+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(k,Q)|0,s=s+Math.imul(k,tt)|0,n=n+Math.imul(m,rt)|0,i=(i=i+Math.imul(m,nt)|0)+Math.imul(b,rt)|0,s=s+Math.imul(b,nt)|0,n=n+Math.imul(p,st)|0,i=(i=i+Math.imul(p,ot)|0)+Math.imul(y,st)|0,s=s+Math.imul(y,ot)|0;var At=(h+(n=n+Math.imul(l,ut)|0)|0)+((8191&(i=(i=i+Math.imul(l,ht)|0)+Math.imul(f,ut)|0))<<13)|0;h=((s=s+Math.imul(f,ht)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(z,H),i=(i=Math.imul(z,D))+Math.imul(R,H)|0,s=Math.imul(R,D),n=n+Math.imul(O,F)|0,i=(i=i+Math.imul(O,q)|0)+Math.imul(L,F)|0,s=s+Math.imul(L,q)|0,n=n+Math.imul(_,V)|0,i=(i=i+Math.imul(_,Z)|0)+Math.imul(P,V)|0,s=s+Math.imul(P,Z)|0,n=n+Math.imul(I,Y)|0,i=(i=i+Math.imul(I,X)|0)+Math.imul(S,Y)|0,s=s+Math.imul(S,X)|0,n=n+Math.imul(A,Q)|0,i=(i=i+Math.imul(A,tt)|0)+Math.imul(E,Q)|0,s=s+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(k,rt)|0,s=s+Math.imul(k,nt)|0,n=n+Math.imul(m,st)|0,i=(i=i+Math.imul(m,ot)|0)+Math.imul(b,st)|0,s=s+Math.imul(b,ot)|0,n=n+Math.imul(p,ut)|0,i=(i=i+Math.imul(p,ht)|0)+Math.imul(y,ut)|0,s=s+Math.imul(y,ht)|0;var Et=(h+(n=n+Math.imul(l,lt)|0)|0)+((8191&(i=(i=i+Math.imul(l,ft)|0)+Math.imul(f,lt)|0))<<13)|0;h=((s=s+Math.imul(f,ft)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(C,H),i=(i=Math.imul(C,D))+Math.imul(N,H)|0,s=Math.imul(N,D),n=n+Math.imul(z,F)|0,i=(i=i+Math.imul(z,q)|0)+Math.imul(R,F)|0,s=s+Math.imul(R,q)|0,n=n+Math.imul(O,V)|0,i=(i=i+Math.imul(O,Z)|0)+Math.imul(L,V)|0,s=s+Math.imul(L,Z)|0,n=n+Math.imul(_,Y)|0,i=(i=i+Math.imul(_,X)|0)+Math.imul(P,Y)|0,s=s+Math.imul(P,X)|0,n=n+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,tt)|0)+Math.imul(S,Q)|0,s=s+Math.imul(S,tt)|0,n=n+Math.imul(A,rt)|0,i=(i=i+Math.imul(A,nt)|0)+Math.imul(E,rt)|0,s=s+Math.imul(E,nt)|0,n=n+Math.imul(v,st)|0,i=(i=i+Math.imul(v,ot)|0)+Math.imul(k,st)|0,s=s+Math.imul(k,ot)|0,n=n+Math.imul(m,ut)|0,i=(i=i+Math.imul(m,ht)|0)+Math.imul(b,ut)|0,s=s+Math.imul(b,ht)|0,n=n+Math.imul(p,lt)|0,i=(i=i+Math.imul(p,ft)|0)+Math.imul(y,lt)|0,s=s+Math.imul(y,ft)|0;var Bt=(h+(n=n+Math.imul(l,pt)|0)|0)+((8191&(i=(i=i+Math.imul(l,yt)|0)+Math.imul(f,pt)|0))<<13)|0;h=((s=s+Math.imul(f,yt)|0)+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,n=Math.imul(C,F),i=(i=Math.imul(C,q))+Math.imul(N,F)|0,s=Math.imul(N,q),n=n+Math.imul(z,V)|0,i=(i=i+Math.imul(z,Z)|0)+Math.imul(R,V)|0,s=s+Math.imul(R,Z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,X)|0)+Math.imul(L,Y)|0,s=s+Math.imul(L,X)|0,n=n+Math.imul(_,Q)|0,i=(i=i+Math.imul(_,tt)|0)+Math.imul(P,Q)|0,s=s+Math.imul(P,tt)|0,n=n+Math.imul(I,rt)|0,i=(i=i+Math.imul(I,nt)|0)+Math.imul(S,rt)|0,s=s+Math.imul(S,nt)|0,n=n+Math.imul(A,st)|0,i=(i=i+Math.imul(A,ot)|0)+Math.imul(E,st)|0,s=s+Math.imul(E,ot)|0,n=n+Math.imul(v,ut)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(k,ut)|0,s=s+Math.imul(k,ht)|0,n=n+Math.imul(m,lt)|0,i=(i=i+Math.imul(m,ft)|0)+Math.imul(b,lt)|0,s=s+Math.imul(b,ft)|0;var It=(h+(n=n+Math.imul(p,pt)|0)|0)+((8191&(i=(i=i+Math.imul(p,yt)|0)+Math.imul(y,pt)|0))<<13)|0;h=((s=s+Math.imul(y,yt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(C,V),i=(i=Math.imul(C,Z))+Math.imul(N,V)|0,s=Math.imul(N,Z),n=n+Math.imul(z,Y)|0,i=(i=i+Math.imul(z,X)|0)+Math.imul(R,Y)|0,s=s+Math.imul(R,X)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(L,Q)|0,s=s+Math.imul(L,tt)|0,n=n+Math.imul(_,rt)|0,i=(i=i+Math.imul(_,nt)|0)+Math.imul(P,rt)|0,s=s+Math.imul(P,nt)|0,n=n+Math.imul(I,st)|0,i=(i=i+Math.imul(I,ot)|0)+Math.imul(S,st)|0,s=s+Math.imul(S,ot)|0,n=n+Math.imul(A,ut)|0,i=(i=i+Math.imul(A,ht)|0)+Math.imul(E,ut)|0,s=s+Math.imul(E,ht)|0,n=n+Math.imul(v,lt)|0,i=(i=i+Math.imul(v,ft)|0)+Math.imul(k,lt)|0,s=s+Math.imul(k,ft)|0;var St=(h+(n=n+Math.imul(m,pt)|0)|0)+((8191&(i=(i=i+Math.imul(m,yt)|0)+Math.imul(b,pt)|0))<<13)|0;h=((s=s+Math.imul(b,yt)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(C,Y),i=(i=Math.imul(C,X))+Math.imul(N,Y)|0,s=Math.imul(N,X),n=n+Math.imul(z,Q)|0,i=(i=i+Math.imul(z,tt)|0)+Math.imul(R,Q)|0,s=s+Math.imul(R,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(L,rt)|0,s=s+Math.imul(L,nt)|0,n=n+Math.imul(_,st)|0,i=(i=i+Math.imul(_,ot)|0)+Math.imul(P,st)|0,s=s+Math.imul(P,ot)|0,n=n+Math.imul(I,ut)|0,i=(i=i+Math.imul(I,ht)|0)+Math.imul(S,ut)|0,s=s+Math.imul(S,ht)|0,n=n+Math.imul(A,lt)|0,i=(i=i+Math.imul(A,ft)|0)+Math.imul(E,lt)|0,s=s+Math.imul(E,ft)|0;var Mt=(h+(n=n+Math.imul(v,pt)|0)|0)+((8191&(i=(i=i+Math.imul(v,yt)|0)+Math.imul(k,pt)|0))<<13)|0;h=((s=s+Math.imul(k,yt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(C,Q),i=(i=Math.imul(C,tt))+Math.imul(N,Q)|0,s=Math.imul(N,tt),n=n+Math.imul(z,rt)|0,i=(i=i+Math.imul(z,nt)|0)+Math.imul(R,rt)|0,s=s+Math.imul(R,nt)|0,n=n+Math.imul(O,st)|0,i=(i=i+Math.imul(O,ot)|0)+Math.imul(L,st)|0,s=s+Math.imul(L,ot)|0,n=n+Math.imul(_,ut)|0,i=(i=i+Math.imul(_,ht)|0)+Math.imul(P,ut)|0,s=s+Math.imul(P,ht)|0,n=n+Math.imul(I,lt)|0,i=(i=i+Math.imul(I,ft)|0)+Math.imul(S,lt)|0,s=s+Math.imul(S,ft)|0;var _t=(h+(n=n+Math.imul(A,pt)|0)|0)+((8191&(i=(i=i+Math.imul(A,yt)|0)+Math.imul(E,pt)|0))<<13)|0;h=((s=s+Math.imul(E,yt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(C,rt),i=(i=Math.imul(C,nt))+Math.imul(N,rt)|0,s=Math.imul(N,nt),n=n+Math.imul(z,st)|0,i=(i=i+Math.imul(z,ot)|0)+Math.imul(R,st)|0,s=s+Math.imul(R,ot)|0,n=n+Math.imul(O,ut)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(L,ut)|0,s=s+Math.imul(L,ht)|0,n=n+Math.imul(_,lt)|0,i=(i=i+Math.imul(_,ft)|0)+Math.imul(P,lt)|0,s=s+Math.imul(P,ft)|0;var Pt=(h+(n=n+Math.imul(I,pt)|0)|0)+((8191&(i=(i=i+Math.imul(I,yt)|0)+Math.imul(S,pt)|0))<<13)|0;h=((s=s+Math.imul(S,yt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(C,st),i=(i=Math.imul(C,ot))+Math.imul(N,st)|0,s=Math.imul(N,ot),n=n+Math.imul(z,ut)|0,i=(i=i+Math.imul(z,ht)|0)+Math.imul(R,ut)|0,s=s+Math.imul(R,ht)|0,n=n+Math.imul(O,lt)|0,i=(i=i+Math.imul(O,ft)|0)+Math.imul(L,lt)|0,s=s+Math.imul(L,ft)|0;var Ut=(h+(n=n+Math.imul(_,pt)|0)|0)+((8191&(i=(i=i+Math.imul(_,yt)|0)+Math.imul(P,pt)|0))<<13)|0;h=((s=s+Math.imul(P,yt)|0)+(i>>>13)|0)+(Ut>>>26)|0,Ut&=67108863,n=Math.imul(C,ut),i=(i=Math.imul(C,ht))+Math.imul(N,ut)|0,s=Math.imul(N,ht),n=n+Math.imul(z,lt)|0,i=(i=i+Math.imul(z,ft)|0)+Math.imul(R,lt)|0,s=s+Math.imul(R,ft)|0;var Ot=(h+(n=n+Math.imul(O,pt)|0)|0)+((8191&(i=(i=i+Math.imul(O,yt)|0)+Math.imul(L,pt)|0))<<13)|0;h=((s=s+Math.imul(L,yt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(C,lt),i=(i=Math.imul(C,ft))+Math.imul(N,lt)|0,s=Math.imul(N,ft);var Lt=(h+(n=n+Math.imul(z,pt)|0)|0)+((8191&(i=(i=i+Math.imul(z,yt)|0)+Math.imul(R,pt)|0))<<13)|0;h=((s=s+Math.imul(R,yt)|0)+(i>>>13)|0)+(Lt>>>26)|0,Lt&=67108863;var Kt=(h+(n=Math.imul(C,pt))|0)+((8191&(i=(i=Math.imul(C,yt))+Math.imul(N,pt)|0))<<13)|0;return h=((s=Math.imul(N,yt))+(i>>>13)|0)+(Kt>>>26)|0,Kt&=67108863,u[0]=gt,u[1]=mt,u[2]=bt,u[3]=wt,u[4]=vt,u[5]=kt,u[6]=xt,u[7]=At,u[8]=Et,u[9]=Bt,u[10]=It,u[11]=St,u[12]=Mt,u[13]=_t,u[14]=Pt,u[15]=Ut,u[16]=Ot,u[17]=Lt,u[18]=Kt,0!==h&&(u[19]=h,r.length++),r};function m(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,s=0;s>>26)|0)>>>26,o&=67108863}r.words[s]=a,n=o,o=i}return 0!==n?r.words[s]=n:r.length--,r._strip()}function b(t,e,r){return m(t,e,r)}function w(t,e){this.x=t,this.y=e}Math.imul||(g=y),s.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?g(this,t,e):r<63?y(this,t,e):r<1024?m(this,t,e):b(this,t,e)},w.prototype.makeRBT=function(t){for(var e=new Array(t),r=s.prototype._countBits(t)-1,n=0;n>=1;return n},w.prototype.permute=function(t,e,r,n,i,s){for(var o=0;o>>=1)i++;return 1<>>=13,r[2*o+1]=8191&s,s>>>=13;for(o=2*e;o>=26,r+=s/67108864|0,r+=o>>>26,this.words[i]=67108863&o}return 0!==r&&(this.words[i]=r,this.length++),this.length=0===t?1:this.length,e?this.ineg():this},s.prototype.muln=function(t){return this.clone().imuln(t)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i&1}return e}(t);if(0===e.length)return new s(1);for(var r=this,n=0;n=0);var e,r=t%26,i=(t-r)/26,s=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(e=0;e>>26-r}o&&(this.words[e]=o,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var s=t%26,o=Math.min((t-s)/26,this.length),a=67108863^67108863>>>s<o)for(this.length-=o,h=0;h=0&&(0!==c||h>=i);h--){var l=0|this.words[h];this.words[h]=c<<26-s|l>>>s,c=l&a}return u&&0!==c&&(u.words[u.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(t,e,r){return n(0===this.negative),this.iushrn(t,e,r)},s.prototype.shln=function(t){return this.clone().ishln(t)},s.prototype.ushln=function(t){return this.clone().iushln(t)},s.prototype.shrn=function(t){return this.clone().ishrn(t)},s.prototype.ushrn=function(t){return this.clone().iushrn(t)},s.prototype.testn=function(t){n("number"==typeof t&&t>=0);var e=t%26,r=(t-e)/26,i=1<=0);var e=t%26,r=(t-e)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==e&&r++,this.length=Math.min(r,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},s.prototype.isubn=function(t){if(n("number"==typeof t),n(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(u/67108864|0),this.words[i+r]=67108863&s}for(;i>26,this.words[i+r]=67108863&s;if(0===a)return this._strip();for(n(-1===a),a=0,i=0;i>26,this.words[i]=67108863&s;return this.negative=1,this._strip()},s.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),i=t,o=0|i.words[i.length-1];0!=(r=26-this._countBits(o))&&(i=i.ushln(r),n.iushln(r),o=0|i.words[i.length-1]);var a,u=n.length-i.length;if("mod"!==e){(a=new s(null)).length=u+1,a.words=new Array(a.length);for(var h=0;h=0;l--){var f=67108864*(0|n.words[i.length+l])+(0|n.words[i.length+l-1]);for(f=Math.min(f/o|0,67108863),n._ishlnsubmul(i,f,l);0!==n.negative;)f--,n.negative=0,n._ishlnsubmul(i,1,l),n.isZero()||(n.negative^=1);a&&(a.words[l]=f)}return a&&a._strip(),n._strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:a||null,mod:n}},s.prototype.divmod=function(t,e,r){return n(!t.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===t.negative?(a=this.neg().divmod(t,e),"mod"!==e&&(i=a.div.neg()),"div"!==e&&(o=a.mod.neg(),r&&0!==o.negative&&o.iadd(t)),{div:i,mod:o}):0===this.negative&&0!==t.negative?(a=this.divmod(t.neg(),e),"mod"!==e&&(i=a.div.neg()),{div:i,mod:a.mod}):0!==(this.negative&t.negative)?(a=this.neg().divmod(t.neg(),e),"div"!==e&&(o=a.mod.neg(),r&&0!==o.negative&&o.isub(t)),{div:a.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new s(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new s(this.modrn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new s(this.modrn(t.words[0]))}:this._wordDiv(t,e);var i,o,a},s.prototype.div=function(t){return this.divmod(t,"div",!1).div},s.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},s.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},s.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),s=r.cmp(n);return s<0||1===i&&0===s?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},s.prototype.modrn=function(t){var e=t<0;e&&(t=-t),n(t<=67108863);for(var r=(1<<26)%t,i=0,s=this.length-1;s>=0;s--)i=(r*i+(0|this.words[s]))%t;return e?-i:i},s.prototype.modn=function(t){return this.modrn(t)},s.prototype.idivn=function(t){var e=t<0;e&&(t=-t),n(t<=67108863);for(var r=0,i=this.length-1;i>=0;i--){var s=(0|this.words[i])+67108864*r;this.words[i]=s/t|0,r=s%t}return this._strip(),e?this.ineg():this},s.prototype.divn=function(t){return this.clone().idivn(t)},s.prototype.egcd=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i=new s(1),o=new s(0),a=new s(0),u=new s(1),h=0;e.isEven()&&r.isEven();)e.iushrn(1),r.iushrn(1),++h;for(var c=r.clone(),l=e.clone();!e.isZero();){for(var f=0,d=1;0===(e.words[0]&d)&&f<26;++f,d<<=1);if(f>0)for(e.iushrn(f);f-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(c),o.isub(l)),i.iushrn(1),o.iushrn(1);for(var p=0,y=1;0===(r.words[0]&y)&&p<26;++p,y<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||u.isOdd())&&(a.iadd(c),u.isub(l)),a.iushrn(1),u.iushrn(1);e.cmp(r)>=0?(e.isub(r),i.isub(a),o.isub(u)):(r.isub(e),a.isub(i),u.isub(o))}return{a,b:u,gcd:r.iushln(h)}},s.prototype._invmp=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i,o=new s(1),a=new s(0),u=r.clone();e.cmpn(1)>0&&r.cmpn(1)>0;){for(var h=0,c=1;0===(e.words[0]&c)&&h<26;++h,c<<=1);if(h>0)for(e.iushrn(h);h-- >0;)o.isOdd()&&o.iadd(u),o.iushrn(1);for(var l=0,f=1;0===(r.words[0]&f)&&l<26;++l,f<<=1);if(l>0)for(r.iushrn(l);l-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);e.cmp(r)>=0?(e.isub(r),o.isub(a)):(r.isub(e),a.isub(o))}return(i=0===e.cmpn(1)?o:a).cmpn(0)<0&&i.iadd(t),i},s.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var s=e;e=r,r=s}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},s.prototype.invm=function(t){return this.egcd(t).a.umod(t)},s.prototype.isEven=function(){return!(1&this.words[0])},s.prototype.isOdd=function(){return!(1&~this.words[0])},s.prototype.andln=function(t){return this.words[0]&t},s.prototype.bincn=function(t){n("number"==typeof t);var e=t%26,r=(t-e)/26,i=1<>>26,a&=67108863,this.words[o]=a}return 0!==s&&(this.words[o]=s,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(t){var e,r=t<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)e=1;else{r&&(t=-t),n(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},s.prototype.gtn=function(t){return 1===this.cmpn(t)},s.prototype.gt=function(t){return 1===this.cmp(t)},s.prototype.gten=function(t){return this.cmpn(t)>=0},s.prototype.gte=function(t){return this.cmp(t)>=0},s.prototype.ltn=function(t){return-1===this.cmpn(t)},s.prototype.lt=function(t){return-1===this.cmp(t)},s.prototype.lten=function(t){return this.cmpn(t)<=0},s.prototype.lte=function(t){return this.cmp(t)<=0},s.prototype.eqn=function(t){return 0===this.cmpn(t)},s.prototype.eq=function(t){return 0===this.cmp(t)},s.red=function(t){return new I(t)},s.prototype.toRed=function(t){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(t){return this.red=t,this},s.prototype.forceRed=function(t){return n(!this.red,"Already a number in reduction context"),this._forceRed(t)},s.prototype.redAdd=function(t){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},s.prototype.redIAdd=function(t){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},s.prototype.redSub=function(t){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},s.prototype.redISub=function(t){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},s.prototype.redShl=function(t){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},s.prototype.redMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},s.prototype.redIMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(t){return n(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var v={k256:null,p224:null,p192:null,p25519:null};function k(t,e){this.name=t,this.p=new s(e,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function x(){k.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function A(){k.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function E(){k.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function B(){k.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function I(t){if("string"==typeof t){var e=s._prime(t);this.m=e.p,this.prime=e}else n(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){I.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(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)}k.prototype._tmp=function(){var t=new s(null);return t.words=new Array(Math.ceil(this.n/13)),t},k.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},k.prototype.split=function(t,e){t.iushrn(this.n,0,e)},k.prototype.imulK=function(t){return t.imul(this.k)},i(x,k),x.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,s=o}s>>>=22,t.words[i-10]=s,0===s&&t.length>10?t.length-=10:t.length-=9},x.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},s._prime=function(t){if(v[t])return v[t];var e;if("k256"===t)e=new x;else if("p224"===t)e=new A;else if("p192"===t)e=new E;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new B}return v[t]=e,e},I.prototype._verify1=function(t){n(0===t.negative,"red works only with positives"),n(t.red,"red works only with red numbers")},I.prototype._verify2=function(t,e){n(0===(t.negative|e.negative),"red works only with positives"),n(t.red&&t.red===e.red,"red works only with red numbers")},I.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):(c(t,t.umod(this.m)._forceRed(this)),t)},I.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},I.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},I.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},I.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},I.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},I.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},I.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},I.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},I.prototype.isqr=function(t){return this.imul(t,t.clone())},I.prototype.sqr=function(t){return this.mul(t,t)},I.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(n(e%2==1),3===e){var r=this.m.add(new s(1)).iushrn(2);return this.pow(t,r)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);n(!i.isZero());var a=new s(1).toRed(this),u=a.redNeg(),h=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new s(2*c*c).toRed(this);0!==this.pow(c,h).cmp(u);)c.redIAdd(u);for(var l=this.pow(c,i),f=this.pow(t,i.addn(1).iushrn(1)),d=this.pow(t,i),p=o;0!==d.cmp(a);){for(var y=d,g=0;0!==y.cmp(a);g++)y=y.redSqr();n(g=0;n--){for(var h=e.words[n],c=u-1;c>=0;c--){var l=h>>c&1;i!==r[0]&&(i=this.sqr(i)),0!==l||0!==o?(o<<=1,o|=l,(4===++a||0===n&&0===c)&&(i=this.mul(i,r[o]),a=0,o=0)):a=0}u=26}return i},I.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},I.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},s.mont=function(t){return new S(t)},i(S,I),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new s(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t=r.nmd(t),this)},526:(t,e)=>{"use strict";e.byteLength=function(t){var e=a(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,s=a(t),o=s[0],u=s[1],h=new i(function(t,e,r){return 3*(e+r)/4-r}(0,o,u)),c=0,l=u>0?o-4:o;for(r=0;r>16&255,h[c++]=e>>8&255,h[c++]=255&e;return 2===u&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,h[c++]=255&e),1===u&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,h[c++]=e>>8&255,h[c++]=255&e),h},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,s=[],o=16383,a=0,u=n-i;au?u:a+o));return 1===i?(e=t[n-1],s.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],s.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"=")),s.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)r[o]=s[o],n[s.charCodeAt(o)]=o;function a(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function u(t){return r[t>>18&63]+r[t>>12&63]+r[t>>6&63]+r[63&t]}function h(t,e,r){for(var n,i=[],s=e;s{"use strict";r.d(e,{_S:()=>z,jn:()=>T,lG:()=>L});const n=2n**255n-19n,i=2n**252n+27742317777372353535851937790883648493n,s=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,o=0x6666666666666666666666666666666666666666666666666666666666666658n,a={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:n,n:i,h:8,Gx:s,Gy:o},u=(t="")=>{throw new Error(t)},h=t=>"string"==typeof t,c=(t,e)=>!(t instanceof Uint8Array)||"number"==typeof e&&e>0&&t.length!==e?u("Uint8Array expected"):t,l=t=>new Uint8Array(t),f=(t,e)=>c(h(t)?k(t):l(t),e),d=(t,e=n)=>{let r=t%e;return r>=0n?r:e+r},p=t=>t instanceof g?t:u("Point expected");let y;class g{constructor(t,e,r,n){this.ex=t,this.ey=e,this.ez=r,this.et=n}static fromAffine(t){return new g(t.x,t.y,1n,d(t.x*t.y))}static fromHex(t,e=!0){const{d:r}=a,i=(t=f(t,32)).slice();i[31]=-129&t[31];const s=A(i);0n===s||(!e||0n0n;i=i.double(),t>>=1n)1n&t?r=r.add(i):e&&(n=n.add(i));return r}multiply(t){return this.mul(t)}clearCofactor(){return this.mul(BigInt(a.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.mul(i/2n,!1).double();return t=t.add(this),t.is0()}toAffine(){const{ex:t,ey:e,ez:r}=this;if(this.is0())return{x:0n,y:0n};const n=B(r);return 1n!==d(r*n)&&u("invalid inverse"),{x:d(t*n),y:d(e*n)}}toRawBytes(){const{x:t,y:e}=this.toAffine(),r=x(e);return r[31]|=1n&t?128:0,r}toHex(){return v(this.toRawBytes())}}g.BASE=new g(s,o,1n,d(s*o)),g.ZERO=new g(0n,1n,1n,0n);const{BASE:m,ZERO:b}=g,w=(t,e)=>t.toString(16).padStart(e,"0"),v=t=>Array.from(t).map(t=>w(t,2)).join(""),k=t=>{const e=t.length;(!h(t)||e%2)&&u("hex invalid 1");const r=l(e/2);for(let e=0;ek(w(t,64)).reverse(),A=t=>BigInt("0x"+v(l(c(t)).reverse())),E=(...t)=>{const e=l(t.reduce((t,e)=>t+c(e).length,0));let r=0;return t.forEach(t=>{e.set(t,r),r+=t.length}),e},B=(t,e=n)=>{(0n===t||e<=0n)&&u("no inverse n="+t+" mod="+e);let r=d(t,e),i=e,s=0n,o=1n,a=1n,h=0n;for(;0n!==r;){const t=i/r,e=i%r,n=s-a*t,u=o-h*t;i=r,r=e,s=a,o=h,a=n,h=u}return 1n===i?d(s,e):u("no inverse")},I=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=n;return r},S=19681161376707505956807079304988542015446066515923890162744021073123829784752n,M=(t,e)=>{const r=d(e*e*e),i=(t=>{const e=t*t%n*t%n,r=I(e,2n)*e%n,i=I(r,1n)*t%n,s=I(i,5n)*i%n,o=I(s,10n)*s%n,a=I(o,20n)*o%n,u=I(a,40n)*a%n,h=I(u,80n)*u%n,c=I(h,80n)*u%n,l=I(c,10n)*s%n;return{pow_p_5_8:I(l,2n)*t%n,b2:e}})(t*d(r*r*e)).pow_p_5_8;let s=d(t*r*i);const o=d(e*s*s),a=s,u=d(s*S),h=o===t,c=o===d(-t),l=o===d(-t*S);return h&&(s=a),(c||l)&&(s=u),1n==(1n&d(s))&&(s=d(-s)),{isValid:h||c,value:s}},_=t=>d(A(t),i);let P;const U=(...t)=>"function"==typeof P?P(...t):u("etc.sha512Sync not set"),O=t=>(t=>{const e=t.slice(0,32);e[0]&=248,e[31]&=127,e[31]|=64;const r=t.slice(32,64),n=_(e),i=m.mul(n),s=i.toRawBytes();return{head:e,prefix:r,scalar:n,point:i,pointBytes:s}})(U(f(t,32))),L=t=>O(t).pointBytes;function K(t,e){return t?((...t)=>T.sha512Async(...t))(e.hashable).then(e.finish):e.finish(U(e.hashable))}const z=(t,e)=>{const r=f(t),n=O(e);return K(!1,((t,e,r)=>{const{pointBytes:n,scalar:s}=t,o=_(e),a=m.mul(o).toRawBytes();return{hashable:E(a,n,r),finish:t=>{const e=d(o+_(t)*s,i);return c(E(a,x(e)),64)}}})(n,U(n.prefix,r),r))},R=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,T={bytesToHex:v,hexToBytes:k,concatBytes:E,mod:d,invert:B,randomBytes:t=>{const e=R();return e||u("crypto.getRandomValues must be defined"),e.getRandomValues(l(t))},sha512Async:async(...t)=>{const e=R();e||u("crypto.subtle or etc.sha512Async must be defined");const r=E(...t);return l(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(T,{sha512Sync:{configurable:!1,get:()=>P,set(t){P||(P=t)}}});const C=t=>{const e=y||(y=(()=>{const t=[];let e=m,r=e;for(let n=0;n<33;n++){r=e,t.push(r);for(let n=1;n<128;n++)r=r.add(e),t.push(r);e=r.double()}return t})()),r=(t,e)=>{let r=e.negate();return t?r:e};let n=b,i=m;const s=BigInt(255),o=BigInt(8);for(let a=0;a<33;a++){const u=128*a;let h=Number(t&s);t>>=o,h>128&&(h-=256,t+=1n);const c=u,l=u+Math.abs(h)-1,f=a%2!=0,d=h<0;0===h?i=i.add(r(f,e[c])):n=n.add(r(d,e[l]))}return{p:n,f:i}}},601:(t,e,r)=>{"use strict";e.I0=e.DH=e.NX=e.u8=e.cY=void 0,e.av=e.O6=e.w3=e.Wg=void 0;const n=r(287);function i(t){if(!(t instanceof Uint8Array))throw new TypeError("b must be a Uint8Array")}function s(t){return i(t),n.Buffer.from(t.buffer,t.byteOffset,t.length)}class o{constructor(t,e){if(!Number.isInteger(t))throw new TypeError("span must be an integer");this.span=t,this.property=e}makeDestinationObject(){return{}}getSpan(t,e){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(t){const e=Object.create(this.constructor.prototype);return Object.assign(e,this),e.property=t,e}fromArray(t){}}function a(t,e){return e.property?t+"["+e.property+"]":t}class u extends o{isCount(){throw new Error("ExternalLayout is abstract")}}class h extends u{constructor(t,e=0,r){if(!(t instanceof o))throw new TypeError("layout must be a Layout");if(!Number.isInteger(e))throw new TypeError("offset must be integer or undefined");super(t.span,r||t.property),this.layout=t,this.offset=e}isCount(){return this.layout instanceof c||this.layout instanceof l}decode(t,e=0){return this.layout.decode(t,e+this.offset)}encode(t,e,r=0){return this.layout.encode(t,e,r+this.offset)}}class c extends o{constructor(t,e){if(super(t,e),6t+n.encode(i,e,r+t),0);return this.count instanceof u&&this.count.encode(t.length,e,r),i}}class b extends o{constructor(t,e,r){if(!Array.isArray(t)||!t.reduce((t,e)=>t&&e instanceof o,!0))throw new TypeError("fields must be array of Layout instances");"boolean"==typeof e&&void 0===r&&(r=e,e=void 0);for(const e of t)if(0>e.span&&void 0===e.property)throw new Error("fields cannot contain unnamed variable-length layout");let n=-1;try{n=t.reduce((t,e)=>t+e.getSpan(),0)}catch(t){}super(n,e),this.fields=t,this.decodePrefixes=!!r}getSpan(t,e=0){if(0<=this.span)return this.span;let r=0;try{r=this.fields.reduce((r,n)=>{const i=n.getSpan(t,e);return e+=i,r+i},0)}catch(t){throw new RangeError("indeterminate span")}return r}decode(t,e=0){i(t);const r=this.makeDestinationObject();for(const n of this.fields)if(void 0!==n.property&&(r[n.property]=n.decode(t,e)),e+=n.getSpan(t,e),this.decodePrefixes&&t.length===e)break;return r}encode(t,e,r=0){const n=r;let i=0,s=0;for(const n of this.fields){let o=n.span;if(s=0o&&(o=n.getSpan(e,r)))}i=r,r+=o}return i+s-n}fromArray(t){const e=this.makeDestinationObject();for(const r of this.fields)void 0!==r.property&&0r.span?e=-1:0<=e&&(e+=r.span)}}}class w extends o{constructor(t,e){if(!(t instanceof u&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let r=-1;t instanceof u||(r=t),super(r,e),this.length=t}getSpan(t,e){let r=this.span;return 0>r&&(r=this.length.decode(t,e)),r}decode(t,e=0){let r=this.span;return 0>r&&(r=this.length.decode(t,e)),s(t).slice(e,e+r)}encode(t,e,r){let n=this.length;if(this.length instanceof u&&(n=t.length),!(t instanceof Uint8Array&&n===t.length))throw new TypeError(a("Blob.encode",this)+" requires (length "+n+") Uint8Array as src");if(r+n>e.length)throw new RangeError("encoding overruns Uint8Array");const i=s(t);return s(e).write(i.toString("hex"),r,n,"hex"),this.length instanceof u&&this.length.encode(n,e,r),n}}e.cY=(t,e,r)=>new h(t,e,r),e.u8=t=>new c(1,t),e.NX=t=>new c(2,t),e.DH=t=>new c(4,t),e.I0=t=>new y(t),e.Wg=t=>new g(t),e.w3=(t,e,r)=>new b(t,e,r),e.O6=(t,e,r)=>new m(t,e,r),e.av=(t,e)=>new w(t,e)},678:t=>{"use strict";var e=Object.prototype.hasOwnProperty,r="~";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function s(t,e,n,s,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new i(n,s||t,o),u=r?r+e:e;return t._events[u]?t._events[u].fn?t._events[u]=[t._events[u],a]:t._events[u].push(a):(t._events[u]=a,t._eventsCount++),t}function o(t,e){0===--t._eventsCount?t._events=new n:delete t._events[e]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var t,n,i=[];if(0===this._eventsCount)return i;for(n in t=this._events)e.call(t,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(t)):i},a.prototype.listeners=function(t){var e=r?r+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i=0;a--)(i=t[a])&&(o=(s<3?i(o):s>3?i(e,r,o):i(e,r))||o);return s>3&&o&&Object.defineProperty(e,r,o),o},o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)"default"!==r&&Object.hasOwnProperty.call(t,r)&&n(e,t,r);return i(e,t),e},a=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.deserializeUnchecked=e.deserialize=e.serialize=e.BinaryReader=e.BinaryWriter=e.BorshError=e.baseDecode=e.baseEncode=void 0;const u=a(r(404)),h=a(r(763)),c=o(r(281)),l=new("function"!=typeof TextDecoder?c.TextDecoder:TextDecoder)("utf-8",{fatal:!0});e.baseEncode=function(t){return"string"==typeof t&&(t=Buffer.from(t,"utf8")),h.default.encode(Buffer.from(t))},e.baseDecode=function(t){return Buffer.from(h.default.decode(t))};const f=1024;class d extends Error{constructor(t){super(t),this.fieldPath=[],this.originalMessage=t}addToFieldPath(t){this.fieldPath.splice(0,0,t),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}e.BorshError=d;class p{constructor(){this.buf=Buffer.alloc(f),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(f)]))}writeU8(t){this.maybeResize(),this.buf.writeUInt8(t,this.length),this.length+=1}writeU16(t){this.maybeResize(),this.buf.writeUInt16LE(t,this.length),this.length+=2}writeU32(t){this.maybeResize(),this.buf.writeUInt32LE(t,this.length),this.length+=4}writeU64(t){this.maybeResize(),this.writeBuffer(Buffer.from(new u.default(t).toArray("le",8)))}writeU128(t){this.maybeResize(),this.writeBuffer(Buffer.from(new u.default(t).toArray("le",16)))}writeU256(t){this.maybeResize(),this.writeBuffer(Buffer.from(new u.default(t).toArray("le",32)))}writeU512(t){this.maybeResize(),this.writeBuffer(Buffer.from(new u.default(t).toArray("le",64)))}writeBuffer(t){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),t,Buffer.alloc(f)]),this.length+=t.length}writeString(t){this.maybeResize();const e=Buffer.from(t,"utf8");this.writeU32(e.length),this.writeBuffer(e)}writeFixedArray(t){this.writeBuffer(Buffer.from(t))}writeArray(t,e){this.maybeResize(),this.writeU32(t.length);for(const r of t)this.maybeResize(),e(r)}toArray(){return this.buf.subarray(0,this.length)}}function y(t,e,r){const n=r.value;r.value=function(...t){try{return n.apply(this,t)}catch(t){if(t instanceof RangeError){const e=t.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(e)>=0)throw new d("Reached the end of buffer when deserializing")}throw t}}}e.BinaryWriter=p;class g{constructor(t){this.buf=t,this.offset=0}readU8(){const t=this.buf.readUInt8(this.offset);return this.offset+=1,t}readU16(){const t=this.buf.readUInt16LE(this.offset);return this.offset+=2,t}readU32(){const t=this.buf.readUInt32LE(this.offset);return this.offset+=4,t}readU64(){const t=this.readBuffer(8);return new u.default(t,"le")}readU128(){const t=this.readBuffer(16);return new u.default(t,"le")}readU256(){const t=this.readBuffer(32);return new u.default(t,"le")}readU512(){const t=this.readBuffer(64);return new u.default(t,"le")}readBuffer(t){if(this.offset+t>this.buf.length)throw new d(`Expected buffer length ${t} isn't within bounds`);const e=this.buf.slice(this.offset,this.offset+t);return this.offset+=t,e}readString(){const t=this.readU32(),e=this.readBuffer(t);try{return l.decode(e)}catch(t){throw new d(`Error decoding UTF-8 string: ${t}`)}}readFixedArray(t){return new Uint8Array(this.readBuffer(t))}readArray(t){const e=this.readU32(),r=Array();for(let n=0;n{b(t,e,r,n[0],i)});else if(void 0!==n.kind)switch(n.kind){case"option":null==r?i.writeU8(0):(i.writeU8(1),b(t,e,r,n.type,i));break;case"map":i.writeU32(r.size),r.forEach((r,s)=>{b(t,e,s,n.key,i),b(t,e,r,n.value,i)});break;default:throw new d(`FieldType ${n} unrecognized`)}else w(t,r,i)}catch(t){throw t instanceof d&&t.addToFieldPath(e),t}}function w(t,e,r){if("function"==typeof e.borshSerialize)return void e.borshSerialize(r);const n=t.get(e.constructor);if(!n)throw new d(`Class ${e.constructor.name} is missing in schema`);if("struct"===n.kind)n.fields.map(([n,i])=>{b(t,n,e[n],i,r)});else{if("enum"!==n.kind)throw new d(`Unexpected schema kind: ${n.kind} for ${e.constructor.name}`);{const i=e[n.field];for(let s=0;sv(t,e,r[0],n))}if("option"===r.kind)return n.readU8()?v(t,e,r.type,n):void 0;if("map"===r.kind){let i=new Map;const s=n.readU32();for(let o=0;o=n.values.length)throw new d(`Enum index: ${i} is out of range`);const[s,o]=n.values[i],a=v(t,s,o,r);return new e({[s]:a})}throw new d(`Unexpected schema kind: ${n.kind} for ${e.constructor.name}`)}s([y],g.prototype,"readU8",null),s([y],g.prototype,"readU16",null),s([y],g.prototype,"readU32",null),s([y],g.prototype,"readU64",null),s([y],g.prototype,"readU128",null),s([y],g.prototype,"readU256",null),s([y],g.prototype,"readU512",null),s([y],g.prototype,"readString",null),s([y],g.prototype,"readFixedArray",null),s([y],g.prototype,"readArray",null),e.BinaryReader=g,e.serialize=function(t,e,r=p){const n=new r;return w(t,e,n),n.toArray()},e.deserialize=function(t,e,r,n=g){const i=new n(r),s=k(t,e,i);if(i.offset{var n=r(364);t.exports=n("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},810:(t,e,r)=>{"use strict";function n(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function i(t,e){!function(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}(t);const r=e.outputLen;if(t.lengthO});const s=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function o(t){if("string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))}(t)),!(t instanceof Uint8Array))throw new Error("expected Uint8Array, got "+typeof t);return t}class a{clone(){return this._cloneInto()}}function u(t){const e=e=>t().update(o(e)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}class h extends a{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=s(this.buffer)}update(t){n(this);const{view:e,buffer:r,blockLen:i}=this,a=(t=o(t)).length;for(let n=0;no-u&&(this.process(r,0),u=0);for(let t=u;t>i&s),a=Number(r&s),u=n?4:0,h=n?0:4;t.setUint32(e+u,o,n),t.setUint32(e+h,a,n)}(r,o-8,BigInt(8*this.length),a),this.process(r,0);const h=s(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t>l&c)}:{h:0|Number(t>>l&c),l:0|Number(t&c)}}const d=function(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;it>>>r,y=(t,e,r)=>t<<32-r|e>>>r,g=(t,e,r)=>t>>>r|e<<32-r,m=(t,e,r)=>t<<32-r|e>>>r,b=(t,e,r)=>t<<64-r|e>>>r-32,w=(t,e,r)=>t>>>r-32|e<<64-r,v=function(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:0|i}},k=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),x=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,A=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),E=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,B=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,I=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),[S,M]=(()=>d(["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(t=>BigInt(t))))(),_=new Uint32Array(80),P=new Uint32Array(80);class U extends h{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:e,Bh:r,Bl:n,Ch:i,Cl:s,Dh:o,Dl:a,Eh:u,El:h,Fh:c,Fl:l,Gh:f,Gl:d,Hh:p,Hl:y}=this;return[t,e,r,n,i,s,o,a,u,h,c,l,f,d,p,y]}set(t,e,r,n,i,s,o,a,u,h,c,l,f,d,p,y){this.Ah=0|t,this.Al=0|e,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|o,this.Dl=0|a,this.Eh=0|u,this.El=0|h,this.Fh=0|c,this.Fl=0|l,this.Gh=0|f,this.Gl=0|d,this.Hh=0|p,this.Hl=0|y}process(t,e){for(let r=0;r<16;r++,e+=4)_[r]=t.getUint32(e),P[r]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|_[t-15],r=0|P[t-15],n=g(e,r,1)^g(e,r,8)^p(e,r,7),i=m(e,r,1)^m(e,r,8)^y(e,r,7),s=0|_[t-2],o=0|P[t-2],a=g(s,o,19)^b(s,o,61)^p(s,o,6),u=m(s,o,19)^w(s,o,61)^y(s,o,6),h=A(i,u,P[t-7],P[t-16]),c=E(h,n,a,_[t-7],_[t-16]);_[t]=0|c,P[t]=0|h}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:o,Cl:a,Dh:u,Dl:h,Eh:c,El:l,Fh:f,Fl:d,Gh:U,Gl:O,Hh:L,Hl:K}=this;for(let t=0;t<80;t++){const e=g(c,l,14)^g(c,l,18)^b(c,l,41),p=m(c,l,14)^m(c,l,18)^w(c,l,41),y=c&f^~c&U,A=I(K,p,l&d^~l&O,M[t],P[t]),E=B(A,L,e,y,S[t],_[t]),z=0|A,R=g(r,n,28)^b(r,n,34)^b(r,n,39),T=m(r,n,28)^w(r,n,34)^w(r,n,39),C=r&i^r&o^i&o,N=n&s^n&a^s&a;L=0|U,K=0|O,U=0|f,O=0|d,f=0|c,d=0|l,({h:c,l}=v(0|u,0|h,0|E,0|z)),u=0|o,h=0|a,o=0|i,a=0|s,i=0|r,s=0|n;const j=k(z,T,N);r=x(j,E,R,C),n=0|j}({h:r,l:n}=v(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=v(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=v(0|this.Ch,0|this.Cl,0|o,0|a)),({h:u,l:h}=v(0|this.Dh,0|this.Dl,0|u,0|h)),({h:c,l}=v(0|this.Eh,0|this.El,0|c,0|l)),({h:f,l:d}=v(0|this.Fh,0|this.Fl,0|f,0|d)),({h:U,l:O}=v(0|this.Gh,0|this.Gl,0|U,0|O)),({h:L,l:K}=v(0|this.Hh,0|this.Hl,0|L,0|K)),this.set(r,n,i,s,o,a,u,h,c,l,f,d,U,O,L,K)}roundClean(){_.fill(0),P.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const O=u(()=>new U)},861:(t,e,r)=>{var n=r(287),i=n.Buffer;function s(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return i(t,e,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(s(n,e),e.Buffer=o),s(i,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return i(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var n=i(t);return void 0!==e?"string"==typeof r?n.fill(e,r):n.fill(e):n.fill(0),n},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return i(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n.SlowBuffer(t)}}}]); +//# sourceMappingURL=bundle.ecd3017216b8f9e85944.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.df1ee7804c25796915e3.js.LICENSE.txt b/export-and-sign/dist/bundle.ecd3017216b8f9e85944.js.LICENSE.txt similarity index 100% rename from export-and-sign/dist/bundle.df1ee7804c25796915e3.js.LICENSE.txt rename to export-and-sign/dist/bundle.ecd3017216b8f9e85944.js.LICENSE.txt diff --git a/export-and-sign/dist/bundle.ecd3017216b8f9e85944.js.map b/export-and-sign/dist/bundle.ecd3017216b8f9e85944.js.map new file mode 100644 index 0000000..050816e --- /dev/null +++ b/export-and-s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ASqlD,GAQnBD,EAAUplD,EAAQqlD,GAElBA,EAAW7/E,KAAO,SAAUwM,EAAKinD,EAAkBz2D,GACjD,GAAmB,iBAARwP,EACT,MAAM,IAAInQ,UAAU,iCAEtB,OAAOm+B,EAAOhuB,EAAKinD,EAAkBz2D,EACvC,EAEA6iF,EAAWhkD,MAAQ,SAAU9b,EAAM1gB,EAAM6xD,GACvC,GAAoB,iBAATnxC,EACT,MAAM,IAAI1jB,UAAU,6BAEtB,IAAI2xB,EAAMwM,EAAOza,GAUjB,YATazjB,IAAT+C,EACsB,iBAAb6xD,EACTljC,EAAI3uB,KAAKA,EAAM6xD,GAEfljC,EAAI3uB,KAAKA,GAGX2uB,EAAI3uB,KAAK,GAEJ2uB,CACT,EAEA6xD,EAAWnsB,YAAc,SAAU3zC,GACjC,GAAoB,iBAATA,EACT,MAAM,IAAI1jB,UAAU,6BAEtB,OAAOm+B,EAAOza,EAChB,EAEA8/D,EAAW9nB,gBAAkB,SAAUh4C,GACrC,GAAoB,iBAATA,EACT,MAAM,IAAI1jB,UAAU,6BAEtB,OAAOoD,EAAO0zD,WAAWpzC,EAC3B,C","sources":["webpack://export-and-sign/./node_modules/jayson/lib/client/browser/index.js","webpack://export-and-sign/./node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js","webpack://export-and-sign/./node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js","webpack://export-and-sign/./node_modules/@noble/curves/node_modules/@noble/hashes/esm/_md.js","webpack://export-and-sign/./node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js","webpack://export-and-sign/./node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha2.js","webpack://export-and-sign/./node_modules/@noble/curves/esm/utils.js","webpack://export-and-sign/./node_modules/@noble/curves/esm/abstract/modular.js","webpack://export-and-sign/./node_modules/@noble/curves/esm/abstract/curve.js","webpack://export-and-sign/./node_modules/@noble/curves/esm/abstract/edwards.js","webpack://export-and-sign/./node_modules/@noble/curves/esm/abstract/hash-to-curve.js","webpack://export-and-sign/./node_modules/@noble/curves/esm/ed25519.js","webpack://export-and-sign/./node_modules/@solana/web3.js/node_modules/@noble/hashes/esm/utils.js","webpack://export-and-sign/./node_modules/@solana/web3.js/node_modules/@noble/hashes/esm/_md.js","webpack://export-and-sign/./node_modules/@solana/web3.js/node_modules/@noble/hashes/esm/_u64.js","webpack://export-and-sign/./node_modules/@solana/web3.js/node_modules/@noble/hashes/esm/sha2.js","webpack://export-and-sign/./node_modules/@solana/web3.js/node_modules/@noble/hashes/esm/sha256.js","webpack://export-and-sign/./node_modules/@solana/errors/dist/index.browser.mjs","webpack://export-and-sign/./node_modules/@solana/codecs-core/dist/index.browser.mjs","webpack://export-and-sign/./node_modules/@solana/codecs-numbers/dist/index.browser.mjs","webpack://export-and-sign/./node_modules/superstruct/dist/index.mjs","webpack://export-and-sign/./node_modules/@solana/web3.js/node_modules/@noble/hashes/esm/sha3.js","webpack://export-and-sign/./node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js","webpack://export-and-sign/./node_modules/@noble/curves/esm/abstract/weierstrass.js","webpack://export-and-sign/./node_modules/@noble/curves/esm/secp256k1.js","webpack://export-and-sign/./node_modules/@noble/curves/esm/_shortw_utils.js","webpack://export-and-sign/./node_modules/@solana/web3.js/lib/index.browser.esm.js","webpack://export-and-sign/./node_modules/ieee754/index.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/errors.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/_dnt.shims.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/algorithm.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/identifiers.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/consts.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/interfaces/kemInterface.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/utils/misc.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/kems/dhkem.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/interfaces/dhkemPrimitives.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/utils/bignum.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/kems/dhkemPrimitives/ec.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/kdfs/hkdf.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/interfaces/aeadEncryptionContext.js","webpack://export-and-sign/./node_modules/@hpke/common/esm/src/curve/montgomery.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/aeads/aesGcm.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/utils/emitNotSupported.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/exporterContext.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/encryptionContext.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/mutex.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/recipientContext.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/senderContext.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/cipherSuiteNative.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/kems/dhkemNative.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/native.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x25519.js","webpack://export-and-sign/./node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x448.js","webpack://export-and-sign/./node_modules/text-encoding-utf-8/lib/encoding.lib.js","webpack://export-and-sign/./node_modules/buffer/index.js","webpack://export-and-sign/./node_modules/jayson/lib/generateRequest.js","webpack://export-and-sign/./node_modules/uuid/dist/esm-browser/rng.js","webpack://export-and-sign/./node_modules/uuid/dist/esm-browser/regex.js","webpack://export-and-sign/./node_modules/uuid/dist/esm-browser/stringify.js","webpack://export-and-sign/./node_modules/uuid/dist/esm-browser/validate.js","webpack://export-and-sign/./node_modules/uuid/dist/esm-browser/v4.js","webpack://export-and-sign/./node_modules/base-x/src/index.js","webpack://export-and-sign/./node_modules/bn.js/lib/bn.js","webpack://export-and-sign/./node_modules/base64-js/index.js","webpack://export-and-sign/./node_modules/@noble/ed25519/index.js","webpack://export-and-sign/./node_modules/@solana/buffer-layout/lib/Layout.js","webpack://export-and-sign/./node_modules/rpc-websockets/node_modules/eventemitter3/index.js","webpack://export-and-sign/./node_modules/borsh/lib/index.js","webpack://export-and-sign/./node_modules/bs58/index.js","webpack://export-and-sign/./node_modules/@noble/hashes/esm/_assert.js","webpack://export-and-sign/./node_modules/@noble/hashes/esm/utils.js","webpack://export-and-sign/./node_modules/@noble/hashes/esm/_sha2.js","webpack://export-and-sign/./node_modules/@noble/hashes/esm/_u64.js","webpack://export-and-sign/./node_modules/@noble/hashes/esm/sha512.js","webpack://export-and-sign/./node_modules/safe-buffer/index.js"],"sourcesContent":["'use strict';\n\nconst uuid = require('uuid').v4;\nconst generateRequest = require('../../generateRequest');\n\n/**\n * Constructor for a Jayson Browser Client that does not depend any node.js core libraries\n * @class ClientBrowser\n * @param {Function} callServer Method that calls the server, receives the stringified request and a regular node-style callback\n * @param {Object} [options]\n * @param {Function} [options.reviver] Reviver function for JSON\n * @param {Function} [options.replacer] Replacer function for JSON\n * @param {Number} [options.version=2] JSON-RPC version to use (1|2)\n * @param {Function} [options.generator] Function to use for generating request IDs\n * @param {Boolean} [options.notificationIdNull=false] When true, version 2 requests will set id to null instead of omitting it\n * @return {ClientBrowser}\n */\nconst ClientBrowser = function(callServer, options) {\n if(!(this instanceof ClientBrowser)) {\n return new ClientBrowser(callServer, options);\n }\n\n if (!options) {\n options = {};\n }\n\n this.options = {\n reviver: typeof options.reviver !== 'undefined' ? options.reviver : null,\n replacer: typeof options.replacer !== 'undefined' ? options.replacer : null,\n generator: typeof options.generator !== 'undefined' ? options.generator : function() { return uuid(); },\n version: typeof options.version !== 'undefined' ? options.version : 2,\n notificationIdNull: typeof options.notificationIdNull === 'boolean' ? options.notificationIdNull : false,\n };\n\n this.callServer = callServer;\n};\n\nmodule.exports = ClientBrowser;\n\n/**\n * Creates a request and dispatches it if given a callback.\n * @param {String|Array} method A batch request if passed an Array, or a method name if passed a String\n * @param {Array|Object} [params] Parameters for the method\n * @param {String|Number} [id] Optional id. If undefined an id will be generated. If null it creates a notification request\n * @param {Function} [callback] Request callback. If specified, executes the request rather than only returning it.\n * @throws {TypeError} Invalid parameters\n * @return {Object} JSON-RPC 1.0 or 2.0 compatible request\n */\nClientBrowser.prototype.request = function(method, params, id, callback) {\n const self = this;\n let request = null;\n\n // is this a batch request?\n const isBatch = Array.isArray(method) && typeof params === 'function';\n\n if (this.options.version === 1 && isBatch) {\n throw new TypeError('JSON-RPC 1.0 does not support batching');\n }\n\n // is this a raw request?\n const isRaw = !isBatch && method && typeof method === 'object' && typeof params === 'function';\n\n if(isBatch || isRaw) {\n callback = params;\n request = method;\n } else {\n if(typeof id === 'function') {\n callback = id;\n // specifically undefined because \"null\" is a notification request\n id = undefined;\n }\n\n const hasCallback = typeof callback === 'function';\n\n try {\n request = generateRequest(method, params, id, {\n generator: this.options.generator,\n version: this.options.version,\n notificationIdNull: this.options.notificationIdNull,\n });\n } catch(err) {\n if(hasCallback) {\n return callback(err);\n }\n throw err;\n }\n\n // no callback means we should just return a raw request\n if(!hasCallback) {\n return request;\n }\n\n }\n\n let message;\n try {\n message = JSON.stringify(request, this.options.replacer);\n } catch(err) {\n return callback(err);\n }\n\n this.callServer(message, function(err, response) {\n self._parseResponse(err, response, callback);\n });\n\n // always return the raw request\n return request;\n};\n\n/**\n * Parses a response from a server\n * @param {Object} err Error to pass on that is unrelated to the actual response\n * @param {String} responseText JSON-RPC 1.0 or 2.0 response\n * @param {Function} callback Callback that will receive different arguments depending on the amount of parameters\n * @private\n */\nClientBrowser.prototype._parseResponse = function(err, responseText, callback) {\n if(err) {\n callback(err);\n return;\n }\n\n if(!responseText) {\n // empty response text, assume that is correct because it could be a\n // notification which jayson does not give any body for\n return callback();\n }\n\n let response;\n try {\n response = JSON.parse(responseText, this.options.reviver);\n } catch(err) {\n return callback(err);\n }\n\n if(callback.length === 3) {\n // if callback length is 3, we split callback arguments on error and response\n\n // is batch response?\n if(Array.isArray(response)) {\n\n // neccesary to split strictly on validity according to spec here\n const isError = function(res) {\n return typeof res.error !== 'undefined';\n };\n\n const isNotError = function (res) {\n return !isError(res);\n };\n\n return callback(null, response.filter(isError), response.filter(isNotError));\n \n } else {\n\n // split regardless of validity\n return callback(null, response.error, response.result);\n \n }\n \n }\n\n callback(null, response);\n};\n","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';\nexport { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(title + ' boolean expected, got ' + value);\n}\n// tmp name until v2\nexport function _abool2(value, title = '') {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value, length, title = '') {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n }\n catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n }\n else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_1n << BigInt(n)) - _1n;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error('invalid validator function');\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\nexport function isHash(val) {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(object, fields, optFields = {}) {\n if (!object || typeof object !== 'object')\n throw new Error('expected valid options object');\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n return FpPow(Field(modulo), num, power);\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction assertIsSquare(Fp, root, n) {\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\nfunction sqrt5mod8(Fp, n) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (Fp, n) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n if (Fp.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t))\n return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp, num, power) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return Fp.ONE;\n if (power === _1n)\n return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n// TODO: remove\nexport function FpDiv(Fp, lhs, rhs) {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre(Fp, n) {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?\nisLE = false, opts = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength = undefined;\n let _sqrt = undefined;\n let modFromBytes = false;\n let allowedLengths = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE)\n throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS)\n _nbitLength = _opts.BITS;\n if (_opts.sqrt)\n _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean')\n isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean')\n modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n }\n else {\n if (typeof bitLenOrOpts === 'number')\n _nbitLength = bitLenOrOpts;\n if (opts.sqrt)\n _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP; // cached sqrtP\n const f = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: _sqrt ||\n ((n) => {\n if (!sqrtP)\n sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n });\n return Object.freeze(f);\n}\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from \"../utils.js\";\nimport { Field, FpInvertBatch, nLength, validateField } from \"./modular.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nexport function negateCt(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ(c, points) {\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\nfunction assert0(n) {\n if (n !== _0n)\n throw new Error('invalid wNAF');\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n // Parametrized with a given Point class (not individual point)\n constructor(Point, bits) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n // non-const time multiplication ladder\n _unsafeLadder(elm, n, p = this.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(point, W) {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points = [];\n let p = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n))\n throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n }\n else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n)\n break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n }\n else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n getPrecomputes(W, point, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W);\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function')\n comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n cached(point, scalar, transform) {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n unsafe(point, scalar, transform, prev) {\n const W = getW(point);\n if (W === 1)\n return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P, W) {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n hasCache(elm) {\n return getW(elm) !== 1;\n }\n}\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe(Point, point, k1, k2) {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n p1 = p1.add(acc);\n if (k2 & _1n)\n p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger(c, fieldN, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, fieldN, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n// TODO: remove\n/** @deprecated */\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\nfunction createField(order, field, isLE) {\n if (field) {\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n//# sourceMappingURL=curve.js.map","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, ensureBytes, isBytes, memoized, notImplemented, randomBytes as randomBytesWeb, } from \"../utils.js\";\nimport { _createCurveFields, normalizeZ, pippenger, wNAF, } from \"./curve.js\";\nimport { Field } from \"./modular.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\nfunction isEdValidXY(Fp, CURVE, x, y) {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\nexport function edwards(params, extraOpts = {}) {\n const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor } = CURVE;\n _validateObject(extraOpts, {}, { uvRatio: 'function' });\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n) => Fp.create(n); // Function overrides\n // sqrt(u/v)\n const uvRatio = extraOpts.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title, n, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n function aextpoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(X, Y, Z, T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes, zip215 = false) {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(bytes, zip215 = false) {\n return Point.fromBytes(ensureBytes('point', bytes), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_2n); // random number\n return this;\n }\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n aextpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n aextpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n // Constant-time multiplication.\n multiply(scalar) {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar))\n throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar, acc = Point.ZERO) {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar))\n throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n)\n return Point.ZERO;\n if (this.is0() || scalar === _1n)\n return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ) {\n return toAffineMemo(this, invertedZ);\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n toBytes() {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return ``;\n }\n // TODO: remove\n get ex() {\n return this.X;\n }\n get ey() {\n return this.Y;\n }\n get ez() {\n return this.Z;\n }\n get et() {\n return this.T;\n }\n static normalizeZ(points) {\n return normalizeZ(Point, points);\n }\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n _setWindowSize(windowSize) {\n this.precompute(windowSize);\n }\n toRawBytes() {\n return this.toBytes();\n }\n }\n // base / generator point\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n Point.Fp = Fp;\n // scalar field\n Point.Fn = Fn;\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport class PrimeEdwardsPoint {\n constructor(ep) {\n this.ep = ep;\n }\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes) {\n notImplemented();\n }\n static fromHex(_hex) {\n notImplemented();\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n // Common implementations\n clearCofactor() {\n // no-op for prime-order groups\n return this;\n }\n assertValidity() {\n this.ep.assertValidity();\n }\n toAffine(invertedZ) {\n return this.ep.toAffine(invertedZ);\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return this.toHex();\n }\n isTorsionFree() {\n return true;\n }\n isSmallOrder() {\n return false;\n }\n add(other) {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n subtract(other) {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return this.init(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return this.init(this.ep.double());\n }\n negate() {\n return this.init(this.ep.negate());\n }\n precompute(windowSize, isLazy) {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n /** @deprecated use `toBytes` */\n toRawBytes() {\n return this.toBytes();\n }\n}\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point, cHash, eddsaOpts = {}) {\n if (typeof cHash !== 'function')\n throw new Error('\"hash\" function param is required');\n _validateObject(eddsaOpts, {}, {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n });\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n const randomBytes = eddsaOpts.randomBytes || randomBytesWeb;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);\n const domain = eddsaOpts.domain ||\n ((data, ctx, phflag) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key) {\n const len = lengths.secretKey;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey) {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, secretKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s))\n throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts = { zip215: true };\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = ensureBytes('signature', sig, len);\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);\n if (zip215 !== undefined)\n abool(zip215, 'zip215');\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false; // zip215 allows public keys of small order\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)) {\n return abytes(seed, lengths.seed, 'seed');\n }\n function keygen(seed) {\n const secretKey = utils.randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n function isValidSecretKey(key) {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n function isValidPublicKey(key, zip215) {\n try {\n return !!Point.fromBytes(key, zip215);\n }\n catch (error) {\n return false;\n }\n }\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey) {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57)\n throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n toMontgomerySecret(secretKey) {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n /** @deprecated */\n randomPrivateKey: randomSecretKey,\n /** @deprecated */\n precompute(windowSize = 8, point = Point.BASE) {\n return point.precompute(windowSize, false);\n },\n };\n return Object.freeze({\n keygen,\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\nfunction _eddsa_legacy_opts_to_new(c) {\n const CURVE = {\n a: c.a,\n d: c.d,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n const Fn = Field(CURVE.n, c.nBitLength, true);\n const curveOpts = { Fp, Fn, uvRatio: c.uvRatio };\n const eddsaOpts = {\n randomBytes: c.randomBytes,\n adjustScalarBytes: c.adjustScalarBytes,\n domain: c.domain,\n prehash: c.prehash,\n mapToCurve: c.mapToCurve,\n };\n return { CURVE, curveOpts, hash: c.hash, eddsaOpts };\n}\nfunction _eddsa_new_output_to_legacy(c, eddsa) {\n const Point = eddsa.Point;\n const legacy = Object.assign({}, eddsa, {\n ExtendedPoint: Point,\n CURVE: c,\n nBitLength: Point.Fn.BITS,\n nByteLength: Point.Fn.BYTES,\n });\n return legacy;\n}\n// TODO: remove. Use eddsa\nexport function twistedEdwards(c) {\n const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);\n const Point = edwards(CURVE, curveOpts);\n const EDDSA = eddsa(Point, hash, eddsaOpts);\n return _eddsa_new_output_to_legacy(c, EDDSA);\n}\n//# sourceMappingURL=edwards.js.map","import { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from \"../utils.js\";\nimport { FpInvertBatch, mod } from \"./modular.js\";\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value, length) {\n anum(value);\n anum(length);\n if (value < 0 || value >= 1 << (8 * length))\n throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0);\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\nfunction strxor(a, b) {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\nfunction anum(item) {\n if (!Number.isSafeInteger(item))\n throw new Error('number expected');\n}\nfunction normDST(DST) {\n if (!isBytes(DST) && typeof DST !== 'string')\n throw new Error('DST must be Uint8Array or string');\n return typeof DST === 'string' ? utf8ToBytes(DST) : DST;\n}\n/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\nexport function expand_message_xmd(msg, DST, lenInBytes, H) {\n abytes(msg);\n anum(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255)\n DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255)\n throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\nexport function expand_message_xof(msg, DST, lenInBytes, k, H) {\n abytes(msg);\n anum(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest());\n}\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg, count, options) {\n _validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n if (!isHash(options.hash))\n throw new Error('expected valid hash');\n abytes(msg);\n anum(count);\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n }\n else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n }\n else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n }\n else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\nexport function isogenyMap(field, map) {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x, y) => {\n const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\nexport const _DST_scalar = utf8ToBytes('HashToScalar-');\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */\nexport function createHasher(Point, mapToCurve, defaults) {\n if (typeof mapToCurve !== 'function')\n throw new Error('mapToCurve() must be defined');\n function map(num) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO))\n return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n return {\n defaults,\n hashToCurve(msg, options) {\n const opts = Object.assign({}, defaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\n },\n encodeToCurve(msg, options) {\n const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};\n const opts = Object.assign({}, defaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars) {\n if (!Array.isArray(scalars))\n throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint')\n throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08\n hashToScalar(msg, options) {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\n };\n}\n//# sourceMappingURL=hash-to-curve.js.map","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';\nimport { pippenger } from \"./abstract/curve.js\";\nimport { PrimeEdwardsPoint, twistedEdwards, } from \"./abstract/edwards.js\";\nimport { _DST_scalar, createHasher, expand_message_xmd, } from \"./abstract/hash-to-curve.js\";\nimport { Field, FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { bytesToNumberLE, ensureBytes, equalBytes } from \"./utils.js\";\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n// P = 2n**255n-19n\nconst ed25519_CURVE_p = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nconst Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();\nconst Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n ...ed25519_CURVE,\n Fp,\n hash: sha512,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n}))();\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const { secretKey, publicKey } = ed25519.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\n/** Context of ed25519. Uses context for domain separation. */\nexport const ed25519ctx = /* @__PURE__ */ (() => twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n}))();\n/** Prehashed version of ed25519. Accepts already-hashed messages in sign() and verify(). */\nexport const ed25519ph = /* @__PURE__ */ (() => twistedEdwards(Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n})))();\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomSecretKey());\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = Fp.ORDER;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x) => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519.Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\nfunction ristretto255_map(bytes) {\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n}\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint {\n constructor(ep) {\n super(ep);\n }\n static fromAffine(ap) {\n return new _RistrettoPoint(ed25519.Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _RistrettoPoint))\n throw new Error('RistrettoPoint expected');\n }\n init(ep) {\n return new _RistrettoPoint(ep);\n }\n /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\n static hashToCurve(hex) {\n return ristretto255_map(ensureBytes('ristrettoHash', hex, 64));\n }\n static fromBytes(bytes) {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519.Point(x, y, _1n, t));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n return _RistrettoPoint.fromBytes(ensureBytes('ristrettoHex', hex, 32));\n }\n static msm(points, scalars) {\n return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes() {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P))\n Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P))\n s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n// Do NOT change syntax: the following gymnastics is done,\n// because typescript strips comments, which makes bundlers disable tree-shaking.\n// prettier-ignore\n_RistrettoPoint.BASE = \n/* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();\n// prettier-ignore\n_RistrettoPoint.ZERO = \n/* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();\n// prettier-ignore\n_RistrettoPoint.Fp = \n/* @__PURE__ */ (() => Fp)();\n// prettier-ignore\n_RistrettoPoint.Fn = \n/* @__PURE__ */ (() => Fn)();\nexport const ristretto255 = { Point: _RistrettoPoint };\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher = {\n hashToCurve(msg, options) {\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return ristretto255_map(xmd);\n },\n hashToScalar(msg, options = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n};\n// export const ristretto255_oprf: OPRF = createORPF({\n// name: 'ristretto255-SHA512',\n// Point: RistrettoPoint,\n// hash: sha512,\n// hashToGroup: ristretto255_hasher.hashToCurve,\n// hashToScalar: ristretto255_hasher.hashToScalar,\n// });\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n return ed25519.utils.toMontgomery(ensureBytes('pub', edwardsPub));\n}\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport const edwardsToMontgomery = edwardsToMontgomeryPub;\n/** @deprecated use `ed25519.utils.toMontgomerySecret` */\nexport function edwardsToMontgomeryPriv(edwardsPriv) {\n return ed25519.utils.toMontgomerySecret(ensureBytes('pub', edwardsPriv));\n}\n/** @deprecated use `ristretto255.Point` */\nexport const RistrettoPoint = _RistrettoPoint;\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToCurve = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const encodeToCurve = /* @__PURE__ */ (() => ed25519_hasher.encodeToCurve)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToRistretto255 = /* @__PURE__ */ (() => ristretto255_hasher.hashToCurve)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hash_to_ristretto255 = /* @__PURE__ */ (() => ristretto255_hasher.hashToCurve)();\n//# sourceMappingURL=ed25519.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map","// src/codes.ts\nvar SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;\nvar SOLANA_ERROR__INVALID_NONCE = 2;\nvar SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;\nvar SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;\nvar SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;\nvar SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;\nvar SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;\nvar SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;\nvar SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;\nvar SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;\nvar SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;\nvar SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;\nvar SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;\nvar SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;\nvar SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;\nvar SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;\nvar SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;\nvar SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 28e5;\nvar SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;\nvar SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;\nvar SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;\nvar SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;\nvar SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;\nvar SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;\nvar SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;\nvar SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;\nvar SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;\nvar SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;\nvar SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;\nvar SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 323e4;\nvar SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;\nvar SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;\nvar SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;\nvar SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 361e4;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;\nvar SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;\nvar SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611e3;\nvar SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704e3;\nvar SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;\nvar SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;\nvar SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;\nvar SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;\nvar SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128e3;\nvar SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;\nvar SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615e3;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;\nvar SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;\nvar SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508e3;\nvar SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;\nvar SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;\nvar SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;\nvar SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;\nvar SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;\nvar SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;\nvar SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;\nvar SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;\nvar SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;\nvar SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;\nvar SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;\nvar SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663e3;\nvar SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;\nvar SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;\nvar SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;\nvar SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;\nvar SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;\nvar SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;\nvar SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;\nvar SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;\nvar SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;\nvar SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;\nvar SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;\nvar SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;\nvar SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;\nvar SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;\nvar SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;\nvar SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;\nvar SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 705e4;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;\nvar SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;\nvar SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;\nvar SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;\nvar SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;\nvar SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;\nvar SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;\nvar SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;\nvar SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;\nvar SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;\nvar SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;\nvar SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;\nvar SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;\nvar SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;\nvar SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;\nvar SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;\nvar SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;\nvar SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;\nvar SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078e3;\nvar SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;\nvar SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;\nvar SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;\nvar SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;\nvar SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;\nvar SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;\nvar SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;\nvar SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;\nvar SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;\nvar SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;\nvar SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;\nvar SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;\nvar SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;\nvar SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;\nvar SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;\nvar SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;\nvar SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;\nvar SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;\nvar SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;\nvar SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;\nvar SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;\nvar SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;\nvar SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 81e5;\nvar SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;\nvar SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;\nvar SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 819e4;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;\nvar SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 99e5;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;\nvar SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;\n\n// src/context.ts\nfunction encodeValue(value) {\n if (Array.isArray(value)) {\n const commaSeparatedValues = value.map(encodeValue).join(\n \"%2C%20\"\n /* \", \" */\n );\n return \"%5B\" + commaSeparatedValues + /* \"]\" */\n \"%5D\";\n } else if (typeof value === \"bigint\") {\n return `${value}n`;\n } else {\n return encodeURIComponent(\n String(\n value != null && Object.getPrototypeOf(value) === null ? (\n // Plain objects with no prototype don't have a `toString` method.\n // Convert them before stringifying them.\n { ...value }\n ) : value\n )\n );\n }\n}\nfunction encodeObjectContextEntry([key, value]) {\n return `${key}=${encodeValue(value)}`;\n}\nfunction encodeContextObject(context) {\n const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join(\"&\");\n return btoa(searchParamsString);\n}\n\n// src/messages.ts\nvar SolanaErrorMessages = {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: \"Account not found at address: $address\",\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: \"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.\",\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: \"Expected decoded account at address: $address\",\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: \"Failed to decode account data at address: $address\",\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: \"Accounts not found at addresses: $addresses\",\n [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]: \"Unable to find a viable program address bump seed.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: \"$putativeAddress is not a base58-encoded address.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: \"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: \"The `CryptoKey` must be an `Ed25519` public key.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]: \"$putativeOffCurveAddress is not a base58-encoded off-curve address.\",\n [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: \"Invalid seeds; point must fall off the Ed25519 curve.\",\n [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]: \"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].\",\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: \"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.\",\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: \"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.\",\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: \"Expected program derived address bump to be in the range [0, 255], got: $bump.\",\n [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: \"Program address cannot end with PDA marker.\",\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: \"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.\",\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: \"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.\",\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: \"The network has progressed past the last block for which this transaction could have been committed.\",\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: \"Codec [$codecDescription] cannot decode empty byte arrays.\",\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: \"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.\",\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: \"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].\",\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: \"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].\",\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: \"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].\",\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]: \"Encoder and decoder must either both be fixed-size or variable-size.\",\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: \"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.\",\n [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: \"Expected a fixed-size codec, got a variable-size one.\",\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: \"Codec [$codecDescription] expected a positive byte length, got $bytesLength.\",\n [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: \"Expected a variable-size codec, got a fixed-size one.\",\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: \"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].\",\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: \"Codec [$codecDescription] expected $expected bytes, got $bytesLength.\",\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: \"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].\",\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: \"Invalid discriminated union variant. Expected one of [$variants], got $value.\",\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: \"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.\",\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: \"Invalid literal union variant. Expected one of [$variants], got $value.\",\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: \"Expected [$codecDescription] to have $expected items, got $actual.\",\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: \"Invalid value $value for base $base with alphabet $alphabet.\",\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: \"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.\",\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: \"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.\",\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: \"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.\",\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: \"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].\",\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: \"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.\",\n [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: \"No random values implementation could be found.\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: \"instruction requires an uninitialized account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]: \"instruction tries to borrow reference for an account which is already borrowed\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: \"instruction left account with an outstanding borrowed reference\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]: \"program other than the account's owner changed the size of the account data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: \"account data too small for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: \"instruction expected an executable account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]: \"An account does not have enough lamports to be rent-exempt\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: \"Program arithmetic overflowed\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: \"Failed to serialize or deserialize account data: $encodedData\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]: \"Builtin programs must consume compute units\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: \"Cross-program invocation call depth too deep\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: \"Computational budget exceeded\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: \"custom program error: #$code\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: \"instruction contains duplicate accounts\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]: \"instruction modifications of multiply-passed account differ\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: \"executable accounts must be rent exempt\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: \"instruction changed executable accounts data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]: \"instruction changed the balance of an executable account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: \"instruction changed executable bit of an account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]: \"instruction modified data of an account it does not own\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]: \"instruction spent from the balance of an account it does not own\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: \"generic instruction error\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: \"Provided owner is not allowed\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: \"Account is immutable\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: \"Incorrect authority provided\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: \"incorrect program id for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: \"insufficient funds for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: \"invalid account data for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: \"Invalid account owner\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: \"invalid program argument\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: \"program returned invalid error code\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: \"invalid instruction data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: \"Failed to reallocate account data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: \"Provided seeds do not result in a valid address\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]: \"Accounts data allocations exceeded the maximum allowed per transaction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: \"Max accounts exceeded\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: \"Max instruction trace length exceeded\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]: \"Length of the seed is too long for address generation\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: \"An account required by the instruction is missing\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: \"missing required signature for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]: \"instruction illegally modified the program id of an account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: \"insufficient account keys for instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]: \"Cross-program invocation with unauthorized signer or writable account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]: \"Failed to create program execution environment\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: \"Program failed to compile\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: \"Program failed to complete\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: \"instruction modified data of a read-only account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]: \"instruction changed the balance of a read-only account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]: \"Cross-program invocation reentrancy not allowed for this instruction\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: \"instruction modified rent epoch of an account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]: \"sum of account balances before and after instruction do not match\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: \"instruction requires an initialized account\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: \"\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: \"Unsupported program id\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: \"Unsupported sysvar\",\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: \"The instruction does not have any accounts.\",\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: \"The instruction does not have any data.\",\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: \"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.\",\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: \"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.\",\n [SOLANA_ERROR__INVALID_NONCE]: \"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: \"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: \"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]: \"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]: \"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant\",\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: \"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant\",\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: \"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: \"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: \"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: \"JSON-RPC error: The method does not exist / is not available ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: \"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)\",\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: \"Minimum context slot has not been reached\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: \"Node is unhealthy; behind by $numSlotsBehind slots\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: \"No snapshot\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: \"Transaction simulation failed\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]: \"Transaction history is not available from this node\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: \"$__serverMessage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: \"Transaction signature length mismatch\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]: \"Transaction signature verification failure\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: \"$__serverMessage\",\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: \"Key pair bytes must be of length 64, got $byteLength.\",\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: \"Expected private key bytes with length 32. Actual length: $actualLength.\",\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: \"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.\",\n [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]: \"The provided private key does not match the provided public key.\",\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: \"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.\",\n [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: \"Lamports value must be in the range [0, 2e64-1]\",\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: \"`$value` cannot be parsed as a `BigInt`\",\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: \"$message\",\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: \"`$value` cannot be parsed as a `Number`\",\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: \"No nonce account could be found at address `$nonceAccountAddress`\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: \"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]: \"WebSocket was closed before payload could be added to the send buffer\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: \"WebSocket connection closed\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: \"WebSocket failed to connect\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]: \"Failed to obtain a subscription id from the server\",\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: \"Could not find an API plan for RPC method: `$method`\",\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: \"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.\",\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: \"HTTP error ($statusCode): $message\",\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: \"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.\",\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: \"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.\",\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: \"The provided value does not implement the `KeyPairSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: \"The provided value does not implement the `MessageModifyingSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: \"The provided value does not implement the `MessagePartialSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: \"The provided value does not implement any of the `MessageSigner` interfaces\",\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: \"The provided value does not implement the `TransactionModifyingSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: \"The provided value does not implement the `TransactionPartialSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: \"The provided value does not implement the `TransactionSendingSigner` interface\",\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: \"The provided value does not implement any of the `TransactionSigner` interfaces\",\n [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]: \"More than one `TransactionSendingSigner` was identified.\",\n [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]: \"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.\",\n [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]: \"Wallet account signers do not support signing multiple messages/transactions in a single operation\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: \"Cannot export a non-extractable key.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: \"No digest implementation could be found.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]: \"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]: \"This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\\n\\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]: \"No signature verification implementation could be found.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: \"No key generation implementation could be found.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: \"No signing implementation could be found.\",\n [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: \"No key export implementation could be found.\",\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: \"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: \"Transaction processing left an account with an outstanding borrowed reference\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: \"Account in use\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: \"Account loaded twice\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]: \"Attempt to debit an account but found no record of a prior credit.\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]: \"Transaction loads an address table account that doesn't exist\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: \"This transaction has already been processed\",\n [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: \"Blockhash not found\",\n [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: \"Loader call chain is too deep\",\n [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]: \"Transactions are currently disabled due to cluster maintenance\",\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: \"Transaction contains a duplicate instruction ($index) that is not allowed\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: \"Insufficient funds for fee\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: \"Transaction results in an account ($accountIndex) with insufficient funds for rent\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: \"This account may not be used to pay transaction fees\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: \"Transaction contains an invalid account reference\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]: \"Transaction loads an address table account with invalid data\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]: \"Transaction address table lookup uses an invalid index\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]: \"Transaction loads an address table account with an invalid owner\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]: \"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]: \"This program may not be used for executing instructions\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]: \"Transaction leaves an account with a lower balance than rent-exempt minimum\",\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]: \"Transaction loads a writable account that cannot be written\",\n [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]: \"Transaction exceeded max loaded accounts data size cap\",\n [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]: \"Transaction requires a fee but has no signature present\",\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: \"Attempt to load a program that does not exist\",\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: \"Execution of the program referenced by account at index $accountIndex is temporarily restricted.\",\n [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: \"ResanitizationNeeded\",\n [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: \"Transaction failed to sanitize accounts offsets correctly\",\n [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: \"Transaction did not pass signature verification\",\n [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: \"Transaction locked too many accounts\",\n [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]: \"Sum of account balances before and after transaction do not match\",\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: \"The transaction failed with the error `$errorName`\",\n [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: \"Transaction version is unsupported\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]: \"Transaction would exceed account data limit within the block\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]: \"Transaction would exceed total account data limit\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]: \"Transaction would exceed max account limit within the block\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]: \"Transaction would exceed max Block Cost Limit\",\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: \"Transaction would exceed max Vote Cost Limit\",\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: \"Attempted to sign a transaction with an address that is not a signer for it\",\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: \"Transaction is missing an address at index: $index.\",\n [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]: \"Transaction has no expected signers therefore it cannot be encoded\",\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: \"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes\",\n [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: \"Transaction does not have a blockhash lifetime\",\n [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: \"Transaction is not a durable nonce transaction\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: \"Contents of these address lookup tables unknown: $lookupTableAddresses\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: \"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: \"No fee payer set in CompiledTransaction\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: \"Could not find program address at index $index\",\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]: \"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more\",\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: \"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more\",\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: \"Transaction is missing a fee payer.\",\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]: \"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.\",\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]: \"Transaction first instruction is not advance nonce account instruction.\",\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]: \"Transaction with no instructions cannot be durable nonce transaction.\",\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: \"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees\",\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: \"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable\",\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: \"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.\",\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: \"Transaction is missing signatures for addresses: $addresses.\",\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: \"Transaction version must be in the range [0, 127]. `$actualVersion` given\"\n};\n\n// src/message-formatter.ts\nvar START_INDEX = \"i\";\nvar TYPE = \"t\";\nfunction getHumanReadableErrorMessage(code, context = {}) {\n const messageFormatString = SolanaErrorMessages[code];\n if (messageFormatString.length === 0) {\n return \"\";\n }\n let state;\n function commitStateUpTo(endIndex) {\n if (state[TYPE] === 2 /* Variable */) {\n const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);\n fragments.push(\n variableName in context ? (\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${context[variableName]}`\n ) : `$${variableName}`\n );\n } else if (state[TYPE] === 1 /* Text */) {\n fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));\n }\n }\n const fragments = [];\n messageFormatString.split(\"\").forEach((char, ii) => {\n if (ii === 0) {\n state = {\n [START_INDEX]: 0,\n [TYPE]: messageFormatString[0] === \"\\\\\" ? 0 /* EscapeSequence */ : messageFormatString[0] === \"$\" ? 2 /* Variable */ : 1 /* Text */\n };\n return;\n }\n let nextState;\n switch (state[TYPE]) {\n case 0 /* EscapeSequence */:\n nextState = { [START_INDEX]: ii, [TYPE]: 1 /* Text */ };\n break;\n case 1 /* Text */:\n if (char === \"\\\\\") {\n nextState = { [START_INDEX]: ii, [TYPE]: 0 /* EscapeSequence */ };\n } else if (char === \"$\") {\n nextState = { [START_INDEX]: ii, [TYPE]: 2 /* Variable */ };\n }\n break;\n case 2 /* Variable */:\n if (char === \"\\\\\") {\n nextState = { [START_INDEX]: ii, [TYPE]: 0 /* EscapeSequence */ };\n } else if (char === \"$\") {\n nextState = { [START_INDEX]: ii, [TYPE]: 2 /* Variable */ };\n } else if (!char.match(/\\w/)) {\n nextState = { [START_INDEX]: ii, [TYPE]: 1 /* Text */ };\n }\n break;\n }\n if (nextState) {\n if (state !== nextState) {\n commitStateUpTo(ii);\n }\n state = nextState;\n }\n });\n commitStateUpTo();\n return fragments.join(\"\");\n}\nfunction getErrorMessage(code, context = {}) {\n if (process.env.NODE_ENV !== \"production\") {\n return getHumanReadableErrorMessage(code, context);\n } else {\n let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \\`npx @solana/errors decode -- ${code}`;\n if (Object.keys(context).length) {\n decodingAdviceMessage += ` '${encodeContextObject(context)}'`;\n }\n return `${decodingAdviceMessage}\\``;\n }\n}\n\n// src/error.ts\nfunction isSolanaError(e, code) {\n const isSolanaError2 = e instanceof Error && e.name === \"SolanaError\";\n if (isSolanaError2) {\n if (code !== void 0) {\n return e.context.__code === code;\n }\n return true;\n }\n return false;\n}\nvar SolanaError = class extends Error {\n /**\n * Indicates the root cause of this {@link SolanaError}, if any.\n *\n * For example, a transaction error might have an instruction error as its root cause. In this\n * case, you will be able to access the instruction error on the transaction error as `cause`.\n */\n cause = this.cause;\n /**\n * Contains context that can assist in understanding or recovering from a {@link SolanaError}.\n */\n context;\n constructor(...[code, contextAndErrorOptions]) {\n let context;\n let errorOptions;\n if (contextAndErrorOptions) {\n const { cause, ...contextRest } = contextAndErrorOptions;\n if (cause) {\n errorOptions = { cause };\n }\n if (Object.keys(contextRest).length > 0) {\n context = contextRest;\n }\n }\n const message = getErrorMessage(code, context);\n super(message, errorOptions);\n this.context = {\n __code: code,\n ...context\n };\n this.name = \"SolanaError\";\n }\n};\n\n// src/stack-trace.ts\nfunction safeCaptureStackTrace(...args) {\n if (\"captureStackTrace\" in Error && typeof Error.captureStackTrace === \"function\") {\n Error.captureStackTrace(...args);\n }\n}\n\n// src/rpc-enum-errors.ts\nfunction getSolanaErrorFromRpcError({ errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }, constructorOpt) {\n let rpcErrorName;\n let rpcErrorContext;\n if (typeof rpcEnumError === \"string\") {\n rpcErrorName = rpcEnumError;\n } else {\n rpcErrorName = Object.keys(rpcEnumError)[0];\n rpcErrorContext = rpcEnumError[rpcErrorName];\n }\n const codeOffset = orderedErrorNames.indexOf(rpcErrorName);\n const errorCode = errorCodeBaseOffset + codeOffset;\n const errorContext = getErrorContext(errorCode, rpcErrorName, rpcErrorContext);\n const err = new SolanaError(errorCode, errorContext);\n safeCaptureStackTrace(err, constructorOpt);\n return err;\n}\n\n// src/instruction-error.ts\nvar ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/program/src/instruction.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n \"GenericError\",\n \"InvalidArgument\",\n \"InvalidInstructionData\",\n \"InvalidAccountData\",\n \"AccountDataTooSmall\",\n \"InsufficientFunds\",\n \"IncorrectProgramId\",\n \"MissingRequiredSignature\",\n \"AccountAlreadyInitialized\",\n \"UninitializedAccount\",\n \"UnbalancedInstruction\",\n \"ModifiedProgramId\",\n \"ExternalAccountLamportSpend\",\n \"ExternalAccountDataModified\",\n \"ReadonlyLamportChange\",\n \"ReadonlyDataModified\",\n \"DuplicateAccountIndex\",\n \"ExecutableModified\",\n \"RentEpochModified\",\n \"NotEnoughAccountKeys\",\n \"AccountDataSizeChanged\",\n \"AccountNotExecutable\",\n \"AccountBorrowFailed\",\n \"AccountBorrowOutstanding\",\n \"DuplicateAccountOutOfSync\",\n \"Custom\",\n \"InvalidError\",\n \"ExecutableDataModified\",\n \"ExecutableLamportChange\",\n \"ExecutableAccountNotRentExempt\",\n \"UnsupportedProgramId\",\n \"CallDepth\",\n \"MissingAccount\",\n \"ReentrancyNotAllowed\",\n \"MaxSeedLengthExceeded\",\n \"InvalidSeeds\",\n \"InvalidRealloc\",\n \"ComputationalBudgetExceeded\",\n \"PrivilegeEscalation\",\n \"ProgramEnvironmentSetupFailure\",\n \"ProgramFailedToComplete\",\n \"ProgramFailedToCompile\",\n \"Immutable\",\n \"IncorrectAuthority\",\n \"BorshIoError\",\n \"AccountNotRentExempt\",\n \"InvalidAccountOwner\",\n \"ArithmeticOverflow\",\n \"UnsupportedSysvar\",\n \"IllegalOwner\",\n \"MaxAccountsDataAllocationsExceeded\",\n \"MaxAccountsExceeded\",\n \"MaxInstructionTraceLengthExceeded\",\n \"BuiltinProgramsMustConsumeComputeUnits\"\n];\nfunction getSolanaErrorFromInstructionError(index, instructionError) {\n const numberIndex = Number(index);\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 4615001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n index: numberIndex,\n ...rpcErrorContext !== void 0 ? { instructionErrorContext: rpcErrorContext } : null\n };\n } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) {\n return {\n code: Number(rpcErrorContext),\n index: numberIndex\n };\n } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR) {\n return {\n encodedData: rpcErrorContext,\n index: numberIndex\n };\n }\n return { index: numberIndex };\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: instructionError\n },\n getSolanaErrorFromInstructionError\n );\n}\n\n// src/transaction-error.ts\nvar ORDERED_ERROR_NAMES2 = [\n // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/src/transaction/error.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n \"AccountInUse\",\n \"AccountLoadedTwice\",\n \"AccountNotFound\",\n \"ProgramAccountNotFound\",\n \"InsufficientFundsForFee\",\n \"InvalidAccountForFee\",\n \"AlreadyProcessed\",\n \"BlockhashNotFound\",\n // `InstructionError` intentionally omitted; delegated to `getSolanaErrorFromInstructionError`\n \"CallChainTooDeep\",\n \"MissingSignatureForFee\",\n \"InvalidAccountIndex\",\n \"SignatureFailure\",\n \"InvalidProgramForExecution\",\n \"SanitizeFailure\",\n \"ClusterMaintenance\",\n \"AccountBorrowOutstanding\",\n \"WouldExceedMaxBlockCostLimit\",\n \"UnsupportedVersion\",\n \"InvalidWritableAccount\",\n \"WouldExceedMaxAccountCostLimit\",\n \"WouldExceedAccountDataBlockLimit\",\n \"TooManyAccountLocks\",\n \"AddressLookupTableNotFound\",\n \"InvalidAddressLookupTableOwner\",\n \"InvalidAddressLookupTableData\",\n \"InvalidAddressLookupTableIndex\",\n \"InvalidRentPayingAccount\",\n \"WouldExceedMaxVoteCostLimit\",\n \"WouldExceedAccountDataTotalLimit\",\n \"DuplicateInstruction\",\n \"InsufficientFundsForRent\",\n \"MaxLoadedAccountsDataSizeExceeded\",\n \"InvalidLoadedAccountsDataSizeLimit\",\n \"ResanitizationNeeded\",\n \"ProgramExecutionTemporarilyRestricted\",\n \"UnbalancedTransaction\"\n];\nfunction getSolanaErrorFromTransactionError(transactionError) {\n if (typeof transactionError === \"object\" && \"InstructionError\" in transactionError) {\n return getSolanaErrorFromInstructionError(\n ...transactionError.InstructionError\n );\n }\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 7050001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n ...rpcErrorContext !== void 0 ? { transactionErrorContext: rpcErrorContext } : null\n };\n } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) {\n return {\n index: Number(rpcErrorContext)\n };\n } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT || errorCode === SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED) {\n return {\n accountIndex: Number(rpcErrorContext.account_index)\n };\n }\n },\n orderedErrorNames: ORDERED_ERROR_NAMES2,\n rpcEnumError: transactionError\n },\n getSolanaErrorFromTransactionError\n );\n}\n\n// src/json-rpc-error.ts\nfunction getSolanaErrorFromJsonRpcError(putativeErrorResponse) {\n let out;\n if (isRpcErrorResponse(putativeErrorResponse)) {\n const { code: rawCode, data, message } = putativeErrorResponse;\n const code = Number(rawCode);\n if (code === SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) {\n const { err, ...preflightErrorContext } = data;\n const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null;\n out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, {\n ...preflightErrorContext,\n ...causeObject\n });\n } else {\n let errorContext;\n switch (code) {\n case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:\n case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:\n case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:\n case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:\n case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:\n case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:\n errorContext = { __serverMessage: message };\n break;\n default:\n if (typeof data === \"object\" && !Array.isArray(data)) {\n errorContext = data;\n }\n }\n out = new SolanaError(code, errorContext);\n }\n } else {\n const message = typeof putativeErrorResponse === \"object\" && putativeErrorResponse !== null && \"message\" in putativeErrorResponse && typeof putativeErrorResponse.message === \"string\" ? putativeErrorResponse.message : \"Malformed JSON-RPC error with no message attribute\";\n out = new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, { error: putativeErrorResponse, message });\n }\n safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError);\n return out;\n}\nfunction isRpcErrorResponse(value) {\n return typeof value === \"object\" && value !== null && \"code\" in value && \"message\" in value && (typeof value.code === \"number\" || typeof value.code === \"bigint\") && typeof value.message === \"string\";\n}\n\nexport { SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED, SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT, SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT, SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND, SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED, SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE, SOLANA_ERROR__ADDRESSES__MALFORMED_PDA, SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH, SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE, SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE, SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, SOLANA_ERROR__CODECS__INVALID_CONSTANT, SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT, SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT, SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE, SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT, SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW, SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR, SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS, SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH, SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX, SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND, SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR, SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER, SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE, SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY, SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID, SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT, SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE, SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID, SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS, SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION, SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE, SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE, SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE, SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE, SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED, SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION, SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT, SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN, SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID, SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR, SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS, SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA, SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH, SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING, SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING, SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR, SOLANA_ERROR__JSON_RPC__INVALID_PARAMS, SOLANA_ERROR__JSON_RPC__INVALID_REQUEST, SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND, SOLANA_ERROR__JSON_RPC__PARSE_ERROR, SOLANA_ERROR__JSON_RPC__SCAN_ERROR, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION, SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH, SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY, SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE, SOLANA_ERROR__MALFORMED_BIGINT_STRING, SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, SOLANA_ERROR__MALFORMED_NUMBER_STRING, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID, SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS, SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING, SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT, SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED, SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP, SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE, SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT, SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED, SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE, SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED, SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED, SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE, SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE, SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS, SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION, SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN, SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT, SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING, SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME, SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT, SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT, SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING, SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE, SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING, SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, SolanaError, getSolanaErrorFromInstructionError, getSolanaErrorFromJsonRpcError, getSolanaErrorFromTransactionError, isSolanaError, safeCaptureStackTrace };\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map","import { SolanaError, SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH, SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL } from '@solana/errors';\n\n// src/add-codec-sentinel.ts\n\n// src/bytes.ts\nvar mergeBytes = (byteArrays) => {\n const nonEmptyByteArrays = byteArrays.filter((arr) => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach((arr) => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\nvar padBytes = (bytes, length) => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\nvar fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\nfunction containsBytes(data, bytes, offset) {\n const slice = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length);\n if (slice.length !== bytes.length) return false;\n return bytes.every((b, i) => b === slice[i]);\n}\nfunction getEncodedSize(value, encoder) {\n return \"fixedSize\" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\nfunction createEncoder(encoder) {\n return Object.freeze({\n ...encoder,\n encode: (value) => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n }\n });\n}\nfunction createDecoder(decoder) {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]\n });\n}\nfunction createCodec(codec) {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: (value) => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n }\n });\n}\nfunction isFixedSize(codec) {\n return \"fixedSize\" in codec && typeof codec.fixedSize === \"number\";\n}\nfunction assertIsFixedSize(codec) {\n if (!isFixedSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);\n }\n}\nfunction isVariableSize(codec) {\n return !isFixedSize(codec);\n}\nfunction assertIsVariableSize(codec) {\n if (!isVariableSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);\n }\n}\nfunction combineCodec(encoder, decoder) {\n if (isFixedSize(encoder) !== isFixedSize(decoder)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH);\n }\n if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, {\n decoderFixedSize: decoder.fixedSize,\n encoderFixedSize: encoder.fixedSize\n });\n }\n if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, {\n decoderMaxSize: decoder.maxSize,\n encoderMaxSize: encoder.maxSize\n });\n }\n return {\n ...decoder,\n ...encoder,\n decode: decoder.decode,\n encode: encoder.encode,\n read: decoder.read,\n write: encoder.write\n };\n}\n\n// src/add-codec-sentinel.ts\nfunction addEncoderSentinel(encoder, sentinel) {\n const write = (value, bytes, offset) => {\n const encoderBytes = encoder.encode(value);\n if (findSentinelIndex(encoderBytes, sentinel) >= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, {\n encodedBytes: encoderBytes,\n hexEncodedBytes: hexBytes(encoderBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel\n });\n }\n bytes.set(encoderBytes, offset);\n offset += encoderBytes.length;\n bytes.set(sentinel, offset);\n offset += sentinel.length;\n return offset;\n };\n if (isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: encoder.fixedSize + sentinel.length, write });\n }\n return createEncoder({\n ...encoder,\n ...encoder.maxSize != null ? { maxSize: encoder.maxSize + sentinel.length } : {},\n getSizeFromValue: (value) => encoder.getSizeFromValue(value) + sentinel.length,\n write\n });\n}\nfunction addDecoderSentinel(decoder, sentinel) {\n const read = (bytes, offset) => {\n const candidateBytes = offset === 0 ? bytes : bytes.slice(offset);\n const sentinelIndex = findSentinelIndex(candidateBytes, sentinel);\n if (sentinelIndex === -1) {\n throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, {\n decodedBytes: candidateBytes,\n hexDecodedBytes: hexBytes(candidateBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel\n });\n }\n const preSentinelBytes = candidateBytes.slice(0, sentinelIndex);\n return [decoder.decode(preSentinelBytes), offset + preSentinelBytes.length + sentinel.length];\n };\n if (isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: decoder.fixedSize + sentinel.length, read });\n }\n return createDecoder({\n ...decoder,\n ...decoder.maxSize != null ? { maxSize: decoder.maxSize + sentinel.length } : {},\n read\n });\n}\nfunction addCodecSentinel(codec, sentinel) {\n return combineCodec(addEncoderSentinel(codec, sentinel), addDecoderSentinel(codec, sentinel));\n}\nfunction findSentinelIndex(bytes, sentinel) {\n return bytes.findIndex((byte, index, arr) => {\n if (sentinel.length === 1) return byte === sentinel[0];\n return containsBytes(arr, sentinel, index);\n });\n}\nfunction hexBytes(bytes) {\n return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, \"0\"), \"\");\n}\nfunction assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {\n if (bytes.length - offset <= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, {\n codecDescription\n });\n }\n}\nfunction assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {\n bytesLength,\n codecDescription,\n expected\n });\n }\n}\nfunction assertByteArrayOffsetIsNotOutOfRange(codecDescription, offset, bytesLength) {\n if (offset < 0 || offset > bytesLength) {\n throw new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, {\n bytesLength,\n codecDescription,\n offset\n });\n }\n}\n\n// src/add-codec-size-prefix.ts\nfunction addEncoderSizePrefix(encoder, prefix) {\n const write = (value, bytes, offset) => {\n const encoderBytes = encoder.encode(value);\n offset = prefix.write(encoderBytes.length, bytes, offset);\n bytes.set(encoderBytes, offset);\n return offset + encoderBytes.length;\n };\n if (isFixedSize(prefix) && isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });\n }\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;\n const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : encoder.maxSize ?? null;\n const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;\n return createEncoder({\n ...encoder,\n ...maxSize !== null ? { maxSize } : {},\n getSizeFromValue: (value) => {\n const encoderSize = getEncodedSize(value, encoder);\n return getEncodedSize(encoderSize, prefix) + encoderSize;\n },\n write\n });\n}\nfunction addDecoderSizePrefix(decoder, prefix) {\n const read = (bytes, offset) => {\n const [bigintSize, decoderOffset] = prefix.read(bytes, offset);\n const size = Number(bigintSize);\n offset = decoderOffset;\n if (offset > 0 || bytes.length > size) {\n bytes = bytes.slice(offset, offset + size);\n }\n assertByteArrayHasEnoughBytesForCodec(\"addDecoderSizePrefix\", size, bytes);\n return [decoder.decode(bytes), offset + size];\n };\n if (isFixedSize(prefix) && isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });\n }\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;\n const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : decoder.maxSize ?? null;\n const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;\n return createDecoder({ ...decoder, ...maxSize !== null ? { maxSize } : {}, read });\n}\nfunction addCodecSizePrefix(codec, prefix) {\n return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));\n}\n\n// src/fix-codec-size.ts\nfunction fixEncoderSize(encoder, fixedBytes) {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value, bytes, offset) => {\n const variableByteArray = encoder.encode(value);\n const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n }\n });\n}\nfunction fixDecoderSize(decoder, fixedBytes) {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes, offset) => {\n assertByteArrayHasEnoughBytesForCodec(\"fixCodecSize\", fixedBytes, bytes, offset);\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n }\n });\n}\nfunction fixCodecSize(codec, fixedBytes) {\n return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(codec, fixedBytes));\n}\n\n// src/offset-codec.ts\nfunction offsetEncoder(encoder, config) {\n return createEncoder({\n ...encoder,\n write: (value, bytes, preOffset) => {\n const wrapBytes = (offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange(\"offsetEncoder\", newPreOffset, bytes.length);\n const postOffset = encoder.write(value, bytes, newPreOffset);\n const newPostOffset = config.postOffset ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes }) : postOffset;\n assertByteArrayOffsetIsNotOutOfRange(\"offsetEncoder\", newPostOffset, bytes.length);\n return newPostOffset;\n }\n });\n}\nfunction offsetDecoder(decoder, config) {\n return createDecoder({\n ...decoder,\n read: (bytes, preOffset) => {\n const wrapBytes = (offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange(\"offsetDecoder\", newPreOffset, bytes.length);\n const [value, postOffset] = decoder.read(bytes, newPreOffset);\n const newPostOffset = config.postOffset ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes }) : postOffset;\n assertByteArrayOffsetIsNotOutOfRange(\"offsetDecoder\", newPostOffset, bytes.length);\n return [value, newPostOffset];\n }\n });\n}\nfunction offsetCodec(codec, config) {\n return combineCodec(offsetEncoder(codec, config), offsetDecoder(codec, config));\n}\nfunction modulo(dividend, divisor) {\n if (divisor === 0) return 0;\n return (dividend % divisor + divisor) % divisor;\n}\nfunction resizeEncoder(encoder, resize) {\n if (isFixedSize(encoder)) {\n const fixedSize = resize(encoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: \"resizeEncoder\"\n });\n }\n return createEncoder({ ...encoder, fixedSize });\n }\n return createEncoder({\n ...encoder,\n getSizeFromValue: (value) => {\n const newSize = resize(encoder.getSizeFromValue(value));\n if (newSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: newSize,\n codecDescription: \"resizeEncoder\"\n });\n }\n return newSize;\n }\n });\n}\nfunction resizeDecoder(decoder, resize) {\n if (isFixedSize(decoder)) {\n const fixedSize = resize(decoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: \"resizeDecoder\"\n });\n }\n return createDecoder({ ...decoder, fixedSize });\n }\n return decoder;\n}\nfunction resizeCodec(codec, resize) {\n return combineCodec(resizeEncoder(codec, resize), resizeDecoder(codec, resize));\n}\n\n// src/pad-codec.ts\nfunction padLeftEncoder(encoder, offset) {\n return offsetEncoder(\n resizeEncoder(encoder, (size) => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset }\n );\n}\nfunction padRightEncoder(encoder, offset) {\n return offsetEncoder(\n resizeEncoder(encoder, (size) => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset }\n );\n}\nfunction padLeftDecoder(decoder, offset) {\n return offsetDecoder(\n resizeDecoder(decoder, (size) => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset }\n );\n}\nfunction padRightDecoder(decoder, offset) {\n return offsetDecoder(\n resizeDecoder(decoder, (size) => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset }\n );\n}\nfunction padLeftCodec(codec, offset) {\n return combineCodec(padLeftEncoder(codec, offset), padLeftDecoder(codec, offset));\n}\nfunction padRightCodec(codec, offset) {\n return combineCodec(padRightEncoder(codec, offset), padRightDecoder(codec, offset));\n}\n\n// src/reverse-codec.ts\nfunction copySourceToTargetInReverse(source, target_WILL_MUTATE, sourceOffset, sourceLength, targetOffset = 0) {\n while (sourceOffset < --sourceLength) {\n const leftValue = source[sourceOffset];\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceLength];\n target_WILL_MUTATE[sourceLength + targetOffset] = leftValue;\n sourceOffset++;\n }\n if (sourceOffset === sourceLength) {\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceOffset];\n }\n}\nfunction reverseEncoder(encoder) {\n assertIsFixedSize(encoder);\n return createEncoder({\n ...encoder,\n write: (value, bytes, offset) => {\n const newOffset = encoder.write(value, bytes, offset);\n copySourceToTargetInReverse(\n bytes,\n bytes,\n offset,\n offset + encoder.fixedSize\n );\n return newOffset;\n }\n });\n}\nfunction reverseDecoder(decoder) {\n assertIsFixedSize(decoder);\n return createDecoder({\n ...decoder,\n read: (bytes, offset) => {\n const reversedBytes = bytes.slice();\n copySourceToTargetInReverse(\n bytes,\n reversedBytes,\n offset,\n offset + decoder.fixedSize\n );\n return decoder.read(reversedBytes, offset);\n }\n });\n}\nfunction reverseCodec(codec) {\n return combineCodec(reverseEncoder(codec), reverseDecoder(codec));\n}\n\n// src/transform-codec.ts\nfunction transformEncoder(encoder, unmap) {\n return createEncoder({\n ...isVariableSize(encoder) ? { ...encoder, getSizeFromValue: (value) => encoder.getSizeFromValue(unmap(value)) } : encoder,\n write: (value, bytes, offset) => encoder.write(unmap(value), bytes, offset)\n });\n}\nfunction transformDecoder(decoder, map) {\n return createDecoder({\n ...decoder,\n read: (bytes, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n }\n });\n}\nfunction transformCodec(codec, unmap, map) {\n return createCodec({\n ...transformEncoder(codec, unmap),\n read: map ? transformDecoder(codec, map).read : codec.read\n });\n}\n\nexport { addCodecSentinel, addCodecSizePrefix, addDecoderSentinel, addDecoderSizePrefix, addEncoderSentinel, addEncoderSizePrefix, assertByteArrayHasEnoughBytesForCodec, assertByteArrayIsNotEmptyForCodec, assertByteArrayOffsetIsNotOutOfRange, assertIsFixedSize, assertIsVariableSize, combineCodec, containsBytes, createCodec, createDecoder, createEncoder, fixBytes, fixCodecSize, fixDecoderSize, fixEncoderSize, getEncodedSize, isFixedSize, isVariableSize, mergeBytes, offsetCodec, offsetDecoder, offsetEncoder, padBytes, padLeftCodec, padLeftDecoder, padLeftEncoder, padRightCodec, padRightDecoder, padRightEncoder, resizeCodec, resizeDecoder, resizeEncoder, reverseCodec, reverseDecoder, reverseEncoder, transformCodec, transformDecoder, transformEncoder };\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map","import { SolanaError, SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE } from '@solana/errors';\nimport { combineCodec, createDecoder, createEncoder, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';\n\n// src/assertions.ts\nfunction assertNumberIsBetweenForCodec(codecDescription, min, max, value) {\n if (value < min || value > max) {\n throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {\n codecDescription,\n max,\n min,\n value\n });\n }\n}\n\n// src/common.ts\nvar Endian = /* @__PURE__ */ ((Endian2) => {\n Endian2[Endian2[\"Little\"] = 0] = \"Little\";\n Endian2[Endian2[\"Big\"] = 1] = \"Big\";\n return Endian2;\n})(Endian || {});\nfunction isLittleEndian(config) {\n return config?.endian === 1 /* Big */ ? false : true;\n}\nfunction numberEncoderFactory(input) {\n return createEncoder({\n fixedSize: input.size,\n write(value, bytes, offset) {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n }\n });\n}\nfunction numberDecoderFactory(input) {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0) {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n }\n });\n}\nfunction toArrayBuffer(bytes, offset, length) {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n\n// src/f32.ts\nvar getF32Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"f32\",\n set: (view, value, le) => view.setFloat32(0, Number(value), le),\n size: 4\n});\nvar getF32Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: \"f32\",\n size: 4\n});\nvar getF32Codec = (config = {}) => combineCodec(getF32Encoder(config), getF32Decoder(config));\nvar getF64Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"f64\",\n set: (view, value, le) => view.setFloat64(0, Number(value), le),\n size: 8\n});\nvar getF64Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat64(0, le),\n name: \"f64\",\n size: 8\n});\nvar getF64Codec = (config = {}) => combineCodec(getF64Encoder(config), getF64Decoder(config));\nvar getI128Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i128\",\n range: [-BigInt(\"0x7fffffffffffffffffffffffffffffff\") - 1n, BigInt(\"0x7fffffffffffffffffffffffffffffff\")],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16\n});\nvar getI128Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigInt64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: \"i128\",\n size: 16\n});\nvar getI128Codec = (config = {}) => combineCodec(getI128Encoder(config), getI128Decoder(config));\nvar getI16Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i16\",\n range: [-Number(\"0x7fff\") - 1, Number(\"0x7fff\")],\n set: (view, value, le) => view.setInt16(0, Number(value), le),\n size: 2\n});\nvar getI16Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getInt16(0, le),\n name: \"i16\",\n size: 2\n});\nvar getI16Codec = (config = {}) => combineCodec(getI16Encoder(config), getI16Decoder(config));\nvar getI32Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i32\",\n range: [-Number(\"0x7fffffff\") - 1, Number(\"0x7fffffff\")],\n set: (view, value, le) => view.setInt32(0, Number(value), le),\n size: 4\n});\nvar getI32Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getInt32(0, le),\n name: \"i32\",\n size: 4\n});\nvar getI32Codec = (config = {}) => combineCodec(getI32Encoder(config), getI32Decoder(config));\nvar getI64Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"i64\",\n range: [-BigInt(\"0x7fffffffffffffff\") - 1n, BigInt(\"0x7fffffffffffffff\")],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8\n});\nvar getI64Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: \"i64\",\n size: 8\n});\nvar getI64Codec = (config = {}) => combineCodec(getI64Encoder(config), getI64Decoder(config));\nvar getI8Encoder = () => numberEncoderFactory({\n name: \"i8\",\n range: [-Number(\"0x7f\") - 1, Number(\"0x7f\")],\n set: (view, value) => view.setInt8(0, Number(value)),\n size: 1\n});\nvar getI8Decoder = () => numberDecoderFactory({\n get: (view) => view.getInt8(0),\n name: \"i8\",\n size: 1\n});\nvar getI8Codec = () => combineCodec(getI8Encoder(), getI8Decoder());\nvar getShortU16Encoder = () => createEncoder({\n getSizeFromValue: (value) => {\n if (value <= 127) return 1;\n if (value <= 16383) return 2;\n return 3;\n },\n maxSize: 3,\n write: (value, bytes, offset) => {\n assertNumberIsBetweenForCodec(\"shortU16\", 0, 65535, value);\n const shortU16Bytes = [0];\n for (let ii = 0; ; ii += 1) {\n const alignedValue = Number(value) >> ii * 7;\n if (alignedValue === 0) {\n break;\n }\n const nextSevenBits = 127 & alignedValue;\n shortU16Bytes[ii] = nextSevenBits;\n if (ii > 0) {\n shortU16Bytes[ii - 1] |= 128;\n }\n }\n bytes.set(shortU16Bytes, offset);\n return offset + shortU16Bytes.length;\n }\n});\nvar getShortU16Decoder = () => createDecoder({\n maxSize: 3,\n read: (bytes, offset) => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 127 & currentByte;\n value |= nextSevenBits << byteIndex * 7;\n if ((currentByte & 128) === 0) {\n break;\n }\n }\n return [value, offset + byteCount];\n }\n});\nvar getShortU16Codec = () => combineCodec(getShortU16Encoder(), getShortU16Decoder());\nvar getU128Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u128\",\n range: [0n, BigInt(\"0xffffffffffffffffffffffffffffffff\")],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16\n});\nvar getU128Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: \"u128\",\n size: 16\n});\nvar getU128Codec = (config = {}) => combineCodec(getU128Encoder(config), getU128Decoder(config));\nvar getU16Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u16\",\n range: [0, Number(\"0xffff\")],\n set: (view, value, le) => view.setUint16(0, Number(value), le),\n size: 2\n});\nvar getU16Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: \"u16\",\n size: 2\n});\nvar getU16Codec = (config = {}) => combineCodec(getU16Encoder(config), getU16Decoder(config));\nvar getU32Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u32\",\n range: [0, Number(\"0xffffffff\")],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n size: 4\n});\nvar getU32Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getUint32(0, le),\n name: \"u32\",\n size: 4\n});\nvar getU32Codec = (config = {}) => combineCodec(getU32Encoder(config), getU32Decoder(config));\nvar getU64Encoder = (config = {}) => numberEncoderFactory({\n config,\n name: \"u64\",\n range: [0n, BigInt(\"0xffffffffffffffff\")],\n set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),\n size: 8\n});\nvar getU64Decoder = (config = {}) => numberDecoderFactory({\n config,\n get: (view, le) => view.getBigUint64(0, le),\n name: \"u64\",\n size: 8\n});\nvar getU64Codec = (config = {}) => combineCodec(getU64Encoder(config), getU64Decoder(config));\nvar getU8Encoder = () => numberEncoderFactory({\n name: \"u8\",\n range: [0, Number(\"0xff\")],\n set: (view, value) => view.setUint8(0, Number(value)),\n size: 1\n});\nvar getU8Decoder = () => numberDecoderFactory({\n get: (view) => view.getUint8(0),\n name: \"u8\",\n size: 1\n});\nvar getU8Codec = () => combineCodec(getU8Encoder(), getU8Decoder());\n\nexport { Endian, assertNumberIsBetweenForCodec, getF32Codec, getF32Decoder, getF32Encoder, getF64Codec, getF64Decoder, getF64Encoder, getI128Codec, getI128Decoder, getI128Encoder, getI16Codec, getI16Decoder, getI16Encoder, getI32Codec, getI32Decoder, getI32Encoder, getI64Codec, getI64Decoder, getI64Encoder, getI8Codec, getI8Decoder, getI8Encoder, getShortU16Codec, getShortU16Decoder, getShortU16Encoder, getU128Codec, getU128Decoder, getU128Encoder, getU16Codec, getU16Decoder, getU16Encoder, getU32Codec, getU32Decoder, getU32Encoder, getU64Codec, getU64Decoder, getU64Encoder, getU8Codec, getU8Decoder, getU8Encoder };\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map","/**\n * A `StructFailure` represents a single specific failure in validation.\n */\n/**\n * `StructError` objects are thrown (or returned) when validation fails.\n *\n * Validation logic is design to exit early for maximum performance. The error\n * represents the first error encountered during validation. For more detail,\n * the `error.failures` property is a generator function that can be run to\n * continue validation and receive all the failures in the data.\n */\nclass StructError extends TypeError {\n constructor(failure, failures) {\n let cached;\n const { message, explanation, ...rest } = failure;\n const { path } = failure;\n const msg = path.length === 0 ? message : `At path: ${path.join('.')} -- ${message}`;\n super(explanation ?? msg);\n if (explanation != null)\n this.cause = msg;\n Object.assign(this, rest);\n this.name = this.constructor.name;\n this.failures = () => {\n return (cached ?? (cached = [failure, ...failures()]));\n };\n }\n}\n\n/**\n * Check if a value is an iterator.\n */\nfunction isIterable(x) {\n return isObject(x) && typeof x[Symbol.iterator] === 'function';\n}\n/**\n * Check if a value is a plain object.\n */\nfunction isObject(x) {\n return typeof x === 'object' && x != null;\n}\n/**\n * Check if a value is a non-array object.\n */\nfunction isNonArrayObject(x) {\n return isObject(x) && !Array.isArray(x);\n}\n/**\n * Check if a value is a plain object.\n */\nfunction isPlainObject(x) {\n if (Object.prototype.toString.call(x) !== '[object Object]') {\n return false;\n }\n const prototype = Object.getPrototypeOf(x);\n return prototype === null || prototype === Object.prototype;\n}\n/**\n * Return a value as a printable string.\n */\nfunction print(value) {\n if (typeof value === 'symbol') {\n return value.toString();\n }\n return typeof value === 'string' ? JSON.stringify(value) : `${value}`;\n}\n/**\n * Shifts (removes and returns) the first value from the `input` iterator.\n * Like `Array.prototype.shift()` but for an `Iterator`.\n */\nfunction shiftIterator(input) {\n const { done, value } = input.next();\n return done ? undefined : value;\n}\n/**\n * Convert a single validation result to a failure.\n */\nfunction toFailure(result, context, struct, value) {\n if (result === true) {\n return;\n }\n else if (result === false) {\n result = {};\n }\n else if (typeof result === 'string') {\n result = { message: result };\n }\n const { path, branch } = context;\n const { type } = struct;\n const { refinement, message = `Expected a value of type \\`${type}\\`${refinement ? ` with refinement \\`${refinement}\\`` : ''}, but received: \\`${print(value)}\\``, } = result;\n return {\n value,\n type,\n refinement,\n key: path[path.length - 1],\n path,\n branch,\n ...result,\n message,\n };\n}\n/**\n * Convert a validation result to an iterable of failures.\n */\nfunction* toFailures(result, context, struct, value) {\n if (!isIterable(result)) {\n result = [result];\n }\n for (const r of result) {\n const failure = toFailure(r, context, struct, value);\n if (failure) {\n yield failure;\n }\n }\n}\n/**\n * Check a value against a struct, traversing deeply into nested values, and\n * returning an iterator of failures or success.\n */\nfunction* run(value, struct, options = {}) {\n const { path = [], branch = [value], coerce = false, mask = false } = options;\n const ctx = { path, branch, mask };\n if (coerce) {\n value = struct.coercer(value, ctx);\n }\n let status = 'valid';\n for (const failure of struct.validator(value, ctx)) {\n failure.explanation = options.message;\n status = 'not_valid';\n yield [failure, undefined];\n }\n for (let [k, v, s] of struct.entries(value, ctx)) {\n const ts = run(v, s, {\n path: k === undefined ? path : [...path, k],\n branch: k === undefined ? branch : [...branch, v],\n coerce,\n mask,\n message: options.message,\n });\n for (const t of ts) {\n if (t[0]) {\n status = t[0].refinement != null ? 'not_refined' : 'not_valid';\n yield [t[0], undefined];\n }\n else if (coerce) {\n v = t[1];\n if (k === undefined) {\n value = v;\n }\n else if (value instanceof Map) {\n value.set(k, v);\n }\n else if (value instanceof Set) {\n value.add(v);\n }\n else if (isObject(value)) {\n if (v !== undefined || k in value)\n value[k] = v;\n }\n }\n }\n }\n if (status !== 'not_valid') {\n for (const failure of struct.refiner(value, ctx)) {\n failure.explanation = options.message;\n status = 'not_refined';\n yield [failure, undefined];\n }\n }\n if (status === 'valid') {\n yield [undefined, value];\n }\n}\n\n/**\n * `Struct` objects encapsulate the validation logic for a specific type of\n * values. Once constructed, you use the `assert`, `is` or `validate` helpers to\n * validate unknown input data against the struct.\n */\nclass Struct {\n constructor(props) {\n const { type, schema, validator, refiner, coercer = (value) => value, entries = function* () { }, } = props;\n this.type = type;\n this.schema = schema;\n this.entries = entries;\n this.coercer = coercer;\n if (validator) {\n this.validator = (value, context) => {\n const result = validator(value, context);\n return toFailures(result, context, this, value);\n };\n }\n else {\n this.validator = () => [];\n }\n if (refiner) {\n this.refiner = (value, context) => {\n const result = refiner(value, context);\n return toFailures(result, context, this, value);\n };\n }\n else {\n this.refiner = () => [];\n }\n }\n /**\n * Assert that a value passes the struct's validation, throwing if it doesn't.\n */\n assert(value, message) {\n return assert(value, this, message);\n }\n /**\n * Create a value with the struct's coercion logic, then validate it.\n */\n create(value, message) {\n return create(value, this, message);\n }\n /**\n * Check if a value passes the struct's validation.\n */\n is(value) {\n return is(value, this);\n }\n /**\n * Mask a value, coercing and validating it, but returning only the subset of\n * properties defined by the struct's schema. Masking applies recursively to\n * props of `object` structs only.\n */\n mask(value, message) {\n return mask(value, this, message);\n }\n /**\n * Validate a value with the struct's validation logic, returning a tuple\n * representing the result.\n *\n * You may optionally pass `true` for the `coerce` argument to coerce\n * the value before attempting to validate it. If you do, the result will\n * contain the coerced result when successful. Also, `mask` will turn on\n * masking of the unknown `object` props recursively if passed.\n */\n validate(value, options = {}) {\n return validate(value, this, options);\n }\n}\n/**\n * Assert that a value passes a struct, throwing if it doesn't.\n */\nfunction assert(value, struct, message) {\n const result = validate(value, struct, { message });\n if (result[0]) {\n throw result[0];\n }\n}\n/**\n * Create a value with the coercion logic of struct and validate it.\n */\nfunction create(value, struct, message) {\n const result = validate(value, struct, { coerce: true, message });\n if (result[0]) {\n throw result[0];\n }\n else {\n return result[1];\n }\n}\n/**\n * Mask a value, returning only the subset of properties defined by a struct.\n */\nfunction mask(value, struct, message) {\n const result = validate(value, struct, { coerce: true, mask: true, message });\n if (result[0]) {\n throw result[0];\n }\n else {\n return result[1];\n }\n}\n/**\n * Check if a value passes a struct.\n */\nfunction is(value, struct) {\n const result = validate(value, struct);\n return !result[0];\n}\n/**\n * Validate a value against a struct, returning an error if invalid, or the\n * value (with potential coercion) if valid.\n */\nfunction validate(value, struct, options = {}) {\n const tuples = run(value, struct, options);\n const tuple = shiftIterator(tuples);\n if (tuple[0]) {\n const error = new StructError(tuple[0], function* () {\n for (const t of tuples) {\n if (t[0]) {\n yield t[0];\n }\n }\n });\n return [error, undefined];\n }\n else {\n const v = tuple[1];\n return [undefined, v];\n }\n}\n\nfunction assign(...Structs) {\n const isType = Structs[0].type === 'type';\n const schemas = Structs.map((s) => s.schema);\n const schema = Object.assign({}, ...schemas);\n return isType ? type(schema) : object(schema);\n}\n/**\n * Define a new struct type with a custom validation function.\n */\nfunction define(name, validator) {\n return new Struct({ type: name, schema: null, validator });\n}\n/**\n * Create a new struct based on an existing struct, but the value is allowed to\n * be `undefined`. `log` will be called if the value is not `undefined`.\n */\nfunction deprecated(struct, log) {\n return new Struct({\n ...struct,\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx),\n validator(value, ctx) {\n if (value === undefined) {\n return true;\n }\n else {\n log(value, ctx);\n return struct.validator(value, ctx);\n }\n },\n });\n}\n/**\n * Create a struct with dynamic validation logic.\n *\n * The callback will receive the value currently being validated, and must\n * return a struct object to validate it with. This can be useful to model\n * validation logic that changes based on its input.\n */\nfunction dynamic(fn) {\n return new Struct({\n type: 'dynamic',\n schema: null,\n *entries(value, ctx) {\n const struct = fn(value, ctx);\n yield* struct.entries(value, ctx);\n },\n validator(value, ctx) {\n const struct = fn(value, ctx);\n return struct.validator(value, ctx);\n },\n coercer(value, ctx) {\n const struct = fn(value, ctx);\n return struct.coercer(value, ctx);\n },\n refiner(value, ctx) {\n const struct = fn(value, ctx);\n return struct.refiner(value, ctx);\n },\n });\n}\n/**\n * Create a struct with lazily evaluated validation logic.\n *\n * The first time validation is run with the struct, the callback will be called\n * and must return a struct object to use. This is useful for cases where you\n * want to have self-referential structs for nested data structures to avoid a\n * circular definition problem.\n */\nfunction lazy(fn) {\n let struct;\n return new Struct({\n type: 'lazy',\n schema: null,\n *entries(value, ctx) {\n struct ?? (struct = fn());\n yield* struct.entries(value, ctx);\n },\n validator(value, ctx) {\n struct ?? (struct = fn());\n return struct.validator(value, ctx);\n },\n coercer(value, ctx) {\n struct ?? (struct = fn());\n return struct.coercer(value, ctx);\n },\n refiner(value, ctx) {\n struct ?? (struct = fn());\n return struct.refiner(value, ctx);\n },\n });\n}\n/**\n * Create a new struct based on an existing object struct, but excluding\n * specific properties.\n *\n * Like TypeScript's `Omit` utility.\n */\nfunction omit(struct, keys) {\n const { schema } = struct;\n const subschema = { ...schema };\n for (const key of keys) {\n delete subschema[key];\n }\n switch (struct.type) {\n case 'type':\n return type(subschema);\n default:\n return object(subschema);\n }\n}\n/**\n * Create a new struct based on an existing object struct, but with all of its\n * properties allowed to be `undefined`.\n *\n * Like TypeScript's `Partial` utility.\n */\nfunction partial(struct) {\n const isStruct = struct instanceof Struct;\n const schema = isStruct ? { ...struct.schema } : { ...struct };\n for (const key in schema) {\n schema[key] = optional(schema[key]);\n }\n if (isStruct && struct.type === 'type') {\n return type(schema);\n }\n return object(schema);\n}\n/**\n * Create a new struct based on an existing object struct, but only including\n * specific properties.\n *\n * Like TypeScript's `Pick` utility.\n */\nfunction pick(struct, keys) {\n const { schema } = struct;\n const subschema = {};\n for (const key of keys) {\n subschema[key] = schema[key];\n }\n switch (struct.type) {\n case 'type':\n return type(subschema);\n default:\n return object(subschema);\n }\n}\n/**\n * Define a new struct type with a custom validation function.\n *\n * @deprecated This function has been renamed to `define`.\n */\nfunction struct(name, validator) {\n console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.');\n return define(name, validator);\n}\n\n/**\n * Ensure that any value passes validation.\n */\nfunction any() {\n return define('any', () => true);\n}\nfunction array(Element) {\n return new Struct({\n type: 'array',\n schema: Element,\n *entries(value) {\n if (Element && Array.isArray(value)) {\n for (const [i, v] of value.entries()) {\n yield [i, v, Element];\n }\n }\n },\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n validator(value) {\n return (Array.isArray(value) ||\n `Expected an array value, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a bigint.\n */\nfunction bigint() {\n return define('bigint', (value) => {\n return typeof value === 'bigint';\n });\n}\n/**\n * Ensure that a value is a boolean.\n */\nfunction boolean() {\n return define('boolean', (value) => {\n return typeof value === 'boolean';\n });\n}\n/**\n * Ensure that a value is a valid `Date`.\n *\n * Note: this also ensures that the value is *not* an invalid `Date` object,\n * which can occur when parsing a date fails but still returns a `Date`.\n */\nfunction date() {\n return define('date', (value) => {\n return ((value instanceof Date && !isNaN(value.getTime())) ||\n `Expected a valid \\`Date\\` object, but received: ${print(value)}`);\n });\n}\nfunction enums(values) {\n const schema = {};\n const description = values.map((v) => print(v)).join();\n for (const key of values) {\n schema[key] = key;\n }\n return new Struct({\n type: 'enums',\n schema,\n validator(value) {\n return (values.includes(value) ||\n `Expected one of \\`${description}\\`, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a function.\n */\nfunction func() {\n return define('func', (value) => {\n return (typeof value === 'function' ||\n `Expected a function, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is an instance of a specific class.\n */\nfunction instance(Class) {\n return define('instance', (value) => {\n return (value instanceof Class ||\n `Expected a \\`${Class.name}\\` instance, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is an integer.\n */\nfunction integer() {\n return define('integer', (value) => {\n return ((typeof value === 'number' && !isNaN(value) && Number.isInteger(value)) ||\n `Expected an integer, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value matches all of a set of types.\n */\nfunction intersection(Structs) {\n return new Struct({\n type: 'intersection',\n schema: null,\n *entries(value, ctx) {\n for (const S of Structs) {\n yield* S.entries(value, ctx);\n }\n },\n *validator(value, ctx) {\n for (const S of Structs) {\n yield* S.validator(value, ctx);\n }\n },\n *refiner(value, ctx) {\n for (const S of Structs) {\n yield* S.refiner(value, ctx);\n }\n },\n });\n}\nfunction literal(constant) {\n const description = print(constant);\n const t = typeof constant;\n return new Struct({\n type: 'literal',\n schema: t === 'string' || t === 'number' || t === 'boolean' ? constant : null,\n validator(value) {\n return (value === constant ||\n `Expected the literal \\`${description}\\`, but received: ${print(value)}`);\n },\n });\n}\nfunction map(Key, Value) {\n return new Struct({\n type: 'map',\n schema: null,\n *entries(value) {\n if (Key && Value && value instanceof Map) {\n for (const [k, v] of value.entries()) {\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n coercer(value) {\n return value instanceof Map ? new Map(value) : value;\n },\n validator(value) {\n return (value instanceof Map ||\n `Expected a \\`Map\\` object, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that no value ever passes validation.\n */\nfunction never() {\n return define('never', () => false);\n}\n/**\n * Augment an existing struct to allow `null` values.\n */\nfunction nullable(struct) {\n return new Struct({\n ...struct,\n validator: (value, ctx) => value === null || struct.validator(value, ctx),\n refiner: (value, ctx) => value === null || struct.refiner(value, ctx),\n });\n}\n/**\n * Ensure that a value is a number.\n */\nfunction number() {\n return define('number', (value) => {\n return ((typeof value === 'number' && !isNaN(value)) ||\n `Expected a number, but received: ${print(value)}`);\n });\n}\nfunction object(schema) {\n const knowns = schema ? Object.keys(schema) : [];\n const Never = never();\n return new Struct({\n type: 'object',\n schema: schema ? schema : null,\n *entries(value) {\n if (schema && isObject(value)) {\n const unknowns = new Set(Object.keys(value));\n for (const key of knowns) {\n unknowns.delete(key);\n yield [key, value[key], schema[key]];\n }\n for (const key of unknowns) {\n yield [key, value[key], Never];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value, ctx) {\n if (!isNonArrayObject(value)) {\n return value;\n }\n const coerced = { ...value };\n // The `object` struct has special behaviour enabled by the mask flag.\n // When masking, properties that are not in the schema are deleted from\n // the coerced object instead of eventually failing validaiton.\n if (ctx.mask && schema) {\n for (const key in coerced) {\n if (schema[key] === undefined) {\n delete coerced[key];\n }\n }\n }\n return coerced;\n },\n });\n}\n/**\n * Augment a struct to allow `undefined` values.\n */\nfunction optional(struct) {\n return new Struct({\n ...struct,\n validator: (value, ctx) => value === undefined || struct.validator(value, ctx),\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx),\n });\n}\n/**\n * Ensure that a value is an object with keys and values of specific types, but\n * without ensuring any specific shape of properties.\n *\n * Like TypeScript's `Record` utility.\n */\nfunction record(Key, Value) {\n return new Struct({\n type: 'record',\n schema: null,\n *entries(value) {\n if (isObject(value)) {\n for (const k in value) {\n const v = value[k];\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value) {\n return isNonArrayObject(value) ? { ...value } : value;\n },\n });\n}\n/**\n * Ensure that a value is a `RegExp`.\n *\n * Note: this does not test the value against the regular expression! For that\n * you need to use the `pattern()` refinement.\n */\nfunction regexp() {\n return define('regexp', (value) => {\n return value instanceof RegExp;\n });\n}\nfunction set(Element) {\n return new Struct({\n type: 'set',\n schema: null,\n *entries(value) {\n if (Element && value instanceof Set) {\n for (const v of value) {\n yield [v, v, Element];\n }\n }\n },\n coercer(value) {\n return value instanceof Set ? new Set(value) : value;\n },\n validator(value) {\n return (value instanceof Set ||\n `Expected a \\`Set\\` object, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a string.\n */\nfunction string() {\n return define('string', (value) => {\n return (typeof value === 'string' ||\n `Expected a string, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is a tuple of a specific length, and that each of its\n * elements is of a specific type.\n */\nfunction tuple(Structs) {\n const Never = never();\n return new Struct({\n type: 'tuple',\n schema: null,\n *entries(value) {\n if (Array.isArray(value)) {\n const length = Math.max(Structs.length, value.length);\n for (let i = 0; i < length; i++) {\n yield [i, value[i], Structs[i] || Never];\n }\n }\n },\n validator(value) {\n return (Array.isArray(value) ||\n `Expected an array, but received: ${print(value)}`);\n },\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n });\n}\n/**\n * Ensure that a value has a set of known properties of specific types.\n *\n * Note: Unrecognized properties are allowed and untouched. This is similar to\n * how TypeScript's structural typing works.\n */\nfunction type(schema) {\n const keys = Object.keys(schema);\n return new Struct({\n type: 'type',\n schema,\n *entries(value) {\n if (isObject(value)) {\n for (const k of keys) {\n yield [k, value[k], schema[k]];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value) {\n return isNonArrayObject(value) ? { ...value } : value;\n },\n });\n}\n/**\n * Ensure that a value matches one of a set of types.\n */\nfunction union(Structs) {\n const description = Structs.map((s) => s.type).join(' | ');\n return new Struct({\n type: 'union',\n schema: null,\n coercer(value, ctx) {\n for (const S of Structs) {\n const [error, coerced] = S.validate(value, {\n coerce: true,\n mask: ctx.mask,\n });\n if (!error) {\n return coerced;\n }\n }\n return value;\n },\n validator(value, ctx) {\n const failures = [];\n for (const S of Structs) {\n const [...tuples] = run(value, S, ctx);\n const [first] = tuples;\n if (!first[0]) {\n return [];\n }\n else {\n for (const [failure] of tuples) {\n if (failure) {\n failures.push(failure);\n }\n }\n }\n }\n return [\n `Expected the value to satisfy a union of \\`${description}\\`, but received: ${print(value)}`,\n ...failures,\n ];\n },\n });\n}\n/**\n * Ensure that any value passes validation, without widening its type to `any`.\n */\nfunction unknown() {\n return define('unknown', () => true);\n}\n\n/**\n * Augment a `Struct` to add an additional coercion step to its input.\n *\n * This allows you to transform input data before validating it, to increase the\n * likelihood that it passes validation—for example for default values, parsing\n * different formats, etc.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction coerce(struct, condition, coercer) {\n return new Struct({\n ...struct,\n coercer: (value, ctx) => {\n return is(value, condition)\n ? struct.coercer(coercer(value, ctx), ctx)\n : struct.coercer(value, ctx);\n },\n });\n}\n/**\n * Augment a struct to replace `undefined` values with a default.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction defaulted(struct, fallback, options = {}) {\n return coerce(struct, unknown(), (x) => {\n const f = typeof fallback === 'function' ? fallback() : fallback;\n if (x === undefined) {\n return f;\n }\n if (!options.strict && isPlainObject(x) && isPlainObject(f)) {\n const ret = { ...x };\n let changed = false;\n for (const key in f) {\n if (ret[key] === undefined) {\n ret[key] = f[key];\n changed = true;\n }\n }\n if (changed) {\n return ret;\n }\n }\n return x;\n });\n}\n/**\n * Augment a struct to trim string inputs.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction trimmed(struct) {\n return coerce(struct, string(), (x) => x.trim());\n}\n\n/**\n * Ensure that a string, array, map, or set is empty.\n */\nfunction empty(struct) {\n return refine(struct, 'empty', (value) => {\n const size = getSize(value);\n return (size === 0 ||\n `Expected an empty ${struct.type} but received one with a size of \\`${size}\\``);\n });\n}\nfunction getSize(value) {\n if (value instanceof Map || value instanceof Set) {\n return value.size;\n }\n else {\n return value.length;\n }\n}\n/**\n * Ensure that a number or date is below a threshold.\n */\nfunction max(struct, threshold, options = {}) {\n const { exclusive } = options;\n return refine(struct, 'max', (value) => {\n return exclusive\n ? value < threshold\n : value <= threshold ||\n `Expected a ${struct.type} less than ${exclusive ? '' : 'or equal to '}${threshold} but received \\`${value}\\``;\n });\n}\n/**\n * Ensure that a number or date is above a threshold.\n */\nfunction min(struct, threshold, options = {}) {\n const { exclusive } = options;\n return refine(struct, 'min', (value) => {\n return exclusive\n ? value > threshold\n : value >= threshold ||\n `Expected a ${struct.type} greater than ${exclusive ? '' : 'or equal to '}${threshold} but received \\`${value}\\``;\n });\n}\n/**\n * Ensure that a string, array, map or set is not empty.\n */\nfunction nonempty(struct) {\n return refine(struct, 'nonempty', (value) => {\n const size = getSize(value);\n return (size > 0 || `Expected a nonempty ${struct.type} but received an empty one`);\n });\n}\n/**\n * Ensure that a string matches a regular expression.\n */\nfunction pattern(struct, regexp) {\n return refine(struct, 'pattern', (value) => {\n return (regexp.test(value) ||\n `Expected a ${struct.type} matching \\`/${regexp.source}/\\` but received \"${value}\"`);\n });\n}\n/**\n * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`.\n */\nfunction size(struct, min, max = min) {\n const expected = `Expected a ${struct.type}`;\n const of = min === max ? `of \\`${min}\\`` : `between \\`${min}\\` and \\`${max}\\``;\n return refine(struct, 'size', (value) => {\n if (typeof value === 'number' || value instanceof Date) {\n return ((min <= value && value <= max) ||\n `${expected} ${of} but received \\`${value}\\``);\n }\n else if (value instanceof Map || value instanceof Set) {\n const { size } = value;\n return ((min <= size && size <= max) ||\n `${expected} with a size ${of} but received one with a size of \\`${size}\\``);\n }\n else {\n const { length } = value;\n return ((min <= length && length <= max) ||\n `${expected} with a length ${of} but received one with a length of \\`${length}\\``);\n }\n });\n}\n/**\n * Augment a `Struct` to add an additional refinement to the validation.\n *\n * The refiner function is guaranteed to receive a value of the struct's type,\n * because the struct's existing validation will already have passed. This\n * allows you to layer additional validation on top of existing structs.\n */\nfunction refine(struct, name, refiner) {\n return new Struct({\n ...struct,\n *refiner(value, ctx) {\n yield* struct.refiner(value, ctx);\n const result = refiner(value, ctx);\n const failures = toFailures(result, ctx, struct, value);\n for (const failure of failures) {\n yield { ...failure, refinement: name };\n }\n },\n });\n}\n\nexport { Struct, StructError, any, array, assert, assign, bigint, boolean, coerce, create, date, defaulted, define, deprecated, dynamic, empty, enums, func, instance, integer, intersection, is, lazy, literal, map, mask, max, min, never, nonempty, nullable, number, object, omit, optional, partial, pattern, pick, record, refine, regexp, set, size, string, struct, trimmed, tuple, type, union, unknown, validate };\n//# sourceMappingURL=index.mjs.map\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createHasher, createXOFer, Hash, swap32IfBE, toBytes, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/** Keccak sponge function. */\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n this.enableXOF = false;\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));\n/** SHA3-224 hash function. */\nexport const sha3_224 = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\nconst genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n//# sourceMappingURL=sha3.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes } from \"./utils.js\";\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils';\nimport { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from \"../utils.js\";\nimport { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from \"./curve.js\";\nimport { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from \"./modular.js\";\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k, basis, n) {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n const optsn = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS, 'lowS');\n abool(optsn.prehash, 'prehash');\n if (optsn.format !== undefined)\n validateSigFormat(optsn.format);\n return optsn;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function _normFnElement(Fn, key) {\n const { BYTES: expected } = Fn;\n let num;\n if (typeof key === 'bigint') {\n num = key;\n }\n else {\n let bytes = ensureBytes('private key', key);\n try {\n num = Fn.fromBytes(bytes);\n }\n catch (error) {\n throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);\n }\n }\n if (!Fn.isValidNot0(num))\n throw new Error('invalid private key: out of range [1..N-1]');\n return num;\n}\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * @example\n```js\nconst opts = {\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n};\nconst p256_Point = weierstrass(opts);\n```\n */\nexport function weierstrassN(params, extraOpts = {}) {\n const validated = _createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n _validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n wrapPrivateKey: 'boolean',\n });\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd(y);\n return concatBytes(pprefix(hasEvenY), bx);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;\n const isHeadOdd = (head & 1) === 1; // ECDSA-specific\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n const toAffineMemo = memoized((p, iz) => {\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(ensureBytes('pointHex', hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo } = extraOpts;\n if (!Fn.isValidNot0(scalar))\n throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point, fake; // Fake point is used to const-time mult\n const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n }\n else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n const { endo } = extraOpts;\n const p = this;\n if (!Fn.isValid(sc))\n throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p; // fast-path\n if (wnaf.hasCache(this))\n return this.multiply(sc);\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n }\n else {\n return wnaf.unsafe(p, sc);\n }\n }\n multiplyAndAddUnsafe(Q, a, b) {\n const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));\n return sum.is0() ? undefined : sum;\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n return toAffineMemo(this, invertedZ);\n }\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree() {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(cofactor);\n }\n isSmallOrder() {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n toBytes(isCompressed = true) {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return ``;\n }\n // TODO: remove\n get px() {\n return this.X;\n }\n get py() {\n return this.X;\n }\n get pz() {\n return this.Z;\n }\n toRawBytes(isCompressed = true) {\n return this.toBytes(isCompressed);\n }\n _setWindowSize(windowSize) {\n this.precompute(windowSize);\n }\n static normalizeZ(points) {\n return normalizeZ(Point, points);\n }\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(_normFnElement(Fn, privateKey));\n }\n }\n // base / generator point\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n Point.Fp = Fp;\n // scalar field\n Point.Fn = Fn;\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\nfunction getWLengths(Fp, Fn) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n function isValidSecretKey(secretKey) {\n try {\n return !!_normFnElement(Fn, secretKey);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n return !!Point.fromBytes(publicKey);\n }\n catch (error) {\n return false;\n }\n }\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)) {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey, isCompressed = true) {\n return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);\n }\n function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n if (typeof item === 'bigint')\n return false;\n if (item instanceof Point)\n return true;\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (Fn.allowedLengths || secretKey === publicKey)\n return undefined;\n const l = ensureBytes('key', item).length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n throw new Error('second arg must be public key');\n const s = _normFnElement(Fn, secretKeyA);\n const b = Point.fromHex(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n // TODO: remove\n isValidPrivateKey: isValidSecretKey,\n randomPrivateKey: randomSecretKey,\n normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),\n precompute(windowSize = 8, point = Point.BASE) {\n return point.precompute(windowSize, false);\n },\n };\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n * We need `hash` for 2 features:\n * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`\n * 2. k generation in `sign`, using HMAC-drbg(hash)\n *\n * ECDSAOpts are only rarely needed.\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n ahash(hash);\n _validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;\n const hmac = ecdsaOpts.hmac ||\n ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts = {\n prehash: false,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,\n format: undefined, //'compact' as ECDSASigFormat,\n extraEntropy: false,\n };\n const defaultSigOpts_format = 'compact';\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function validateSigLength(bytes, format) {\n validateSigFormat(format);\n const size = lengths.signature;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer, `${format} signature`);\n }\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null)\n this.recovery = recovery;\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts_format) {\n validateSigLength(bytes, format);\n let recid;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = Fn.BYTES;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(messageHash) {\n const FIELD_ORDER = Fp.ORDER;\n const { r, s, recovery: rec } = this;\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;\n if (hasCofactor && rec > 1)\n throw new Error('recovery id is ambiguous for h>1 curve');\n const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj))\n throw new Error('recovery id 2 or 3 invalid');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0())\n throw new Error('point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts_format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\n const r = Fn.toBytes(this.r);\n const s = Fn.toBytes(this.s);\n if (format === 'recovered') {\n if (this.recovery == null)\n throw new Error('recovery bit must be present');\n return concatBytes(Uint8Array.of(this.recovery), r, s);\n }\n return concatBytes(r, s);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n // TODO: remove\n assertValidity() { }\n static fromCompact(hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'compact');\n }\n static fromDER(hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'der');\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;\n }\n toDERRawBytes() {\n return this.toBytes('der');\n }\n toDERHex() {\n return bytesToHex(this.toBytes('der'));\n }\n toCompactRawBytes() {\n return this.toBytes('compact');\n }\n toCompactHex() {\n return bytesToHex(this.toBytes('compact'));\n }\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = ecdsaOpts.bits2int ||\n function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num) {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message, privateKey, opts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // mod n, not mod p\n if (!Fn.isValidNot0(k))\n return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n message = ensureBytes('message', message);\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig;\n }\n function tryParsingSig(sg) {\n // Try to deduce format\n let sig = undefined;\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj = !isHex &&\n sg !== null &&\n typeof sg === 'object' &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n if (isObj) {\n sig = new Signature(sg.r, sg.s);\n }\n else if (isHex) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n }\n if (!sig) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');\n }\n catch (error) {\n return false;\n }\n }\n }\n if (!sig)\n return false;\n return sig;\n }\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = ensureBytes('publicKey', publicKey);\n message = validateMsgAndHash(ensureBytes('message', message), prehash);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const sig = format === undefined\n ? tryParsingSig(signature)\n : Signature.fromBytes(ensureBytes('sig', signature), format);\n if (sig === false)\n return false;\n try {\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS())\n return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0())\n return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n });\n}\n/** @deprecated use `weierstrass` in newer releases */\nexport function weierstrassPoints(c) {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n return _weierstrass_new_output_to_legacy(c, Point);\n}\nfunction _weierstrass_legacy_opts_to_new(c) {\n const CURVE = {\n a: c.a,\n b: c.b,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n let allowedLengths = c.allowedPrivateKeyLengths\n ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))\n : undefined;\n const Fn = Field(CURVE.n, {\n BITS: c.nBitLength,\n allowedLengths: allowedLengths,\n modFromBytes: c.wrapPrivateKey,\n });\n const curveOpts = {\n Fp,\n Fn,\n allowInfinityPoint: c.allowInfinityPoint,\n endo: c.endo,\n isTorsionFree: c.isTorsionFree,\n clearCofactor: c.clearCofactor,\n fromBytes: c.fromBytes,\n toBytes: c.toBytes,\n };\n return { CURVE, curveOpts };\n}\nfunction _ecdsa_legacy_opts_to_new(c) {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const ecdsaOpts = {\n hmac: c.hmac,\n randomBytes: c.randomBytes,\n lowS: c.lowS,\n bits2int: c.bits2int,\n bits2int_modN: c.bits2int_modN,\n };\n return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };\n}\nexport function _legacyHelperEquat(Fp, a, b) {\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².\n * @returns y²\n */\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n return weierstrassEquation;\n}\nfunction _weierstrass_new_output_to_legacy(c, Point) {\n const { Fp, Fn } = Point;\n function isWithinCurveOrder(num) {\n return inRange(num, _1n, Fn.ORDER);\n }\n const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);\n return Object.assign({}, {\n CURVE: c,\n Point: Point,\n ProjectivePoint: Point,\n normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),\n weierstrassEquation,\n isWithinCurveOrder,\n });\n}\nfunction _ecdsa_new_output_to_legacy(c, _ecdsa) {\n const Point = _ecdsa.Point;\n return Object.assign({}, _ecdsa, {\n ProjectivePoint: Point,\n CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),\n });\n}\n// _ecdsa_legacy\nexport function weierstrass(c) {\n const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n const signs = ecdsa(Point, hash, ecdsaOpts);\n return _ecdsa_new_output_to_legacy(c, signs);\n}\n//# sourceMappingURL=weierstrass.js.map","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createCurve } from \"./_shortw_utils.js\";\nimport { createHasher, isogenyMap, } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, mod, pow2 } from \"./abstract/modular.js\";\nimport { _normFnElement, mapToCurveSimpleSWU, } from \"./abstract/weierstrass.js\";\nimport { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey) === true;\n * ```\n */\nexport const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(utf8ToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();\nconst hasEven = (y) => y % _2n === _0n;\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = _normFnElement(Fn, priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x))\n throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y))\n y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey) {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n const { Fn } = Pointk1;\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const { Fn, BASE } = Pointk1;\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1_CURVE.p))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1_CURVE.n))\n return false;\n // int(challenge(bytes(r)||bytes(P)||m))%n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r)\n return false;\n return true;\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)) => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n // TODO: remove\n secp256k1.utils.randomSecretKey;\n function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };\n }\n return {\n keygen,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey: randomSecretKey,\n randomPrivateKey: randomSecretKey,\n taggedHash,\n // TODO: remove\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n mod,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\n };\n})();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n}))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { weierstrass } from \"./abstract/weierstrass.js\";\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash) {\n return { hash };\n}\n/** @deprecated use new `weierstrass()` and `ecdsa()` methods */\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, hash: hash });\n return { ...create(defHash), create };\n}\n//# sourceMappingURL=_shortw_utils.js.map","import { Buffer } from 'buffer';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport BN from 'bn.js';\nimport bs58 from 'bs58';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { serialize, deserialize, deserializeUnchecked } from 'borsh';\nimport * as BufferLayout from '@solana/buffer-layout';\nimport { blob } from '@solana/buffer-layout';\nimport { getU64Codec, getU64Encoder } from '@solana/codecs-numbers';\nimport { coerce, instance, string, tuple, literal, unknown, type, number, array, nullable, optional, boolean, record, union, create, any, assert as assert$1 } from 'superstruct';\nimport RpcClient from 'jayson/lib/client/browser';\nimport { CommonClient, WebSocket } from 'rpc-websockets';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { secp256k1 } from '@noble/curves/secp256k1';\n\n/**\n * A 64 byte secret key, the first 32 bytes of which is the\n * private scalar and the last 32 bytes is the public key.\n * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/\n */\n\n/**\n * Ed25519 Keypair\n */\n\nconst generatePrivateKey = ed25519.utils.randomPrivateKey;\nconst generateKeypair = () => {\n const privateScalar = ed25519.utils.randomPrivateKey();\n const publicKey = getPublicKey(privateScalar);\n const secretKey = new Uint8Array(64);\n secretKey.set(privateScalar);\n secretKey.set(publicKey, 32);\n return {\n publicKey,\n secretKey\n };\n};\nconst getPublicKey = ed25519.getPublicKey;\nfunction isOnCurve(publicKey) {\n try {\n ed25519.ExtendedPoint.fromHex(publicKey);\n return true;\n } catch {\n return false;\n }\n}\nconst sign = (message, secretKey) => ed25519.sign(message, secretKey.slice(0, 32));\nconst verify = ed25519.verify;\n\nconst toBuffer = arr => {\n if (Buffer.isBuffer(arr)) {\n return arr;\n } else if (arr instanceof Uint8Array) {\n return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);\n } else {\n return Buffer.from(arr);\n }\n};\n\n// Class wrapping a plain object\nclass Struct {\n constructor(properties) {\n Object.assign(this, properties);\n }\n encode() {\n return Buffer.from(serialize(SOLANA_SCHEMA, this));\n }\n static decode(data) {\n return deserialize(SOLANA_SCHEMA, this, data);\n }\n static decodeUnchecked(data) {\n return deserializeUnchecked(SOLANA_SCHEMA, this, data);\n }\n}\n\n// Class representing a Rust-compatible enum, since enums are only strings or\n// numbers in pure JS\nclass Enum extends Struct {\n constructor(properties) {\n super(properties);\n this.enum = '';\n if (Object.keys(properties).length !== 1) {\n throw new Error('Enum can only take single value');\n }\n Object.keys(properties).map(key => {\n this.enum = key;\n });\n }\n}\nconst SOLANA_SCHEMA = new Map();\n\nvar _PublicKey;\n\n/**\n * Maximum length of derived pubkey seed\n */\nconst MAX_SEED_LENGTH = 32;\n\n/**\n * Size of public key in bytes\n */\nconst PUBLIC_KEY_LENGTH = 32;\n\n/**\n * Value to be converted into public key\n */\n\n/**\n * JSON object representation of PublicKey class\n */\n\nfunction isPublicKeyData(value) {\n return value._bn !== undefined;\n}\n\n// local counter used by PublicKey.unique()\nlet uniquePublicKeyCounter = 1;\n\n/**\n * A public key\n */\nclass PublicKey extends Struct {\n /**\n * Create a new PublicKey object\n * @param value ed25519 public key as buffer or base-58 encoded string\n */\n constructor(value) {\n super({});\n /** @internal */\n this._bn = void 0;\n if (isPublicKeyData(value)) {\n this._bn = value._bn;\n } else {\n if (typeof value === 'string') {\n // assume base 58 encoding by default\n const decoded = bs58.decode(value);\n if (decoded.length != PUBLIC_KEY_LENGTH) {\n throw new Error(`Invalid public key input`);\n }\n this._bn = new BN(decoded);\n } else {\n this._bn = new BN(value);\n }\n if (this._bn.byteLength() > PUBLIC_KEY_LENGTH) {\n throw new Error(`Invalid public key input`);\n }\n }\n }\n\n /**\n * Returns a unique PublicKey for tests and benchmarks using a counter\n */\n static unique() {\n const key = new PublicKey(uniquePublicKeyCounter);\n uniquePublicKeyCounter += 1;\n return new PublicKey(key.toBuffer());\n }\n\n /**\n * Default public key value. The base58-encoded string representation is all ones (as seen below)\n * The underlying BN number is 32 bytes that are all zeros\n */\n\n /**\n * Checks if two publicKeys are equal\n */\n equals(publicKey) {\n return this._bn.eq(publicKey._bn);\n }\n\n /**\n * Return the base-58 representation of the public key\n */\n toBase58() {\n return bs58.encode(this.toBytes());\n }\n toJSON() {\n return this.toBase58();\n }\n\n /**\n * Return the byte array representation of the public key in big endian\n */\n toBytes() {\n const buf = this.toBuffer();\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n }\n\n /**\n * Return the Buffer representation of the public key in big endian\n */\n toBuffer() {\n const b = this._bn.toArrayLike(Buffer);\n if (b.length === PUBLIC_KEY_LENGTH) {\n return b;\n }\n const zeroPad = Buffer.alloc(32);\n b.copy(zeroPad, 32 - b.length);\n return zeroPad;\n }\n get [Symbol.toStringTag]() {\n return `PublicKey(${this.toString()})`;\n }\n\n /**\n * Return the base-58 representation of the public key\n */\n toString() {\n return this.toBase58();\n }\n\n /**\n * Derive a public key from another key, a seed, and a program ID.\n * The program ID will also serve as the owner of the public key, giving\n * it permission to write data to the account.\n */\n /* eslint-disable require-await */\n static async createWithSeed(fromPublicKey, seed, programId) {\n const buffer = Buffer.concat([fromPublicKey.toBuffer(), Buffer.from(seed), programId.toBuffer()]);\n const publicKeyBytes = sha256(buffer);\n return new PublicKey(publicKeyBytes);\n }\n\n /**\n * Derive a program address from seeds and a program ID.\n */\n /* eslint-disable require-await */\n static createProgramAddressSync(seeds, programId) {\n let buffer = Buffer.alloc(0);\n seeds.forEach(function (seed) {\n if (seed.length > MAX_SEED_LENGTH) {\n throw new TypeError(`Max seed length exceeded`);\n }\n buffer = Buffer.concat([buffer, toBuffer(seed)]);\n });\n buffer = Buffer.concat([buffer, programId.toBuffer(), Buffer.from('ProgramDerivedAddress')]);\n const publicKeyBytes = sha256(buffer);\n if (isOnCurve(publicKeyBytes)) {\n throw new Error(`Invalid seeds, address must fall off the curve`);\n }\n return new PublicKey(publicKeyBytes);\n }\n\n /**\n * Async version of createProgramAddressSync\n * For backwards compatibility\n *\n * @deprecated Use {@link createProgramAddressSync} instead\n */\n /* eslint-disable require-await */\n static async createProgramAddress(seeds, programId) {\n return this.createProgramAddressSync(seeds, programId);\n }\n\n /**\n * Find a valid program address\n *\n * Valid program addresses must fall off the ed25519 curve. This function\n * iterates a nonce until it finds one that when combined with the seeds\n * results in a valid program address.\n */\n static findProgramAddressSync(seeds, programId) {\n let nonce = 255;\n let address;\n while (nonce != 0) {\n try {\n const seedsWithNonce = seeds.concat(Buffer.from([nonce]));\n address = this.createProgramAddressSync(seedsWithNonce, programId);\n } catch (err) {\n if (err instanceof TypeError) {\n throw err;\n }\n nonce--;\n continue;\n }\n return [address, nonce];\n }\n throw new Error(`Unable to find a viable program address nonce`);\n }\n\n /**\n * Async version of findProgramAddressSync\n * For backwards compatibility\n *\n * @deprecated Use {@link findProgramAddressSync} instead\n */\n static async findProgramAddress(seeds, programId) {\n return this.findProgramAddressSync(seeds, programId);\n }\n\n /**\n * Check that a pubkey is on the ed25519 curve.\n */\n static isOnCurve(pubkeyData) {\n const pubkey = new PublicKey(pubkeyData);\n return isOnCurve(pubkey.toBytes());\n }\n}\n_PublicKey = PublicKey;\nPublicKey.default = new _PublicKey('11111111111111111111111111111111');\nSOLANA_SCHEMA.set(PublicKey, {\n kind: 'struct',\n fields: [['_bn', 'u256']]\n});\n\n/**\n * An account key pair (public and secret keys).\n *\n * @deprecated since v1.10.0, please use {@link Keypair} instead.\n */\nclass Account {\n /**\n * Create a new Account object\n *\n * If the secretKey parameter is not provided a new key pair is randomly\n * created for the account\n *\n * @param secretKey Secret key for the account\n */\n constructor(secretKey) {\n /** @internal */\n this._publicKey = void 0;\n /** @internal */\n this._secretKey = void 0;\n if (secretKey) {\n const secretKeyBuffer = toBuffer(secretKey);\n if (secretKey.length !== 64) {\n throw new Error('bad secret key size');\n }\n this._publicKey = secretKeyBuffer.slice(32, 64);\n this._secretKey = secretKeyBuffer.slice(0, 32);\n } else {\n this._secretKey = toBuffer(generatePrivateKey());\n this._publicKey = toBuffer(getPublicKey(this._secretKey));\n }\n }\n\n /**\n * The public key for this account\n */\n get publicKey() {\n return new PublicKey(this._publicKey);\n }\n\n /**\n * The **unencrypted** secret key for this account. The first 32 bytes\n * is the private scalar and the last 32 bytes is the public key.\n * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/\n */\n get secretKey() {\n return Buffer.concat([this._secretKey, this._publicKey], 64);\n }\n}\n\nconst BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey('BPFLoader1111111111111111111111111111111111');\n\n/**\n * Maximum over-the-wire size of a Transaction\n *\n * 1280 is IPv6 minimum MTU\n * 40 bytes is the size of the IPv6 header\n * 8 bytes is the size of the fragment header\n */\nconst PACKET_DATA_SIZE = 1280 - 40 - 8;\nconst VERSION_PREFIX_MASK = 0x7f;\nconst SIGNATURE_LENGTH_IN_BYTES = 64;\n\nclass TransactionExpiredBlockheightExceededError extends Error {\n constructor(signature) {\n super(`Signature ${signature} has expired: block height exceeded.`);\n this.signature = void 0;\n this.signature = signature;\n }\n}\nObject.defineProperty(TransactionExpiredBlockheightExceededError.prototype, 'name', {\n value: 'TransactionExpiredBlockheightExceededError'\n});\nclass TransactionExpiredTimeoutError extends Error {\n constructor(signature, timeoutSeconds) {\n 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.`);\n this.signature = void 0;\n this.signature = signature;\n }\n}\nObject.defineProperty(TransactionExpiredTimeoutError.prototype, 'name', {\n value: 'TransactionExpiredTimeoutError'\n});\nclass TransactionExpiredNonceInvalidError extends Error {\n constructor(signature) {\n super(`Signature ${signature} has expired: the nonce is no longer valid.`);\n this.signature = void 0;\n this.signature = signature;\n }\n}\nObject.defineProperty(TransactionExpiredNonceInvalidError.prototype, 'name', {\n value: 'TransactionExpiredNonceInvalidError'\n});\n\nclass MessageAccountKeys {\n constructor(staticAccountKeys, accountKeysFromLookups) {\n this.staticAccountKeys = void 0;\n this.accountKeysFromLookups = void 0;\n this.staticAccountKeys = staticAccountKeys;\n this.accountKeysFromLookups = accountKeysFromLookups;\n }\n keySegments() {\n const keySegments = [this.staticAccountKeys];\n if (this.accountKeysFromLookups) {\n keySegments.push(this.accountKeysFromLookups.writable);\n keySegments.push(this.accountKeysFromLookups.readonly);\n }\n return keySegments;\n }\n get(index) {\n for (const keySegment of this.keySegments()) {\n if (index < keySegment.length) {\n return keySegment[index];\n } else {\n index -= keySegment.length;\n }\n }\n return;\n }\n get length() {\n return this.keySegments().flat().length;\n }\n compileInstructions(instructions) {\n // Bail early if any account indexes would overflow a u8\n const U8_MAX = 255;\n if (this.length > U8_MAX + 1) {\n throw new Error('Account index overflow encountered during compilation');\n }\n const keyIndexMap = new Map();\n this.keySegments().flat().forEach((key, index) => {\n keyIndexMap.set(key.toBase58(), index);\n });\n const findKeyIndex = key => {\n const keyIndex = keyIndexMap.get(key.toBase58());\n if (keyIndex === undefined) throw new Error('Encountered an unknown instruction account key during compilation');\n return keyIndex;\n };\n return instructions.map(instruction => {\n return {\n programIdIndex: findKeyIndex(instruction.programId),\n accountKeyIndexes: instruction.keys.map(meta => findKeyIndex(meta.pubkey)),\n data: instruction.data\n };\n });\n }\n}\n\n/**\n * Layout for a public key\n */\nconst publicKey = (property = 'publicKey') => {\n return BufferLayout.blob(32, property);\n};\n\n/**\n * Layout for a signature\n */\nconst signature = (property = 'signature') => {\n return BufferLayout.blob(64, property);\n};\n/**\n * Layout for a Rust String type\n */\nconst rustString = (property = 'string') => {\n const rsl = BufferLayout.struct([BufferLayout.u32('length'), BufferLayout.u32('lengthPadding'), BufferLayout.blob(BufferLayout.offset(BufferLayout.u32(), -8), 'chars')], property);\n const _decode = rsl.decode.bind(rsl);\n const _encode = rsl.encode.bind(rsl);\n const rslShim = rsl;\n rslShim.decode = (b, offset) => {\n const data = _decode(b, offset);\n return data['chars'].toString();\n };\n rslShim.encode = (str, b, offset) => {\n const data = {\n chars: Buffer.from(str, 'utf8')\n };\n return _encode(data, b, offset);\n };\n rslShim.alloc = str => {\n return BufferLayout.u32().span + BufferLayout.u32().span + Buffer.from(str, 'utf8').length;\n };\n return rslShim;\n};\n\n/**\n * Layout for an Authorized object\n */\nconst authorized = (property = 'authorized') => {\n return BufferLayout.struct([publicKey('staker'), publicKey('withdrawer')], property);\n};\n\n/**\n * Layout for a Lockup object\n */\nconst lockup = (property = 'lockup') => {\n return BufferLayout.struct([BufferLayout.ns64('unixTimestamp'), BufferLayout.ns64('epoch'), publicKey('custodian')], property);\n};\n\n/**\n * Layout for a VoteInit object\n */\nconst voteInit = (property = 'voteInit') => {\n return BufferLayout.struct([publicKey('nodePubkey'), publicKey('authorizedVoter'), publicKey('authorizedWithdrawer'), BufferLayout.u8('commission')], property);\n};\n\n/**\n * Layout for a VoteAuthorizeWithSeedArgs object\n */\nconst voteAuthorizeWithSeedArgs = (property = 'voteAuthorizeWithSeedArgs') => {\n return BufferLayout.struct([BufferLayout.u32('voteAuthorizationType'), publicKey('currentAuthorityDerivedKeyOwnerPubkey'), rustString('currentAuthorityDerivedKeySeed'), publicKey('newAuthorized')], property);\n};\nfunction getAlloc(type, fields) {\n const getItemAlloc = item => {\n if (item.span >= 0) {\n return item.span;\n } else if (typeof item.alloc === 'function') {\n return item.alloc(fields[item.property]);\n } else if ('count' in item && 'elementLayout' in item) {\n const field = fields[item.property];\n if (Array.isArray(field)) {\n return field.length * getItemAlloc(item.elementLayout);\n }\n } else if ('fields' in item) {\n // This is a `Structure` whose size needs to be recursively measured.\n return getAlloc({\n layout: item\n }, fields[item.property]);\n }\n // Couldn't determine allocated size of layout\n return 0;\n };\n let alloc = 0;\n type.layout.fields.forEach(item => {\n alloc += getItemAlloc(item);\n });\n return alloc;\n}\n\nfunction decodeLength(bytes) {\n let len = 0;\n let size = 0;\n for (;;) {\n let elem = bytes.shift();\n len |= (elem & 0x7f) << size * 7;\n size += 1;\n if ((elem & 0x80) === 0) {\n break;\n }\n }\n return len;\n}\nfunction encodeLength(bytes, len) {\n let rem_len = len;\n for (;;) {\n let elem = rem_len & 0x7f;\n rem_len >>= 7;\n if (rem_len == 0) {\n bytes.push(elem);\n break;\n } else {\n elem |= 0x80;\n bytes.push(elem);\n }\n }\n}\n\nfunction assert (condition, message) {\n if (!condition) {\n throw new Error(message || 'Assertion failed');\n }\n}\n\nclass CompiledKeys {\n constructor(payer, keyMetaMap) {\n this.payer = void 0;\n this.keyMetaMap = void 0;\n this.payer = payer;\n this.keyMetaMap = keyMetaMap;\n }\n static compile(instructions, payer) {\n const keyMetaMap = new Map();\n const getOrInsertDefault = pubkey => {\n const address = pubkey.toBase58();\n let keyMeta = keyMetaMap.get(address);\n if (keyMeta === undefined) {\n keyMeta = {\n isSigner: false,\n isWritable: false,\n isInvoked: false\n };\n keyMetaMap.set(address, keyMeta);\n }\n return keyMeta;\n };\n const payerKeyMeta = getOrInsertDefault(payer);\n payerKeyMeta.isSigner = true;\n payerKeyMeta.isWritable = true;\n for (const ix of instructions) {\n getOrInsertDefault(ix.programId).isInvoked = true;\n for (const accountMeta of ix.keys) {\n const keyMeta = getOrInsertDefault(accountMeta.pubkey);\n keyMeta.isSigner ||= accountMeta.isSigner;\n keyMeta.isWritable ||= accountMeta.isWritable;\n }\n }\n return new CompiledKeys(payer, keyMetaMap);\n }\n getMessageComponents() {\n const mapEntries = [...this.keyMetaMap.entries()];\n assert(mapEntries.length <= 256, 'Max static account keys length exceeded');\n const writableSigners = mapEntries.filter(([, meta]) => meta.isSigner && meta.isWritable);\n const readonlySigners = mapEntries.filter(([, meta]) => meta.isSigner && !meta.isWritable);\n const writableNonSigners = mapEntries.filter(([, meta]) => !meta.isSigner && meta.isWritable);\n const readonlyNonSigners = mapEntries.filter(([, meta]) => !meta.isSigner && !meta.isWritable);\n const header = {\n numRequiredSignatures: writableSigners.length + readonlySigners.length,\n numReadonlySignedAccounts: readonlySigners.length,\n numReadonlyUnsignedAccounts: readonlyNonSigners.length\n };\n\n // sanity checks\n {\n assert(writableSigners.length > 0, 'Expected at least one writable signer key');\n const [payerAddress] = writableSigners[0];\n assert(payerAddress === this.payer.toBase58(), 'Expected first writable signer key to be the fee payer');\n }\n const staticAccountKeys = [...writableSigners.map(([address]) => new PublicKey(address)), ...readonlySigners.map(([address]) => new PublicKey(address)), ...writableNonSigners.map(([address]) => new PublicKey(address)), ...readonlyNonSigners.map(([address]) => new PublicKey(address))];\n return [header, staticAccountKeys];\n }\n extractTableLookup(lookupTable) {\n const [writableIndexes, drainedWritableKeys] = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, keyMeta => !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable);\n const [readonlyIndexes, drainedReadonlyKeys] = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, keyMeta => !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable);\n\n // Don't extract lookup if no keys were found\n if (writableIndexes.length === 0 && readonlyIndexes.length === 0) {\n return;\n }\n return [{\n accountKey: lookupTable.key,\n writableIndexes,\n readonlyIndexes\n }, {\n writable: drainedWritableKeys,\n readonly: drainedReadonlyKeys\n }];\n }\n\n /** @internal */\n drainKeysFoundInLookupTable(lookupTableEntries, keyMetaFilter) {\n const lookupTableIndexes = new Array();\n const drainedKeys = new Array();\n for (const [address, keyMeta] of this.keyMetaMap.entries()) {\n if (keyMetaFilter(keyMeta)) {\n const key = new PublicKey(address);\n const lookupTableIndex = lookupTableEntries.findIndex(entry => entry.equals(key));\n if (lookupTableIndex >= 0) {\n assert(lookupTableIndex < 256, 'Max lookup table index exceeded');\n lookupTableIndexes.push(lookupTableIndex);\n drainedKeys.push(key);\n this.keyMetaMap.delete(address);\n }\n }\n }\n return [lookupTableIndexes, drainedKeys];\n }\n}\n\nconst END_OF_BUFFER_ERROR_MESSAGE = 'Reached end of buffer unexpectedly';\n\n/**\n * Delegates to `Array#shift`, but throws if the array is zero-length.\n */\nfunction guardedShift(byteArray) {\n if (byteArray.length === 0) {\n throw new Error(END_OF_BUFFER_ERROR_MESSAGE);\n }\n return byteArray.shift();\n}\n\n/**\n * Delegates to `Array#splice`, but throws if the section being spliced out extends past the end of\n * the array.\n */\nfunction guardedSplice(byteArray, ...args) {\n const [start] = args;\n if (args.length === 2 // Implies that `deleteCount` was supplied\n ? start + (args[1] ?? 0) > byteArray.length : start >= byteArray.length) {\n throw new Error(END_OF_BUFFER_ERROR_MESSAGE);\n }\n return byteArray.splice(...args);\n}\n\n/**\n * An instruction to execute by a program\n *\n * @property {number} programIdIndex\n * @property {number[]} accounts\n * @property {string} data\n */\n\n/**\n * Message constructor arguments\n */\n\n/**\n * List of instructions to be processed atomically\n */\nclass Message {\n constructor(args) {\n this.header = void 0;\n this.accountKeys = void 0;\n this.recentBlockhash = void 0;\n this.instructions = void 0;\n this.indexToProgramIds = new Map();\n this.header = args.header;\n this.accountKeys = args.accountKeys.map(account => new PublicKey(account));\n this.recentBlockhash = args.recentBlockhash;\n this.instructions = args.instructions;\n this.instructions.forEach(ix => this.indexToProgramIds.set(ix.programIdIndex, this.accountKeys[ix.programIdIndex]));\n }\n get version() {\n return 'legacy';\n }\n get staticAccountKeys() {\n return this.accountKeys;\n }\n get compiledInstructions() {\n return this.instructions.map(ix => ({\n programIdIndex: ix.programIdIndex,\n accountKeyIndexes: ix.accounts,\n data: bs58.decode(ix.data)\n }));\n }\n get addressTableLookups() {\n return [];\n }\n getAccountKeys() {\n return new MessageAccountKeys(this.staticAccountKeys);\n }\n static compile(args) {\n const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);\n const [header, staticAccountKeys] = compiledKeys.getMessageComponents();\n const accountKeys = new MessageAccountKeys(staticAccountKeys);\n const instructions = accountKeys.compileInstructions(args.instructions).map(ix => ({\n programIdIndex: ix.programIdIndex,\n accounts: ix.accountKeyIndexes,\n data: bs58.encode(ix.data)\n }));\n return new Message({\n header,\n accountKeys: staticAccountKeys,\n recentBlockhash: args.recentBlockhash,\n instructions\n });\n }\n isAccountSigner(index) {\n return index < this.header.numRequiredSignatures;\n }\n isAccountWritable(index) {\n const numSignedAccounts = this.header.numRequiredSignatures;\n if (index >= this.header.numRequiredSignatures) {\n const unsignedAccountIndex = index - numSignedAccounts;\n const numUnsignedAccounts = this.accountKeys.length - numSignedAccounts;\n const numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts;\n return unsignedAccountIndex < numWritableUnsignedAccounts;\n } else {\n const numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts;\n return index < numWritableSignedAccounts;\n }\n }\n isProgramId(index) {\n return this.indexToProgramIds.has(index);\n }\n programIds() {\n return [...this.indexToProgramIds.values()];\n }\n nonProgramIds() {\n return this.accountKeys.filter((_, index) => !this.isProgramId(index));\n }\n serialize() {\n const numKeys = this.accountKeys.length;\n let keyCount = [];\n encodeLength(keyCount, numKeys);\n const instructions = this.instructions.map(instruction => {\n const {\n accounts,\n programIdIndex\n } = instruction;\n const data = Array.from(bs58.decode(instruction.data));\n let keyIndicesCount = [];\n encodeLength(keyIndicesCount, accounts.length);\n let dataCount = [];\n encodeLength(dataCount, data.length);\n return {\n programIdIndex,\n keyIndicesCount: Buffer.from(keyIndicesCount),\n keyIndices: accounts,\n dataLength: Buffer.from(dataCount),\n data\n };\n });\n let instructionCount = [];\n encodeLength(instructionCount, instructions.length);\n let instructionBuffer = Buffer.alloc(PACKET_DATA_SIZE);\n Buffer.from(instructionCount).copy(instructionBuffer);\n let instructionBufferLength = instructionCount.length;\n instructions.forEach(instruction => {\n const instructionLayout = BufferLayout.struct([BufferLayout.u8('programIdIndex'), BufferLayout.blob(instruction.keyIndicesCount.length, 'keyIndicesCount'), BufferLayout.seq(BufferLayout.u8('keyIndex'), instruction.keyIndices.length, 'keyIndices'), BufferLayout.blob(instruction.dataLength.length, 'dataLength'), BufferLayout.seq(BufferLayout.u8('userdatum'), instruction.data.length, 'data')]);\n const length = instructionLayout.encode(instruction, instructionBuffer, instructionBufferLength);\n instructionBufferLength += length;\n });\n instructionBuffer = instructionBuffer.slice(0, instructionBufferLength);\n const signDataLayout = BufferLayout.struct([BufferLayout.blob(1, 'numRequiredSignatures'), BufferLayout.blob(1, 'numReadonlySignedAccounts'), BufferLayout.blob(1, 'numReadonlyUnsignedAccounts'), BufferLayout.blob(keyCount.length, 'keyCount'), BufferLayout.seq(publicKey('key'), numKeys, 'keys'), publicKey('recentBlockhash')]);\n const transaction = {\n numRequiredSignatures: Buffer.from([this.header.numRequiredSignatures]),\n numReadonlySignedAccounts: Buffer.from([this.header.numReadonlySignedAccounts]),\n numReadonlyUnsignedAccounts: Buffer.from([this.header.numReadonlyUnsignedAccounts]),\n keyCount: Buffer.from(keyCount),\n keys: this.accountKeys.map(key => toBuffer(key.toBytes())),\n recentBlockhash: bs58.decode(this.recentBlockhash)\n };\n let signData = Buffer.alloc(2048);\n const length = signDataLayout.encode(transaction, signData);\n instructionBuffer.copy(signData, length);\n return signData.slice(0, length + instructionBuffer.length);\n }\n\n /**\n * Decode a compiled message into a Message object.\n */\n static from(buffer) {\n // Slice up wire data\n let byteArray = [...buffer];\n const numRequiredSignatures = guardedShift(byteArray);\n if (numRequiredSignatures !== (numRequiredSignatures & VERSION_PREFIX_MASK)) {\n throw new Error('Versioned messages must be deserialized with VersionedMessage.deserialize()');\n }\n const numReadonlySignedAccounts = guardedShift(byteArray);\n const numReadonlyUnsignedAccounts = guardedShift(byteArray);\n const accountCount = decodeLength(byteArray);\n let accountKeys = [];\n for (let i = 0; i < accountCount; i++) {\n const account = guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH);\n accountKeys.push(new PublicKey(Buffer.from(account)));\n }\n const recentBlockhash = guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH);\n const instructionCount = decodeLength(byteArray);\n let instructions = [];\n for (let i = 0; i < instructionCount; i++) {\n const programIdIndex = guardedShift(byteArray);\n const accountCount = decodeLength(byteArray);\n const accounts = guardedSplice(byteArray, 0, accountCount);\n const dataLength = decodeLength(byteArray);\n const dataSlice = guardedSplice(byteArray, 0, dataLength);\n const data = bs58.encode(Buffer.from(dataSlice));\n instructions.push({\n programIdIndex,\n accounts,\n data\n });\n }\n const messageArgs = {\n header: {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts\n },\n recentBlockhash: bs58.encode(Buffer.from(recentBlockhash)),\n accountKeys,\n instructions\n };\n return new Message(messageArgs);\n }\n}\n\n/**\n * Message constructor arguments\n */\n\nclass MessageV0 {\n constructor(args) {\n this.header = void 0;\n this.staticAccountKeys = void 0;\n this.recentBlockhash = void 0;\n this.compiledInstructions = void 0;\n this.addressTableLookups = void 0;\n this.header = args.header;\n this.staticAccountKeys = args.staticAccountKeys;\n this.recentBlockhash = args.recentBlockhash;\n this.compiledInstructions = args.compiledInstructions;\n this.addressTableLookups = args.addressTableLookups;\n }\n get version() {\n return 0;\n }\n get numAccountKeysFromLookups() {\n let count = 0;\n for (const lookup of this.addressTableLookups) {\n count += lookup.readonlyIndexes.length + lookup.writableIndexes.length;\n }\n return count;\n }\n getAccountKeys(args) {\n let accountKeysFromLookups;\n if (args && 'accountKeysFromLookups' in args && args.accountKeysFromLookups) {\n if (this.numAccountKeysFromLookups != args.accountKeysFromLookups.writable.length + args.accountKeysFromLookups.readonly.length) {\n throw new Error('Failed to get account keys because of a mismatch in the number of account keys from lookups');\n }\n accountKeysFromLookups = args.accountKeysFromLookups;\n } else if (args && 'addressLookupTableAccounts' in args && args.addressLookupTableAccounts) {\n accountKeysFromLookups = this.resolveAddressTableLookups(args.addressLookupTableAccounts);\n } else if (this.addressTableLookups.length > 0) {\n throw new Error('Failed to get account keys because address table lookups were not resolved');\n }\n return new MessageAccountKeys(this.staticAccountKeys, accountKeysFromLookups);\n }\n isAccountSigner(index) {\n return index < this.header.numRequiredSignatures;\n }\n isAccountWritable(index) {\n const numSignedAccounts = this.header.numRequiredSignatures;\n const numStaticAccountKeys = this.staticAccountKeys.length;\n if (index >= numStaticAccountKeys) {\n const lookupAccountKeysIndex = index - numStaticAccountKeys;\n const numWritableLookupAccountKeys = this.addressTableLookups.reduce((count, lookup) => count + lookup.writableIndexes.length, 0);\n return lookupAccountKeysIndex < numWritableLookupAccountKeys;\n } else if (index >= this.header.numRequiredSignatures) {\n const unsignedAccountIndex = index - numSignedAccounts;\n const numUnsignedAccounts = numStaticAccountKeys - numSignedAccounts;\n const numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts;\n return unsignedAccountIndex < numWritableUnsignedAccounts;\n } else {\n const numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts;\n return index < numWritableSignedAccounts;\n }\n }\n resolveAddressTableLookups(addressLookupTableAccounts) {\n const accountKeysFromLookups = {\n writable: [],\n readonly: []\n };\n for (const tableLookup of this.addressTableLookups) {\n const tableAccount = addressLookupTableAccounts.find(account => account.key.equals(tableLookup.accountKey));\n if (!tableAccount) {\n throw new Error(`Failed to find address lookup table account for table key ${tableLookup.accountKey.toBase58()}`);\n }\n for (const index of tableLookup.writableIndexes) {\n if (index < tableAccount.state.addresses.length) {\n accountKeysFromLookups.writable.push(tableAccount.state.addresses[index]);\n } else {\n throw new Error(`Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`);\n }\n }\n for (const index of tableLookup.readonlyIndexes) {\n if (index < tableAccount.state.addresses.length) {\n accountKeysFromLookups.readonly.push(tableAccount.state.addresses[index]);\n } else {\n throw new Error(`Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`);\n }\n }\n }\n return accountKeysFromLookups;\n }\n static compile(args) {\n const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);\n const addressTableLookups = new Array();\n const accountKeysFromLookups = {\n writable: new Array(),\n readonly: new Array()\n };\n const lookupTableAccounts = args.addressLookupTableAccounts || [];\n for (const lookupTable of lookupTableAccounts) {\n const extractResult = compiledKeys.extractTableLookup(lookupTable);\n if (extractResult !== undefined) {\n const [addressTableLookup, {\n writable,\n readonly\n }] = extractResult;\n addressTableLookups.push(addressTableLookup);\n accountKeysFromLookups.writable.push(...writable);\n accountKeysFromLookups.readonly.push(...readonly);\n }\n }\n const [header, staticAccountKeys] = compiledKeys.getMessageComponents();\n const accountKeys = new MessageAccountKeys(staticAccountKeys, accountKeysFromLookups);\n const compiledInstructions = accountKeys.compileInstructions(args.instructions);\n return new MessageV0({\n header,\n staticAccountKeys,\n recentBlockhash: args.recentBlockhash,\n compiledInstructions,\n addressTableLookups\n });\n }\n serialize() {\n const encodedStaticAccountKeysLength = Array();\n encodeLength(encodedStaticAccountKeysLength, this.staticAccountKeys.length);\n const serializedInstructions = this.serializeInstructions();\n const encodedInstructionsLength = Array();\n encodeLength(encodedInstructionsLength, this.compiledInstructions.length);\n const serializedAddressTableLookups = this.serializeAddressTableLookups();\n const encodedAddressTableLookupsLength = Array();\n encodeLength(encodedAddressTableLookupsLength, this.addressTableLookups.length);\n const messageLayout = BufferLayout.struct([BufferLayout.u8('prefix'), BufferLayout.struct([BufferLayout.u8('numRequiredSignatures'), BufferLayout.u8('numReadonlySignedAccounts'), BufferLayout.u8('numReadonlyUnsignedAccounts')], 'header'), BufferLayout.blob(encodedStaticAccountKeysLength.length, 'staticAccountKeysLength'), BufferLayout.seq(publicKey(), this.staticAccountKeys.length, 'staticAccountKeys'), publicKey('recentBlockhash'), BufferLayout.blob(encodedInstructionsLength.length, 'instructionsLength'), BufferLayout.blob(serializedInstructions.length, 'serializedInstructions'), BufferLayout.blob(encodedAddressTableLookupsLength.length, 'addressTableLookupsLength'), BufferLayout.blob(serializedAddressTableLookups.length, 'serializedAddressTableLookups')]);\n const serializedMessage = new Uint8Array(PACKET_DATA_SIZE);\n const MESSAGE_VERSION_0_PREFIX = 1 << 7;\n const serializedMessageLength = messageLayout.encode({\n prefix: MESSAGE_VERSION_0_PREFIX,\n header: this.header,\n staticAccountKeysLength: new Uint8Array(encodedStaticAccountKeysLength),\n staticAccountKeys: this.staticAccountKeys.map(key => key.toBytes()),\n recentBlockhash: bs58.decode(this.recentBlockhash),\n instructionsLength: new Uint8Array(encodedInstructionsLength),\n serializedInstructions,\n addressTableLookupsLength: new Uint8Array(encodedAddressTableLookupsLength),\n serializedAddressTableLookups\n }, serializedMessage);\n return serializedMessage.slice(0, serializedMessageLength);\n }\n serializeInstructions() {\n let serializedLength = 0;\n const serializedInstructions = new Uint8Array(PACKET_DATA_SIZE);\n for (const instruction of this.compiledInstructions) {\n const encodedAccountKeyIndexesLength = Array();\n encodeLength(encodedAccountKeyIndexesLength, instruction.accountKeyIndexes.length);\n const encodedDataLength = Array();\n encodeLength(encodedDataLength, instruction.data.length);\n const instructionLayout = BufferLayout.struct([BufferLayout.u8('programIdIndex'), BufferLayout.blob(encodedAccountKeyIndexesLength.length, 'encodedAccountKeyIndexesLength'), BufferLayout.seq(BufferLayout.u8(), instruction.accountKeyIndexes.length, 'accountKeyIndexes'), BufferLayout.blob(encodedDataLength.length, 'encodedDataLength'), BufferLayout.blob(instruction.data.length, 'data')]);\n serializedLength += instructionLayout.encode({\n programIdIndex: instruction.programIdIndex,\n encodedAccountKeyIndexesLength: new Uint8Array(encodedAccountKeyIndexesLength),\n accountKeyIndexes: instruction.accountKeyIndexes,\n encodedDataLength: new Uint8Array(encodedDataLength),\n data: instruction.data\n }, serializedInstructions, serializedLength);\n }\n return serializedInstructions.slice(0, serializedLength);\n }\n serializeAddressTableLookups() {\n let serializedLength = 0;\n const serializedAddressTableLookups = new Uint8Array(PACKET_DATA_SIZE);\n for (const lookup of this.addressTableLookups) {\n const encodedWritableIndexesLength = Array();\n encodeLength(encodedWritableIndexesLength, lookup.writableIndexes.length);\n const encodedReadonlyIndexesLength = Array();\n encodeLength(encodedReadonlyIndexesLength, lookup.readonlyIndexes.length);\n const addressTableLookupLayout = BufferLayout.struct([publicKey('accountKey'), BufferLayout.blob(encodedWritableIndexesLength.length, 'encodedWritableIndexesLength'), BufferLayout.seq(BufferLayout.u8(), lookup.writableIndexes.length, 'writableIndexes'), BufferLayout.blob(encodedReadonlyIndexesLength.length, 'encodedReadonlyIndexesLength'), BufferLayout.seq(BufferLayout.u8(), lookup.readonlyIndexes.length, 'readonlyIndexes')]);\n serializedLength += addressTableLookupLayout.encode({\n accountKey: lookup.accountKey.toBytes(),\n encodedWritableIndexesLength: new Uint8Array(encodedWritableIndexesLength),\n writableIndexes: lookup.writableIndexes,\n encodedReadonlyIndexesLength: new Uint8Array(encodedReadonlyIndexesLength),\n readonlyIndexes: lookup.readonlyIndexes\n }, serializedAddressTableLookups, serializedLength);\n }\n return serializedAddressTableLookups.slice(0, serializedLength);\n }\n static deserialize(serializedMessage) {\n let byteArray = [...serializedMessage];\n const prefix = guardedShift(byteArray);\n const maskedPrefix = prefix & VERSION_PREFIX_MASK;\n assert(prefix !== maskedPrefix, `Expected versioned message but received legacy message`);\n const version = maskedPrefix;\n assert(version === 0, `Expected versioned message with version 0 but found version ${version}`);\n const header = {\n numRequiredSignatures: guardedShift(byteArray),\n numReadonlySignedAccounts: guardedShift(byteArray),\n numReadonlyUnsignedAccounts: guardedShift(byteArray)\n };\n const staticAccountKeys = [];\n const staticAccountKeysLength = decodeLength(byteArray);\n for (let i = 0; i < staticAccountKeysLength; i++) {\n staticAccountKeys.push(new PublicKey(guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH)));\n }\n const recentBlockhash = bs58.encode(guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH));\n const instructionCount = decodeLength(byteArray);\n const compiledInstructions = [];\n for (let i = 0; i < instructionCount; i++) {\n const programIdIndex = guardedShift(byteArray);\n const accountKeyIndexesLength = decodeLength(byteArray);\n const accountKeyIndexes = guardedSplice(byteArray, 0, accountKeyIndexesLength);\n const dataLength = decodeLength(byteArray);\n const data = new Uint8Array(guardedSplice(byteArray, 0, dataLength));\n compiledInstructions.push({\n programIdIndex,\n accountKeyIndexes,\n data\n });\n }\n const addressTableLookupsCount = decodeLength(byteArray);\n const addressTableLookups = [];\n for (let i = 0; i < addressTableLookupsCount; i++) {\n const accountKey = new PublicKey(guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH));\n const writableIndexesLength = decodeLength(byteArray);\n const writableIndexes = guardedSplice(byteArray, 0, writableIndexesLength);\n const readonlyIndexesLength = decodeLength(byteArray);\n const readonlyIndexes = guardedSplice(byteArray, 0, readonlyIndexesLength);\n addressTableLookups.push({\n accountKey,\n writableIndexes,\n readonlyIndexes\n });\n }\n return new MessageV0({\n header,\n staticAccountKeys,\n recentBlockhash,\n compiledInstructions,\n addressTableLookups\n });\n }\n}\n\n// eslint-disable-next-line no-redeclare\nconst VersionedMessage = {\n deserializeMessageVersion(serializedMessage) {\n const prefix = serializedMessage[0];\n const maskedPrefix = prefix & VERSION_PREFIX_MASK;\n\n // if the highest bit of the prefix is not set, the message is not versioned\n if (maskedPrefix === prefix) {\n return 'legacy';\n }\n\n // the lower 7 bits of the prefix indicate the message version\n return maskedPrefix;\n },\n deserialize: serializedMessage => {\n const version = VersionedMessage.deserializeMessageVersion(serializedMessage);\n if (version === 'legacy') {\n return Message.from(serializedMessage);\n }\n if (version === 0) {\n return MessageV0.deserialize(serializedMessage);\n } else {\n throw new Error(`Transaction message version ${version} deserialization is not supported`);\n }\n }\n};\n\n/** @internal */\n\n/**\n * Transaction signature as base-58 encoded string\n */\n\nlet TransactionStatus = /*#__PURE__*/function (TransactionStatus) {\n TransactionStatus[TransactionStatus[\"BLOCKHEIGHT_EXCEEDED\"] = 0] = \"BLOCKHEIGHT_EXCEEDED\";\n TransactionStatus[TransactionStatus[\"PROCESSED\"] = 1] = \"PROCESSED\";\n TransactionStatus[TransactionStatus[\"TIMED_OUT\"] = 2] = \"TIMED_OUT\";\n TransactionStatus[TransactionStatus[\"NONCE_INVALID\"] = 3] = \"NONCE_INVALID\";\n return TransactionStatus;\n}({});\n\n/**\n * Default (empty) signature\n */\nconst DEFAULT_SIGNATURE = Buffer.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0);\n\n/**\n * Account metadata used to define instructions\n */\n\n/**\n * List of TransactionInstruction object fields that may be initialized at construction\n */\n\n/**\n * Configuration object for Transaction.serialize()\n */\n\n/**\n * @internal\n */\n\n/**\n * Transaction Instruction class\n */\nclass TransactionInstruction {\n constructor(opts) {\n /**\n * Public keys to include in this transaction\n * Boolean represents whether this pubkey needs to sign the transaction\n */\n this.keys = void 0;\n /**\n * Program Id to execute\n */\n this.programId = void 0;\n /**\n * Program input\n */\n this.data = Buffer.alloc(0);\n this.programId = opts.programId;\n this.keys = opts.keys;\n if (opts.data) {\n this.data = opts.data;\n }\n }\n\n /**\n * @internal\n */\n toJSON() {\n return {\n keys: this.keys.map(({\n pubkey,\n isSigner,\n isWritable\n }) => ({\n pubkey: pubkey.toJSON(),\n isSigner,\n isWritable\n })),\n programId: this.programId.toJSON(),\n data: [...this.data]\n };\n }\n}\n\n/**\n * Pair of signature and corresponding public key\n */\n\n/**\n * List of Transaction object fields that may be initialized at construction\n */\n\n// For backward compatibility; an unfortunate consequence of being\n// forced to over-export types by the documentation generator.\n// See https://github.com/solana-labs/solana/pull/25820\n\n/**\n * Blockhash-based transactions have a lifetime that are defined by\n * the blockhash they include. Any transaction whose blockhash is\n * too old will be rejected.\n */\n\n/**\n * Use these options to construct a durable nonce transaction.\n */\n\n/**\n * Nonce information to be used to build an offline Transaction.\n */\n\n/**\n * @internal\n */\n\n/**\n * Transaction class\n */\nclass Transaction {\n /**\n * The first (payer) Transaction signature\n *\n * @returns {Buffer | null} Buffer of payer's signature\n */\n get signature() {\n if (this.signatures.length > 0) {\n return this.signatures[0].signature;\n }\n return null;\n }\n\n /**\n * The transaction fee payer\n */\n\n // Construct a transaction with a blockhash and lastValidBlockHeight\n\n // Construct a transaction using a durable nonce\n\n /**\n * @deprecated `TransactionCtorFields` has been deprecated and will be removed in a future version.\n * Please supply a `TransactionBlockhashCtor` instead.\n */\n\n /**\n * Construct an empty Transaction\n */\n constructor(opts) {\n /**\n * Signatures for the transaction. Typically created by invoking the\n * `sign()` method\n */\n this.signatures = [];\n this.feePayer = void 0;\n /**\n * The instructions to atomically execute\n */\n this.instructions = [];\n /**\n * A recent transaction id. Must be populated by the caller\n */\n this.recentBlockhash = void 0;\n /**\n * the last block chain can advance to before tx is declared expired\n * */\n this.lastValidBlockHeight = void 0;\n /**\n * Optional Nonce information. If populated, transaction will use a durable\n * Nonce hash instead of a recentBlockhash. Must be populated by the caller\n */\n this.nonceInfo = void 0;\n /**\n * If this is a nonce transaction this represents the minimum slot from which\n * to evaluate if the nonce has advanced when attempting to confirm the\n * transaction. This protects against a case where the transaction confirmation\n * logic loads the nonce account from an old slot and assumes the mismatch in\n * nonce value implies that the nonce has been advanced.\n */\n this.minNonceContextSlot = void 0;\n /**\n * @internal\n */\n this._message = void 0;\n /**\n * @internal\n */\n this._json = void 0;\n if (!opts) {\n return;\n }\n if (opts.feePayer) {\n this.feePayer = opts.feePayer;\n }\n if (opts.signatures) {\n this.signatures = opts.signatures;\n }\n if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) {\n const {\n minContextSlot,\n nonceInfo\n } = opts;\n this.minNonceContextSlot = minContextSlot;\n this.nonceInfo = nonceInfo;\n } else if (Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')) {\n const {\n blockhash,\n lastValidBlockHeight\n } = opts;\n this.recentBlockhash = blockhash;\n this.lastValidBlockHeight = lastValidBlockHeight;\n } else {\n const {\n recentBlockhash,\n nonceInfo\n } = opts;\n if (nonceInfo) {\n this.nonceInfo = nonceInfo;\n }\n this.recentBlockhash = recentBlockhash;\n }\n }\n\n /**\n * @internal\n */\n toJSON() {\n return {\n recentBlockhash: this.recentBlockhash || null,\n feePayer: this.feePayer ? this.feePayer.toJSON() : null,\n nonceInfo: this.nonceInfo ? {\n nonce: this.nonceInfo.nonce,\n nonceInstruction: this.nonceInfo.nonceInstruction.toJSON()\n } : null,\n instructions: this.instructions.map(instruction => instruction.toJSON()),\n signers: this.signatures.map(({\n publicKey\n }) => {\n return publicKey.toJSON();\n })\n };\n }\n\n /**\n * Add one or more instructions to this Transaction\n *\n * @param {Array< Transaction | TransactionInstruction | TransactionInstructionCtorFields >} items - Instructions to add to the Transaction\n */\n add(...items) {\n if (items.length === 0) {\n throw new Error('No instructions');\n }\n items.forEach(item => {\n if ('instructions' in item) {\n this.instructions = this.instructions.concat(item.instructions);\n } else if ('data' in item && 'programId' in item && 'keys' in item) {\n this.instructions.push(item);\n } else {\n this.instructions.push(new TransactionInstruction(item));\n }\n });\n return this;\n }\n\n /**\n * Compile transaction data\n */\n compileMessage() {\n if (this._message && JSON.stringify(this.toJSON()) === JSON.stringify(this._json)) {\n return this._message;\n }\n let recentBlockhash;\n let instructions;\n if (this.nonceInfo) {\n recentBlockhash = this.nonceInfo.nonce;\n if (this.instructions[0] != this.nonceInfo.nonceInstruction) {\n instructions = [this.nonceInfo.nonceInstruction, ...this.instructions];\n } else {\n instructions = this.instructions;\n }\n } else {\n recentBlockhash = this.recentBlockhash;\n instructions = this.instructions;\n }\n if (!recentBlockhash) {\n throw new Error('Transaction recentBlockhash required');\n }\n if (instructions.length < 1) {\n console.warn('No instructions provided');\n }\n let feePayer;\n if (this.feePayer) {\n feePayer = this.feePayer;\n } else if (this.signatures.length > 0 && this.signatures[0].publicKey) {\n // Use implicit fee payer\n feePayer = this.signatures[0].publicKey;\n } else {\n throw new Error('Transaction fee payer required');\n }\n for (let i = 0; i < instructions.length; i++) {\n if (instructions[i].programId === undefined) {\n throw new Error(`Transaction instruction index ${i} has undefined program id`);\n }\n }\n const programIds = [];\n const accountMetas = [];\n instructions.forEach(instruction => {\n instruction.keys.forEach(accountMeta => {\n accountMetas.push({\n ...accountMeta\n });\n });\n const programId = instruction.programId.toString();\n if (!programIds.includes(programId)) {\n programIds.push(programId);\n }\n });\n\n // Append programID account metas\n programIds.forEach(programId => {\n accountMetas.push({\n pubkey: new PublicKey(programId),\n isSigner: false,\n isWritable: false\n });\n });\n\n // Cull duplicate account metas\n const uniqueMetas = [];\n accountMetas.forEach(accountMeta => {\n const pubkeyString = accountMeta.pubkey.toString();\n const uniqueIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.toString() === pubkeyString;\n });\n if (uniqueIndex > -1) {\n uniqueMetas[uniqueIndex].isWritable = uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable;\n uniqueMetas[uniqueIndex].isSigner = uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner;\n } else {\n uniqueMetas.push(accountMeta);\n }\n });\n\n // Sort. Prioritizing first by signer, then by writable\n uniqueMetas.sort(function (x, y) {\n if (x.isSigner !== y.isSigner) {\n // Signers always come before non-signers\n return x.isSigner ? -1 : 1;\n }\n if (x.isWritable !== y.isWritable) {\n // Writable accounts always come before read-only accounts\n return x.isWritable ? -1 : 1;\n }\n // Otherwise, sort by pubkey, stringwise.\n const options = {\n localeMatcher: 'best fit',\n usage: 'sort',\n sensitivity: 'variant',\n ignorePunctuation: false,\n numeric: false,\n caseFirst: 'lower'\n };\n return x.pubkey.toBase58().localeCompare(y.pubkey.toBase58(), 'en', options);\n });\n\n // Move fee payer to the front\n const feePayerIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.equals(feePayer);\n });\n if (feePayerIndex > -1) {\n const [payerMeta] = uniqueMetas.splice(feePayerIndex, 1);\n payerMeta.isSigner = true;\n payerMeta.isWritable = true;\n uniqueMetas.unshift(payerMeta);\n } else {\n uniqueMetas.unshift({\n pubkey: feePayer,\n isSigner: true,\n isWritable: true\n });\n }\n\n // Disallow unknown signers\n for (const signature of this.signatures) {\n const uniqueIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.equals(signature.publicKey);\n });\n if (uniqueIndex > -1) {\n if (!uniqueMetas[uniqueIndex].isSigner) {\n uniqueMetas[uniqueIndex].isSigner = true;\n 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.');\n }\n } else {\n throw new Error(`unknown signer: ${signature.publicKey.toString()}`);\n }\n }\n let numRequiredSignatures = 0;\n let numReadonlySignedAccounts = 0;\n let numReadonlyUnsignedAccounts = 0;\n\n // Split out signing from non-signing keys and count header values\n const signedKeys = [];\n const unsignedKeys = [];\n uniqueMetas.forEach(({\n pubkey,\n isSigner,\n isWritable\n }) => {\n if (isSigner) {\n signedKeys.push(pubkey.toString());\n numRequiredSignatures += 1;\n if (!isWritable) {\n numReadonlySignedAccounts += 1;\n }\n } else {\n unsignedKeys.push(pubkey.toString());\n if (!isWritable) {\n numReadonlyUnsignedAccounts += 1;\n }\n }\n });\n const accountKeys = signedKeys.concat(unsignedKeys);\n const compiledInstructions = instructions.map(instruction => {\n const {\n data,\n programId\n } = instruction;\n return {\n programIdIndex: accountKeys.indexOf(programId.toString()),\n accounts: instruction.keys.map(meta => accountKeys.indexOf(meta.pubkey.toString())),\n data: bs58.encode(data)\n };\n });\n compiledInstructions.forEach(instruction => {\n assert(instruction.programIdIndex >= 0);\n instruction.accounts.forEach(keyIndex => assert(keyIndex >= 0));\n });\n return new Message({\n header: {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts\n },\n accountKeys,\n recentBlockhash,\n instructions: compiledInstructions\n });\n }\n\n /**\n * @internal\n */\n _compile() {\n const message = this.compileMessage();\n const signedKeys = message.accountKeys.slice(0, message.header.numRequiredSignatures);\n if (this.signatures.length === signedKeys.length) {\n const valid = this.signatures.every((pair, index) => {\n return signedKeys[index].equals(pair.publicKey);\n });\n if (valid) return message;\n }\n this.signatures = signedKeys.map(publicKey => ({\n signature: null,\n publicKey\n }));\n return message;\n }\n\n /**\n * Get a buffer of the Transaction data that need to be covered by signatures\n */\n serializeMessage() {\n return this._compile().serialize();\n }\n\n /**\n * Get the estimated fee associated with a transaction\n *\n * @param {Connection} connection Connection to RPC Endpoint.\n *\n * @returns {Promise} The estimated fee for the transaction\n */\n async getEstimatedFee(connection) {\n return (await connection.getFeeForMessage(this.compileMessage())).value;\n }\n\n /**\n * Specify the public keys which will be used to sign the Transaction.\n * The first signer will be used as the transaction fee payer account.\n *\n * Signatures can be added with either `partialSign` or `addSignature`\n *\n * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be\n * specified and it can be set in the Transaction constructor or with the\n * `feePayer` property.\n */\n setSigners(...signers) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n const seen = new Set();\n this.signatures = signers.filter(publicKey => {\n const key = publicKey.toString();\n if (seen.has(key)) {\n return false;\n } else {\n seen.add(key);\n return true;\n }\n }).map(publicKey => ({\n signature: null,\n publicKey\n }));\n }\n\n /**\n * Sign the Transaction with the specified signers. Multiple signatures may\n * be applied to a Transaction. The first signature is considered \"primary\"\n * and is used identify and confirm transactions.\n *\n * If the Transaction `feePayer` is not set, the first signer will be used\n * as the transaction fee payer account.\n *\n * Transaction fields should not be modified after the first call to `sign`,\n * as doing so may invalidate the signature and cause the Transaction to be\n * rejected.\n *\n * The Transaction must be assigned a valid `recentBlockhash` before invoking this method\n *\n * @param {Array} signers Array of signers that will sign the transaction\n */\n sign(...signers) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n // Dedupe signers\n const seen = new Set();\n const uniqueSigners = [];\n for (const signer of signers) {\n const key = signer.publicKey.toString();\n if (seen.has(key)) {\n continue;\n } else {\n seen.add(key);\n uniqueSigners.push(signer);\n }\n }\n this.signatures = uniqueSigners.map(signer => ({\n signature: null,\n publicKey: signer.publicKey\n }));\n const message = this._compile();\n this._partialSign(message, ...uniqueSigners);\n }\n\n /**\n * Partially sign a transaction with the specified accounts. All accounts must\n * correspond to either the fee payer or a signer account in the transaction\n * instructions.\n *\n * All the caveats from the `sign` method apply to `partialSign`\n *\n * @param {Array} signers Array of signers that will sign the transaction\n */\n partialSign(...signers) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n // Dedupe signers\n const seen = new Set();\n const uniqueSigners = [];\n for (const signer of signers) {\n const key = signer.publicKey.toString();\n if (seen.has(key)) {\n continue;\n } else {\n seen.add(key);\n uniqueSigners.push(signer);\n }\n }\n const message = this._compile();\n this._partialSign(message, ...uniqueSigners);\n }\n\n /**\n * @internal\n */\n _partialSign(message, ...signers) {\n const signData = message.serialize();\n signers.forEach(signer => {\n const signature = sign(signData, signer.secretKey);\n this._addSignature(signer.publicKey, toBuffer(signature));\n });\n }\n\n /**\n * Add an externally created signature to a transaction. The public key\n * must correspond to either the fee payer or a signer account in the transaction\n * instructions.\n *\n * @param {PublicKey} pubkey Public key that will be added to the transaction.\n * @param {Buffer} signature An externally created signature to add to the transaction.\n */\n addSignature(pubkey, signature) {\n this._compile(); // Ensure signatures array is populated\n this._addSignature(pubkey, signature);\n }\n\n /**\n * @internal\n */\n _addSignature(pubkey, signature) {\n assert(signature.length === 64);\n const index = this.signatures.findIndex(sigpair => pubkey.equals(sigpair.publicKey));\n if (index < 0) {\n throw new Error(`unknown signer: ${pubkey.toString()}`);\n }\n this.signatures[index].signature = Buffer.from(signature);\n }\n\n /**\n * Verify signatures of a Transaction\n * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one.\n * If no boolean is provided, we expect a fully signed Transaction by default.\n *\n * @param {boolean} [requireAllSignatures=true] Require a fully signed Transaction\n */\n verifySignatures(requireAllSignatures = true) {\n const signatureErrors = this._getMessageSignednessErrors(this.serializeMessage(), requireAllSignatures);\n return !signatureErrors;\n }\n\n /**\n * @internal\n */\n _getMessageSignednessErrors(message, requireAllSignatures) {\n const errors = {};\n for (const {\n signature,\n publicKey\n } of this.signatures) {\n if (signature === null) {\n if (requireAllSignatures) {\n (errors.missing ||= []).push(publicKey);\n }\n } else {\n if (!verify(signature, message, publicKey.toBytes())) {\n (errors.invalid ||= []).push(publicKey);\n }\n }\n }\n return errors.invalid || errors.missing ? errors : undefined;\n }\n\n /**\n * Serialize the Transaction in the wire format.\n *\n * @param {Buffer} [config] Config of transaction.\n *\n * @returns {Buffer} Signature of transaction in wire format.\n */\n serialize(config) {\n const {\n requireAllSignatures,\n verifySignatures\n } = Object.assign({\n requireAllSignatures: true,\n verifySignatures: true\n }, config);\n const signData = this.serializeMessage();\n if (verifySignatures) {\n const sigErrors = this._getMessageSignednessErrors(signData, requireAllSignatures);\n if (sigErrors) {\n let errorMessage = 'Signature verification failed.';\n if (sigErrors.invalid) {\n errorMessage += `\\nInvalid signature for public key${sigErrors.invalid.length === 1 ? '' : '(s)'} [\\`${sigErrors.invalid.map(p => p.toBase58()).join('`, `')}\\`].`;\n }\n if (sigErrors.missing) {\n errorMessage += `\\nMissing signature for public key${sigErrors.missing.length === 1 ? '' : '(s)'} [\\`${sigErrors.missing.map(p => p.toBase58()).join('`, `')}\\`].`;\n }\n throw new Error(errorMessage);\n }\n }\n return this._serialize(signData);\n }\n\n /**\n * @internal\n */\n _serialize(signData) {\n const {\n signatures\n } = this;\n const signatureCount = [];\n encodeLength(signatureCount, signatures.length);\n const transactionLength = signatureCount.length + signatures.length * 64 + signData.length;\n const wireTransaction = Buffer.alloc(transactionLength);\n assert(signatures.length < 256);\n Buffer.from(signatureCount).copy(wireTransaction, 0);\n signatures.forEach(({\n signature\n }, index) => {\n if (signature !== null) {\n assert(signature.length === 64, `signature has invalid length`);\n Buffer.from(signature).copy(wireTransaction, signatureCount.length + index * 64);\n }\n });\n signData.copy(wireTransaction, signatureCount.length + signatures.length * 64);\n assert(wireTransaction.length <= PACKET_DATA_SIZE, `Transaction too large: ${wireTransaction.length} > ${PACKET_DATA_SIZE}`);\n return wireTransaction;\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get keys() {\n assert(this.instructions.length === 1);\n return this.instructions[0].keys.map(keyObj => keyObj.pubkey);\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get programId() {\n assert(this.instructions.length === 1);\n return this.instructions[0].programId;\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get data() {\n assert(this.instructions.length === 1);\n return this.instructions[0].data;\n }\n\n /**\n * Parse a wire transaction into a Transaction object.\n *\n * @param {Buffer | Uint8Array | Array} buffer Signature of wire Transaction\n *\n * @returns {Transaction} Transaction associated with the signature\n */\n static from(buffer) {\n // Slice up wire data\n let byteArray = [...buffer];\n const signatureCount = decodeLength(byteArray);\n let signatures = [];\n for (let i = 0; i < signatureCount; i++) {\n const signature = guardedSplice(byteArray, 0, SIGNATURE_LENGTH_IN_BYTES);\n signatures.push(bs58.encode(Buffer.from(signature)));\n }\n return Transaction.populate(Message.from(byteArray), signatures);\n }\n\n /**\n * Populate Transaction object from message and signatures\n *\n * @param {Message} message Message of transaction\n * @param {Array} signatures List of signatures to assign to the transaction\n *\n * @returns {Transaction} The populated Transaction\n */\n static populate(message, signatures = []) {\n const transaction = new Transaction();\n transaction.recentBlockhash = message.recentBlockhash;\n if (message.header.numRequiredSignatures > 0) {\n transaction.feePayer = message.accountKeys[0];\n }\n signatures.forEach((signature, index) => {\n const sigPubkeyPair = {\n signature: signature == bs58.encode(DEFAULT_SIGNATURE) ? null : bs58.decode(signature),\n publicKey: message.accountKeys[index]\n };\n transaction.signatures.push(sigPubkeyPair);\n });\n message.instructions.forEach(instruction => {\n const keys = instruction.accounts.map(account => {\n const pubkey = message.accountKeys[account];\n return {\n pubkey,\n isSigner: transaction.signatures.some(keyObj => keyObj.publicKey.toString() === pubkey.toString()) || message.isAccountSigner(account),\n isWritable: message.isAccountWritable(account)\n };\n });\n transaction.instructions.push(new TransactionInstruction({\n keys,\n programId: message.accountKeys[instruction.programIdIndex],\n data: bs58.decode(instruction.data)\n }));\n });\n transaction._message = message;\n transaction._json = transaction.toJSON();\n return transaction;\n }\n}\n\nclass TransactionMessage {\n constructor(args) {\n this.payerKey = void 0;\n this.instructions = void 0;\n this.recentBlockhash = void 0;\n this.payerKey = args.payerKey;\n this.instructions = args.instructions;\n this.recentBlockhash = args.recentBlockhash;\n }\n static decompile(message, args) {\n const {\n header,\n compiledInstructions,\n recentBlockhash\n } = message;\n const {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts\n } = header;\n const numWritableSignedAccounts = numRequiredSignatures - numReadonlySignedAccounts;\n assert(numWritableSignedAccounts > 0, 'Message header is invalid');\n const numWritableUnsignedAccounts = message.staticAccountKeys.length - numRequiredSignatures - numReadonlyUnsignedAccounts;\n assert(numWritableUnsignedAccounts >= 0, 'Message header is invalid');\n const accountKeys = message.getAccountKeys(args);\n const payerKey = accountKeys.get(0);\n if (payerKey === undefined) {\n throw new Error('Failed to decompile message because no account keys were found');\n }\n const instructions = [];\n for (const compiledIx of compiledInstructions) {\n const keys = [];\n for (const keyIndex of compiledIx.accountKeyIndexes) {\n const pubkey = accountKeys.get(keyIndex);\n if (pubkey === undefined) {\n throw new Error(`Failed to find key for account key index ${keyIndex}`);\n }\n const isSigner = keyIndex < numRequiredSignatures;\n let isWritable;\n if (isSigner) {\n isWritable = keyIndex < numWritableSignedAccounts;\n } else if (keyIndex < accountKeys.staticAccountKeys.length) {\n isWritable = keyIndex - numRequiredSignatures < numWritableUnsignedAccounts;\n } else {\n isWritable = keyIndex - accountKeys.staticAccountKeys.length <\n // accountKeysFromLookups cannot be undefined because we already found a pubkey for this index above\n accountKeys.accountKeysFromLookups.writable.length;\n }\n keys.push({\n pubkey,\n isSigner: keyIndex < header.numRequiredSignatures,\n isWritable\n });\n }\n const programId = accountKeys.get(compiledIx.programIdIndex);\n if (programId === undefined) {\n throw new Error(`Failed to find program id for program id index ${compiledIx.programIdIndex}`);\n }\n instructions.push(new TransactionInstruction({\n programId,\n data: toBuffer(compiledIx.data),\n keys\n }));\n }\n return new TransactionMessage({\n payerKey,\n instructions,\n recentBlockhash\n });\n }\n compileToLegacyMessage() {\n return Message.compile({\n payerKey: this.payerKey,\n recentBlockhash: this.recentBlockhash,\n instructions: this.instructions\n });\n }\n compileToV0Message(addressLookupTableAccounts) {\n return MessageV0.compile({\n payerKey: this.payerKey,\n recentBlockhash: this.recentBlockhash,\n instructions: this.instructions,\n addressLookupTableAccounts\n });\n }\n}\n\n/**\n * Versioned transaction class\n */\nclass VersionedTransaction {\n get version() {\n return this.message.version;\n }\n constructor(message, signatures) {\n this.signatures = void 0;\n this.message = void 0;\n if (signatures !== undefined) {\n assert(signatures.length === message.header.numRequiredSignatures, 'Expected signatures length to be equal to the number of required signatures');\n this.signatures = signatures;\n } else {\n const defaultSignatures = [];\n for (let i = 0; i < message.header.numRequiredSignatures; i++) {\n defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES));\n }\n this.signatures = defaultSignatures;\n }\n this.message = message;\n }\n serialize() {\n const serializedMessage = this.message.serialize();\n const encodedSignaturesLength = Array();\n encodeLength(encodedSignaturesLength, this.signatures.length);\n const transactionLayout = BufferLayout.struct([BufferLayout.blob(encodedSignaturesLength.length, 'encodedSignaturesLength'), BufferLayout.seq(signature(), this.signatures.length, 'signatures'), BufferLayout.blob(serializedMessage.length, 'serializedMessage')]);\n const serializedTransaction = new Uint8Array(2048);\n const serializedTransactionLength = transactionLayout.encode({\n encodedSignaturesLength: new Uint8Array(encodedSignaturesLength),\n signatures: this.signatures,\n serializedMessage\n }, serializedTransaction);\n return serializedTransaction.slice(0, serializedTransactionLength);\n }\n static deserialize(serializedTransaction) {\n let byteArray = [...serializedTransaction];\n const signatures = [];\n const signaturesLength = decodeLength(byteArray);\n for (let i = 0; i < signaturesLength; i++) {\n signatures.push(new Uint8Array(guardedSplice(byteArray, 0, SIGNATURE_LENGTH_IN_BYTES)));\n }\n const message = VersionedMessage.deserialize(new Uint8Array(byteArray));\n return new VersionedTransaction(message, signatures);\n }\n sign(signers) {\n const messageData = this.message.serialize();\n const signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures);\n for (const signer of signers) {\n const signerIndex = signerPubkeys.findIndex(pubkey => pubkey.equals(signer.publicKey));\n assert(signerIndex >= 0, `Cannot sign with non signer key ${signer.publicKey.toBase58()}`);\n this.signatures[signerIndex] = sign(messageData, signer.secretKey);\n }\n }\n addSignature(publicKey, signature) {\n assert(signature.byteLength === 64, 'Signature must be 64 bytes long');\n const signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures);\n const signerIndex = signerPubkeys.findIndex(pubkey => pubkey.equals(publicKey));\n assert(signerIndex >= 0, `Can not add signature; \\`${publicKey.toBase58()}\\` is not required to sign this transaction`);\n this.signatures[signerIndex] = signature;\n }\n}\n\n// TODO: These constants should be removed in favor of reading them out of a\n// Syscall account\n\n/**\n * @internal\n */\nconst NUM_TICKS_PER_SECOND = 160;\n\n/**\n * @internal\n */\nconst DEFAULT_TICKS_PER_SLOT = 64;\n\n/**\n * @internal\n */\nconst NUM_SLOTS_PER_SECOND = NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT;\n\n/**\n * @internal\n */\nconst MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND;\n\nconst SYSVAR_CLOCK_PUBKEY = new PublicKey('SysvarC1ock11111111111111111111111111111111');\nconst SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey('SysvarEpochSchedu1e111111111111111111111111');\nconst SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey('Sysvar1nstructions1111111111111111111111111');\nconst SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey('SysvarRecentB1ockHashes11111111111111111111');\nconst SYSVAR_RENT_PUBKEY = new PublicKey('SysvarRent111111111111111111111111111111111');\nconst SYSVAR_REWARDS_PUBKEY = new PublicKey('SysvarRewards111111111111111111111111111111');\nconst SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey('SysvarS1otHashes111111111111111111111111111');\nconst SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey('SysvarS1otHistory11111111111111111111111111');\nconst SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey('SysvarStakeHistory1111111111111111111111111');\n\nclass SendTransactionError extends Error {\n constructor({\n action,\n signature,\n transactionMessage,\n logs\n }) {\n const maybeLogsOutput = logs ? `Logs: \\n${JSON.stringify(logs.slice(-10), null, 2)}. ` : '';\n const guideText = '\\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.';\n let message;\n switch (action) {\n case 'send':\n message = `Transaction ${signature} resulted in an error. \\n` + `${transactionMessage}. ` + maybeLogsOutput + guideText;\n break;\n case 'simulate':\n message = `Simulation failed. \\nMessage: ${transactionMessage}. \\n` + maybeLogsOutput + guideText;\n break;\n default:\n {\n message = `Unknown action '${(a => a)(action)}'`;\n }\n }\n super(message);\n this.signature = void 0;\n this.transactionMessage = void 0;\n this.transactionLogs = void 0;\n this.signature = signature;\n this.transactionMessage = transactionMessage;\n this.transactionLogs = logs ? logs : undefined;\n }\n get transactionError() {\n return {\n message: this.transactionMessage,\n logs: Array.isArray(this.transactionLogs) ? this.transactionLogs : undefined\n };\n }\n\n /* @deprecated Use `await getLogs()` instead */\n get logs() {\n const cachedLogs = this.transactionLogs;\n if (cachedLogs != null && typeof cachedLogs === 'object' && 'then' in cachedLogs) {\n return undefined;\n }\n return cachedLogs;\n }\n async getLogs(connection) {\n if (!Array.isArray(this.transactionLogs)) {\n this.transactionLogs = new Promise((resolve, reject) => {\n connection.getTransaction(this.signature).then(tx => {\n if (tx && tx.meta && tx.meta.logMessages) {\n const logs = tx.meta.logMessages;\n this.transactionLogs = logs;\n resolve(logs);\n } else {\n reject(new Error('Log messages not found'));\n }\n }).catch(reject);\n });\n }\n return await this.transactionLogs;\n }\n}\n\n// Keep in sync with client/src/rpc_custom_errors.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nconst SolanaJSONRPCErrorCode = {\n JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n JSON_RPC_SCAN_ERROR: -32012,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016\n};\nclass SolanaJSONRPCError extends Error {\n constructor({\n code,\n message,\n data\n }, customMessage) {\n super(customMessage != null ? `${customMessage}: ${message}` : message);\n this.code = void 0;\n this.data = void 0;\n this.code = code;\n this.data = data;\n this.name = 'SolanaJSONRPCError';\n }\n}\n\n/**\n * Sign, send and confirm a transaction.\n *\n * If `commitment` option is not specified, defaults to 'max' commitment.\n *\n * @param {Connection} connection\n * @param {Transaction} transaction\n * @param {Array} signers\n * @param {ConfirmOptions} [options]\n * @returns {Promise}\n */\nasync function sendAndConfirmTransaction(connection, transaction, signers, options) {\n const sendOptions = options && {\n skipPreflight: options.skipPreflight,\n preflightCommitment: options.preflightCommitment || options.commitment,\n maxRetries: options.maxRetries,\n minContextSlot: options.minContextSlot\n };\n const signature = await connection.sendTransaction(transaction, signers, sendOptions);\n let status;\n if (transaction.recentBlockhash != null && transaction.lastValidBlockHeight != null) {\n status = (await connection.confirmTransaction({\n abortSignal: options?.abortSignal,\n signature: signature,\n blockhash: transaction.recentBlockhash,\n lastValidBlockHeight: transaction.lastValidBlockHeight\n }, options && options.commitment)).value;\n } else if (transaction.minNonceContextSlot != null && transaction.nonceInfo != null) {\n const {\n nonceInstruction\n } = transaction.nonceInfo;\n const nonceAccountPubkey = nonceInstruction.keys[0].pubkey;\n status = (await connection.confirmTransaction({\n abortSignal: options?.abortSignal,\n minContextSlot: transaction.minNonceContextSlot,\n nonceAccountPubkey,\n nonceValue: transaction.nonceInfo.nonce,\n signature\n }, options && options.commitment)).value;\n } else {\n if (options?.abortSignal != null) {\n 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.');\n }\n status = (await connection.confirmTransaction(signature, options && options.commitment)).value;\n }\n if (status.err) {\n if (signature != null) {\n throw new SendTransactionError({\n action: 'send',\n signature: signature,\n transactionMessage: `Status: (${JSON.stringify(status)})`\n });\n }\n throw new Error(`Transaction ${signature} failed (${JSON.stringify(status)})`);\n }\n return signature;\n}\n\n// zzz\nfunction sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * @internal\n */\n\n/**\n * Populate a buffer of instruction data using an InstructionType\n * @internal\n */\nfunction encodeData(type, fields) {\n const allocLength = type.layout.span >= 0 ? type.layout.span : getAlloc(type, fields);\n const data = Buffer.alloc(allocLength);\n const layoutFields = Object.assign({\n instruction: type.index\n }, fields);\n type.layout.encode(layoutFields, data);\n return data;\n}\n\n/**\n * Decode instruction data buffer using an InstructionType\n * @internal\n */\nfunction decodeData$1(type, buffer) {\n let data;\n try {\n data = type.layout.decode(buffer);\n } catch (err) {\n throw new Error('invalid instruction; ' + err);\n }\n if (data.instruction !== type.index) {\n throw new Error(`invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`);\n }\n return data;\n}\n\n/**\n * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11\n *\n * @internal\n */\nconst FeeCalculatorLayout = BufferLayout.nu64('lamportsPerSignature');\n\n/**\n * Calculator for transaction fees.\n *\n * @deprecated Deprecated since Solana v1.8.0.\n */\n\n/**\n * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32\n *\n * @internal\n */\nconst NonceAccountLayout = BufferLayout.struct([BufferLayout.u32('version'), BufferLayout.u32('state'), publicKey('authorizedPubkey'), publicKey('nonce'), BufferLayout.struct([FeeCalculatorLayout], 'feeCalculator')]);\nconst NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span;\n\n/**\n * A durable nonce is a 32 byte value encoded as a base58 string.\n */\n\n/**\n * NonceAccount class\n */\nclass NonceAccount {\n /**\n * @internal\n */\n constructor(args) {\n this.authorizedPubkey = void 0;\n this.nonce = void 0;\n this.feeCalculator = void 0;\n this.authorizedPubkey = args.authorizedPubkey;\n this.nonce = args.nonce;\n this.feeCalculator = args.feeCalculator;\n }\n\n /**\n * Deserialize NonceAccount from the account data.\n *\n * @param buffer account data\n * @return NonceAccount\n */\n static fromAccountData(buffer) {\n const nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0);\n return new NonceAccount({\n authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey),\n nonce: new PublicKey(nonceAccount.nonce).toString(),\n feeCalculator: nonceAccount.feeCalculator\n });\n }\n}\n\nfunction u64(property) {\n const layout = blob(8 /* bytes */, property);\n const decode = layout.decode.bind(layout);\n const encode = layout.encode.bind(layout);\n const bigIntLayout = layout;\n const codec = getU64Codec();\n bigIntLayout.decode = (buffer, offset) => {\n const src = decode(buffer, offset);\n return codec.decode(src);\n };\n bigIntLayout.encode = (bigInt, buffer, offset) => {\n const src = codec.encode(bigInt);\n return encode(src, buffer, offset);\n };\n return bigIntLayout;\n}\n\n/**\n * Create account system transaction params\n */\n\n/**\n * Transfer system transaction params\n */\n\n/**\n * Assign system transaction params\n */\n\n/**\n * Create account with seed system transaction params\n */\n\n/**\n * Create nonce account system transaction params\n */\n\n/**\n * Create nonce account with seed system transaction params\n */\n\n/**\n * Initialize nonce account system instruction params\n */\n\n/**\n * Advance nonce account system instruction params\n */\n\n/**\n * Withdraw nonce account system transaction params\n */\n\n/**\n * Authorize nonce account system transaction params\n */\n\n/**\n * Allocate account system transaction params\n */\n\n/**\n * Allocate account with seed system transaction params\n */\n\n/**\n * Assign account with seed system transaction params\n */\n\n/**\n * Transfer with seed system transaction params\n */\n\n/** Decoded transfer system transaction instruction */\n\n/** Decoded transferWithSeed system transaction instruction */\n\n/**\n * System Instruction class\n */\nclass SystemInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a system instruction and retrieve the instruction type.\n */\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [ixType, layout] of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType;\n break;\n }\n }\n if (!type) {\n throw new Error('Instruction type incorrect; not a SystemInstruction');\n }\n return type;\n }\n\n /**\n * Decode a create account system instruction and retrieve the instruction params.\n */\n static decodeCreateAccount(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n lamports,\n space,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Create, instruction.data);\n return {\n fromPubkey: instruction.keys[0].pubkey,\n newAccountPubkey: instruction.keys[1].pubkey,\n lamports,\n space,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode a transfer system instruction and retrieve the instruction params.\n */\n static decodeTransfer(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n lamports\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Transfer, instruction.data);\n return {\n fromPubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n lamports\n };\n }\n\n /**\n * Decode a transfer with seed system instruction and retrieve the instruction params.\n */\n static decodeTransferWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n lamports,\n seed,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed, instruction.data);\n return {\n fromPubkey: instruction.keys[0].pubkey,\n basePubkey: instruction.keys[1].pubkey,\n toPubkey: instruction.keys[2].pubkey,\n lamports,\n seed,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode an allocate system instruction and retrieve the instruction params.\n */\n static decodeAllocate(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n const {\n space\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Allocate, instruction.data);\n return {\n accountPubkey: instruction.keys[0].pubkey,\n space\n };\n }\n\n /**\n * Decode an allocate with seed system instruction and retrieve the instruction params.\n */\n static decodeAllocateWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n const {\n base,\n seed,\n space,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed, instruction.data);\n return {\n accountPubkey: instruction.keys[0].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n space,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode an assign system instruction and retrieve the instruction params.\n */\n static decodeAssign(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n const {\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Assign, instruction.data);\n return {\n accountPubkey: instruction.keys[0].pubkey,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode an assign with seed system instruction and retrieve the instruction params.\n */\n static decodeAssignWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n const {\n base,\n seed,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed, instruction.data);\n return {\n accountPubkey: instruction.keys[0].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode a create account with seed system instruction and retrieve the instruction params.\n */\n static decodeCreateWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n base,\n seed,\n lamports,\n space,\n programId\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed, instruction.data);\n return {\n fromPubkey: instruction.keys[0].pubkey,\n newAccountPubkey: instruction.keys[1].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n lamports,\n space,\n programId: new PublicKey(programId)\n };\n }\n\n /**\n * Decode a nonce initialize system instruction and retrieve the instruction params.\n */\n static decodeNonceInitialize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n authorized\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount, instruction.data);\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: new PublicKey(authorized)\n };\n }\n\n /**\n * Decode a nonce advance system instruction and retrieve the instruction params.\n */\n static decodeNonceAdvance(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount, instruction.data);\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey\n };\n }\n\n /**\n * Decode a nonce withdraw system instruction and retrieve the instruction params.\n */\n static decodeNonceWithdraw(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 5);\n const {\n lamports\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount, instruction.data);\n return {\n noncePubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n lamports\n };\n }\n\n /**\n * Decode a nonce authorize system instruction and retrieve the instruction params.\n */\n static decodeNonceAuthorize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n authorized\n } = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount, instruction.data);\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[1].pubkey,\n newAuthorizedPubkey: new PublicKey(authorized)\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(SystemProgram.programId)) {\n throw new Error('invalid instruction; programId is not SystemProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys, expectedLength) {\n if (keys.length < expectedLength) {\n throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`);\n }\n }\n}\n\n/**\n * An enumeration of valid SystemInstructionType's\n */\n\n/**\n * An enumeration of valid system InstructionType's\n * @internal\n */\nconst SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze({\n Create: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports'), BufferLayout.ns64('space'), publicKey('programId')])\n },\n Assign: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('programId')])\n },\n Transfer: {\n index: 2,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), u64('lamports')])\n },\n CreateWithSeed: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('base'), rustString('seed'), BufferLayout.ns64('lamports'), BufferLayout.ns64('space'), publicKey('programId')])\n },\n AdvanceNonceAccount: {\n index: 4,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n WithdrawNonceAccount: {\n index: 5,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')])\n },\n InitializeNonceAccount: {\n index: 6,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('authorized')])\n },\n AuthorizeNonceAccount: {\n index: 7,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('authorized')])\n },\n Allocate: {\n index: 8,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('space')])\n },\n AllocateWithSeed: {\n index: 9,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('base'), rustString('seed'), BufferLayout.ns64('space'), publicKey('programId')])\n },\n AssignWithSeed: {\n index: 10,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('base'), rustString('seed'), publicKey('programId')])\n },\n TransferWithSeed: {\n index: 11,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), u64('lamports'), rustString('seed'), publicKey('programId')])\n },\n UpgradeNonceAccount: {\n index: 12,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n }\n});\n\n/**\n * Factory class for transactions to interact with the System program\n */\nclass SystemProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the System program\n */\n\n /**\n * Generate a transaction instruction that creates a new account\n */\n static createAccount(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Create;\n const data = encodeData(type, {\n lamports: params.lamports,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer())\n });\n return new TransactionInstruction({\n keys: [{\n pubkey: params.fromPubkey,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: params.newAccountPubkey,\n isSigner: true,\n isWritable: true\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that transfers lamports from one account to another\n */\n static transfer(params) {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;\n data = encodeData(type, {\n lamports: BigInt(params.lamports),\n seed: params.seed,\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.fromPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: params.toPubkey,\n isSigner: false,\n isWritable: true\n }];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;\n data = encodeData(type, {\n lamports: BigInt(params.lamports)\n });\n keys = [{\n pubkey: params.fromPubkey,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: params.toPubkey,\n isSigner: false,\n isWritable: true\n }];\n }\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that assigns an account to a program\n */\n static assign(params) {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n }];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Assign;\n data = encodeData(type, {\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: true,\n isWritable: true\n }];\n }\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that creates a new account at\n * an address generated with `from`, a seed, and programId\n */\n static createAccountWithSeed(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;\n const data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n lamports: params.lamports,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer())\n });\n let keys = [{\n pubkey: params.fromPubkey,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: params.newAccountPubkey,\n isSigner: false,\n isWritable: true\n }];\n if (!params.basePubkey.equals(params.fromPubkey)) {\n keys.push({\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n });\n }\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction that creates a new Nonce account\n */\n static createNonceAccount(params) {\n const transaction = new Transaction();\n if ('basePubkey' in params && 'seed' in params) {\n transaction.add(SystemProgram.createAccountWithSeed({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.noncePubkey,\n basePubkey: params.basePubkey,\n seed: params.seed,\n lamports: params.lamports,\n space: NONCE_ACCOUNT_LENGTH,\n programId: this.programId\n }));\n } else {\n transaction.add(SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.noncePubkey,\n lamports: params.lamports,\n space: NONCE_ACCOUNT_LENGTH,\n programId: this.programId\n }));\n }\n const initParams = {\n noncePubkey: params.noncePubkey,\n authorizedPubkey: params.authorizedPubkey\n };\n transaction.add(this.nonceInitialize(initParams));\n return transaction;\n }\n\n /**\n * Generate an instruction to initialize a Nonce account\n */\n static nonceInitialize(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;\n const data = encodeData(type, {\n authorized: toBuffer(params.authorizedPubkey.toBuffer())\n });\n const instructionData = {\n keys: [{\n pubkey: params.noncePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }],\n programId: this.programId,\n data\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate an instruction to advance the nonce in a Nonce account\n */\n static nonceAdvance(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount;\n const data = encodeData(type);\n const instructionData = {\n keys: [{\n pubkey: params.noncePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: params.authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a transaction instruction that withdraws lamports from a Nonce account\n */\n static nonceWithdraw(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount;\n const data = encodeData(type, {\n lamports: params.lamports\n });\n return new TransactionInstruction({\n keys: [{\n pubkey: params.noncePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.toPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: params.authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that authorizes a new PublicKey as the authority\n * on a Nonce account.\n */\n static nonceAuthorize(params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;\n const data = encodeData(type, {\n authorized: toBuffer(params.newAuthorizedPubkey.toBuffer())\n });\n return new TransactionInstruction({\n keys: [{\n pubkey: params.noncePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction instruction that allocates space in an account without funding\n */\n static allocate(params) {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n }];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;\n data = encodeData(type, {\n space: params.space\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: true,\n isWritable: true\n }];\n }\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }\n}\nSystemProgram.programId = new PublicKey('11111111111111111111111111111111');\n\n// Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the\n// rest of the Transaction fields\n//\n// TODO: replace 300 with a proper constant for the size of the other\n// Transaction fields\nconst CHUNK_SIZE = PACKET_DATA_SIZE - 300;\n\n/**\n * Program loader interface\n */\nclass Loader {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Amount of program data placed in each load Transaction\n */\n\n /**\n * Minimum number of signatures required to load a program not including\n * retries\n *\n * Can be used to calculate transaction fees\n */\n static getMinNumSignatures(dataLength) {\n return 2 * (\n // Every transaction requires two signatures (payer + program)\n Math.ceil(dataLength / Loader.chunkSize) + 1 +\n // Add one for Create transaction\n 1) // Add one for Finalize transaction\n ;\n }\n\n /**\n * Loads a generic program\n *\n * @param connection The connection to use\n * @param payer System account that pays to load the program\n * @param program Account to load the program into\n * @param programId Public key that identifies the loader\n * @param data Program octets\n * @return true if program was loaded successfully, false if program was already loaded\n */\n static async load(connection, payer, program, programId, data) {\n {\n const balanceNeeded = await connection.getMinimumBalanceForRentExemption(data.length);\n\n // Fetch program account info to check if it has already been created\n const programInfo = await connection.getAccountInfo(program.publicKey, 'confirmed');\n let transaction = null;\n if (programInfo !== null) {\n if (programInfo.executable) {\n console.error('Program load failed, account is already executable');\n return false;\n }\n if (programInfo.data.length !== data.length) {\n transaction = transaction || new Transaction();\n transaction.add(SystemProgram.allocate({\n accountPubkey: program.publicKey,\n space: data.length\n }));\n }\n if (!programInfo.owner.equals(programId)) {\n transaction = transaction || new Transaction();\n transaction.add(SystemProgram.assign({\n accountPubkey: program.publicKey,\n programId\n }));\n }\n if (programInfo.lamports < balanceNeeded) {\n transaction = transaction || new Transaction();\n transaction.add(SystemProgram.transfer({\n fromPubkey: payer.publicKey,\n toPubkey: program.publicKey,\n lamports: balanceNeeded - programInfo.lamports\n }));\n }\n } else {\n transaction = new Transaction().add(SystemProgram.createAccount({\n fromPubkey: payer.publicKey,\n newAccountPubkey: program.publicKey,\n lamports: balanceNeeded > 0 ? balanceNeeded : 1,\n space: data.length,\n programId\n }));\n }\n\n // If the account is already created correctly, skip this step\n // and proceed directly to loading instructions\n if (transaction !== null) {\n await sendAndConfirmTransaction(connection, transaction, [payer, program], {\n commitment: 'confirmed'\n });\n }\n }\n const dataLayout = BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.u32('offset'), BufferLayout.u32('bytesLength'), BufferLayout.u32('bytesLengthPadding'), BufferLayout.seq(BufferLayout.u8('byte'), BufferLayout.offset(BufferLayout.u32(), -8), 'bytes')]);\n const chunkSize = Loader.chunkSize;\n let offset = 0;\n let array = data;\n let transactions = [];\n while (array.length > 0) {\n const bytes = array.slice(0, chunkSize);\n const data = Buffer.alloc(chunkSize + 16);\n dataLayout.encode({\n instruction: 0,\n // Load instruction\n offset,\n bytes: bytes,\n bytesLength: 0,\n bytesLengthPadding: 0\n }, data);\n const transaction = new Transaction().add({\n keys: [{\n pubkey: program.publicKey,\n isSigner: true,\n isWritable: true\n }],\n programId,\n data\n });\n transactions.push(sendAndConfirmTransaction(connection, transaction, [payer, program], {\n commitment: 'confirmed'\n }));\n\n // Delay between sends in an attempt to reduce rate limit errors\n if (connection._rpcEndpoint.includes('solana.com')) {\n const REQUESTS_PER_SECOND = 4;\n await sleep(1000 / REQUESTS_PER_SECOND);\n }\n offset += chunkSize;\n array = array.slice(chunkSize);\n }\n await Promise.all(transactions);\n\n // Finalize the account loaded with program data for execution\n {\n const dataLayout = BufferLayout.struct([BufferLayout.u32('instruction')]);\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode({\n instruction: 1 // Finalize instruction\n }, data);\n const transaction = new Transaction().add({\n keys: [{\n pubkey: program.publicKey,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }],\n programId,\n data\n });\n const deployCommitment = 'processed';\n const finalizeSignature = await connection.sendTransaction(transaction, [payer, program], {\n preflightCommitment: deployCommitment\n });\n const {\n context,\n value\n } = await connection.confirmTransaction({\n signature: finalizeSignature,\n lastValidBlockHeight: transaction.lastValidBlockHeight,\n blockhash: transaction.recentBlockhash\n }, deployCommitment);\n if (value.err) {\n throw new Error(`Transaction ${finalizeSignature} failed (${JSON.stringify(value)})`);\n }\n // We prevent programs from being usable until the slot after their deployment.\n // See https://github.com/solana-labs/solana/pull/29654\n while (true // eslint-disable-line no-constant-condition\n ) {\n try {\n const currentSlot = await connection.getSlot({\n commitment: deployCommitment\n });\n if (currentSlot > context.slot) {\n break;\n }\n } catch {\n /* empty */\n }\n await new Promise(resolve => setTimeout(resolve, Math.round(MS_PER_SLOT / 2)));\n }\n }\n\n // success\n return true;\n }\n}\nLoader.chunkSize = CHUNK_SIZE;\n\n/**\n * @deprecated Deprecated since Solana v1.17.20.\n */\nconst BPF_LOADER_PROGRAM_ID = new PublicKey('BPFLoader2111111111111111111111111111111111');\n\n/**\n * Factory class for transactions to interact with a program loader\n *\n * @deprecated Deprecated since Solana v1.17.20.\n */\nclass BpfLoader {\n /**\n * Minimum number of signatures required to load a program not including\n * retries\n *\n * Can be used to calculate transaction fees\n */\n static getMinNumSignatures(dataLength) {\n return Loader.getMinNumSignatures(dataLength);\n }\n\n /**\n * Load a SBF program\n *\n * @param connection The connection to use\n * @param payer Account that will pay program loading fees\n * @param program Account to load the program into\n * @param elf The entire ELF containing the SBF program\n * @param loaderProgramId The program id of the BPF loader to use\n * @return true if program was loaded successfully, false if program was already loaded\n */\n static load(connection, payer, program, elf, loaderProgramId) {\n return Loader.load(connection, payer, program, loaderProgramId, elf);\n }\n}\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar fastStableStringify$1;\nvar hasRequiredFastStableStringify;\n\nfunction requireFastStableStringify () {\n\tif (hasRequiredFastStableStringify) return fastStableStringify$1;\n\thasRequiredFastStableStringify = 1;\n\tvar objToString = Object.prototype.toString;\n\tvar objKeys = Object.keys || function(obj) {\n\t\t\tvar keys = [];\n\t\t\tfor (var name in obj) {\n\t\t\t\tkeys.push(name);\n\t\t\t}\n\t\t\treturn keys;\n\t\t};\n\n\tfunction stringify(val, isArrayProp) {\n\t\tvar i, max, str, keys, key, propVal, toStr;\n\t\tif (val === true) {\n\t\t\treturn \"true\";\n\t\t}\n\t\tif (val === false) {\n\t\t\treturn \"false\";\n\t\t}\n\t\tswitch (typeof val) {\n\t\t\tcase \"object\":\n\t\t\t\tif (val === null) {\n\t\t\t\t\treturn null;\n\t\t\t\t} else if (val.toJSON && typeof val.toJSON === \"function\") {\n\t\t\t\t\treturn stringify(val.toJSON(), isArrayProp);\n\t\t\t\t} else {\n\t\t\t\t\ttoStr = objToString.call(val);\n\t\t\t\t\tif (toStr === \"[object Array]\") {\n\t\t\t\t\t\tstr = '[';\n\t\t\t\t\t\tmax = val.length - 1;\n\t\t\t\t\t\tfor(i = 0; i < max; i++) {\n\t\t\t\t\t\t\tstr += stringify(val[i], true) + ',';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (max > -1) {\n\t\t\t\t\t\t\tstr += stringify(val[i], true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn str + ']';\n\t\t\t\t\t} else if (toStr === \"[object Object]\") {\n\t\t\t\t\t\t// only object is left\n\t\t\t\t\t\tkeys = objKeys(val).sort();\n\t\t\t\t\t\tmax = keys.length;\n\t\t\t\t\t\tstr = \"\";\n\t\t\t\t\t\ti = 0;\n\t\t\t\t\t\twhile (i < max) {\n\t\t\t\t\t\t\tkey = keys[i];\n\t\t\t\t\t\t\tpropVal = stringify(val[key], false);\n\t\t\t\t\t\t\tif (propVal !== undefined) {\n\t\t\t\t\t\t\t\tif (str) {\n\t\t\t\t\t\t\t\t\tstr += ',';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tstr += JSON.stringify(key) + ':' + propVal;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn '{' + str + '}';\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn JSON.stringify(val);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"function\":\n\t\t\tcase \"undefined\":\n\t\t\t\treturn isArrayProp ? null : undefined;\n\t\t\tcase \"string\":\n\t\t\t\treturn JSON.stringify(val);\n\t\t\tdefault:\n\t\t\t\treturn isFinite(val) ? val : null;\n\t\t}\n\t}\n\n\tfastStableStringify$1 = function(val) {\n\t\tvar returnVal = stringify(val, false);\n\t\tif (returnVal !== undefined) {\n\t\t\treturn ''+ returnVal;\n\t\t}\n\t};\n\treturn fastStableStringify$1;\n}\n\nvar fastStableStringifyExports = /*@__PURE__*/ requireFastStableStringify();\nvar fastStableStringify = /*@__PURE__*/getDefaultExportFromCjs(fastStableStringifyExports);\n\nconst MINIMUM_SLOT_PER_EPOCH = 32;\n\n// Returns the number of trailing zeros in the binary representation of self.\nfunction trailingZeros(n) {\n let trailingZeros = 0;\n while (n > 1) {\n n /= 2;\n trailingZeros++;\n }\n return trailingZeros;\n}\n\n// Returns the smallest power of two greater than or equal to n\nfunction nextPowerOfTwo(n) {\n if (n === 0) return 1;\n n--;\n n |= n >> 1;\n n |= n >> 2;\n n |= n >> 4;\n n |= n >> 8;\n n |= n >> 16;\n n |= n >> 32;\n return n + 1;\n}\n\n/**\n * Epoch schedule\n * (see https://docs.solana.com/terminology#epoch)\n * Can be retrieved with the {@link Connection.getEpochSchedule} method\n */\nclass EpochSchedule {\n constructor(slotsPerEpoch, leaderScheduleSlotOffset, warmup, firstNormalEpoch, firstNormalSlot) {\n /** The maximum number of slots in each epoch */\n this.slotsPerEpoch = void 0;\n /** The number of slots before beginning of an epoch to calculate a leader schedule for that epoch */\n this.leaderScheduleSlotOffset = void 0;\n /** Indicates whether epochs start short and grow */\n this.warmup = void 0;\n /** The first epoch with `slotsPerEpoch` slots */\n this.firstNormalEpoch = void 0;\n /** The first slot of `firstNormalEpoch` */\n this.firstNormalSlot = void 0;\n this.slotsPerEpoch = slotsPerEpoch;\n this.leaderScheduleSlotOffset = leaderScheduleSlotOffset;\n this.warmup = warmup;\n this.firstNormalEpoch = firstNormalEpoch;\n this.firstNormalSlot = firstNormalSlot;\n }\n getEpoch(slot) {\n return this.getEpochAndSlotIndex(slot)[0];\n }\n getEpochAndSlotIndex(slot) {\n if (slot < this.firstNormalSlot) {\n const epoch = trailingZeros(nextPowerOfTwo(slot + MINIMUM_SLOT_PER_EPOCH + 1)) - trailingZeros(MINIMUM_SLOT_PER_EPOCH) - 1;\n const epochLen = this.getSlotsInEpoch(epoch);\n const slotIndex = slot - (epochLen - MINIMUM_SLOT_PER_EPOCH);\n return [epoch, slotIndex];\n } else {\n const normalSlotIndex = slot - this.firstNormalSlot;\n const normalEpochIndex = Math.floor(normalSlotIndex / this.slotsPerEpoch);\n const epoch = this.firstNormalEpoch + normalEpochIndex;\n const slotIndex = normalSlotIndex % this.slotsPerEpoch;\n return [epoch, slotIndex];\n }\n }\n getFirstSlotInEpoch(epoch) {\n if (epoch <= this.firstNormalEpoch) {\n return (Math.pow(2, epoch) - 1) * MINIMUM_SLOT_PER_EPOCH;\n } else {\n return (epoch - this.firstNormalEpoch) * this.slotsPerEpoch + this.firstNormalSlot;\n }\n }\n getLastSlotInEpoch(epoch) {\n return this.getFirstSlotInEpoch(epoch) + this.getSlotsInEpoch(epoch) - 1;\n }\n getSlotsInEpoch(epoch) {\n if (epoch < this.firstNormalEpoch) {\n return Math.pow(2, epoch + trailingZeros(MINIMUM_SLOT_PER_EPOCH));\n } else {\n return this.slotsPerEpoch;\n }\n }\n}\n\nvar fetchImpl = globalThis.fetch;\n\nclass RpcWebSocketClient extends CommonClient {\n constructor(address, options, generate_request_id) {\n const webSocketFactory = url => {\n const rpc = WebSocket(url, {\n autoconnect: true,\n max_reconnects: 5,\n reconnect: true,\n reconnect_interval: 1000,\n ...options\n });\n if ('socket' in rpc) {\n this.underlyingSocket = rpc.socket;\n } else {\n this.underlyingSocket = rpc;\n }\n return rpc;\n };\n super(webSocketFactory, address, options, generate_request_id);\n this.underlyingSocket = void 0;\n }\n call(...args) {\n const readyState = this.underlyingSocket?.readyState;\n if (readyState === 1 /* WebSocket.OPEN */) {\n return super.call(...args);\n }\n return Promise.reject(new Error('Tried to call a JSON-RPC method `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')'));\n }\n notify(...args) {\n const readyState = this.underlyingSocket?.readyState;\n if (readyState === 1 /* WebSocket.OPEN */) {\n return super.notify(...args);\n }\n return Promise.reject(new Error('Tried to send a JSON-RPC notification `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')'));\n }\n}\n\n/**\n * @internal\n */\n\n/**\n * Decode account data buffer using an AccountType\n * @internal\n */\nfunction decodeData(type, data) {\n let decoded;\n try {\n decoded = type.layout.decode(data);\n } catch (err) {\n throw new Error('invalid instruction; ' + err);\n }\n if (decoded.typeIndex !== type.index) {\n throw new Error(`invalid account data; account type mismatch ${decoded.typeIndex} != ${type.index}`);\n }\n return decoded;\n}\n\n/// The serialized size of lookup table metadata\nconst LOOKUP_TABLE_META_SIZE = 56;\nclass AddressLookupTableAccount {\n constructor(args) {\n this.key = void 0;\n this.state = void 0;\n this.key = args.key;\n this.state = args.state;\n }\n isActive() {\n const U64_MAX = BigInt('0xffffffffffffffff');\n return this.state.deactivationSlot === U64_MAX;\n }\n static deserialize(accountData) {\n const meta = decodeData(LookupTableMetaLayout, accountData);\n const serializedAddressesLen = accountData.length - LOOKUP_TABLE_META_SIZE;\n assert(serializedAddressesLen >= 0, 'lookup table is invalid');\n assert(serializedAddressesLen % 32 === 0, 'lookup table is invalid');\n const numSerializedAddresses = serializedAddressesLen / 32;\n const {\n addresses\n } = BufferLayout.struct([BufferLayout.seq(publicKey(), numSerializedAddresses, 'addresses')]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE));\n return {\n deactivationSlot: meta.deactivationSlot,\n lastExtendedSlot: meta.lastExtendedSlot,\n lastExtendedSlotStartIndex: meta.lastExtendedStartIndex,\n authority: meta.authority.length !== 0 ? new PublicKey(meta.authority[0]) : undefined,\n addresses: addresses.map(address => new PublicKey(address))\n };\n }\n}\nconst LookupTableMetaLayout = {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('typeIndex'), u64('deactivationSlot'), BufferLayout.nu64('lastExtendedSlot'), BufferLayout.u8('lastExtendedStartIndex'), BufferLayout.u8(),\n // option\n BufferLayout.seq(publicKey(), BufferLayout.offset(BufferLayout.u8(), -1), 'authority')])\n};\n\nconst URL_RE = /^[^:]+:\\/\\/([^:[]+|\\[[^\\]]+\\])(:\\d+)?(.*)/i;\nfunction makeWebsocketUrl(endpoint) {\n const matches = endpoint.match(URL_RE);\n if (matches == null) {\n throw TypeError(`Failed to validate endpoint URL \\`${endpoint}\\``);\n }\n const [_,\n // eslint-disable-line @typescript-eslint/no-unused-vars\n hostish, portWithColon, rest] = matches;\n const protocol = endpoint.startsWith('https:') ? 'wss:' : 'ws:';\n const startPort = portWithColon == null ? null : parseInt(portWithColon.slice(1), 10);\n const websocketPort =\n // Only shift the port by +1 as a convention for ws(s) only if given endpoint\n // is explicitly specifying the endpoint port (HTTP-based RPC), assuming\n // we're directly trying to connect to agave-validator's ws listening port.\n // When the endpoint omits the port, we're connecting to the protocol\n // default ports: http(80) or https(443) and it's assumed we're behind a reverse\n // proxy which manages WebSocket upgrade and backend port redirection.\n startPort == null ? '' : `:${startPort + 1}`;\n return `${protocol}//${hostish}${websocketPort}${rest}`;\n}\n\nconst PublicKeyFromString = coerce(instance(PublicKey), string(), value => new PublicKey(value));\nconst RawAccountDataResult = tuple([string(), literal('base64')]);\nconst BufferFromRawAccountData = coerce(instance(Buffer), RawAccountDataResult, value => Buffer.from(value[0], 'base64'));\n\n/**\n * Attempt to use a recent blockhash for up to 30 seconds\n * @internal\n */\nconst BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000;\n\n/**\n * HACK.\n * Copied from rpc-websockets/dist/lib/client.\n * Otherwise, `yarn build` fails with:\n * https://gist.github.com/steveluscher/c057eca81d479ef705cdb53162f9971d\n */\n\n/** @internal */\n/** @internal */\n/** @internal */\n/** @internal */\n\n/** @internal */\n/**\n * @internal\n * Every subscription contains the args used to open the subscription with\n * the server, and a list of callers interested in notifications.\n */\n\n/**\n * @internal\n * A subscription may be in various states of connectedness. Only when it is\n * fully connected will it have a server subscription id associated with it.\n * This id can be returned to the server to unsubscribe the client entirely.\n */\n\n/**\n * A type that encapsulates a subscription's RPC method\n * names and notification (callback) signature.\n */\n\n/**\n * @internal\n * Utility type that keeps tagged unions intact while omitting properties.\n */\n\n/**\n * @internal\n * This type represents a single subscribable 'topic.' It's made up of:\n *\n * - The args used to open the subscription with the server,\n * - The state of the subscription, in terms of its connectedness, and\n * - The set of callbacks to call when the server publishes notifications\n *\n * This record gets indexed by `SubscriptionConfigHash` and is used to\n * set up subscriptions, fan out notifications, and track subscription state.\n */\n\n/**\n * @internal\n */\n\n/**\n * Extra contextual information for RPC responses\n */\n\n/**\n * Options for sending transactions\n */\n\n/**\n * Options for confirming transactions\n */\n\n/**\n * Options for getConfirmedSignaturesForAddress2\n */\n\n/**\n * Options for getSignaturesForAddress\n */\n\n/**\n * RPC Response with extra contextual information\n */\n\n/**\n * A strategy for confirming transactions that uses the last valid\n * block height for a given blockhash to check for transaction expiration.\n */\n\n/**\n * A strategy for confirming durable nonce transactions.\n */\n\n/**\n * Properties shared by all transaction confirmation strategies\n */\n\n/**\n * This type represents all transaction confirmation strategies\n */\n\n/* @internal */\nfunction assertEndpointUrl(putativeUrl) {\n if (/^https?:/.test(putativeUrl) === false) {\n throw new TypeError('Endpoint URL must start with `http:` or `https:`.');\n }\n return putativeUrl;\n}\n\n/** @internal */\nfunction extractCommitmentFromConfig(commitmentOrConfig) {\n let commitment;\n let config;\n if (typeof commitmentOrConfig === 'string') {\n commitment = commitmentOrConfig;\n } else if (commitmentOrConfig) {\n const {\n commitment: specifiedCommitment,\n ...specifiedConfig\n } = commitmentOrConfig;\n commitment = specifiedCommitment;\n config = specifiedConfig;\n }\n return {\n commitment,\n config\n };\n}\n\n/**\n * @internal\n */\nfunction applyDefaultMemcmpEncodingToFilters(filters) {\n return filters.map(filter => 'memcmp' in filter ? {\n ...filter,\n memcmp: {\n ...filter.memcmp,\n encoding: filter.memcmp.encoding ?? 'base58'\n }\n } : filter);\n}\n\n/**\n * @internal\n */\nfunction createRpcResult(result) {\n return union([type({\n jsonrpc: literal('2.0'),\n id: string(),\n result\n }), type({\n jsonrpc: literal('2.0'),\n id: string(),\n error: type({\n code: unknown(),\n message: string(),\n data: optional(any())\n })\n })]);\n}\nconst UnknownRpcResult = createRpcResult(unknown());\n\n/**\n * @internal\n */\nfunction jsonRpcResult(schema) {\n return coerce(createRpcResult(schema), UnknownRpcResult, value => {\n if ('error' in value) {\n return value;\n } else {\n return {\n ...value,\n result: create(value.result, schema)\n };\n }\n });\n}\n\n/**\n * @internal\n */\nfunction jsonRpcResultAndContext(value) {\n return jsonRpcResult(type({\n context: type({\n slot: number()\n }),\n value\n }));\n}\n\n/**\n * @internal\n */\nfunction notificationResultAndContext(value) {\n return type({\n context: type({\n slot: number()\n }),\n value\n });\n}\n\n/**\n * @internal\n */\nfunction versionedMessageFromResponse(version, response) {\n if (version === 0) {\n return new MessageV0({\n header: response.header,\n staticAccountKeys: response.accountKeys.map(accountKey => new PublicKey(accountKey)),\n recentBlockhash: response.recentBlockhash,\n compiledInstructions: response.instructions.map(ix => ({\n programIdIndex: ix.programIdIndex,\n accountKeyIndexes: ix.accounts,\n data: bs58.decode(ix.data)\n })),\n addressTableLookups: response.addressTableLookups\n });\n } else {\n return new Message(response);\n }\n}\n\n/**\n * The level of commitment desired when querying state\n *
\n *   'processed': Query the most recent block which has reached 1 confirmation by the connected node\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * 
\n */\n\n// Deprecated as of v1.5.5\n\n/**\n * A subset of Commitment levels, which are at least optimistically confirmed\n *
\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * 
\n */\n\n/**\n * Filter for largest accounts query\n *
\n *   'circulating':    Return the largest accounts that are part of the circulating supply\n *   'nonCirculating': Return the largest accounts that are not part of the circulating supply\n * 
\n */\n\n/**\n * Configuration object for changing `getAccountInfo` query behavior\n */\n\n/**\n * Configuration object for changing `getBalance` query behavior\n */\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\n\n/**\n * Configuration object for changing `getStakeMinimumDelegation` query behavior\n */\n\n/**\n * Configuration object for changing `getBlockHeight` query behavior\n */\n\n/**\n * Configuration object for changing `getEpochInfo` query behavior\n */\n\n/**\n * Configuration object for changing `getInflationReward` query behavior\n */\n\n/**\n * Configuration object for changing `getLatestBlockhash` query behavior\n */\n\n/**\n * Configuration object for changing `isBlockhashValid` query behavior\n */\n\n/**\n * Configuration object for changing `getSlot` query behavior\n */\n\n/**\n * Configuration object for changing `getSlotLeader` query behavior\n */\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\n\n/**\n * Configuration object for changing `getLargestAccounts` query behavior\n */\n\n/**\n * Configuration object for changing `getSupply` request behavior\n */\n\n/**\n * Configuration object for changing query behavior\n */\n\n/**\n * Information describing a cluster node\n */\n\n/**\n * Information describing a vote account\n */\n\n/**\n * A collection of cluster vote accounts\n */\n\n/**\n * Network Inflation\n * (see https://docs.solana.com/implemented-proposals/ed_overview)\n */\n\nconst GetInflationGovernorResult = type({\n foundation: number(),\n foundationTerm: number(),\n initial: number(),\n taper: number(),\n terminal: number()\n});\n\n/**\n * The inflation reward for an epoch\n */\n\n/**\n * Expected JSON RPC response for the \"getInflationReward\" message\n */\nconst GetInflationRewardResult = jsonRpcResult(array(nullable(type({\n epoch: number(),\n effectiveSlot: number(),\n amount: number(),\n postBalance: number(),\n commission: optional(nullable(number()))\n}))));\n\n/**\n * Configuration object for changing `getRecentPrioritizationFees` query behavior\n */\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesResult = array(type({\n slot: number(),\n prioritizationFee: number()\n}));\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateResult = type({\n total: number(),\n validator: number(),\n foundation: number(),\n epoch: number()\n});\n\n/**\n * Information about the current epoch\n */\n\nconst GetEpochInfoResult = type({\n epoch: number(),\n slotIndex: number(),\n slotsInEpoch: number(),\n absoluteSlot: number(),\n blockHeight: optional(number()),\n transactionCount: optional(number())\n});\nconst GetEpochScheduleResult = type({\n slotsPerEpoch: number(),\n leaderScheduleSlotOffset: number(),\n warmup: boolean(),\n firstNormalEpoch: number(),\n firstNormalSlot: number()\n});\n\n/**\n * Leader schedule\n * (see https://docs.solana.com/terminology#leader-schedule)\n */\n\nconst GetLeaderScheduleResult = record(string(), array(number()));\n\n/**\n * Transaction error or null\n */\nconst TransactionErrorResult = nullable(union([type({}), string()]));\n\n/**\n * Signature status for a transaction\n */\nconst SignatureStatusResult = type({\n err: TransactionErrorResult\n});\n\n/**\n * Transaction signature received notification\n */\nconst SignatureReceivedResult = literal('receivedSignature');\n\n/**\n * Version info for a node\n */\n\nconst VersionResult = type({\n 'solana-core': string(),\n 'feature-set': optional(number())\n});\nconst ParsedInstructionStruct = type({\n program: string(),\n programId: PublicKeyFromString,\n parsed: unknown()\n});\nconst PartiallyDecodedInstructionStruct = type({\n programId: PublicKeyFromString,\n accounts: array(PublicKeyFromString),\n data: string()\n});\nconst SimulatedTransactionResponseStruct = jsonRpcResultAndContext(type({\n err: nullable(union([type({}), string()])),\n logs: nullable(array(string())),\n accounts: optional(nullable(array(nullable(type({\n executable: boolean(),\n owner: string(),\n lamports: number(),\n data: array(string()),\n rentEpoch: optional(number())\n }))))),\n unitsConsumed: optional(number()),\n returnData: optional(nullable(type({\n programId: string(),\n data: tuple([string(), literal('base64')])\n }))),\n innerInstructions: optional(nullable(array(type({\n index: number(),\n instructions: array(union([ParsedInstructionStruct, PartiallyDecodedInstructionStruct]))\n }))))\n}));\n\n/**\n * Metadata for a parsed confirmed transaction on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link ParsedTransactionMeta} instead.\n */\n\n/**\n * Collection of addresses loaded by a transaction using address table lookups\n */\n\n/**\n * Metadata for a parsed transaction on the ledger\n */\n\n/**\n * Metadata for a confirmed transaction on the ledger\n */\n\n/**\n * A processed transaction from the RPC API\n */\n\n/**\n * A processed transaction from the RPC API\n */\n\n/**\n * A processed transaction message from the RPC API\n */\n\n/**\n * A confirmed transaction on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0.\n */\n\n/**\n * A partially decoded transaction instruction\n */\n\n/**\n * A parsed transaction message account\n */\n\n/**\n * A parsed transaction instruction\n */\n\n/**\n * A parsed address table lookup\n */\n\n/**\n * A parsed transaction message\n */\n\n/**\n * A parsed transaction\n */\n\n/**\n * A parsed and confirmed transaction on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link ParsedTransactionWithMeta} instead.\n */\n\n/**\n * A parsed transaction on the ledger with meta\n */\n\n/**\n * A processed block fetched from the RPC API\n */\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\n\n/**\n * A block with parsed transactions\n */\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `accounts`\n */\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `none`\n */\n\n/**\n * A processed block fetched from the RPC API\n */\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\n\n/**\n * A confirmed block on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0.\n */\n\n/**\n * A Block on the ledger with signatures only\n */\n\n/**\n * recent block production information\n */\n\n/**\n * Expected JSON RPC response for the \"getBlockProduction\" message\n */\nconst BlockProductionResponseStruct = jsonRpcResultAndContext(type({\n byIdentity: record(string(), array(number())),\n range: type({\n firstSlot: number(),\n lastSlot: number()\n })\n}));\n\n/**\n * A performance sample\n */\n\nfunction createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent) {\n const fetch = customFetch ? customFetch : fetchImpl;\n let agent;\n {\n if (httpAgent != null) {\n 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.');\n }\n }\n let fetchWithMiddleware;\n if (fetchMiddleware) {\n fetchWithMiddleware = async (info, init) => {\n const modifiedFetchArgs = await new Promise((resolve, reject) => {\n try {\n fetchMiddleware(info, init, (modifiedInfo, modifiedInit) => resolve([modifiedInfo, modifiedInit]));\n } catch (error) {\n reject(error);\n }\n });\n return await fetch(...modifiedFetchArgs);\n };\n }\n const clientBrowser = new RpcClient(async (request, callback) => {\n const options = {\n method: 'POST',\n body: request,\n agent,\n headers: Object.assign({\n 'Content-Type': 'application/json'\n }, httpHeaders || {}, COMMON_HTTP_HEADERS)\n };\n try {\n let too_many_requests_retries = 5;\n let res;\n let waitTime = 500;\n for (;;) {\n if (fetchWithMiddleware) {\n res = await fetchWithMiddleware(url, options);\n } else {\n res = await fetch(url, options);\n }\n if (res.status !== 429 /* Too many requests */) {\n break;\n }\n if (disableRetryOnRateLimit === true) {\n break;\n }\n too_many_requests_retries -= 1;\n if (too_many_requests_retries === 0) {\n break;\n }\n console.error(`Server responded with ${res.status} ${res.statusText}. Retrying after ${waitTime}ms delay...`);\n await sleep(waitTime);\n waitTime *= 2;\n }\n const text = await res.text();\n if (res.ok) {\n callback(null, text);\n } else {\n callback(new Error(`${res.status} ${res.statusText}: ${text}`));\n }\n } catch (err) {\n if (err instanceof Error) callback(err);\n }\n }, {});\n return clientBrowser;\n}\nfunction createRpcRequest(client) {\n return (method, args) => {\n return new Promise((resolve, reject) => {\n client.request(method, args, (err, response) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(response);\n });\n });\n };\n}\nfunction createRpcBatchRequest(client) {\n return requests => {\n return new Promise((resolve, reject) => {\n // Do nothing if requests is empty\n if (requests.length === 0) resolve([]);\n const batch = requests.map(params => {\n return client.request(params.methodName, params.args);\n });\n client.request(batch, (err, response) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(response);\n });\n });\n };\n}\n\n/**\n * Expected JSON RPC response for the \"getInflationGovernor\" message\n */\nconst GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult);\n\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateRpcResult = jsonRpcResult(GetInflationRateResult);\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesRpcResult = jsonRpcResult(GetRecentPrioritizationFeesResult);\n\n/**\n * Expected JSON RPC response for the \"getEpochInfo\" message\n */\nconst GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult);\n\n/**\n * Expected JSON RPC response for the \"getEpochSchedule\" message\n */\nconst GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"getLeaderSchedule\" message\n */\nconst GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"minimumLedgerSlot\" and \"getFirstAvailableBlock\" messages\n */\nconst SlotRpcResult = jsonRpcResult(number());\n\n/**\n * Supply\n */\n\n/**\n * Expected JSON RPC response for the \"getSupply\" message\n */\nconst GetSupplyRpcResult = jsonRpcResultAndContext(type({\n total: number(),\n circulating: number(),\n nonCirculating: number(),\n nonCirculatingAccounts: array(PublicKeyFromString)\n}));\n\n/**\n * Token amount object which returns a token amount in different formats\n * for various client use cases.\n */\n\n/**\n * Expected JSON RPC structure for token amounts\n */\nconst TokenAmountResult = type({\n amount: string(),\n uiAmount: nullable(number()),\n decimals: number(),\n uiAmountString: optional(string())\n});\n\n/**\n * Token address and balance.\n */\n\n/**\n * Expected JSON RPC response for the \"getTokenLargestAccounts\" message\n */\nconst GetTokenLargestAccountsResult = jsonRpcResultAndContext(array(type({\n address: PublicKeyFromString,\n amount: string(),\n uiAmount: nullable(number()),\n decimals: number(),\n uiAmountString: optional(string())\n})));\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message\n */\nconst GetTokenAccountsByOwner = jsonRpcResultAndContext(array(type({\n pubkey: PublicKeyFromString,\n account: type({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: BufferFromRawAccountData,\n rentEpoch: number()\n })\n})));\nconst ParsedAccountDataResult = type({\n program: string(),\n parsed: unknown(),\n space: number()\n});\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message with parsed data\n */\nconst GetParsedTokenAccountsByOwner = jsonRpcResultAndContext(array(type({\n pubkey: PublicKeyFromString,\n account: type({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: ParsedAccountDataResult,\n rentEpoch: number()\n })\n})));\n\n/**\n * Pair of an account address and its balance\n */\n\n/**\n * Expected JSON RPC response for the \"getLargestAccounts\" message\n */\nconst GetLargestAccountsRpcResult = jsonRpcResultAndContext(array(type({\n lamports: number(),\n address: PublicKeyFromString\n})));\n\n/**\n * @internal\n */\nconst AccountInfoResult = type({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: BufferFromRawAccountData,\n rentEpoch: number()\n});\n\n/**\n * @internal\n */\nconst KeyedAccountInfoResult = type({\n pubkey: PublicKeyFromString,\n account: AccountInfoResult\n});\nconst ParsedOrRawAccountData = coerce(union([instance(Buffer), ParsedAccountDataResult]), union([RawAccountDataResult, ParsedAccountDataResult]), value => {\n if (Array.isArray(value)) {\n return create(value, BufferFromRawAccountData);\n } else {\n return value;\n }\n});\n\n/**\n * @internal\n */\nconst ParsedAccountInfoResult = type({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: ParsedOrRawAccountData,\n rentEpoch: number()\n});\nconst KeyedParsedAccountInfoResult = type({\n pubkey: PublicKeyFromString,\n account: ParsedAccountInfoResult\n});\n\n/**\n * @internal\n */\nconst StakeActivationResult = type({\n state: union([literal('active'), literal('inactive'), literal('activating'), literal('deactivating')]),\n active: number(),\n inactive: number()\n});\n\n/**\n * Expected JSON RPC response for the \"getConfirmedSignaturesForAddress2\" message\n */\n\nconst GetConfirmedSignaturesForAddress2RpcResult = jsonRpcResult(array(type({\n signature: string(),\n slot: number(),\n err: TransactionErrorResult,\n memo: nullable(string()),\n blockTime: optional(nullable(number()))\n})));\n\n/**\n * Expected JSON RPC response for the \"getSignaturesForAddress\" message\n */\nconst GetSignaturesForAddressRpcResult = jsonRpcResult(array(type({\n signature: string(),\n slot: number(),\n err: TransactionErrorResult,\n memo: nullable(string()),\n blockTime: optional(nullable(number()))\n})));\n\n/***\n * Expected JSON RPC response for the \"accountNotification\" message\n */\nconst AccountNotificationResult = type({\n subscription: number(),\n result: notificationResultAndContext(AccountInfoResult)\n});\n\n/**\n * @internal\n */\nconst ProgramAccountInfoResult = type({\n pubkey: PublicKeyFromString,\n account: AccountInfoResult\n});\n\n/***\n * Expected JSON RPC response for the \"programNotification\" message\n */\nconst ProgramAccountNotificationResult = type({\n subscription: number(),\n result: notificationResultAndContext(ProgramAccountInfoResult)\n});\n\n/**\n * @internal\n */\nconst SlotInfoResult = type({\n parent: number(),\n slot: number(),\n root: number()\n});\n\n/**\n * Expected JSON RPC response for the \"slotNotification\" message\n */\nconst SlotNotificationResult = type({\n subscription: number(),\n result: SlotInfoResult\n});\n\n/**\n * Slot updates which can be used for tracking the live progress of a cluster.\n * - `\"firstShredReceived\"`: connected node received the first shred of a block.\n * Indicates that a new block that is being produced.\n * - `\"completed\"`: connected node has received all shreds of a block. Indicates\n * a block was recently produced.\n * - `\"optimisticConfirmation\"`: block was optimistically confirmed by the\n * cluster. It is not guaranteed that an optimistic confirmation notification\n * will be sent for every finalized blocks.\n * - `\"root\"`: the connected node rooted this block.\n * - `\"createdBank\"`: the connected node has started validating this block.\n * - `\"frozen\"`: the connected node has validated this block.\n * - `\"dead\"`: the connected node failed to validate this block.\n */\n\n/**\n * @internal\n */\nconst SlotUpdateResult = union([type({\n type: union([literal('firstShredReceived'), literal('completed'), literal('optimisticConfirmation'), literal('root')]),\n slot: number(),\n timestamp: number()\n}), type({\n type: literal('createdBank'),\n parent: number(),\n slot: number(),\n timestamp: number()\n}), type({\n type: literal('frozen'),\n slot: number(),\n timestamp: number(),\n stats: type({\n numTransactionEntries: number(),\n numSuccessfulTransactions: number(),\n numFailedTransactions: number(),\n maxTransactionsPerEntry: number()\n })\n}), type({\n type: literal('dead'),\n slot: number(),\n timestamp: number(),\n err: string()\n})]);\n\n/**\n * Expected JSON RPC response for the \"slotsUpdatesNotification\" message\n */\nconst SlotUpdateNotificationResult = type({\n subscription: number(),\n result: SlotUpdateResult\n});\n\n/**\n * Expected JSON RPC response for the \"signatureNotification\" message\n */\nconst SignatureNotificationResult = type({\n subscription: number(),\n result: notificationResultAndContext(union([SignatureStatusResult, SignatureReceivedResult]))\n});\n\n/**\n * Expected JSON RPC response for the \"rootNotification\" message\n */\nconst RootNotificationResult = type({\n subscription: number(),\n result: number()\n});\nconst ContactInfoResult = type({\n pubkey: string(),\n gossip: nullable(string()),\n tpu: nullable(string()),\n rpc: nullable(string()),\n version: nullable(string())\n});\nconst VoteAccountInfoResult = type({\n votePubkey: string(),\n nodePubkey: string(),\n activatedStake: number(),\n epochVoteAccount: boolean(),\n epochCredits: array(tuple([number(), number(), number()])),\n commission: number(),\n lastVote: number(),\n rootSlot: nullable(number())\n});\n\n/**\n * Expected JSON RPC response for the \"getVoteAccounts\" message\n */\nconst GetVoteAccounts = jsonRpcResult(type({\n current: array(VoteAccountInfoResult),\n delinquent: array(VoteAccountInfoResult)\n}));\nconst ConfirmationStatus = union([literal('processed'), literal('confirmed'), literal('finalized')]);\nconst SignatureStatusResponse = type({\n slot: number(),\n confirmations: nullable(number()),\n err: TransactionErrorResult,\n confirmationStatus: optional(ConfirmationStatus)\n});\n\n/**\n * Expected JSON RPC response for the \"getSignatureStatuses\" message\n */\nconst GetSignatureStatusesRpcResult = jsonRpcResultAndContext(array(nullable(SignatureStatusResponse)));\n\n/**\n * Expected JSON RPC response for the \"getMinimumBalanceForRentExemption\" message\n */\nconst GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number());\nconst AddressTableLookupStruct = type({\n accountKey: PublicKeyFromString,\n writableIndexes: array(number()),\n readonlyIndexes: array(number())\n});\nconst ConfirmedTransactionResult = type({\n signatures: array(string()),\n message: type({\n accountKeys: array(string()),\n header: type({\n numRequiredSignatures: number(),\n numReadonlySignedAccounts: number(),\n numReadonlyUnsignedAccounts: number()\n }),\n instructions: array(type({\n accounts: array(number()),\n data: string(),\n programIdIndex: number()\n })),\n recentBlockhash: string(),\n addressTableLookups: optional(array(AddressTableLookupStruct))\n })\n});\nconst AnnotatedAccountKey = type({\n pubkey: PublicKeyFromString,\n signer: boolean(),\n writable: boolean(),\n source: optional(union([literal('transaction'), literal('lookupTable')]))\n});\nconst ConfirmedTransactionAccountsModeResult = type({\n accountKeys: array(AnnotatedAccountKey),\n signatures: array(string())\n});\nconst ParsedInstructionResult = type({\n parsed: unknown(),\n program: string(),\n programId: PublicKeyFromString\n});\nconst RawInstructionResult = type({\n accounts: array(PublicKeyFromString),\n data: string(),\n programId: PublicKeyFromString\n});\nconst InstructionResult = union([RawInstructionResult, ParsedInstructionResult]);\nconst UnknownInstructionResult = union([type({\n parsed: unknown(),\n program: string(),\n programId: string()\n}), type({\n accounts: array(string()),\n data: string(),\n programId: string()\n})]);\nconst ParsedOrRawInstruction = coerce(InstructionResult, UnknownInstructionResult, value => {\n if ('accounts' in value) {\n return create(value, RawInstructionResult);\n } else {\n return create(value, ParsedInstructionResult);\n }\n});\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionResult = type({\n signatures: array(string()),\n message: type({\n accountKeys: array(AnnotatedAccountKey),\n instructions: array(ParsedOrRawInstruction),\n recentBlockhash: string(),\n addressTableLookups: optional(nullable(array(AddressTableLookupStruct)))\n })\n});\nconst TokenBalanceResult = type({\n accountIndex: number(),\n mint: string(),\n owner: optional(string()),\n programId: optional(string()),\n uiTokenAmount: TokenAmountResult\n});\nconst LoadedAddressesResult = type({\n writable: array(PublicKeyFromString),\n readonly: array(PublicKeyFromString)\n});\n\n/**\n * @internal\n */\nconst ConfirmedTransactionMetaResult = type({\n err: TransactionErrorResult,\n fee: number(),\n innerInstructions: optional(nullable(array(type({\n index: number(),\n instructions: array(type({\n accounts: array(number()),\n data: string(),\n programIdIndex: number()\n }))\n })))),\n preBalances: array(number()),\n postBalances: array(number()),\n logMessages: optional(nullable(array(string()))),\n preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n loadedAddresses: optional(LoadedAddressesResult),\n computeUnitsConsumed: optional(number()),\n costUnits: optional(number())\n});\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionMetaResult = type({\n err: TransactionErrorResult,\n fee: number(),\n innerInstructions: optional(nullable(array(type({\n index: number(),\n instructions: array(ParsedOrRawInstruction)\n })))),\n preBalances: array(number()),\n postBalances: array(number()),\n logMessages: optional(nullable(array(string()))),\n preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n loadedAddresses: optional(LoadedAddressesResult),\n computeUnitsConsumed: optional(number()),\n costUnits: optional(number())\n});\nconst TransactionVersionStruct = union([literal(0), literal('legacy')]);\n\n/** @internal */\nconst RewardsResult = type({\n pubkey: string(),\n lamports: number(),\n postBalance: nullable(number()),\n rewardType: nullable(string()),\n commission: optional(nullable(number()))\n});\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ConfirmedTransactionResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `none`\n */\nconst GetNoneModeBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `accounts`\n */\nconst GetAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ConfirmedTransactionAccountsModeResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message\n */\nconst GetParsedBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ParsedConfirmedTransactionResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message when `transactionDetails` is `accounts`\n */\nconst GetParsedAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ConfirmedTransactionAccountsModeResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message when `transactionDetails` is `none`\n */\nconst GetParsedNoneModeBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getConfirmedBlock\" message\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link GetBlockRpcResult} instead.\n */\nconst GetConfirmedBlockRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(type({\n transaction: ConfirmedTransactionResult,\n meta: nullable(ConfirmedTransactionMetaResult)\n })),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockSignaturesRpcResult = jsonRpcResult(nullable(type({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n signatures: array(string()),\n blockTime: nullable(number())\n})));\n\n/**\n * Expected JSON RPC response for the \"getTransaction\" message\n */\nconst GetTransactionRpcResult = jsonRpcResult(nullable(type({\n slot: number(),\n meta: nullable(ConfirmedTransactionMetaResult),\n blockTime: optional(nullable(number())),\n transaction: ConfirmedTransactionResult,\n version: optional(TransactionVersionStruct)\n})));\n\n/**\n * Expected parsed JSON RPC response for the \"getTransaction\" message\n */\nconst GetParsedTransactionRpcResult = jsonRpcResult(nullable(type({\n slot: number(),\n transaction: ParsedConfirmedTransactionResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n blockTime: optional(nullable(number())),\n version: optional(TransactionVersionStruct)\n})));\n\n/**\n * Expected JSON RPC response for the \"getLatestBlockhash\" message\n */\nconst GetLatestBlockhashRpcResult = jsonRpcResultAndContext(type({\n blockhash: string(),\n lastValidBlockHeight: number()\n}));\n\n/**\n * Expected JSON RPC response for the \"isBlockhashValid\" message\n */\nconst IsBlockhashValidRpcResult = jsonRpcResultAndContext(boolean());\nconst PerfSampleResult = type({\n slot: number(),\n numTransactions: number(),\n numSlots: number(),\n samplePeriodSecs: number()\n});\n\n/*\n * Expected JSON RPC response for \"getRecentPerformanceSamples\" message\n */\nconst GetRecentPerformanceSamplesRpcResult = jsonRpcResult(array(PerfSampleResult));\n\n/**\n * Expected JSON RPC response for the \"getFeeCalculatorForBlockhash\" message\n */\nconst GetFeeCalculatorRpcResult = jsonRpcResultAndContext(nullable(type({\n feeCalculator: type({\n lamportsPerSignature: number()\n })\n})));\n\n/**\n * Expected JSON RPC response for the \"requestAirdrop\" message\n */\nconst RequestAirdropRpcResult = jsonRpcResult(string());\n\n/**\n * Expected JSON RPC response for the \"sendTransaction\" message\n */\nconst SendTransactionRpcResult = jsonRpcResult(string());\n\n/**\n * Information about the latest slot being processed by a node\n */\n\n/**\n * Parsed account data\n */\n\n/**\n * Stake Activation data\n */\n\n/**\n * Data slice argument for getProgramAccounts\n */\n\n/**\n * Memory comparison filter for getProgramAccounts\n */\n\n/**\n * Data size comparison filter for getProgramAccounts\n */\n\n/**\n * A filter object for getProgramAccounts\n */\n\n/**\n * Configuration object for getProgramAccounts requests\n */\n\n/**\n * Configuration object for getParsedProgramAccounts\n */\n\n/**\n * Configuration object for getMultipleAccounts\n */\n\n/**\n * Configuration object for `getStakeActivation`\n */\n\n/**\n * Configuration object for `getStakeActivation`\n */\n\n/**\n * Configuration object for `getStakeActivation`\n */\n\n/**\n * Configuration object for `getNonce`\n */\n\n/**\n * Configuration object for `getNonceAndContext`\n */\n\n/**\n * Information describing an account\n */\n\n/**\n * Account information identified by pubkey\n */\n\n/**\n * Callback function for account change notifications\n */\n\n/**\n * Callback function for program account change notifications\n */\n\n/**\n * Callback function for slot change notifications\n */\n\n/**\n * Callback function for slot update notifications\n */\n\n/**\n * Callback function for signature status notifications\n */\n\n/**\n * Signature status notification with transaction result\n */\n\n/**\n * Signature received notification\n */\n\n/**\n * Callback function for signature notifications\n */\n\n/**\n * Signature subscription options\n */\n\n/**\n * Callback function for root change notifications\n */\n\n/**\n * @internal\n */\nconst LogsResult = type({\n err: TransactionErrorResult,\n logs: array(string()),\n signature: string()\n});\n\n/**\n * Logs result.\n */\n\n/**\n * Expected JSON RPC response for the \"logsNotification\" message.\n */\nconst LogsNotificationResult = type({\n result: notificationResultAndContext(LogsResult),\n subscription: number()\n});\n\n/**\n * Filter for log subscriptions.\n */\n\n/**\n * Callback function for log notifications.\n */\n\n/**\n * Signature result\n */\n\n/**\n * Transaction error\n */\n\n/**\n * Transaction confirmation status\n *
\n *   'processed': Transaction landed in a block which has reached 1 confirmation by the connected node\n *   'confirmed': Transaction landed in a block which has reached 1 confirmation by the cluster\n *   'finalized': Transaction landed in a block which has been finalized by the cluster\n * 
\n */\n\n/**\n * Signature status\n */\n\n/**\n * A confirmed signature with its status\n */\n\n/**\n * An object defining headers to be passed to the RPC server\n */\n\n/**\n * The type of the JavaScript `fetch()` API\n */\n\n/**\n * A callback used to augment the outgoing HTTP request\n */\n\n/**\n * Configuration for instantiating a Connection\n */\n\n/** @internal */\nconst COMMON_HTTP_HEADERS = {\n 'solana-client': `js/${\"1.0.0-maintenance\"}`\n};\n\n/**\n * A connection to a fullnode JSON RPC endpoint\n */\nclass Connection {\n /**\n * Establish a JSON RPC connection\n *\n * @param endpoint URL to the fullnode JSON RPC endpoint\n * @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object\n */\n constructor(endpoint, _commitmentOrConfig) {\n /** @internal */\n this._commitment = void 0;\n /** @internal */\n this._confirmTransactionInitialTimeout = void 0;\n /** @internal */\n this._rpcEndpoint = void 0;\n /** @internal */\n this._rpcWsEndpoint = void 0;\n /** @internal */\n this._rpcClient = void 0;\n /** @internal */\n this._rpcRequest = void 0;\n /** @internal */\n this._rpcBatchRequest = void 0;\n /** @internal */\n this._rpcWebSocket = void 0;\n /** @internal */\n this._rpcWebSocketConnected = false;\n /** @internal */\n this._rpcWebSocketHeartbeat = null;\n /** @internal */\n this._rpcWebSocketIdleTimeout = null;\n /** @internal\n * A number that we increment every time an active connection closes.\n * Used to determine whether the same socket connection that was open\n * when an async operation started is the same one that's active when\n * its continuation fires.\n *\n */\n this._rpcWebSocketGeneration = 0;\n /** @internal */\n this._disableBlockhashCaching = false;\n /** @internal */\n this._pollingBlockhash = false;\n /** @internal */\n this._blockhashInfo = {\n latestBlockhash: null,\n lastFetch: 0,\n transactionSignatures: [],\n simulatedSignatures: []\n };\n /** @internal */\n this._nextClientSubscriptionId = 0;\n /** @internal */\n this._subscriptionDisposeFunctionsByClientSubscriptionId = {};\n /** @internal */\n this._subscriptionHashByClientSubscriptionId = {};\n /** @internal */\n this._subscriptionStateChangeCallbacksByHash = {};\n /** @internal */\n this._subscriptionCallbacksByServerSubscriptionId = {};\n /** @internal */\n this._subscriptionsByHash = {};\n /**\n * Special case.\n * After a signature is processed, RPCs automatically dispose of the\n * subscription on the server side. We need to track which of these\n * subscriptions have been disposed in such a way, so that we know\n * whether the client is dealing with a not-yet-processed signature\n * (in which case we must tear down the server subscription) or an\n * already-processed signature (in which case the client can simply\n * clear out the subscription locally without telling the server).\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n /** @internal */\n this._subscriptionsAutoDisposedByRpc = new Set();\n /*\n * Returns the current block height of the node\n */\n this.getBlockHeight = (() => {\n const requestPromises = {};\n return async commitmentOrConfig => {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const requestHash = fastStableStringify(args);\n requestPromises[requestHash] = requestPromises[requestHash] ?? (async () => {\n try {\n const unsafeRes = await this._rpcRequest('getBlockHeight', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get block height information');\n }\n return res.result;\n } finally {\n delete requestPromises[requestHash];\n }\n })();\n return await requestPromises[requestHash];\n };\n })();\n let wsEndpoint;\n let httpHeaders;\n let fetch;\n let fetchMiddleware;\n let disableRetryOnRateLimit;\n let httpAgent;\n if (_commitmentOrConfig && typeof _commitmentOrConfig === 'string') {\n this._commitment = _commitmentOrConfig;\n } else if (_commitmentOrConfig) {\n this._commitment = _commitmentOrConfig.commitment;\n this._confirmTransactionInitialTimeout = _commitmentOrConfig.confirmTransactionInitialTimeout;\n wsEndpoint = _commitmentOrConfig.wsEndpoint;\n httpHeaders = _commitmentOrConfig.httpHeaders;\n fetch = _commitmentOrConfig.fetch;\n fetchMiddleware = _commitmentOrConfig.fetchMiddleware;\n disableRetryOnRateLimit = _commitmentOrConfig.disableRetryOnRateLimit;\n httpAgent = _commitmentOrConfig.httpAgent;\n }\n this._rpcEndpoint = assertEndpointUrl(endpoint);\n this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint);\n this._rpcClient = createRpcClient(endpoint, httpHeaders, fetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent);\n this._rpcRequest = createRpcRequest(this._rpcClient);\n this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient);\n this._rpcWebSocket = new RpcWebSocketClient(this._rpcWsEndpoint, {\n autoconnect: false,\n max_reconnects: Infinity\n });\n this._rpcWebSocket.on('open', this._wsOnOpen.bind(this));\n this._rpcWebSocket.on('error', this._wsOnError.bind(this));\n this._rpcWebSocket.on('close', this._wsOnClose.bind(this));\n this._rpcWebSocket.on('accountNotification', this._wsOnAccountNotification.bind(this));\n this._rpcWebSocket.on('programNotification', this._wsOnProgramAccountNotification.bind(this));\n this._rpcWebSocket.on('slotNotification', this._wsOnSlotNotification.bind(this));\n this._rpcWebSocket.on('slotsUpdatesNotification', this._wsOnSlotUpdatesNotification.bind(this));\n this._rpcWebSocket.on('signatureNotification', this._wsOnSignatureNotification.bind(this));\n this._rpcWebSocket.on('rootNotification', this._wsOnRootNotification.bind(this));\n this._rpcWebSocket.on('logsNotification', this._wsOnLogsNotification.bind(this));\n }\n\n /**\n * The default commitment used for requests\n */\n get commitment() {\n return this._commitment;\n }\n\n /**\n * The RPC endpoint\n */\n get rpcEndpoint() {\n return this._rpcEndpoint;\n }\n\n /**\n * Fetch the balance for the specified public key, return with context\n */\n async getBalanceAndContext(publicKey, commitmentOrConfig) {\n /** @internal */\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getBalance', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get balance for ${publicKey.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch the balance for the specified public key\n */\n async getBalance(publicKey, commitmentOrConfig) {\n return await this.getBalanceAndContext(publicKey, commitmentOrConfig).then(x => x.value).catch(e => {\n throw new Error('failed to get balance of account ' + publicKey.toBase58() + ': ' + e);\n });\n }\n\n /**\n * Fetch the estimated production time of a block\n */\n async getBlockTime(slot) {\n const unsafeRes = await this._rpcRequest('getBlockTime', [slot]);\n const res = create(unsafeRes, jsonRpcResult(nullable(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get block time for slot ${slot}`);\n }\n return res.result;\n }\n\n /**\n * Fetch the lowest slot that the node has information about in its ledger.\n * This value may increase over time if the node is configured to purge older ledger data\n */\n async getMinimumLedgerSlot() {\n const unsafeRes = await this._rpcRequest('minimumLedgerSlot', []);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get minimum ledger slot');\n }\n return res.result;\n }\n\n /**\n * Fetch the slot of the lowest confirmed block that has not been purged from the ledger\n */\n async getFirstAvailableBlock() {\n const unsafeRes = await this._rpcRequest('getFirstAvailableBlock', []);\n const res = create(unsafeRes, SlotRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get first available block');\n }\n return res.result;\n }\n\n /**\n * Fetch information about the current supply\n */\n async getSupply(config) {\n let configArg = {};\n if (typeof config === 'string') {\n configArg = {\n commitment: config\n };\n } else if (config) {\n configArg = {\n ...config,\n commitment: config && config.commitment || this.commitment\n };\n } else {\n configArg = {\n commitment: this.commitment\n };\n }\n const unsafeRes = await this._rpcRequest('getSupply', [configArg]);\n const res = create(unsafeRes, GetSupplyRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get supply');\n }\n return res.result;\n }\n\n /**\n * Fetch the current supply of a token mint\n */\n async getTokenSupply(tokenMintAddress, commitment) {\n const args = this._buildArgs([tokenMintAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenSupply', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get token supply');\n }\n return res.result;\n }\n\n /**\n * Fetch the current balance of a token account\n */\n async getTokenAccountBalance(tokenAddress, commitment) {\n const args = this._buildArgs([tokenAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenAccountBalance', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get token account balance');\n }\n return res.result;\n }\n\n /**\n * Fetch all the token accounts owned by the specified account\n *\n * @return {Promise}\n */\n async getTokenAccountsByOwner(ownerAddress, filter, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n let _args = [ownerAddress.toBase58()];\n if ('mint' in filter) {\n _args.push({\n mint: filter.mint.toBase58()\n });\n } else {\n _args.push({\n programId: filter.programId.toBase58()\n });\n }\n const args = this._buildArgs(_args, commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n const res = create(unsafeRes, GetTokenAccountsByOwner);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get token accounts owned by account ${ownerAddress.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch parsed token accounts owned by the specified account\n *\n * @return {Promise}>>>}\n */\n async getParsedTokenAccountsByOwner(ownerAddress, filter, commitment) {\n let _args = [ownerAddress.toBase58()];\n if ('mint' in filter) {\n _args.push({\n mint: filter.mint.toBase58()\n });\n } else {\n _args.push({\n programId: filter.programId.toBase58()\n });\n }\n const args = this._buildArgs(_args, commitment, 'jsonParsed');\n const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n const res = create(unsafeRes, GetParsedTokenAccountsByOwner);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get token accounts owned by account ${ownerAddress.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch the 20 largest accounts with their current balances\n */\n async getLargestAccounts(config) {\n const arg = {\n ...config,\n commitment: config && config.commitment || this.commitment\n };\n const args = arg.filter || arg.commitment ? [arg] : [];\n const unsafeRes = await this._rpcRequest('getLargestAccounts', args);\n const res = create(unsafeRes, GetLargestAccountsRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get largest accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch the 20 largest token accounts with their current balances\n * for a given mint.\n */\n async getTokenLargestAccounts(mintAddress, commitment) {\n const args = this._buildArgs([mintAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenLargestAccounts', args);\n const res = create(unsafeRes, GetTokenLargestAccountsResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get token largest accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for the specified public key, return with context\n */\n async getAccountInfoAndContext(publicKey, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(nullable(AccountInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get info about account ${publicKey.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch parsed account info for the specified public key\n */\n async getParsedAccountInfo(publicKey, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get info about account ${publicKey.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for the specified public key\n */\n async getAccountInfo(publicKey, commitmentOrConfig) {\n try {\n const res = await this.getAccountInfoAndContext(publicKey, commitmentOrConfig);\n return res.value;\n } catch (e) {\n throw new Error('failed to get info about account ' + publicKey.toBase58() + ': ' + e);\n }\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n */\n async getMultipleParsedAccounts(publicKeys, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const keys = publicKeys.map(key => key.toBase58());\n const args = this._buildArgs([keys], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult))));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get info for accounts ${keys}`);\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n */\n async getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const keys = publicKeys.map(key => key.toBase58());\n const args = this._buildArgs([keys], commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(array(nullable(AccountInfoResult))));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get info for accounts ${keys}`);\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys\n */\n async getMultipleAccountsInfo(publicKeys, commitmentOrConfig) {\n const res = await this.getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig);\n return res.value;\n }\n\n /**\n * Returns epoch activation information for a stake account that has been delegated\n *\n * @deprecated Deprecated since RPC v1.18; will be removed in a future version.\n */\n async getStakeActivation(publicKey, commitmentOrConfig, epoch) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment, undefined /* encoding */, {\n ...config,\n epoch: epoch != null ? epoch : config?.epoch\n });\n const unsafeRes = await this._rpcRequest('getStakeActivation', args);\n const res = create(unsafeRes, jsonRpcResult(StakeActivationResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get Stake Activation ${publicKey.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch all the accounts owned by the specified program id\n *\n * @return {Promise}>>}\n */\n\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n async getProgramAccounts(programId, configOrCommitment) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(configOrCommitment);\n const {\n encoding,\n ...configWithoutEncoding\n } = config || {};\n const args = this._buildArgs([programId.toBase58()], commitment, encoding || 'base64', {\n ...configWithoutEncoding,\n ...(configWithoutEncoding.filters ? {\n filters: applyDefaultMemcmpEncodingToFilters(configWithoutEncoding.filters)\n } : null)\n });\n const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n const baseSchema = array(KeyedAccountInfoResult);\n const res = configWithoutEncoding.withContext === true ? create(unsafeRes, jsonRpcResultAndContext(baseSchema)) : create(unsafeRes, jsonRpcResult(baseSchema));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get accounts owned by program ${programId.toBase58()}`);\n }\n return res.result;\n }\n\n /**\n * Fetch and parse all the accounts owned by the specified program id\n *\n * @return {Promise}>>}\n */\n async getParsedProgramAccounts(programId, configOrCommitment) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(configOrCommitment);\n const args = this._buildArgs([programId.toBase58()], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n const res = create(unsafeRes, jsonRpcResult(array(KeyedParsedAccountInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get accounts owned by program ${programId.toBase58()}`);\n }\n return res.result;\n }\n\n /** @deprecated Instead, call `confirmTransaction` and pass in {@link TransactionConfirmationStrategy} */\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n async confirmTransaction(strategy, commitment) {\n let rawSignature;\n if (typeof strategy == 'string') {\n rawSignature = strategy;\n } else {\n const config = strategy;\n if (config.abortSignal?.aborted) {\n return Promise.reject(config.abortSignal.reason);\n }\n rawSignature = config.signature;\n }\n let decodedSignature;\n try {\n decodedSignature = bs58.decode(rawSignature);\n } catch (err) {\n throw new Error('signature must be base58 encoded: ' + rawSignature);\n }\n assert(decodedSignature.length === 64, 'signature has invalid length');\n if (typeof strategy === 'string') {\n return await this.confirmTransactionUsingLegacyTimeoutStrategy({\n commitment: commitment || this.commitment,\n signature: rawSignature\n });\n } else if ('lastValidBlockHeight' in strategy) {\n return await this.confirmTransactionUsingBlockHeightExceedanceStrategy({\n commitment: commitment || this.commitment,\n strategy\n });\n } else {\n return await this.confirmTransactionUsingDurableNonceStrategy({\n commitment: commitment || this.commitment,\n strategy\n });\n }\n }\n getCancellationPromise(signal) {\n return new Promise((_, reject) => {\n if (signal == null) {\n return;\n }\n if (signal.aborted) {\n reject(signal.reason);\n } else {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n });\n }\n });\n }\n getTransactionConfirmationPromise({\n commitment,\n signature\n }) {\n let signatureSubscriptionId;\n let disposeSignatureSubscriptionStateChangeObserver;\n let done = false;\n const confirmationPromise = new Promise((resolve, reject) => {\n try {\n signatureSubscriptionId = this.onSignature(signature, (result, context) => {\n signatureSubscriptionId = undefined;\n const response = {\n context,\n value: result\n };\n resolve({\n __type: TransactionStatus.PROCESSED,\n response\n });\n }, commitment);\n const subscriptionSetupPromise = new Promise(resolveSubscriptionSetup => {\n if (signatureSubscriptionId == null) {\n resolveSubscriptionSetup();\n } else {\n disposeSignatureSubscriptionStateChangeObserver = this._onSubscriptionStateChange(signatureSubscriptionId, nextState => {\n if (nextState === 'subscribed') {\n resolveSubscriptionSetup();\n }\n });\n }\n });\n (async () => {\n await subscriptionSetupPromise;\n if (done) return;\n const response = await this.getSignatureStatus(signature);\n if (done) return;\n if (response == null) {\n return;\n }\n const {\n context,\n value\n } = response;\n if (value == null) {\n return;\n }\n if (value?.err) {\n reject(value.err);\n } else {\n switch (commitment) {\n case 'confirmed':\n case 'single':\n case 'singleGossip':\n {\n if (value.confirmationStatus === 'processed') {\n return;\n }\n break;\n }\n case 'finalized':\n case 'max':\n case 'root':\n {\n if (value.confirmationStatus === 'processed' || value.confirmationStatus === 'confirmed') {\n return;\n }\n break;\n }\n // exhaust enums to ensure full coverage\n case 'processed':\n case 'recent':\n }\n done = true;\n resolve({\n __type: TransactionStatus.PROCESSED,\n response: {\n context,\n value\n }\n });\n }\n })();\n } catch (err) {\n reject(err);\n }\n });\n const abortConfirmation = () => {\n if (disposeSignatureSubscriptionStateChangeObserver) {\n disposeSignatureSubscriptionStateChangeObserver();\n disposeSignatureSubscriptionStateChangeObserver = undefined;\n }\n if (signatureSubscriptionId != null) {\n this.removeSignatureListener(signatureSubscriptionId);\n signatureSubscriptionId = undefined;\n }\n };\n return {\n abortConfirmation,\n confirmationPromise\n };\n }\n async confirmTransactionUsingBlockHeightExceedanceStrategy({\n commitment,\n strategy: {\n abortSignal,\n lastValidBlockHeight,\n signature\n }\n }) {\n let done = false;\n const expiryPromise = new Promise(resolve => {\n const checkBlockHeight = async () => {\n try {\n const blockHeight = await this.getBlockHeight(commitment);\n return blockHeight;\n } catch (_e) {\n return -1;\n }\n };\n (async () => {\n let currentBlockHeight = await checkBlockHeight();\n if (done) return;\n while (currentBlockHeight <= lastValidBlockHeight) {\n await sleep(1000);\n if (done) return;\n currentBlockHeight = await checkBlockHeight();\n if (done) return;\n }\n resolve({\n __type: TransactionStatus.BLOCKHEIGHT_EXCEEDED\n });\n })();\n });\n const {\n abortConfirmation,\n confirmationPromise\n } = this.getTransactionConfirmationPromise({\n commitment,\n signature\n });\n const cancellationPromise = this.getCancellationPromise(abortSignal);\n let result;\n try {\n const outcome = await Promise.race([cancellationPromise, confirmationPromise, expiryPromise]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n throw new TransactionExpiredBlockheightExceededError(signature);\n }\n } finally {\n done = true;\n abortConfirmation();\n }\n return result;\n }\n async confirmTransactionUsingDurableNonceStrategy({\n commitment,\n strategy: {\n abortSignal,\n minContextSlot,\n nonceAccountPubkey,\n nonceValue,\n signature\n }\n }) {\n let done = false;\n const expiryPromise = new Promise(resolve => {\n let currentNonceValue = nonceValue;\n let lastCheckedSlot = null;\n const getCurrentNonceValue = async () => {\n try {\n const {\n context,\n value: nonceAccount\n } = await this.getNonceAndContext(nonceAccountPubkey, {\n commitment,\n minContextSlot\n });\n lastCheckedSlot = context.slot;\n return nonceAccount?.nonce;\n } catch (e) {\n // If for whatever reason we can't reach/read the nonce\n // account, just keep using the last-known value.\n return currentNonceValue;\n }\n };\n (async () => {\n currentNonceValue = await getCurrentNonceValue();\n if (done) return;\n while (true // eslint-disable-line no-constant-condition\n ) {\n if (nonceValue !== currentNonceValue) {\n resolve({\n __type: TransactionStatus.NONCE_INVALID,\n slotInWhichNonceDidAdvance: lastCheckedSlot\n });\n return;\n }\n await sleep(2000);\n if (done) return;\n currentNonceValue = await getCurrentNonceValue();\n if (done) return;\n }\n })();\n });\n const {\n abortConfirmation,\n confirmationPromise\n } = this.getTransactionConfirmationPromise({\n commitment,\n signature\n });\n const cancellationPromise = this.getCancellationPromise(abortSignal);\n let result;\n try {\n const outcome = await Promise.race([cancellationPromise, confirmationPromise, expiryPromise]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n // Double check that the transaction is indeed unconfirmed.\n let signatureStatus;\n while (true // eslint-disable-line no-constant-condition\n ) {\n const status = await this.getSignatureStatus(signature);\n if (status == null) {\n break;\n }\n if (status.context.slot < (outcome.slotInWhichNonceDidAdvance ?? minContextSlot)) {\n await sleep(400);\n continue;\n }\n signatureStatus = status;\n break;\n }\n if (signatureStatus?.value) {\n const commitmentForStatus = commitment || 'finalized';\n const {\n confirmationStatus\n } = signatureStatus.value;\n switch (commitmentForStatus) {\n case 'processed':\n case 'recent':\n if (confirmationStatus !== 'processed' && confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized') {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n case 'confirmed':\n case 'single':\n case 'singleGossip':\n if (confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized') {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n case 'finalized':\n case 'max':\n case 'root':\n if (confirmationStatus !== 'finalized') {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n default:\n // Exhaustive switch.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n (_ => {})(commitmentForStatus);\n }\n result = {\n context: signatureStatus.context,\n value: {\n err: signatureStatus.value.err\n }\n };\n } else {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n }\n } finally {\n done = true;\n abortConfirmation();\n }\n return result;\n }\n async confirmTransactionUsingLegacyTimeoutStrategy({\n commitment,\n signature\n }) {\n let timeoutId;\n const expiryPromise = new Promise(resolve => {\n let timeoutMs = this._confirmTransactionInitialTimeout || 60 * 1000;\n switch (commitment) {\n case 'processed':\n case 'recent':\n case 'single':\n case 'confirmed':\n case 'singleGossip':\n {\n timeoutMs = this._confirmTransactionInitialTimeout || 30 * 1000;\n break;\n }\n }\n timeoutId = setTimeout(() => resolve({\n __type: TransactionStatus.TIMED_OUT,\n timeoutMs\n }), timeoutMs);\n });\n const {\n abortConfirmation,\n confirmationPromise\n } = this.getTransactionConfirmationPromise({\n commitment,\n signature\n });\n let result;\n try {\n const outcome = await Promise.race([confirmationPromise, expiryPromise]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n throw new TransactionExpiredTimeoutError(signature, outcome.timeoutMs / 1000);\n }\n } finally {\n clearTimeout(timeoutId);\n abortConfirmation();\n }\n return result;\n }\n\n /**\n * Return the list of nodes that are currently participating in the cluster\n */\n async getClusterNodes() {\n const unsafeRes = await this._rpcRequest('getClusterNodes', []);\n const res = create(unsafeRes, jsonRpcResult(array(ContactInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get cluster nodes');\n }\n return res.result;\n }\n\n /**\n * Return the list of nodes that are currently participating in the cluster\n */\n async getVoteAccounts(commitment) {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getVoteAccounts', args);\n const res = create(unsafeRes, GetVoteAccounts);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get vote accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch the current slot that the node is processing\n */\n async getSlot(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getSlot', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot');\n }\n return res.result;\n }\n\n /**\n * Fetch the current slot leader of the cluster\n */\n async getSlotLeader(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getSlotLeader', args);\n const res = create(unsafeRes, jsonRpcResult(string()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot leader');\n }\n return res.result;\n }\n\n /**\n * Fetch `limit` number of slot leaders starting from `startSlot`\n *\n * @param startSlot fetch slot leaders starting from this slot\n * @param limit number of slot leaders to return\n */\n async getSlotLeaders(startSlot, limit) {\n const args = [startSlot, limit];\n const unsafeRes = await this._rpcRequest('getSlotLeaders', args);\n const res = create(unsafeRes, jsonRpcResult(array(PublicKeyFromString)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot leaders');\n }\n return res.result;\n }\n\n /**\n * Fetch the current status of a signature\n */\n async getSignatureStatus(signature, config) {\n const {\n context,\n value: values\n } = await this.getSignatureStatuses([signature], config);\n assert(values.length === 1);\n const value = values[0];\n return {\n context,\n value\n };\n }\n\n /**\n * Fetch the current statuses of a batch of signatures\n */\n async getSignatureStatuses(signatures, config) {\n const params = [signatures];\n if (config) {\n params.push(config);\n }\n const unsafeRes = await this._rpcRequest('getSignatureStatuses', params);\n const res = create(unsafeRes, GetSignatureStatusesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get signature status');\n }\n return res.result;\n }\n\n /**\n * Fetch the current transaction count of the cluster\n */\n async getTransactionCount(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getTransactionCount', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction count');\n }\n return res.result;\n }\n\n /**\n * Fetch the current total currency supply of the cluster in lamports\n *\n * @deprecated Deprecated since RPC v1.2.8. Please use {@link getSupply} instead.\n */\n async getTotalSupply(commitment) {\n const result = await this.getSupply({\n commitment,\n excludeNonCirculatingAccountsList: true\n });\n return result.value.total;\n }\n\n /**\n * Fetch the cluster InflationGovernor parameters\n */\n async getInflationGovernor(commitment) {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getInflationGovernor', args);\n const res = create(unsafeRes, GetInflationGovernorRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation');\n }\n return res.result;\n }\n\n /**\n * Fetch the inflation reward for a list of addresses for an epoch\n */\n async getInflationReward(addresses, epoch, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([addresses.map(pubkey => pubkey.toBase58())], commitment, undefined /* encoding */, {\n ...config,\n epoch: epoch != null ? epoch : config?.epoch\n });\n const unsafeRes = await this._rpcRequest('getInflationReward', args);\n const res = create(unsafeRes, GetInflationRewardResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation reward');\n }\n return res.result;\n }\n\n /**\n * Fetch the specific inflation values for the current epoch\n */\n async getInflationRate() {\n const unsafeRes = await this._rpcRequest('getInflationRate', []);\n const res = create(unsafeRes, GetInflationRateRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation rate');\n }\n return res.result;\n }\n\n /**\n * Fetch the Epoch Info parameters\n */\n async getEpochInfo(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getEpochInfo', args);\n const res = create(unsafeRes, GetEpochInfoRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get epoch info');\n }\n return res.result;\n }\n\n /**\n * Fetch the Epoch Schedule parameters\n */\n async getEpochSchedule() {\n const unsafeRes = await this._rpcRequest('getEpochSchedule', []);\n const res = create(unsafeRes, GetEpochScheduleRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get epoch schedule');\n }\n const epochSchedule = res.result;\n return new EpochSchedule(epochSchedule.slotsPerEpoch, epochSchedule.leaderScheduleSlotOffset, epochSchedule.warmup, epochSchedule.firstNormalEpoch, epochSchedule.firstNormalSlot);\n }\n\n /**\n * Fetch the leader schedule for the current epoch\n * @return {Promise>}\n */\n async getLeaderSchedule() {\n const unsafeRes = await this._rpcRequest('getLeaderSchedule', []);\n const res = create(unsafeRes, GetLeaderScheduleRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get leader schedule');\n }\n return res.result;\n }\n\n /**\n * Fetch the minimum balance needed to exempt an account of `dataLength`\n * size from rent\n */\n async getMinimumBalanceForRentExemption(dataLength, commitment) {\n const args = this._buildArgs([dataLength], commitment);\n const unsafeRes = await this._rpcRequest('getMinimumBalanceForRentExemption', args);\n const res = create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult);\n if ('error' in res) {\n console.warn('Unable to fetch minimum balance for rent exemption');\n return 0;\n }\n return res.result;\n }\n\n /**\n * Fetch a recent blockhash from the cluster, return with context\n * @return {Promise>}\n *\n * @deprecated Deprecated since RPC v1.9.0. Please use {@link getLatestBlockhash} instead.\n */\n async getRecentBlockhashAndContext(commitment) {\n const {\n context,\n value: {\n blockhash\n }\n } = await this.getLatestBlockhashAndContext(commitment);\n const feeCalculator = {\n get lamportsPerSignature() {\n 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.');\n },\n toJSON() {\n return {};\n }\n };\n return {\n context,\n value: {\n blockhash,\n feeCalculator\n }\n };\n }\n\n /**\n * Fetch recent performance samples\n * @return {Promise>}\n */\n async getRecentPerformanceSamples(limit) {\n const unsafeRes = await this._rpcRequest('getRecentPerformanceSamples', limit ? [limit] : []);\n const res = create(unsafeRes, GetRecentPerformanceSamplesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get recent performance samples');\n }\n return res.result;\n }\n\n /**\n * Fetch the fee calculator for a recent blockhash from the cluster, return with context\n *\n * @deprecated Deprecated since RPC v1.9.0. Please use {@link getFeeForMessage} instead.\n */\n async getFeeCalculatorForBlockhash(blockhash, commitment) {\n const args = this._buildArgs([blockhash], commitment);\n const unsafeRes = await this._rpcRequest('getFeeCalculatorForBlockhash', args);\n const res = create(unsafeRes, GetFeeCalculatorRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get fee calculator');\n }\n const {\n context,\n value\n } = res.result;\n return {\n context,\n value: value !== null ? value.feeCalculator : null\n };\n }\n\n /**\n * Fetch the fee for a message from the cluster, return with context\n */\n async getFeeForMessage(message, commitment) {\n const wireMessage = toBuffer(message.serialize()).toString('base64');\n const args = this._buildArgs([wireMessage], commitment);\n const unsafeRes = await this._rpcRequest('getFeeForMessage', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(nullable(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get fee for message');\n }\n if (res.result === null) {\n throw new Error('invalid blockhash');\n }\n return res.result;\n }\n\n /**\n * Fetch a list of prioritization fees from recent blocks.\n */\n async getRecentPrioritizationFees(config) {\n const accounts = config?.lockedWritableAccounts?.map(key => key.toBase58());\n const args = accounts?.length ? [accounts] : [];\n const unsafeRes = await this._rpcRequest('getRecentPrioritizationFees', args);\n const res = create(unsafeRes, GetRecentPrioritizationFeesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get recent prioritization fees');\n }\n return res.result;\n }\n /**\n * Fetch a recent blockhash from the cluster\n * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>}\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link getLatestBlockhash} instead.\n */\n async getRecentBlockhash(commitment) {\n try {\n const res = await this.getRecentBlockhashAndContext(commitment);\n return res.value;\n } catch (e) {\n throw new Error('failed to get recent blockhash: ' + e);\n }\n }\n\n /**\n * Fetch the latest blockhash from the cluster\n * @return {Promise}\n */\n async getLatestBlockhash(commitmentOrConfig) {\n try {\n const res = await this.getLatestBlockhashAndContext(commitmentOrConfig);\n return res.value;\n } catch (e) {\n throw new Error('failed to get recent blockhash: ' + e);\n }\n }\n\n /**\n * Fetch the latest blockhash from the cluster\n * @return {Promise}\n */\n async getLatestBlockhashAndContext(commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getLatestBlockhash', args);\n const res = create(unsafeRes, GetLatestBlockhashRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get latest blockhash');\n }\n return res.result;\n }\n\n /**\n * Returns whether a blockhash is still valid or not\n */\n async isBlockhashValid(blockhash, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgs([blockhash], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('isBlockhashValid', args);\n const res = create(unsafeRes, IsBlockhashValidRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to determine if the blockhash `' + blockhash + '`is valid');\n }\n return res.result;\n }\n\n /**\n * Fetch the node version\n */\n async getVersion() {\n const unsafeRes = await this._rpcRequest('getVersion', []);\n const res = create(unsafeRes, jsonRpcResult(VersionResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get version');\n }\n return res.result;\n }\n\n /**\n * Fetch the genesis hash\n */\n async getGenesisHash() {\n const unsafeRes = await this._rpcRequest('getGenesisHash', []);\n const res = create(unsafeRes, jsonRpcResult(string()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get genesis hash');\n }\n return res.result;\n }\n\n /**\n * Fetch a processed block from the cluster.\n *\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n\n /**\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Fetch a processed block from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Fetch a processed block from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(slot, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getBlock', args);\n try {\n switch (config?.transactionDetails) {\n case 'accounts':\n {\n const res = create(unsafeRes, GetAccountsModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n case 'none':\n {\n const res = create(unsafeRes, GetNoneModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n default:\n {\n const res = create(unsafeRes, GetBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n const {\n result\n } = res;\n return result ? {\n ...result,\n transactions: result.transactions.map(({\n transaction,\n meta,\n version\n }) => ({\n meta,\n transaction: {\n ...transaction,\n message: versionedMessageFromResponse(version, transaction.message)\n },\n version\n }))\n } : null;\n }\n }\n } catch (e) {\n throw new SolanaJSONRPCError(e, 'failed to get confirmed block');\n }\n }\n\n /**\n * Fetch parsed transaction details for a confirmed or finalized block\n */\n\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n async getParsedBlock(slot, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed([slot], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getBlock', args);\n try {\n switch (config?.transactionDetails) {\n case 'accounts':\n {\n const res = create(unsafeRes, GetParsedAccountsModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n case 'none':\n {\n const res = create(unsafeRes, GetParsedNoneModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n default:\n {\n const res = create(unsafeRes, GetParsedBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n }\n } catch (e) {\n throw new SolanaJSONRPCError(e, 'failed to get block');\n }\n }\n /*\n * Returns recent block production information from the current or previous epoch\n */\n async getBlockProduction(configOrCommitment) {\n let extra;\n let commitment;\n if (typeof configOrCommitment === 'string') {\n commitment = configOrCommitment;\n } else if (configOrCommitment) {\n const {\n commitment: c,\n ...rest\n } = configOrCommitment;\n commitment = c;\n extra = rest;\n }\n const args = this._buildArgs([], commitment, 'base64', extra);\n const unsafeRes = await this._rpcRequest('getBlockProduction', args);\n const res = create(unsafeRes, BlockProductionResponseStruct);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get block production information');\n }\n return res.result;\n }\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n *\n * @deprecated Instead, call `getTransaction` using a\n * `GetVersionedTransactionConfig` by setting the\n * `maxSupportedTransactionVersion` property.\n */\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransaction(signature, rawConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, undefined /* encoding */, config);\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n const result = res.result;\n if (!result) return result;\n return {\n ...result,\n transaction: {\n ...result.transaction,\n message: versionedMessageFromResponse(result.version, result.transaction.message)\n }\n };\n }\n\n /**\n * Fetch parsed transaction details for a confirmed or finalized transaction\n */\n async getParsedTransaction(signature, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n return res.result;\n }\n\n /**\n * Fetch parsed transaction details for a batch of confirmed transactions\n */\n async getParsedTransactions(signatures, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config);\n return {\n methodName: 'getTransaction',\n args\n };\n });\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map(unsafeRes => {\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n }\n return res.result;\n });\n return res;\n }\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link TransactionResponse}.\n *\n * @deprecated Instead, call `getTransactions` using a\n * `GetVersionedTransactionConfig` by setting the\n * `maxSupportedTransactionVersion` property.\n */\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link\n * VersionedTransactionResponse}.\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link\n * VersionedTransactionResponse}.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransactions(signatures, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, undefined /* encoding */, config);\n return {\n methodName: 'getTransaction',\n args\n };\n });\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map(unsafeRes => {\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n }\n const result = res.result;\n if (!result) return result;\n return {\n ...result,\n transaction: {\n ...result.transaction,\n message: versionedMessageFromResponse(result.version, result.transaction.message)\n }\n };\n });\n return res;\n }\n\n /**\n * Fetch a list of Transactions and transaction statuses from the cluster\n * for a confirmed block.\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getBlock} instead.\n */\n async getConfirmedBlock(slot, commitment) {\n const args = this._buildArgsAtLeastConfirmed([slot], commitment);\n const unsafeRes = await this._rpcRequest('getBlock', args);\n const res = create(unsafeRes, GetConfirmedBlockRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Confirmed block ' + slot + ' not found');\n }\n const block = {\n ...result,\n transactions: result.transactions.map(({\n transaction,\n meta\n }) => {\n const message = new Message(transaction.message);\n return {\n meta,\n transaction: {\n ...transaction,\n message\n }\n };\n })\n };\n return {\n ...block,\n transactions: block.transactions.map(({\n transaction,\n meta\n }) => {\n return {\n meta,\n transaction: Transaction.populate(transaction.message, transaction.signatures)\n };\n })\n };\n }\n\n /**\n * Fetch confirmed blocks between two slots\n */\n async getBlocks(startSlot, endSlot, commitment) {\n const args = this._buildArgsAtLeastConfirmed(endSlot !== undefined ? [startSlot, endSlot] : [startSlot], commitment);\n const unsafeRes = await this._rpcRequest('getBlocks', args);\n const res = create(unsafeRes, jsonRpcResult(array(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get blocks');\n }\n return res.result;\n }\n\n /**\n * Fetch a list of Signatures from the cluster for a block, excluding rewards\n */\n async getBlockSignatures(slot, commitment) {\n const args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, {\n transactionDetails: 'signatures',\n rewards: false\n });\n const unsafeRes = await this._rpcRequest('getBlock', args);\n const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Block ' + slot + ' not found');\n }\n return result;\n }\n\n /**\n * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getBlockSignatures} instead.\n */\n async getConfirmedBlockSignatures(slot, commitment) {\n const args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, {\n transactionDetails: 'signatures',\n rewards: false\n });\n const unsafeRes = await this._rpcRequest('getBlock', args);\n const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Confirmed block ' + slot + ' not found');\n }\n return result;\n }\n\n /**\n * Fetch a transaction details for a confirmed transaction\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getTransaction} instead.\n */\n async getConfirmedTransaction(signature, commitment) {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment);\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n const result = res.result;\n if (!result) return result;\n const message = new Message(result.transaction.message);\n const signatures = result.transaction.signatures;\n return {\n ...result,\n transaction: Transaction.populate(message, signatures)\n };\n }\n\n /**\n * Fetch parsed transaction details for a confirmed transaction\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getParsedTransaction} instead.\n */\n async getParsedConfirmedTransaction(signature, commitment) {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed');\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transaction');\n }\n return res.result;\n }\n\n /**\n * Fetch parsed transaction details for a batch of confirmed transactions\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getParsedTransactions} instead.\n */\n async getParsedConfirmedTransactions(signatures, commitment) {\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed');\n return {\n methodName: 'getTransaction',\n args\n };\n });\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map(unsafeRes => {\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transactions');\n }\n return res.result;\n });\n return res;\n }\n\n /**\n * Fetch a list of all the confirmed signatures for transactions involving an address\n * within a specified slot range. Max range allowed is 10,000 slots.\n *\n * @deprecated Deprecated since RPC v1.3. Please use {@link getConfirmedSignaturesForAddress2} instead.\n *\n * @param address queried address\n * @param startSlot start slot, inclusive\n * @param endSlot end slot, inclusive\n */\n async getConfirmedSignaturesForAddress(address, startSlot, endSlot) {\n let options = {};\n let firstAvailableBlock = await this.getFirstAvailableBlock();\n while (!('until' in options)) {\n startSlot--;\n if (startSlot <= 0 || startSlot < firstAvailableBlock) {\n break;\n }\n try {\n const block = await this.getConfirmedBlockSignatures(startSlot, 'finalized');\n if (block.signatures.length > 0) {\n options.until = block.signatures[block.signatures.length - 1].toString();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('skipped')) {\n continue;\n } else {\n throw err;\n }\n }\n }\n let highestConfirmedRoot = await this.getSlot('finalized');\n while (!('before' in options)) {\n endSlot++;\n if (endSlot > highestConfirmedRoot) {\n break;\n }\n try {\n const block = await this.getConfirmedBlockSignatures(endSlot);\n if (block.signatures.length > 0) {\n options.before = block.signatures[block.signatures.length - 1].toString();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('skipped')) {\n continue;\n } else {\n throw err;\n }\n }\n }\n const confirmedSignatureInfo = await this.getConfirmedSignaturesForAddress2(address, options);\n return confirmedSignatureInfo.map(info => info.signature);\n }\n\n /**\n * Returns confirmed signatures for transactions involving an\n * address backwards in time from the provided signature or most recent confirmed block\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getSignaturesForAddress} instead.\n */\n async getConfirmedSignaturesForAddress2(address, options, commitment) {\n const args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options);\n const unsafeRes = await this._rpcRequest('getConfirmedSignaturesForAddress2', args);\n const res = create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed signatures for address');\n }\n return res.result;\n }\n\n /**\n * Returns confirmed signatures for transactions involving an\n * address backwards in time from the provided signature or most recent confirmed block\n *\n *\n * @param address queried address\n * @param options\n */\n async getSignaturesForAddress(address, options, commitment) {\n const args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options);\n const unsafeRes = await this._rpcRequest('getSignaturesForAddress', args);\n const res = create(unsafeRes, GetSignaturesForAddressRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get signatures for address');\n }\n return res.result;\n }\n async getAddressLookupTable(accountKey, config) {\n const {\n context,\n value: accountInfo\n } = await this.getAccountInfoAndContext(accountKey, config);\n let value = null;\n if (accountInfo !== null) {\n value = new AddressLookupTableAccount({\n key: accountKey,\n state: AddressLookupTableAccount.deserialize(accountInfo.data)\n });\n }\n return {\n context,\n value\n };\n }\n\n /**\n * Fetch the contents of a Nonce account from the cluster, return with context\n */\n async getNonceAndContext(nonceAccount, commitmentOrConfig) {\n const {\n context,\n value: accountInfo\n } = await this.getAccountInfoAndContext(nonceAccount, commitmentOrConfig);\n let value = null;\n if (accountInfo !== null) {\n value = NonceAccount.fromAccountData(accountInfo.data);\n }\n return {\n context,\n value\n };\n }\n\n /**\n * Fetch the contents of a Nonce account from the cluster\n */\n async getNonce(nonceAccount, commitmentOrConfig) {\n return await this.getNonceAndContext(nonceAccount, commitmentOrConfig).then(x => x.value).catch(e => {\n throw new Error('failed to get nonce for account ' + nonceAccount.toBase58() + ': ' + e);\n });\n }\n\n /**\n * Request an allocation of lamports to the specified address\n *\n * ```typescript\n * import { Connection, PublicKey, LAMPORTS_PER_SOL } from \"@solana/web3.js\";\n *\n * (async () => {\n * const connection = new Connection(\"https://api.testnet.solana.com\", \"confirmed\");\n * const myAddress = new PublicKey(\"2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM\");\n * const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL);\n * await connection.confirmTransaction(signature);\n * })();\n * ```\n */\n async requestAirdrop(to, lamports) {\n const unsafeRes = await this._rpcRequest('requestAirdrop', [to.toBase58(), lamports]);\n const res = create(unsafeRes, RequestAirdropRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `airdrop to ${to.toBase58()} failed`);\n }\n return res.result;\n }\n\n /**\n * @internal\n */\n async _blockhashWithExpiryBlockHeight(disableCache) {\n if (!disableCache) {\n // Wait for polling to finish\n while (this._pollingBlockhash) {\n await sleep(100);\n }\n const timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch;\n const expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS;\n if (this._blockhashInfo.latestBlockhash !== null && !expired) {\n return this._blockhashInfo.latestBlockhash;\n }\n }\n return await this._pollNewBlockhash();\n }\n\n /**\n * @internal\n */\n async _pollNewBlockhash() {\n this._pollingBlockhash = true;\n try {\n const startTime = Date.now();\n const cachedLatestBlockhash = this._blockhashInfo.latestBlockhash;\n const cachedBlockhash = cachedLatestBlockhash ? cachedLatestBlockhash.blockhash : null;\n for (let i = 0; i < 50; i++) {\n const latestBlockhash = await this.getLatestBlockhash('finalized');\n if (cachedBlockhash !== latestBlockhash.blockhash) {\n this._blockhashInfo = {\n latestBlockhash,\n lastFetch: Date.now(),\n transactionSignatures: [],\n simulatedSignatures: []\n };\n return latestBlockhash;\n }\n\n // Sleep for approximately half a slot\n await sleep(MS_PER_SLOT / 2);\n }\n throw new Error(`Unable to obtain a new blockhash after ${Date.now() - startTime}ms`);\n } finally {\n this._pollingBlockhash = false;\n }\n }\n\n /**\n * get the stake minimum delegation\n */\n async getStakeMinimumDelegation(config) {\n const {\n commitment,\n config: configArg\n } = extractCommitmentFromConfig(config);\n const args = this._buildArgs([], commitment, 'base64', configArg);\n const unsafeRes = await this._rpcRequest('getStakeMinimumDelegation', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, `failed to get stake minimum delegation`);\n }\n return res.result;\n }\n\n /**\n * Simulate a transaction\n *\n * @deprecated Instead, call {@link simulateTransaction} with {@link\n * VersionedTransaction} and {@link SimulateTransactionConfig} parameters\n */\n\n /**\n * Simulate a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Simulate a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n async simulateTransaction(transactionOrMessage, configOrSigners, includeAccounts) {\n if ('message' in transactionOrMessage) {\n const versionedTx = transactionOrMessage;\n const wireTransaction = versionedTx.serialize();\n const encodedTransaction = Buffer.from(wireTransaction).toString('base64');\n if (Array.isArray(configOrSigners) || includeAccounts !== undefined) {\n throw new Error('Invalid arguments');\n }\n const config = configOrSigners || {};\n config.encoding = 'base64';\n if (!('commitment' in config)) {\n config.commitment = this.commitment;\n }\n if (configOrSigners && typeof configOrSigners === 'object' && 'innerInstructions' in configOrSigners) {\n config.innerInstructions = configOrSigners.innerInstructions;\n }\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n if ('error' in res) {\n throw new Error('failed to simulate transaction: ' + res.error.message);\n }\n return res.result;\n }\n let transaction;\n if (transactionOrMessage instanceof Transaction) {\n let originalTx = transactionOrMessage;\n transaction = new Transaction();\n transaction.feePayer = originalTx.feePayer;\n transaction.instructions = transactionOrMessage.instructions;\n transaction.nonceInfo = originalTx.nonceInfo;\n transaction.signatures = originalTx.signatures;\n } else {\n transaction = Transaction.populate(transactionOrMessage);\n // HACK: this function relies on mutating the populated transaction\n transaction._message = transaction._json = undefined;\n }\n if (configOrSigners !== undefined && !Array.isArray(configOrSigners)) {\n throw new Error('Invalid arguments');\n }\n const signers = configOrSigners;\n if (transaction.nonceInfo && signers) {\n transaction.sign(...signers);\n } else {\n let disableCache = this._disableBlockhashCaching;\n for (;;) {\n const latestBlockhash = await this._blockhashWithExpiryBlockHeight(disableCache);\n transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n transaction.recentBlockhash = latestBlockhash.blockhash;\n if (!signers) break;\n transaction.sign(...signers);\n if (!transaction.signature) {\n throw new Error('!signature'); // should never happen\n }\n const signature = transaction.signature.toString('base64');\n if (!this._blockhashInfo.simulatedSignatures.includes(signature) && !this._blockhashInfo.transactionSignatures.includes(signature)) {\n // The signature of this transaction has not been seen before with the\n // current recentBlockhash, all done. Let's break\n this._blockhashInfo.simulatedSignatures.push(signature);\n break;\n } else {\n // This transaction would be treated as duplicate (its derived signature\n // matched to one of already recorded signatures).\n // So, we must fetch a new blockhash for a different signature by disabling\n // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n disableCache = true;\n }\n }\n }\n const message = transaction._compile();\n const signData = message.serialize();\n const wireTransaction = transaction._serialize(signData);\n const encodedTransaction = wireTransaction.toString('base64');\n const config = {\n encoding: 'base64',\n commitment: this.commitment\n };\n if (includeAccounts) {\n const addresses = (Array.isArray(includeAccounts) ? includeAccounts : message.nonProgramIds()).map(key => key.toBase58());\n config['accounts'] = {\n encoding: 'base64',\n addresses\n };\n }\n if (signers) {\n config.sigVerify = true;\n }\n if (configOrSigners && typeof configOrSigners === 'object' && 'innerInstructions' in configOrSigners) {\n config.innerInstructions = configOrSigners.innerInstructions;\n }\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n if ('error' in res) {\n let logs;\n if ('data' in res.error) {\n logs = res.error.data.logs;\n if (logs && Array.isArray(logs)) {\n const traceIndent = '\\n ';\n const logTrace = traceIndent + logs.join(traceIndent);\n console.error(res.error.message, logTrace);\n }\n }\n throw new SendTransactionError({\n action: 'simulate',\n signature: '',\n transactionMessage: res.error.message,\n logs: logs\n });\n }\n return res.result;\n }\n\n /**\n * Sign and send a transaction\n *\n * @deprecated Instead, call {@link sendTransaction} with a {@link\n * VersionedTransaction}\n */\n\n /**\n * Send a signed transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n\n /**\n * Sign and send a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n async sendTransaction(transaction, signersOrOptions, options) {\n if ('version' in transaction) {\n if (signersOrOptions && Array.isArray(signersOrOptions)) {\n throw new Error('Invalid arguments');\n }\n const wireTransaction = transaction.serialize();\n return await this.sendRawTransaction(wireTransaction, signersOrOptions);\n }\n if (signersOrOptions === undefined || !Array.isArray(signersOrOptions)) {\n throw new Error('Invalid arguments');\n }\n const signers = signersOrOptions;\n if (transaction.nonceInfo) {\n transaction.sign(...signers);\n } else {\n let disableCache = this._disableBlockhashCaching;\n for (;;) {\n const latestBlockhash = await this._blockhashWithExpiryBlockHeight(disableCache);\n transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n transaction.recentBlockhash = latestBlockhash.blockhash;\n transaction.sign(...signers);\n if (!transaction.signature) {\n throw new Error('!signature'); // should never happen\n }\n const signature = transaction.signature.toString('base64');\n if (!this._blockhashInfo.transactionSignatures.includes(signature)) {\n // The signature of this transaction has not been seen before with the\n // current recentBlockhash, all done. Let's break\n this._blockhashInfo.transactionSignatures.push(signature);\n break;\n } else {\n // This transaction would be treated as duplicate (its derived signature\n // matched to one of already recorded signatures).\n // So, we must fetch a new blockhash for a different signature by disabling\n // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n disableCache = true;\n }\n }\n }\n const wireTransaction = transaction.serialize();\n return await this.sendRawTransaction(wireTransaction, options);\n }\n\n /**\n * Send a transaction that has already been signed and serialized into the\n * wire format\n */\n async sendRawTransaction(rawTransaction, options) {\n const encodedTransaction = toBuffer(rawTransaction).toString('base64');\n const result = await this.sendEncodedTransaction(encodedTransaction, options);\n return result;\n }\n\n /**\n * Send a transaction that has already been signed, serialized into the\n * wire format, and encoded as a base64 string\n */\n async sendEncodedTransaction(encodedTransaction, options) {\n const config = {\n encoding: 'base64'\n };\n const skipPreflight = options && options.skipPreflight;\n const preflightCommitment = skipPreflight === true ? 'processed' // FIXME Remove when https://github.com/anza-xyz/agave/pull/483 is deployed.\n : options && options.preflightCommitment || this.commitment;\n if (options && options.maxRetries != null) {\n config.maxRetries = options.maxRetries;\n }\n if (options && options.minContextSlot != null) {\n config.minContextSlot = options.minContextSlot;\n }\n if (skipPreflight) {\n config.skipPreflight = skipPreflight;\n }\n if (preflightCommitment) {\n config.preflightCommitment = preflightCommitment;\n }\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('sendTransaction', args);\n const res = create(unsafeRes, SendTransactionRpcResult);\n if ('error' in res) {\n let logs = undefined;\n if ('data' in res.error) {\n logs = res.error.data.logs;\n }\n throw new SendTransactionError({\n action: skipPreflight ? 'send' : 'simulate',\n signature: '',\n transactionMessage: res.error.message,\n logs: logs\n });\n }\n return res.result;\n }\n\n /**\n * @internal\n */\n _wsOnOpen() {\n this._rpcWebSocketConnected = true;\n this._rpcWebSocketHeartbeat = setInterval(() => {\n // Ping server every 5s to prevent idle timeouts\n (async () => {\n try {\n await this._rpcWebSocket.notify('ping');\n // eslint-disable-next-line no-empty\n } catch {}\n })();\n }, 5000);\n this._updateSubscriptions();\n }\n\n /**\n * @internal\n */\n _wsOnError(err) {\n this._rpcWebSocketConnected = false;\n console.error('ws error:', err.message);\n }\n\n /**\n * @internal\n */\n _wsOnClose(code) {\n this._rpcWebSocketConnected = false;\n this._rpcWebSocketGeneration = (this._rpcWebSocketGeneration + 1) % Number.MAX_SAFE_INTEGER;\n if (this._rpcWebSocketIdleTimeout) {\n clearTimeout(this._rpcWebSocketIdleTimeout);\n this._rpcWebSocketIdleTimeout = null;\n }\n if (this._rpcWebSocketHeartbeat) {\n clearInterval(this._rpcWebSocketHeartbeat);\n this._rpcWebSocketHeartbeat = null;\n }\n if (code === 1000) {\n // explicit close, check if any subscriptions have been made since close\n this._updateSubscriptions();\n return;\n }\n\n // implicit close, prepare subscriptions for auto-reconnect\n this._subscriptionCallbacksByServerSubscriptionId = {};\n Object.entries(this._subscriptionsByHash).forEach(([hash, subscription]) => {\n this._setSubscription(hash, {\n ...subscription,\n state: 'pending'\n });\n });\n }\n\n /**\n * @internal\n */\n _setSubscription(hash, nextSubscription) {\n const prevState = this._subscriptionsByHash[hash]?.state;\n this._subscriptionsByHash[hash] = nextSubscription;\n if (prevState !== nextSubscription.state) {\n const stateChangeCallbacks = this._subscriptionStateChangeCallbacksByHash[hash];\n if (stateChangeCallbacks) {\n stateChangeCallbacks.forEach(cb => {\n try {\n cb(nextSubscription.state);\n // eslint-disable-next-line no-empty\n } catch {}\n });\n }\n }\n }\n\n /**\n * @internal\n */\n _onSubscriptionStateChange(clientSubscriptionId, callback) {\n const hash = this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n if (hash == null) {\n return () => {};\n }\n const stateChangeCallbacks = this._subscriptionStateChangeCallbacksByHash[hash] ||= new Set();\n stateChangeCallbacks.add(callback);\n return () => {\n stateChangeCallbacks.delete(callback);\n if (stateChangeCallbacks.size === 0) {\n delete this._subscriptionStateChangeCallbacksByHash[hash];\n }\n };\n }\n\n /**\n * @internal\n */\n async _updateSubscriptions() {\n if (Object.keys(this._subscriptionsByHash).length === 0) {\n if (this._rpcWebSocketConnected) {\n this._rpcWebSocketConnected = false;\n this._rpcWebSocketIdleTimeout = setTimeout(() => {\n this._rpcWebSocketIdleTimeout = null;\n try {\n this._rpcWebSocket.close();\n } catch (err) {\n // swallow error if socket has already been closed.\n if (err instanceof Error) {\n console.log(`Error when closing socket connection: ${err.message}`);\n }\n }\n }, 500);\n }\n return;\n }\n if (this._rpcWebSocketIdleTimeout !== null) {\n clearTimeout(this._rpcWebSocketIdleTimeout);\n this._rpcWebSocketIdleTimeout = null;\n this._rpcWebSocketConnected = true;\n }\n if (!this._rpcWebSocketConnected) {\n this._rpcWebSocket.connect();\n return;\n }\n const activeWebSocketGeneration = this._rpcWebSocketGeneration;\n const isCurrentConnectionStillActive = () => {\n return activeWebSocketGeneration === this._rpcWebSocketGeneration;\n };\n await Promise.all(\n // Don't be tempted to change this to `Object.entries`. We call\n // `_updateSubscriptions` recursively when processing the state,\n // so it's important that we look up the *current* version of\n // each subscription, every time we process a hash.\n Object.keys(this._subscriptionsByHash).map(async hash => {\n const subscription = this._subscriptionsByHash[hash];\n if (subscription === undefined) {\n // This entry has since been deleted. Skip.\n return;\n }\n switch (subscription.state) {\n case 'pending':\n case 'unsubscribed':\n if (subscription.callbacks.size === 0) {\n /**\n * You can end up here when:\n *\n * - a subscription has recently unsubscribed\n * without having new callbacks added to it\n * while the unsubscribe was in flight, or\n * - when a pending subscription has its\n * listeners removed before a request was\n * sent to the server.\n *\n * Being that nobody is interested in this\n * subscription any longer, delete it.\n */\n delete this._subscriptionsByHash[hash];\n if (subscription.state === 'unsubscribed') {\n delete this._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId];\n }\n await this._updateSubscriptions();\n return;\n }\n await (async () => {\n const {\n args,\n method\n } = subscription;\n try {\n this._setSubscription(hash, {\n ...subscription,\n state: 'subscribing'\n });\n const serverSubscriptionId = await this._rpcWebSocket.call(method, args);\n this._setSubscription(hash, {\n ...subscription,\n serverSubscriptionId,\n state: 'subscribed'\n });\n this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId] = subscription.callbacks;\n await this._updateSubscriptions();\n } catch (e) {\n console.error(`Received ${e instanceof Error ? '' : 'JSON-RPC '}error calling \\`${method}\\``, {\n args,\n error: e\n });\n if (!isCurrentConnectionStillActive()) {\n return;\n }\n // TODO: Maybe add an 'errored' state or a retry limit?\n this._setSubscription(hash, {\n ...subscription,\n state: 'pending'\n });\n await this._updateSubscriptions();\n }\n })();\n break;\n case 'subscribed':\n if (subscription.callbacks.size === 0) {\n // By the time we successfully set up a subscription\n // with the server, the client stopped caring about it.\n // Tear it down now.\n await (async () => {\n const {\n serverSubscriptionId,\n unsubscribeMethod\n } = subscription;\n if (this._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)) {\n /**\n * Special case.\n * If we're dealing with a subscription that has been auto-\n * disposed by the RPC, then we can skip the RPC call to\n * tear down the subscription here.\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n this._subscriptionsAutoDisposedByRpc.delete(serverSubscriptionId);\n } else {\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribing'\n });\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribing'\n });\n try {\n await this._rpcWebSocket.call(unsubscribeMethod, [serverSubscriptionId]);\n } catch (e) {\n if (e instanceof Error) {\n console.error(`${unsubscribeMethod} error:`, e.message);\n }\n if (!isCurrentConnectionStillActive()) {\n return;\n }\n // TODO: Maybe add an 'errored' state or a retry limit?\n this._setSubscription(hash, {\n ...subscription,\n state: 'subscribed'\n });\n await this._updateSubscriptions();\n return;\n }\n }\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribed'\n });\n await this._updateSubscriptions();\n })();\n }\n break;\n }\n }));\n }\n\n /**\n * @internal\n */\n _handleServerNotification(serverSubscriptionId, callbackArgs) {\n const callbacks = this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId];\n if (callbacks === undefined) {\n return;\n }\n callbacks.forEach(cb => {\n try {\n cb(\n // I failed to find a way to convince TypeScript that `cb` is of type\n // `TCallback` which is certainly compatible with `Parameters`.\n // See https://github.com/microsoft/TypeScript/issues/47615\n // @ts-ignore\n ...callbackArgs);\n } catch (e) {\n console.error(e);\n }\n });\n }\n\n /**\n * @internal\n */\n _wsOnAccountNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, AccountNotificationResult);\n this._handleServerNotification(subscription, [result.value, result.context]);\n }\n\n /**\n * @internal\n */\n _makeSubscription(subscriptionConfig,\n /**\n * When preparing `args` for a call to `_makeSubscription`, be sure\n * to carefully apply a default `commitment` property, if necessary.\n *\n * - If the user supplied a `commitment` use that.\n * - Otherwise, if the `Connection::commitment` is set, use that.\n * - Otherwise, set it to the RPC server default: `finalized`.\n *\n * This is extremely important to ensure that these two fundamentally\n * identical subscriptions produce the same identifying hash:\n *\n * - A subscription made without specifying a commitment.\n * - A subscription made where the commitment specified is the same\n * as the default applied to the subscription above.\n *\n * Example; these two subscriptions must produce the same hash:\n *\n * - An `accountSubscribe` subscription for `'PUBKEY'`\n * - An `accountSubscribe` subscription for `'PUBKEY'` with commitment\n * `'finalized'`.\n *\n * See the 'making a subscription with defaulted params omitted' test\n * in `connection-subscriptions.ts` for more.\n */\n args) {\n const clientSubscriptionId = this._nextClientSubscriptionId++;\n const hash = fastStableStringify([subscriptionConfig.method, args]);\n const existingSubscription = this._subscriptionsByHash[hash];\n if (existingSubscription === undefined) {\n this._subscriptionsByHash[hash] = {\n ...subscriptionConfig,\n args,\n callbacks: new Set([subscriptionConfig.callback]),\n state: 'pending'\n };\n } else {\n existingSubscription.callbacks.add(subscriptionConfig.callback);\n }\n this._subscriptionHashByClientSubscriptionId[clientSubscriptionId] = hash;\n this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId] = async () => {\n delete this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];\n delete this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n const subscription = this._subscriptionsByHash[hash];\n assert(subscription !== undefined, `Could not find a \\`Subscription\\` when tearing down client subscription #${clientSubscriptionId}`);\n subscription.callbacks.delete(subscriptionConfig.callback);\n await this._updateSubscriptions();\n };\n this._updateSubscriptions();\n return clientSubscriptionId;\n }\n\n /**\n * Register a callback to be invoked whenever the specified account changes\n *\n * @param publicKey Public key of the account to monitor\n * @param callback Function to invoke whenever the account is changed\n * @param config\n * @return subscription id\n */\n\n /** @deprecated Instead, pass in an {@link AccountSubscriptionConfig} */\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n onAccountChange(publicKey, callback, commitmentOrConfig) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([publicKey.toBase58()], commitment || this._commitment || 'finalized',\n // Apply connection/server default.\n 'base64', config);\n return this._makeSubscription({\n callback,\n method: 'accountSubscribe',\n unsubscribeMethod: 'accountUnsubscribe'\n }, args);\n }\n\n /**\n * Deregister an account notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeAccountChangeListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'account change');\n }\n\n /**\n * @internal\n */\n _wsOnProgramAccountNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, ProgramAccountNotificationResult);\n this._handleServerNotification(subscription, [{\n accountId: result.value.pubkey,\n accountInfo: result.value.account\n }, result.context]);\n }\n\n /**\n * Register a callback to be invoked whenever accounts owned by the\n * specified program change\n *\n * @param programId Public key of the program to monitor\n * @param callback Function to invoke whenever the account is changed\n * @param config\n * @return subscription id\n */\n\n /** @deprecated Instead, pass in a {@link ProgramAccountSubscriptionConfig} */\n // eslint-disable-next-line no-dupe-class-members\n\n // eslint-disable-next-line no-dupe-class-members\n onProgramAccountChange(programId, callback, commitmentOrConfig, maybeFilters) {\n const {\n commitment,\n config\n } = extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs([programId.toBase58()], commitment || this._commitment || 'finalized',\n // Apply connection/server default.\n 'base64' /* encoding */, config ? config : maybeFilters ? {\n filters: applyDefaultMemcmpEncodingToFilters(maybeFilters)\n } : undefined /* extra */);\n return this._makeSubscription({\n callback,\n method: 'programSubscribe',\n unsubscribeMethod: 'programUnsubscribe'\n }, args);\n }\n\n /**\n * Deregister an account notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeProgramAccountChangeListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'program account change');\n }\n\n /**\n * Registers a callback to be invoked whenever logs are emitted.\n */\n onLogs(filter, callback, commitment) {\n const args = this._buildArgs([typeof filter === 'object' ? {\n mentions: [filter.toString()]\n } : filter], commitment || this._commitment || 'finalized' // Apply connection/server default.\n );\n return this._makeSubscription({\n callback,\n method: 'logsSubscribe',\n unsubscribeMethod: 'logsUnsubscribe'\n }, args);\n }\n\n /**\n * Deregister a logs callback.\n *\n * @param clientSubscriptionId client subscription id to deregister.\n */\n async removeOnLogsListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'logs');\n }\n\n /**\n * @internal\n */\n _wsOnLogsNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, LogsNotificationResult);\n this._handleServerNotification(subscription, [result.value, result.context]);\n }\n\n /**\n * @internal\n */\n _wsOnSlotNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, SlotNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon slot changes\n *\n * @param callback Function to invoke whenever the slot changes\n * @return subscription id\n */\n onSlotChange(callback) {\n return this._makeSubscription({\n callback,\n method: 'slotSubscribe',\n unsubscribeMethod: 'slotUnsubscribe'\n }, [] /* args */);\n }\n\n /**\n * Deregister a slot notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeSlotChangeListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'slot change');\n }\n\n /**\n * @internal\n */\n _wsOnSlotUpdatesNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, SlotUpdateNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s\n * may be useful to track live progress of a cluster.\n *\n * @param callback Function to invoke whenever the slot updates\n * @return subscription id\n */\n onSlotUpdate(callback) {\n return this._makeSubscription({\n callback,\n method: 'slotsUpdatesSubscribe',\n unsubscribeMethod: 'slotsUpdatesUnsubscribe'\n }, [] /* args */);\n }\n\n /**\n * Deregister a slot update notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeSlotUpdateListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'slot update');\n }\n\n /**\n * @internal\n */\n\n async _unsubscribeClientSubscription(clientSubscriptionId, subscriptionName) {\n const dispose = this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];\n if (dispose) {\n await dispose();\n } else {\n console.warn('Ignored unsubscribe request because an active subscription with id ' + `\\`${clientSubscriptionId}\\` for '${subscriptionName}' events ` + 'could not be found.');\n }\n }\n _buildArgs(args, override, encoding, extra) {\n const commitment = override || this._commitment;\n if (commitment || encoding || extra) {\n let options = {};\n if (encoding) {\n options.encoding = encoding;\n }\n if (commitment) {\n options.commitment = commitment;\n }\n if (extra) {\n options = Object.assign(options, extra);\n }\n args.push(options);\n }\n return args;\n }\n\n /**\n * @internal\n */\n _buildArgsAtLeastConfirmed(args, override, encoding, extra) {\n const commitment = override || this._commitment;\n if (commitment && !['confirmed', 'finalized'].includes(commitment)) {\n throw new Error('Using Connection with default commitment: `' + this._commitment + '`, but method requires at least `confirmed`');\n }\n return this._buildArgs(args, override, encoding, extra);\n }\n\n /**\n * @internal\n */\n _wsOnSignatureNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, SignatureNotificationResult);\n if (result.value !== 'receivedSignature') {\n /**\n * Special case.\n * After a signature is processed, RPCs automatically dispose of the\n * subscription on the server side. We need to track which of these\n * subscriptions have been disposed in such a way, so that we know\n * whether the client is dealing with a not-yet-processed signature\n * (in which case we must tear down the server subscription) or an\n * already-processed signature (in which case the client can simply\n * clear out the subscription locally without telling the server).\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n this._subscriptionsAutoDisposedByRpc.add(subscription);\n }\n this._handleServerNotification(subscription, result.value === 'receivedSignature' ? [{\n type: 'received'\n }, result.context] : [{\n type: 'status',\n result: result.value\n }, result.context]);\n }\n\n /**\n * Register a callback to be invoked upon signature updates\n *\n * @param signature Transaction signature string in base 58\n * @param callback Function to invoke on signature notifications\n * @param commitment Specify the commitment level signature must reach before notification\n * @return subscription id\n */\n onSignature(signature, callback, commitment) {\n const args = this._buildArgs([signature], commitment || this._commitment || 'finalized' // Apply connection/server default.\n );\n const clientSubscriptionId = this._makeSubscription({\n callback: (notification, context) => {\n if (notification.type === 'status') {\n callback(notification.result, context);\n // Signatures subscriptions are auto-removed by the RPC service\n // so no need to explicitly send an unsubscribe message.\n try {\n this.removeSignatureListener(clientSubscriptionId);\n // eslint-disable-next-line no-empty\n } catch (_err) {\n // Already removed.\n }\n }\n },\n method: 'signatureSubscribe',\n unsubscribeMethod: 'signatureUnsubscribe'\n }, args);\n return clientSubscriptionId;\n }\n\n /**\n * Register a callback to be invoked when a transaction is\n * received and/or processed.\n *\n * @param signature Transaction signature string in base 58\n * @param callback Function to invoke on signature notifications\n * @param options Enable received notifications and set the commitment\n * level that signature must reach before notification\n * @return subscription id\n */\n onSignatureWithOptions(signature, callback, options) {\n const {\n commitment,\n ...extra\n } = {\n ...options,\n commitment: options && options.commitment || this._commitment || 'finalized' // Apply connection/server default.\n };\n const args = this._buildArgs([signature], commitment, undefined /* encoding */, extra);\n const clientSubscriptionId = this._makeSubscription({\n callback: (notification, context) => {\n callback(notification, context);\n // Signatures subscriptions are auto-removed by the RPC service\n // so no need to explicitly send an unsubscribe message.\n try {\n this.removeSignatureListener(clientSubscriptionId);\n // eslint-disable-next-line no-empty\n } catch (_err) {\n // Already removed.\n }\n },\n method: 'signatureSubscribe',\n unsubscribeMethod: 'signatureUnsubscribe'\n }, args);\n return clientSubscriptionId;\n }\n\n /**\n * Deregister a signature notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeSignatureListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'signature result');\n }\n\n /**\n * @internal\n */\n _wsOnRootNotification(notification) {\n const {\n result,\n subscription\n } = create(notification, RootNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon root changes\n *\n * @param callback Function to invoke whenever the root changes\n * @return subscription id\n */\n onRootChange(callback) {\n return this._makeSubscription({\n callback,\n method: 'rootSubscribe',\n unsubscribeMethod: 'rootUnsubscribe'\n }, [] /* args */);\n }\n\n /**\n * Deregister a root notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeRootChangeListener(clientSubscriptionId) {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'root change');\n }\n}\n\n/**\n * Keypair signer interface\n */\n\n/**\n * An account keypair used for signing transactions.\n */\nclass Keypair {\n /**\n * Create a new keypair instance.\n * Generate random keypair if no {@link Ed25519Keypair} is provided.\n *\n * @param {Ed25519Keypair} keypair ed25519 keypair\n */\n constructor(keypair) {\n this._keypair = void 0;\n this._keypair = keypair ?? generateKeypair();\n }\n\n /**\n * Generate a new random keypair\n *\n * @returns {Keypair} Keypair\n */\n static generate() {\n return new Keypair(generateKeypair());\n }\n\n /**\n * Create a keypair from a raw secret key byte array.\n *\n * This method should only be used to recreate a keypair from a previously\n * generated secret key. Generating keypairs from a random seed should be done\n * with the {@link Keypair.fromSeed} method.\n *\n * @throws error if the provided secret key is invalid and validation is not skipped.\n *\n * @param secretKey secret key byte array\n * @param options skip secret key validation\n *\n * @returns {Keypair} Keypair\n */\n static fromSecretKey(secretKey, options) {\n if (secretKey.byteLength !== 64) {\n throw new Error('bad secret key size');\n }\n const publicKey = secretKey.slice(32, 64);\n if (!options || !options.skipValidation) {\n const privateScalar = secretKey.slice(0, 32);\n const computedPublicKey = getPublicKey(privateScalar);\n for (let ii = 0; ii < 32; ii++) {\n if (publicKey[ii] !== computedPublicKey[ii]) {\n throw new Error('provided secretKey is invalid');\n }\n }\n }\n return new Keypair({\n publicKey,\n secretKey\n });\n }\n\n /**\n * Generate a keypair from a 32 byte seed.\n *\n * @param seed seed byte array\n *\n * @returns {Keypair} Keypair\n */\n static fromSeed(seed) {\n const publicKey = getPublicKey(seed);\n const secretKey = new Uint8Array(64);\n secretKey.set(seed);\n secretKey.set(publicKey, 32);\n return new Keypair({\n publicKey,\n secretKey\n });\n }\n\n /**\n * The public key for this keypair\n *\n * @returns {PublicKey} PublicKey\n */\n get publicKey() {\n return new PublicKey(this._keypair.publicKey);\n }\n\n /**\n * The raw secret key for this keypair\n * @returns {Uint8Array} Secret key in an array of Uint8 bytes\n */\n get secretKey() {\n return new Uint8Array(this._keypair.secretKey);\n }\n}\n\n/**\n * An enumeration of valid LookupTableInstructionType's\n */\n\n/**\n * An enumeration of valid address lookup table InstructionType's\n * @internal\n */\nconst LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({\n CreateLookupTable: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), u64('recentSlot'), BufferLayout.u8('bumpSeed')])\n },\n FreezeLookupTable: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n ExtendLookupTable: {\n index: 2,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), u64(), BufferLayout.seq(publicKey(), BufferLayout.offset(BufferLayout.u32(), -8), 'addresses')])\n },\n DeactivateLookupTable: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n CloseLookupTable: {\n index: 4,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n }\n});\nclass AddressLookupTableInstruction {\n /**\n * @internal\n */\n constructor() {}\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const index = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [layoutType, layout] of Object.entries(LOOKUP_TABLE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == index) {\n type = layoutType;\n break;\n }\n }\n if (!type) {\n throw new Error('Invalid Instruction. Should be a LookupTable Instruction');\n }\n return type;\n }\n static decodeCreateLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 4);\n const {\n recentSlot\n } = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable, instruction.data);\n return {\n authority: instruction.keys[1].pubkey,\n payer: instruction.keys[2].pubkey,\n recentSlot: Number(recentSlot)\n };\n }\n static decodeExtendLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n if (instruction.keys.length < 2) {\n throw new Error(`invalid instruction; found ${instruction.keys.length} keys, expected at least 2`);\n }\n const {\n addresses\n } = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable, instruction.data);\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n payer: instruction.keys.length > 2 ? instruction.keys[2].pubkey : undefined,\n addresses: addresses.map(buffer => new PublicKey(buffer))\n };\n }\n static decodeCloseLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 3);\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n recipient: instruction.keys[2].pubkey\n };\n }\n static decodeFreezeLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 2);\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey\n };\n }\n static decodeDeactivateLookupTable(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 2);\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(AddressLookupTableProgram.programId)) {\n throw new Error('invalid instruction; programId is not AddressLookupTable Program');\n }\n }\n /**\n * @internal\n */\n static checkKeysLength(keys, expectedLength) {\n if (keys.length < expectedLength) {\n throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`);\n }\n }\n}\nclass AddressLookupTableProgram {\n /**\n * @internal\n */\n constructor() {}\n static createLookupTable(params) {\n const [lookupTableAddress, bumpSeed] = PublicKey.findProgramAddressSync([params.authority.toBuffer(), getU64Encoder().encode(params.recentSlot)], this.programId);\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;\n const data = encodeData(type, {\n recentSlot: BigInt(params.recentSlot),\n bumpSeed: bumpSeed\n });\n const keys = [{\n pubkey: lookupTableAddress,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: params.payer,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false\n }];\n return [new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n }), lookupTableAddress];\n }\n static freezeLookupTable(params) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;\n const data = encodeData(type);\n const keys = [{\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }];\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n });\n }\n static extendLookupTable(params) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;\n const data = encodeData(type, {\n addresses: params.addresses.map(addr => addr.toBytes())\n });\n const keys = [{\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }];\n if (params.payer) {\n keys.push({\n pubkey: params.payer,\n isSigner: true,\n isWritable: true\n }, {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false\n });\n }\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n });\n }\n static deactivateLookupTable(params) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;\n const data = encodeData(type);\n const keys = [{\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }];\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n });\n }\n static closeLookupTable(params) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;\n const data = encodeData(type);\n const keys = [{\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: params.recipient,\n isSigner: false,\n isWritable: true\n }];\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data\n });\n }\n}\nAddressLookupTableProgram.programId = new PublicKey('AddressLookupTab1e1111111111111111111111111');\n\n/**\n * Compute Budget Instruction class\n */\nclass ComputeBudgetInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a compute budget instruction and retrieve the instruction type.\n */\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u8('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [ixType, layout] of Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType;\n break;\n }\n }\n if (!type) {\n throw new Error('Instruction type incorrect; not a ComputeBudgetInstruction');\n }\n return type;\n }\n\n /**\n * Decode request units compute budget instruction and retrieve the instruction params.\n */\n static decodeRequestUnits(instruction) {\n this.checkProgramId(instruction.programId);\n const {\n units,\n additionalFee\n } = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits, instruction.data);\n return {\n units,\n additionalFee\n };\n }\n\n /**\n * Decode request heap frame compute budget instruction and retrieve the instruction params.\n */\n static decodeRequestHeapFrame(instruction) {\n this.checkProgramId(instruction.programId);\n const {\n bytes\n } = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame, instruction.data);\n return {\n bytes\n };\n }\n\n /**\n * Decode set compute unit limit compute budget instruction and retrieve the instruction params.\n */\n static decodeSetComputeUnitLimit(instruction) {\n this.checkProgramId(instruction.programId);\n const {\n units\n } = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit, instruction.data);\n return {\n units\n };\n }\n\n /**\n * Decode set compute unit price compute budget instruction and retrieve the instruction params.\n */\n static decodeSetComputeUnitPrice(instruction) {\n this.checkProgramId(instruction.programId);\n const {\n microLamports\n } = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice, instruction.data);\n return {\n microLamports\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(ComputeBudgetProgram.programId)) {\n throw new Error('invalid instruction; programId is not ComputeBudgetProgram');\n }\n }\n}\n\n/**\n * An enumeration of valid ComputeBudgetInstructionType's\n */\n\n/**\n * Request units instruction params\n */\n\n/**\n * Request heap frame instruction params\n */\n\n/**\n * Set compute unit limit instruction params\n */\n\n/**\n * Set compute unit price instruction params\n */\n\n/**\n * An enumeration of valid ComputeBudget InstructionType's\n * @internal\n */\nconst COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({\n RequestUnits: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u8('instruction'), BufferLayout.u32('units'), BufferLayout.u32('additionalFee')])\n },\n RequestHeapFrame: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u8('instruction'), BufferLayout.u32('bytes')])\n },\n SetComputeUnitLimit: {\n index: 2,\n layout: BufferLayout.struct([BufferLayout.u8('instruction'), BufferLayout.u32('units')])\n },\n SetComputeUnitPrice: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u8('instruction'), u64('microLamports')])\n }\n});\n\n/**\n * Factory class for transaction instructions to interact with the Compute Budget program\n */\nclass ComputeBudgetProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Compute Budget program\n */\n\n /**\n * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}\n */\n static requestUnits(params) {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data\n });\n }\n static requestHeapFrame(params) {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data\n });\n }\n static setComputeUnitLimit(params) {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data\n });\n }\n static setComputeUnitPrice(params) {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;\n const data = encodeData(type, {\n microLamports: BigInt(params.microLamports)\n });\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data\n });\n }\n}\nComputeBudgetProgram.programId = new PublicKey('ComputeBudget111111111111111111111111111111');\n\nconst PRIVATE_KEY_BYTES$1 = 64;\nconst PUBLIC_KEY_BYTES$1 = 32;\nconst SIGNATURE_BYTES = 64;\n\n/**\n * Params for creating an ed25519 instruction using a public key\n */\n\n/**\n * Params for creating an ed25519 instruction using a private key\n */\n\nconst ED25519_INSTRUCTION_LAYOUT = BufferLayout.struct([BufferLayout.u8('numSignatures'), BufferLayout.u8('padding'), BufferLayout.u16('signatureOffset'), BufferLayout.u16('signatureInstructionIndex'), BufferLayout.u16('publicKeyOffset'), BufferLayout.u16('publicKeyInstructionIndex'), BufferLayout.u16('messageDataOffset'), BufferLayout.u16('messageDataSize'), BufferLayout.u16('messageInstructionIndex')]);\nclass Ed25519Program {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the ed25519 program\n */\n\n /**\n * Create an ed25519 instruction with a public key and signature. The\n * public key must be a buffer that is 32 bytes long, and the signature\n * must be a buffer of 64 bytes.\n */\n static createInstructionWithPublicKey(params) {\n const {\n publicKey,\n message,\n signature,\n instructionIndex\n } = params;\n assert(publicKey.length === PUBLIC_KEY_BYTES$1, `Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey.length} bytes`);\n assert(signature.length === SIGNATURE_BYTES, `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);\n const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;\n const signatureOffset = publicKeyOffset + publicKey.length;\n const messageDataOffset = signatureOffset + signature.length;\n const numSignatures = 1;\n const instructionData = Buffer.alloc(messageDataOffset + message.length);\n const index = instructionIndex == null ? 0xffff // An index of `u16::MAX` makes it default to the current instruction.\n : instructionIndex;\n ED25519_INSTRUCTION_LAYOUT.encode({\n numSignatures,\n padding: 0,\n signatureOffset,\n signatureInstructionIndex: index,\n publicKeyOffset,\n publicKeyInstructionIndex: index,\n messageDataOffset,\n messageDataSize: message.length,\n messageInstructionIndex: index\n }, instructionData);\n instructionData.fill(publicKey, publicKeyOffset);\n instructionData.fill(signature, signatureOffset);\n instructionData.fill(message, messageDataOffset);\n return new TransactionInstruction({\n keys: [],\n programId: Ed25519Program.programId,\n data: instructionData\n });\n }\n\n /**\n * Create an ed25519 instruction with a private key. The private key\n * must be a buffer that is 64 bytes long.\n */\n static createInstructionWithPrivateKey(params) {\n const {\n privateKey,\n message,\n instructionIndex\n } = params;\n assert(privateKey.length === PRIVATE_KEY_BYTES$1, `Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);\n try {\n const keypair = Keypair.fromSecretKey(privateKey);\n const publicKey = keypair.publicKey.toBytes();\n const signature = sign(message, keypair.secretKey);\n return this.createInstructionWithPublicKey({\n publicKey,\n message,\n signature,\n instructionIndex\n });\n } catch (error) {\n throw new Error(`Error creating instruction; ${error}`);\n }\n }\n}\nEd25519Program.programId = new PublicKey('Ed25519SigVerify111111111111111111111111111');\n\nconst ecdsaSign = (msgHash, privKey) => {\n const signature = secp256k1.sign(msgHash, privKey);\n return [signature.toCompactRawBytes(), signature.recovery];\n};\nsecp256k1.utils.isValidPrivateKey;\nconst publicKeyCreate = secp256k1.getPublicKey;\n\nconst PRIVATE_KEY_BYTES = 32;\nconst ETHEREUM_ADDRESS_BYTES = 20;\nconst PUBLIC_KEY_BYTES = 64;\nconst SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;\n\n/**\n * Params for creating an secp256k1 instruction using a public key\n */\n\n/**\n * Params for creating an secp256k1 instruction using an Ethereum address\n */\n\n/**\n * Params for creating an secp256k1 instruction using a private key\n */\n\nconst SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct([BufferLayout.u8('numSignatures'), BufferLayout.u16('signatureOffset'), BufferLayout.u8('signatureInstructionIndex'), BufferLayout.u16('ethAddressOffset'), BufferLayout.u8('ethAddressInstructionIndex'), BufferLayout.u16('messageDataOffset'), BufferLayout.u16('messageDataSize'), BufferLayout.u8('messageInstructionIndex'), BufferLayout.blob(20, 'ethAddress'), BufferLayout.blob(64, 'signature'), BufferLayout.u8('recoveryId')]);\nclass Secp256k1Program {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the secp256k1 program\n */\n\n /**\n * Construct an Ethereum address from a secp256k1 public key buffer.\n * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer\n */\n static publicKeyToEthAddress(publicKey) {\n assert(publicKey.length === PUBLIC_KEY_BYTES, `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`);\n try {\n return Buffer.from(keccak_256(toBuffer(publicKey))).slice(-ETHEREUM_ADDRESS_BYTES);\n } catch (error) {\n throw new Error(`Error constructing Ethereum address: ${error}`);\n }\n }\n\n /**\n * Create an secp256k1 instruction with a public key. The public key\n * must be a buffer that is 64 bytes long.\n */\n static createInstructionWithPublicKey(params) {\n const {\n publicKey,\n message,\n signature,\n recoveryId,\n instructionIndex\n } = params;\n return Secp256k1Program.createInstructionWithEthAddress({\n ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey),\n message,\n signature,\n recoveryId,\n instructionIndex\n });\n }\n\n /**\n * Create an secp256k1 instruction with an Ethereum address. The address\n * must be a hex string or a buffer that is 20 bytes long.\n */\n static createInstructionWithEthAddress(params) {\n const {\n ethAddress: rawAddress,\n message,\n signature,\n recoveryId,\n instructionIndex = 0\n } = params;\n let ethAddress;\n if (typeof rawAddress === 'string') {\n if (rawAddress.startsWith('0x')) {\n ethAddress = Buffer.from(rawAddress.substr(2), 'hex');\n } else {\n ethAddress = Buffer.from(rawAddress, 'hex');\n }\n } else {\n ethAddress = rawAddress;\n }\n assert(ethAddress.length === ETHEREUM_ADDRESS_BYTES, `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`);\n const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;\n const ethAddressOffset = dataStart;\n const signatureOffset = dataStart + ethAddress.length;\n const messageDataOffset = signatureOffset + signature.length + 1;\n const numSignatures = 1;\n const instructionData = Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length);\n SECP256K1_INSTRUCTION_LAYOUT.encode({\n numSignatures,\n signatureOffset,\n signatureInstructionIndex: instructionIndex,\n ethAddressOffset,\n ethAddressInstructionIndex: instructionIndex,\n messageDataOffset,\n messageDataSize: message.length,\n messageInstructionIndex: instructionIndex,\n signature: toBuffer(signature),\n ethAddress: toBuffer(ethAddress),\n recoveryId\n }, instructionData);\n instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);\n return new TransactionInstruction({\n keys: [],\n programId: Secp256k1Program.programId,\n data: instructionData\n });\n }\n\n /**\n * Create an secp256k1 instruction with a private key. The private key\n * must be a buffer that is 32 bytes long.\n */\n static createInstructionWithPrivateKey(params) {\n const {\n privateKey: pkey,\n message,\n instructionIndex\n } = params;\n assert(pkey.length === PRIVATE_KEY_BYTES, `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`);\n try {\n const privateKey = toBuffer(pkey);\n const publicKey = publicKeyCreate(privateKey, false /* isCompressed */).slice(1); // throw away leading byte\n const messageHash = Buffer.from(keccak_256(toBuffer(message)));\n const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);\n return this.createInstructionWithPublicKey({\n publicKey,\n message,\n signature,\n recoveryId,\n instructionIndex\n });\n } catch (error) {\n throw new Error(`Error creating instruction; ${error}`);\n }\n }\n}\nSecp256k1Program.programId = new PublicKey('KeccakSecp256k11111111111111111111111111111');\n\nvar _Lockup;\n\n/**\n * Address of the stake config account which configures the rate\n * of stake warmup and cooldown as well as the slashing penalty.\n */\nconst STAKE_CONFIG_ID = new PublicKey('StakeConfig11111111111111111111111111111111');\n\n/**\n * Stake account authority info\n */\nclass Authorized {\n /**\n * Create a new Authorized object\n * @param staker the stake authority\n * @param withdrawer the withdraw authority\n */\n constructor(staker, withdrawer) {\n /** stake authority */\n this.staker = void 0;\n /** withdraw authority */\n this.withdrawer = void 0;\n this.staker = staker;\n this.withdrawer = withdrawer;\n }\n}\n/**\n * Stake account lockup info\n */\nclass Lockup {\n /**\n * Create a new Lockup object\n */\n constructor(unixTimestamp, epoch, custodian) {\n /** Unix timestamp of lockup expiration */\n this.unixTimestamp = void 0;\n /** Epoch of lockup expiration */\n this.epoch = void 0;\n /** Lockup custodian authority */\n this.custodian = void 0;\n this.unixTimestamp = unixTimestamp;\n this.epoch = epoch;\n this.custodian = custodian;\n }\n\n /**\n * Default, inactive Lockup value\n */\n}\n_Lockup = Lockup;\nLockup.default = new _Lockup(0, 0, PublicKey.default);\n/**\n * Create stake account transaction params\n */\n/**\n * Create stake account with seed transaction params\n */\n/**\n * Initialize stake instruction params\n */\n/**\n * Delegate stake instruction params\n */\n/**\n * Authorize stake instruction params\n */\n/**\n * Authorize stake instruction params using a derived key\n */\n/**\n * Split stake instruction params\n */\n/**\n * Split with seed transaction params\n */\n/**\n * Withdraw stake instruction params\n */\n/**\n * Deactivate stake instruction params\n */\n/**\n * Merge stake instruction params\n */\n/**\n * Stake Instruction class\n */\nclass StakeInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a stake instruction and retrieve the instruction type.\n */\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [ixType, layout] of Object.entries(STAKE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType;\n break;\n }\n }\n if (!type) {\n throw new Error('Instruction type incorrect; not a StakeInstruction');\n }\n return type;\n }\n\n /**\n * Decode a initialize stake instruction and retrieve the instruction params.\n */\n static decodeInitialize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n authorized,\n lockup\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Initialize, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n authorized: new Authorized(new PublicKey(authorized.staker), new PublicKey(authorized.withdrawer)),\n lockup: new Lockup(lockup.unixTimestamp, lockup.epoch, new PublicKey(lockup.custodian))\n };\n }\n\n /**\n * Decode a delegate stake instruction and retrieve the instruction params.\n */\n static decodeDelegate(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 6);\n decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Delegate, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n votePubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[5].pubkey\n };\n }\n\n /**\n * Decode an authorize stake instruction and retrieve the instruction params.\n */\n static decodeAuthorize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n newAuthorized,\n stakeAuthorizationType\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Authorize, instruction.data);\n const o = {\n stakePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n stakeAuthorizationType: {\n index: stakeAuthorizationType\n }\n };\n if (instruction.keys.length > 3) {\n o.custodianPubkey = instruction.keys[3].pubkey;\n }\n return o;\n }\n\n /**\n * Decode an authorize-with-seed stake instruction and retrieve the instruction params.\n */\n static decodeAuthorizeWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n const {\n newAuthorized,\n stakeAuthorizationType,\n authoritySeed,\n authorityOwner\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data);\n const o = {\n stakePubkey: instruction.keys[0].pubkey,\n authorityBase: instruction.keys[1].pubkey,\n authoritySeed: authoritySeed,\n authorityOwner: new PublicKey(authorityOwner),\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n stakeAuthorizationType: {\n index: stakeAuthorizationType\n }\n };\n if (instruction.keys.length > 3) {\n o.custodianPubkey = instruction.keys[3].pubkey;\n }\n return o;\n }\n\n /**\n * Decode a split stake instruction and retrieve the instruction params.\n */\n static decodeSplit(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n lamports\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Split, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n splitStakePubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n lamports\n };\n }\n\n /**\n * Decode a merge stake instruction and retrieve the instruction params.\n */\n static decodeMerge(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Merge, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n sourceStakePubKey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey\n };\n }\n\n /**\n * Decode a withdraw stake instruction and retrieve the instruction params.\n */\n static decodeWithdraw(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 5);\n const {\n lamports\n } = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data);\n const o = {\n stakePubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n lamports\n };\n if (instruction.keys.length > 5) {\n o.custodianPubkey = instruction.keys[5].pubkey;\n }\n return o;\n }\n\n /**\n * Decode a deactivate stake instruction and retrieve the instruction params.\n */\n static decodeDeactivate(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Deactivate, instruction.data);\n return {\n stakePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(StakeProgram.programId)) {\n throw new Error('invalid instruction; programId is not StakeProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys, expectedLength) {\n if (keys.length < expectedLength) {\n throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`);\n }\n }\n}\n\n/**\n * An enumeration of valid StakeInstructionType's\n */\n\n/**\n * An enumeration of valid stake InstructionType's\n * @internal\n */\nconst STAKE_INSTRUCTION_LAYOUTS = Object.freeze({\n Initialize: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), authorized(), lockup()])\n },\n Authorize: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('newAuthorized'), BufferLayout.u32('stakeAuthorizationType')])\n },\n Delegate: {\n index: 2,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n Split: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')])\n },\n Withdraw: {\n index: 4,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')])\n },\n Deactivate: {\n index: 5,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n Merge: {\n index: 7,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n AuthorizeWithSeed: {\n index: 8,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('newAuthorized'), BufferLayout.u32('stakeAuthorizationType'), rustString('authoritySeed'), publicKey('authorityOwner')])\n }\n});\n\n/**\n * Stake authorization type\n */\n\n/**\n * An enumeration of valid StakeAuthorizationLayout's\n */\nconst StakeAuthorizationLayout = Object.freeze({\n Staker: {\n index: 0\n },\n Withdrawer: {\n index: 1\n }\n});\n\n/**\n * Factory class for transactions to interact with the Stake program\n */\nclass StakeProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Stake program\n */\n\n /**\n * Generate an Initialize instruction to add to a Stake Create transaction\n */\n static initialize(params) {\n const {\n stakePubkey,\n authorized,\n lockup: maybeLockup\n } = params;\n const lockup = maybeLockup || Lockup.default;\n const type = STAKE_INSTRUCTION_LAYOUTS.Initialize;\n const data = encodeData(type, {\n authorized: {\n staker: toBuffer(authorized.staker.toBuffer()),\n withdrawer: toBuffer(authorized.withdrawer.toBuffer())\n },\n lockup: {\n unixTimestamp: lockup.unixTimestamp,\n epoch: lockup.epoch,\n custodian: toBuffer(lockup.custodian.toBuffer())\n }\n });\n const instructionData = {\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }],\n programId: this.programId,\n data\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a Transaction that creates a new Stake account at\n * an address generated with `from`, a seed, and the Stake programId\n */\n static createAccountWithSeed(params) {\n const transaction = new Transaction();\n transaction.add(SystemProgram.createAccountWithSeed({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.stakePubkey,\n basePubkey: params.basePubkey,\n seed: params.seed,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId\n }));\n const {\n stakePubkey,\n authorized,\n lockup\n } = params;\n return transaction.add(this.initialize({\n stakePubkey,\n authorized,\n lockup\n }));\n }\n\n /**\n * Generate a Transaction that creates a new Stake account\n */\n static createAccount(params) {\n const transaction = new Transaction();\n transaction.add(SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.stakePubkey,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId\n }));\n const {\n stakePubkey,\n authorized,\n lockup\n } = params;\n return transaction.add(this.initialize({\n stakePubkey,\n authorized,\n lockup\n }));\n }\n\n /**\n * Generate a Transaction that delegates Stake tokens to a validator\n * Vote PublicKey. This transaction can also be used to redelegate Stake\n * to a new validator Vote PublicKey.\n */\n static delegate(params) {\n const {\n stakePubkey,\n authorizedPubkey,\n votePubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Delegate;\n const data = encodeData(type);\n return new Transaction().add({\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: votePubkey,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: STAKE_CONFIG_ID,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that authorizes a new PublicKey as Staker\n * or Withdrawer on the Stake account.\n */\n static authorize(params) {\n const {\n stakePubkey,\n authorizedPubkey,\n newAuthorizedPubkey,\n stakeAuthorizationType,\n custodianPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Authorize;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n stakeAuthorizationType: stakeAuthorizationType.index\n });\n const keys = [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: true,\n isWritable: false\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that authorizes a new PublicKey as Staker\n * or Withdrawer on the Stake account.\n */\n static authorizeWithSeed(params) {\n const {\n stakePubkey,\n authorityBase,\n authoritySeed,\n authorityOwner,\n newAuthorizedPubkey,\n stakeAuthorizationType,\n custodianPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n stakeAuthorizationType: stakeAuthorizationType.index,\n authoritySeed: authoritySeed,\n authorityOwner: toBuffer(authorityOwner.toBuffer())\n });\n const keys = [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: authorityBase,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: true,\n isWritable: false\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * @internal\n */\n static splitInstruction(params) {\n const {\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n lamports\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Split;\n const data = encodeData(type, {\n lamports\n });\n return new TransactionInstruction({\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: splitStakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that splits Stake tokens into another stake account\n */\n static split(params,\n // Compute the cost of allocating the new stake account in lamports\n rentExemptReserve) {\n const transaction = new Transaction();\n transaction.add(SystemProgram.createAccount({\n fromPubkey: params.authorizedPubkey,\n newAccountPubkey: params.splitStakePubkey,\n lamports: rentExemptReserve,\n space: this.space,\n programId: this.programId\n }));\n return transaction.add(this.splitInstruction(params));\n }\n\n /**\n * Generate a Transaction that splits Stake tokens into another account\n * derived from a base public key and seed\n */\n static splitWithSeed(params,\n // If this stake account is new, compute the cost of allocating it in lamports\n rentExemptReserve) {\n const {\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n basePubkey,\n seed,\n lamports\n } = params;\n const transaction = new Transaction();\n transaction.add(SystemProgram.allocate({\n accountPubkey: splitStakePubkey,\n basePubkey,\n seed,\n space: this.space,\n programId: this.programId\n }));\n if (rentExemptReserve && rentExemptReserve > 0) {\n transaction.add(SystemProgram.transfer({\n fromPubkey: params.authorizedPubkey,\n toPubkey: splitStakePubkey,\n lamports: rentExemptReserve\n }));\n }\n return transaction.add(this.splitInstruction({\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n lamports\n }));\n }\n\n /**\n * Generate a Transaction that merges Stake accounts.\n */\n static merge(params) {\n const {\n stakePubkey,\n sourceStakePubKey,\n authorizedPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Merge;\n const data = encodeData(type);\n return new Transaction().add({\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: sourceStakePubKey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that withdraws deactivated Stake tokens.\n */\n static withdraw(params) {\n const {\n stakePubkey,\n authorizedPubkey,\n toPubkey,\n lamports,\n custodianPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Withdraw;\n const data = encodeData(type, {\n lamports\n });\n const keys = [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: toPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: true,\n isWritable: false\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a Transaction that deactivates Stake tokens.\n */\n static deactivate(params) {\n const {\n stakePubkey,\n authorizedPubkey\n } = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Deactivate;\n const data = encodeData(type);\n return new Transaction().add({\n keys: [{\n pubkey: stakePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n });\n }\n}\nStakeProgram.programId = new PublicKey('Stake11111111111111111111111111111111111111');\n/**\n * Max space of a Stake account\n *\n * This is generated from the solana-stake-program StakeState struct as\n * `StakeStateV2::size_of()`:\n * https://docs.rs/solana-stake-program/latest/solana_stake_program/stake_state/enum.StakeStateV2.html\n */\nStakeProgram.space = 200;\n\n/**\n * Vote account info\n */\nclass VoteInit {\n /** [0, 100] */\n\n constructor(nodePubkey, authorizedVoter, authorizedWithdrawer, commission) {\n this.nodePubkey = void 0;\n this.authorizedVoter = void 0;\n this.authorizedWithdrawer = void 0;\n this.commission = void 0;\n this.nodePubkey = nodePubkey;\n this.authorizedVoter = authorizedVoter;\n this.authorizedWithdrawer = authorizedWithdrawer;\n this.commission = commission;\n }\n}\n\n/**\n * Create vote account transaction params\n */\n\n/**\n * InitializeAccount instruction params\n */\n\n/**\n * Authorize instruction params\n */\n\n/**\n * AuthorizeWithSeed instruction params\n */\n\n/**\n * Withdraw from vote account transaction params\n */\n\n/**\n * Update validator identity (node pubkey) vote account instruction params.\n */\n\n/**\n * Vote Instruction class\n */\nclass VoteInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a vote instruction and retrieve the instruction type.\n */\n static decodeInstructionType(instruction) {\n this.checkProgramId(instruction.programId);\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n let type;\n for (const [ixType, layout] of Object.entries(VOTE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType;\n break;\n }\n }\n if (!type) {\n throw new Error('Instruction type incorrect; not a VoteInstruction');\n }\n return type;\n }\n\n /**\n * Decode an initialize vote instruction and retrieve the instruction params.\n */\n static decodeInitializeAccount(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 4);\n const {\n voteInit\n } = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount, instruction.data);\n return {\n votePubkey: instruction.keys[0].pubkey,\n nodePubkey: instruction.keys[3].pubkey,\n voteInit: new VoteInit(new PublicKey(voteInit.nodePubkey), new PublicKey(voteInit.authorizedVoter), new PublicKey(voteInit.authorizedWithdrawer), voteInit.commission)\n };\n }\n\n /**\n * Decode an authorize instruction and retrieve the instruction params.\n */\n static decodeAuthorize(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n newAuthorized,\n voteAuthorizationType\n } = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Authorize, instruction.data);\n return {\n votePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n voteAuthorizationType: {\n index: voteAuthorizationType\n }\n };\n }\n\n /**\n * Decode an authorize instruction and retrieve the instruction params.\n */\n static decodeAuthorizeWithSeed(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n voteAuthorizeWithSeedArgs: {\n currentAuthorityDerivedKeyOwnerPubkey,\n currentAuthorityDerivedKeySeed,\n newAuthorized,\n voteAuthorizationType\n }\n } = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data);\n return {\n currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey,\n currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(currentAuthorityDerivedKeyOwnerPubkey),\n currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n voteAuthorizationType: {\n index: voteAuthorizationType\n },\n votePubkey: instruction.keys[0].pubkey\n };\n }\n\n /**\n * Decode a withdraw instruction and retrieve the instruction params.\n */\n static decodeWithdraw(instruction) {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {\n lamports\n } = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data);\n return {\n votePubkey: instruction.keys[0].pubkey,\n authorizedWithdrawerPubkey: instruction.keys[2].pubkey,\n lamports,\n toPubkey: instruction.keys[1].pubkey\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId) {\n if (!programId.equals(VoteProgram.programId)) {\n throw new Error('invalid instruction; programId is not VoteProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys, expectedLength) {\n if (keys.length < expectedLength) {\n throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`);\n }\n }\n}\n\n/**\n * An enumeration of valid VoteInstructionType's\n */\n\n/** @internal */\n\nconst VOTE_INSTRUCTION_LAYOUTS = Object.freeze({\n InitializeAccount: {\n index: 0,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), voteInit()])\n },\n Authorize: {\n index: 1,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), publicKey('newAuthorized'), BufferLayout.u32('voteAuthorizationType')])\n },\n Withdraw: {\n index: 3,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')])\n },\n UpdateValidatorIdentity: {\n index: 4,\n layout: BufferLayout.struct([BufferLayout.u32('instruction')])\n },\n AuthorizeWithSeed: {\n index: 10,\n layout: BufferLayout.struct([BufferLayout.u32('instruction'), voteAuthorizeWithSeedArgs()])\n }\n});\n\n/**\n * VoteAuthorize type\n */\n\n/**\n * An enumeration of valid VoteAuthorization layouts.\n */\nconst VoteAuthorizationLayout = Object.freeze({\n Voter: {\n index: 0\n },\n Withdrawer: {\n index: 1\n }\n});\n\n/**\n * Factory class for transactions to interact with the Vote program\n */\nclass VoteProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Vote program\n */\n\n /**\n * Generate an Initialize instruction.\n */\n static initializeAccount(params) {\n const {\n votePubkey,\n nodePubkey,\n voteInit\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;\n const data = encodeData(type, {\n voteInit: {\n nodePubkey: toBuffer(voteInit.nodePubkey.toBuffer()),\n authorizedVoter: toBuffer(voteInit.authorizedVoter.toBuffer()),\n authorizedWithdrawer: toBuffer(voteInit.authorizedWithdrawer.toBuffer()),\n commission: voteInit.commission\n }\n });\n const instructionData = {\n keys: [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: nodePubkey,\n isSigner: true,\n isWritable: false\n }],\n programId: this.programId,\n data\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a transaction that creates a new Vote account.\n */\n static createAccount(params) {\n const transaction = new Transaction();\n transaction.add(SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.votePubkey,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId\n }));\n return transaction.add(this.initializeAccount({\n votePubkey: params.votePubkey,\n nodePubkey: params.voteInit.nodePubkey,\n voteInit: params.voteInit\n }));\n }\n\n /**\n * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.\n */\n static authorize(params) {\n const {\n votePubkey,\n authorizedPubkey,\n newAuthorizedPubkey,\n voteAuthorizationType\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.Authorize;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n voteAuthorizationType: voteAuthorizationType.index\n });\n const keys = [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: authorizedPubkey,\n isSigner: true,\n isWritable: false\n }];\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account\n * where the current Voter or Withdrawer authority is a derived key.\n */\n static authorizeWithSeed(params) {\n const {\n currentAuthorityDerivedKeyBasePubkey,\n currentAuthorityDerivedKeyOwnerPubkey,\n currentAuthorityDerivedKeySeed,\n newAuthorizedPubkey,\n voteAuthorizationType,\n votePubkey\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n const data = encodeData(type, {\n voteAuthorizeWithSeedArgs: {\n currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()),\n currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n voteAuthorizationType: voteAuthorizationType.index\n }\n });\n const keys = [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: SYSVAR_CLOCK_PUBKEY,\n isSigner: false,\n isWritable: false\n }, {\n pubkey: currentAuthorityDerivedKeyBasePubkey,\n isSigner: true,\n isWritable: false\n }];\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction to withdraw from a Vote account.\n */\n static withdraw(params) {\n const {\n votePubkey,\n authorizedWithdrawerPubkey,\n lamports,\n toPubkey\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.Withdraw;\n const data = encodeData(type, {\n lamports\n });\n const keys = [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: toPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: authorizedWithdrawerPubkey,\n isSigner: true,\n isWritable: false\n }];\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n\n /**\n * Generate a transaction to withdraw safely from a Vote account.\n *\n * This function was created as a safeguard for vote accounts running validators, `safeWithdraw`\n * checks that the withdraw amount will not exceed the specified balance while leaving enough left\n * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the\n * `withdraw` method directly.\n */\n static safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) {\n if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {\n throw new Error('Withdraw will leave vote account with insufficient funds.');\n }\n return VoteProgram.withdraw(params);\n }\n\n /**\n * Generate a transaction to update the validator identity (node pubkey) of a Vote account.\n */\n static updateValidatorIdentity(params) {\n const {\n votePubkey,\n authorizedWithdrawerPubkey,\n nodePubkey\n } = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.UpdateValidatorIdentity;\n const data = encodeData(type);\n const keys = [{\n pubkey: votePubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: nodePubkey,\n isSigner: true,\n isWritable: false\n }, {\n pubkey: authorizedWithdrawerPubkey,\n isSigner: true,\n isWritable: false\n }];\n return new Transaction().add({\n keys,\n programId: this.programId,\n data\n });\n }\n}\nVoteProgram.programId = new PublicKey('Vote111111111111111111111111111111111111111');\n/**\n * Max space of a Vote account\n *\n * This is generated from the solana-vote-program VoteState struct as\n * `VoteState::size_of()`:\n * https://docs.rs/solana-vote-program/1.9.5/solana_vote_program/vote_state/struct.VoteState.html#method.size_of\n *\n * KEEP IN SYNC WITH `VoteState::size_of()` in https://github.com/solana-labs/solana/blob/a474cb24b9238f5edcc982f65c0b37d4a1046f7e/sdk/program/src/vote/state/mod.rs#L340-L342\n */\nVoteProgram.space = 3762;\n\nconst VALIDATOR_INFO_KEY = new PublicKey('Va1idator1nfo111111111111111111111111111111');\n\n/**\n * @internal\n */\n\n/**\n * Info used to identity validators.\n */\n\nconst InfoString = type({\n name: string(),\n website: optional(string()),\n details: optional(string()),\n iconUrl: optional(string()),\n keybaseUsername: optional(string())\n});\n\n/**\n * ValidatorInfo class\n */\nclass ValidatorInfo {\n /**\n * Construct a valid ValidatorInfo\n *\n * @param key validator public key\n * @param info validator information\n */\n constructor(key, info) {\n /**\n * validator public key\n */\n this.key = void 0;\n /**\n * validator information\n */\n this.info = void 0;\n this.key = key;\n this.info = info;\n }\n\n /**\n * Deserialize ValidatorInfo from the config account data. Exactly two config\n * keys are required in the data.\n *\n * @param buffer config account data\n * @return null if info was not found\n */\n static fromConfigData(buffer) {\n let byteArray = [...buffer];\n const configKeyCount = decodeLength(byteArray);\n if (configKeyCount !== 2) return null;\n const configKeys = [];\n for (let i = 0; i < 2; i++) {\n const publicKey = new PublicKey(guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH));\n const isSigner = guardedShift(byteArray) === 1;\n configKeys.push({\n publicKey,\n isSigner\n });\n }\n if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) {\n if (configKeys[1].isSigner) {\n const rawInfo = rustString().decode(Buffer.from(byteArray));\n const info = JSON.parse(rawInfo);\n assert$1(info, InfoString);\n return new ValidatorInfo(configKeys[1].publicKey, info);\n }\n }\n return null;\n }\n}\n\nconst VOTE_PROGRAM_ID = new PublicKey('Vote111111111111111111111111111111111111111');\n\n/**\n * History of how many credits earned by the end of each epoch\n */\n\n/**\n * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88\n *\n * @internal\n */\nconst VoteAccountLayout = BufferLayout.struct([publicKey('nodePubkey'), publicKey('authorizedWithdrawer'), BufferLayout.u8('commission'), BufferLayout.nu64(),\n// votes.length\nBufferLayout.seq(BufferLayout.struct([BufferLayout.nu64('slot'), BufferLayout.u32('confirmationCount')]), BufferLayout.offset(BufferLayout.u32(), -8), 'votes'), BufferLayout.u8('rootSlotValid'), BufferLayout.nu64('rootSlot'), BufferLayout.nu64(),\n// authorizedVoters.length\nBufferLayout.seq(BufferLayout.struct([BufferLayout.nu64('epoch'), publicKey('authorizedVoter')]), BufferLayout.offset(BufferLayout.u32(), -8), 'authorizedVoters'), BufferLayout.struct([BufferLayout.seq(BufferLayout.struct([publicKey('authorizedPubkey'), BufferLayout.nu64('epochOfLastAuthorizedSwitch'), BufferLayout.nu64('targetEpoch')]), 32, 'buf'), BufferLayout.nu64('idx'), BufferLayout.u8('isEmpty')], 'priorVoters'), BufferLayout.nu64(),\n// epochCredits.length\nBufferLayout.seq(BufferLayout.struct([BufferLayout.nu64('epoch'), BufferLayout.nu64('credits'), BufferLayout.nu64('prevCredits')]), BufferLayout.offset(BufferLayout.u32(), -8), 'epochCredits'), BufferLayout.struct([BufferLayout.nu64('slot'), BufferLayout.nu64('timestamp')], 'lastTimestamp')]);\n/**\n * VoteAccount class\n */\nclass VoteAccount {\n /**\n * @internal\n */\n constructor(args) {\n this.nodePubkey = void 0;\n this.authorizedWithdrawer = void 0;\n this.commission = void 0;\n this.rootSlot = void 0;\n this.votes = void 0;\n this.authorizedVoters = void 0;\n this.priorVoters = void 0;\n this.epochCredits = void 0;\n this.lastTimestamp = void 0;\n this.nodePubkey = args.nodePubkey;\n this.authorizedWithdrawer = args.authorizedWithdrawer;\n this.commission = args.commission;\n this.rootSlot = args.rootSlot;\n this.votes = args.votes;\n this.authorizedVoters = args.authorizedVoters;\n this.priorVoters = args.priorVoters;\n this.epochCredits = args.epochCredits;\n this.lastTimestamp = args.lastTimestamp;\n }\n\n /**\n * Deserialize VoteAccount from the account data.\n *\n * @param buffer account data\n * @return VoteAccount\n */\n static fromAccountData(buffer) {\n const versionOffset = 4;\n const va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset);\n let rootSlot = va.rootSlot;\n if (!va.rootSlotValid) {\n rootSlot = null;\n }\n return new VoteAccount({\n nodePubkey: new PublicKey(va.nodePubkey),\n authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer),\n commission: va.commission,\n votes: va.votes,\n rootSlot,\n authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter),\n priorVoters: getPriorVoters(va.priorVoters),\n epochCredits: va.epochCredits,\n lastTimestamp: va.lastTimestamp\n });\n }\n}\nfunction parseAuthorizedVoter({\n authorizedVoter,\n epoch\n}) {\n return {\n epoch,\n authorizedVoter: new PublicKey(authorizedVoter)\n };\n}\nfunction parsePriorVoters({\n authorizedPubkey,\n epochOfLastAuthorizedSwitch,\n targetEpoch\n}) {\n return {\n authorizedPubkey: new PublicKey(authorizedPubkey),\n epochOfLastAuthorizedSwitch,\n targetEpoch\n };\n}\nfunction getPriorVoters({\n buf,\n idx,\n isEmpty\n}) {\n if (isEmpty) {\n return [];\n }\n return [...buf.slice(idx + 1).map(parsePriorVoters), ...buf.slice(0, idx).map(parsePriorVoters)];\n}\n\nconst endpoint = {\n http: {\n devnet: 'http://api.devnet.solana.com',\n testnet: 'http://api.testnet.solana.com',\n 'mainnet-beta': 'http://api.mainnet-beta.solana.com/'\n },\n https: {\n devnet: 'https://api.devnet.solana.com',\n testnet: 'https://api.testnet.solana.com',\n 'mainnet-beta': 'https://api.mainnet-beta.solana.com/'\n }\n};\n/**\n * Retrieves the RPC API URL for the specified cluster\n * @param {Cluster} [cluster=\"devnet\"] - The cluster name of the RPC API URL to use. Possible options: 'devnet' | 'testnet' | 'mainnet-beta'\n * @param {boolean} [tls=\"http\"] - Use TLS when connecting to cluster.\n *\n * @returns {string} URL string of the RPC endpoint\n */\nfunction clusterApiUrl(cluster, tls) {\n const key = tls === false ? 'http' : 'https';\n if (!cluster) {\n return endpoint[key]['devnet'];\n }\n const url = endpoint[key][cluster];\n if (!url) {\n throw new Error(`Unknown ${key} cluster: ${cluster}`);\n }\n return url;\n}\n\n/**\n * Send and confirm a raw transaction\n *\n * If `commitment` option is not specified, defaults to 'max' commitment.\n *\n * @param {Connection} connection\n * @param {Buffer} rawTransaction\n * @param {TransactionConfirmationStrategy} confirmationStrategy\n * @param {ConfirmOptions} [options]\n * @returns {Promise}\n */\n\n/**\n * @deprecated Calling `sendAndConfirmRawTransaction()` without a `confirmationStrategy`\n * is no longer supported and will be removed in a future version.\n */\n// eslint-disable-next-line no-redeclare\n\n// eslint-disable-next-line no-redeclare\nasync function sendAndConfirmRawTransaction(connection, rawTransaction, confirmationStrategyOrConfirmOptions, maybeConfirmOptions) {\n let confirmationStrategy;\n let options;\n if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'lastValidBlockHeight')) {\n confirmationStrategy = confirmationStrategyOrConfirmOptions;\n options = maybeConfirmOptions;\n } else if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'nonceValue')) {\n confirmationStrategy = confirmationStrategyOrConfirmOptions;\n options = maybeConfirmOptions;\n } else {\n options = confirmationStrategyOrConfirmOptions;\n }\n const sendOptions = options && {\n skipPreflight: options.skipPreflight,\n preflightCommitment: options.preflightCommitment || options.commitment,\n minContextSlot: options.minContextSlot\n };\n const signature = await connection.sendRawTransaction(rawTransaction, sendOptions);\n const commitment = options && options.commitment;\n const confirmationPromise = confirmationStrategy ? connection.confirmTransaction(confirmationStrategy, commitment) : connection.confirmTransaction(signature, commitment);\n const status = (await confirmationPromise).value;\n if (status.err) {\n if (signature != null) {\n throw new SendTransactionError({\n action: sendOptions?.skipPreflight ? 'send' : 'simulate',\n signature: signature,\n transactionMessage: `Status: (${JSON.stringify(status)})`\n });\n }\n throw new Error(`Raw transaction ${signature} failed (${JSON.stringify(status)})`);\n }\n return signature;\n}\n\n/**\n * There are 1-billion lamports in one SOL\n */\nconst LAMPORTS_PER_SOL = 1000000000;\n\nexport { Account, AddressLookupTableAccount, AddressLookupTableInstruction, AddressLookupTableProgram, Authorized, BLOCKHASH_CACHE_TIMEOUT_MS, BPF_LOADER_DEPRECATED_PROGRAM_ID, BPF_LOADER_PROGRAM_ID, BpfLoader, COMPUTE_BUDGET_INSTRUCTION_LAYOUTS, ComputeBudgetInstruction, ComputeBudgetProgram, Connection, Ed25519Program, Enum, EpochSchedule, FeeCalculatorLayout, Keypair, LAMPORTS_PER_SOL, LOOKUP_TABLE_INSTRUCTION_LAYOUTS, Loader, Lockup, MAX_SEED_LENGTH, Message, MessageAccountKeys, MessageV0, NONCE_ACCOUNT_LENGTH, NonceAccount, PACKET_DATA_SIZE, PUBLIC_KEY_LENGTH, PublicKey, SIGNATURE_LENGTH_IN_BYTES, SOLANA_SCHEMA, STAKE_CONFIG_ID, STAKE_INSTRUCTION_LAYOUTS, SYSTEM_INSTRUCTION_LAYOUTS, SYSVAR_CLOCK_PUBKEY, SYSVAR_EPOCH_SCHEDULE_PUBKEY, SYSVAR_INSTRUCTIONS_PUBKEY, SYSVAR_RECENT_BLOCKHASHES_PUBKEY, SYSVAR_RENT_PUBKEY, SYSVAR_REWARDS_PUBKEY, SYSVAR_SLOT_HASHES_PUBKEY, SYSVAR_SLOT_HISTORY_PUBKEY, SYSVAR_STAKE_HISTORY_PUBKEY, Secp256k1Program, SendTransactionError, SolanaJSONRPCError, SolanaJSONRPCErrorCode, StakeAuthorizationLayout, StakeInstruction, StakeProgram, Struct, SystemInstruction, SystemProgram, Transaction, TransactionExpiredBlockheightExceededError, TransactionExpiredNonceInvalidError, TransactionExpiredTimeoutError, TransactionInstruction, TransactionMessage, TransactionStatus, VALIDATOR_INFO_KEY, VERSION_PREFIX_MASK, VOTE_PROGRAM_ID, ValidatorInfo, VersionedMessage, VersionedTransaction, VoteAccount, VoteAuthorizationLayout, VoteInit, VoteInstruction, VoteProgram, clusterApiUrl, sendAndConfirmRawTransaction, sendAndConfirmTransaction };\n//# sourceMappingURL=index.browser.esm.js.map\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/**\n * The base error class of hpke-js.\n * @group Errors\n */\nexport class HpkeError extends Error {\n constructor(e) {\n let message;\n if (e instanceof Error) {\n message = e.message;\n }\n else if (typeof e === \"string\") {\n message = e;\n }\n else {\n message = \"\";\n }\n super(message);\n this.name = this.constructor.name;\n }\n}\n/**\n * Invalid parameter.\n * @group Errors\n */\nexport class InvalidParamError extends HpkeError {\n}\n/**\n * KEM input or output validation failure.\n * @group Errors\n */\nexport class ValidationError extends HpkeError {\n}\n/**\n * Public or private key serialization failure.\n * @group Errors\n */\nexport class SerializeError extends HpkeError {\n}\n/**\n * Public or private key deserialization failure.\n * @group Errors\n */\nexport class DeserializeError extends HpkeError {\n}\n/**\n * encap() failure.\n * @group Errors\n */\nexport class EncapError extends HpkeError {\n}\n/**\n * decap() failure.\n * @group Errors\n */\nexport class DecapError extends HpkeError {\n}\n/**\n * Secret export failure.\n * @group Errors\n */\nexport class ExportError extends HpkeError {\n}\n/**\n * seal() failure.\n * @group Errors\n */\nexport class SealError extends HpkeError {\n}\n/**\n * open() failure.\n * @group Errors\n */\nexport class OpenError extends HpkeError {\n}\n/**\n * Sequence number overflow on the encryption context.\n * @group Errors\n */\nexport class MessageLimitReachedError extends HpkeError {\n}\n/**\n * Key pair derivation failure.\n * @group Errors\n */\nexport class DeriveKeyPairError extends HpkeError {\n}\n/**\n * Not supported failure.\n * @group Errors\n */\nexport class NotSupportedError extends HpkeError {\n}\n","const dntGlobals = {};\nexport const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\nfunction createMergeProxy(baseObj, extObj) {\n return new Proxy(baseObj, {\n get(_target, prop, _receiver) {\n if (prop in extObj) {\n return extObj[prop];\n }\n else {\n return baseObj[prop];\n }\n },\n set(_target, prop, value) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n baseObj[prop] = value;\n return true;\n },\n deleteProperty(_target, prop) {\n let success = false;\n if (prop in extObj) {\n delete extObj[prop];\n success = true;\n }\n if (prop in baseObj) {\n delete baseObj[prop];\n success = true;\n }\n return success;\n },\n ownKeys(_target) {\n const baseKeys = Reflect.ownKeys(baseObj);\n const extKeys = Reflect.ownKeys(extObj);\n const extKeysSet = new Set(extKeys);\n return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n },\n defineProperty(_target, prop, desc) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n Reflect.defineProperty(baseObj, prop, desc);\n return true;\n },\n getOwnPropertyDescriptor(_target, prop) {\n if (prop in extObj) {\n return Reflect.getOwnPropertyDescriptor(extObj, prop);\n }\n else {\n return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n }\n },\n has(_target, prop) {\n return prop in extObj || prop in baseObj;\n },\n });\n}\n","import * as dntShim from \"../_dnt.shims.js\";\nimport { NotSupportedError } from \"./errors.js\";\nasync function loadSubtleCrypto() {\n if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) {\n // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc.\n return globalThis.crypto.subtle;\n }\n // Node.js <= v18\n try {\n // @ts-ignore: to ignore \"crypto\"\n const { webcrypto } = await import(\"crypto\"); // node:crypto\n return webcrypto.subtle;\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n}\nexport class NativeAlgorithm {\n constructor() {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: undefined\n });\n }\n async _setup() {\n if (this._api !== undefined) {\n return;\n }\n this._api = await loadSubtleCrypto();\n }\n}\n","/**\n * The supported HPKE modes.\n */\nexport const Mode = {\n Base: 0x00,\n Psk: 0x01,\n Auth: 0x02,\n AuthPsk: 0x03,\n};\n/**\n * The supported Key Encapsulation Mechanism (KEM) identifiers.\n */\nexport const KemId = {\n NotAssigned: 0x0000,\n DhkemP256HkdfSha256: 0x0010,\n DhkemP384HkdfSha384: 0x0011,\n DhkemP521HkdfSha512: 0x0012,\n DhkemSecp256k1HkdfSha256: 0x0013,\n DhkemX25519HkdfSha256: 0x0020,\n DhkemX448HkdfSha512: 0x0021,\n HybridkemX25519Kyber768: 0x0030,\n MlKem512: 0x0040,\n MlKem768: 0x0041,\n MlKem1024: 0x0042,\n XWing: 0x647a,\n};\n/**\n * The supported Key Derivation Function (KDF) identifiers.\n */\nexport const KdfId = {\n HkdfSha256: 0x0001,\n HkdfSha384: 0x0002,\n HkdfSha512: 0x0003,\n};\n/**\n * The supported Authenticated Encryption with Associated Data (AEAD) identifiers.\n */\nexport const AeadId = {\n Aes128Gcm: 0x0001,\n Aes256Gcm: 0x0002,\n Chacha20Poly1305: 0x0003,\n ExportOnly: 0xFFFF,\n};\n","// The input length limit (psk, psk_id, info, exporter_context, ikm).\nexport const INPUT_LENGTH_LIMIT = 8192;\nexport const INFO_LENGTH_LIMIT = 65536;\n// The minimum length of a PSK.\nexport const MINIMUM_PSK_LENGTH = 32;\n// b\"\"\nexport const EMPTY = new Uint8Array(0);\n","// b\"KEM\"\nexport const SUITE_ID_HEADER_KEM = new Uint8Array([\n 75,\n 69,\n 77,\n 0,\n 0,\n]);\n","import * as dntShim from \"../../_dnt.shims.js\";\nimport { KemId } from \"../identifiers.js\";\nexport const isDenoV1 = () => \n// deno-lint-ignore no-explicit-any\ndntShim.dntGlobalThis.process === undefined;\n/**\n * Checks whether the runtime is Deno or not (Node.js).\n * @returns boolean - true if the runtime is Deno, false Node.js.\n */\nexport function isDeno() {\n // deno-lint-ignore no-explicit-any\n if (dntShim.dntGlobalThis.process === undefined) {\n return true;\n }\n // deno-lint-ignore no-explicit-any\n return dntShim.dntGlobalThis.process?.versions?.deno !== undefined;\n}\n/**\n * Checks whetehr the type of input is CryptoKeyPair or not.\n */\nexport const isCryptoKeyPair = (x) => typeof x === \"object\" &&\n x !== null &&\n typeof x.privateKey === \"object\" &&\n typeof x.publicKey === \"object\";\n/**\n * Converts integer to octet string. I2OSP implementation.\n */\nexport function i2Osp(n, w) {\n if (w <= 0) {\n throw new Error(\"i2Osp: too small size\");\n }\n if (n >= 256 ** w) {\n throw new Error(\"i2Osp: too large integer\");\n }\n const ret = new Uint8Array(w);\n for (let i = 0; i < w && n; i++) {\n ret[w - (i + 1)] = n % 256;\n n = n >> 8;\n }\n return ret;\n}\n/**\n * Concatenates two Uint8Arrays.\n * @param a Uint8Array\n * @param b Uint8Array\n * @returns Concatenated Uint8Array\n */\nexport function concat(a, b) {\n const ret = new Uint8Array(a.length + b.length);\n ret.set(a, 0);\n ret.set(b, a.length);\n return ret;\n}\n/**\n * Decodes Base64Url-encoded data.\n * @param v Base64Url-encoded string\n * @returns Uint8Array\n */\nexport function base64UrlToBytes(v) {\n const base64 = v.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const byteString = atob(base64);\n const ret = new Uint8Array(byteString.length);\n for (let i = 0; i < byteString.length; i++) {\n ret[i] = byteString.charCodeAt(i);\n }\n return ret;\n}\n/**\n * Encodes Uint8Array to Base64Url.\n * @param v Uint8Array\n * @returns Base64Url-encoded string\n */\nexport function bytesToBase64Url(v) {\n return btoa(String.fromCharCode(...v))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=*$/g, \"\");\n}\n/**\n * Decodes hex string to Uint8Array.\n * @param v Hex string\n * @returns Uint8Array\n * @throws Error if the input is not a hex string.\n */\nexport function hexToBytes(v) {\n if (v.length === 0) {\n return new Uint8Array([]);\n }\n const res = v.match(/[\\da-f]{2}/gi);\n if (res == null) {\n throw new Error(\"Not hex string.\");\n }\n return new Uint8Array(res.map(function (h) {\n return parseInt(h, 16);\n }));\n}\n/**\n * Encodes Uint8Array to hex string.\n * @param v Uint8Array\n * @returns Hex string\n */\nexport function bytesToHex(v) {\n return [...v].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/**\n * Converts KemId to KeyAlgorithm.\n * @param kem KemId\n * @returns KeyAlgorithm\n */\nexport function kemToKeyGenAlgorithm(kem) {\n switch (kem) {\n case KemId.DhkemP256HkdfSha256:\n return {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n };\n case KemId.DhkemP384HkdfSha384:\n return {\n name: \"ECDH\",\n namedCurve: \"P-384\",\n };\n case KemId.DhkemP521HkdfSha512:\n return {\n name: \"ECDH\",\n namedCurve: \"P-521\",\n };\n default:\n // case KemId.DhkemX25519HkdfSha256\n return {\n name: \"X25519\",\n };\n }\n}\nexport async function loadSubtleCrypto() {\n if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) {\n // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc.\n return globalThis.crypto.subtle;\n }\n // Node.js <= v18\n try {\n // @ts-ignore: to ignore \"crypto\"\n const { webcrypto } = await import(\"crypto\"); // node:crypto\n return webcrypto.subtle;\n }\n catch (_e) {\n throw new Error(\"Failed to load SubtleCrypto\");\n }\n}\nexport async function loadCrypto() {\n if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) {\n // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc.\n return globalThis.crypto;\n }\n // Node.js <= v18\n try {\n // @ts-ignore: to ignore \"crypto\"\n const { webcrypto } = await import(\"crypto\"); // node:crypto\n return webcrypto;\n }\n catch (_e) {\n throw new Error(\"Web Cryptograph API not supported\");\n }\n}\n/**\n * XOR for Uint8Array.\n */\nexport function xor(a, b) {\n if (a.byteLength !== b.byteLength) {\n throw new Error(\"xor: different length inputs\");\n }\n const buf = new Uint8Array(a.byteLength);\n for (let i = 0; i < a.byteLength; i++) {\n buf[i] = a[i] ^ b[i];\n }\n return buf;\n}\n","import { EMPTY, INPUT_LENGTH_LIMIT } from \"../consts.js\";\nimport { DecapError, EncapError, InvalidParamError } from \"../errors.js\";\nimport { SUITE_ID_HEADER_KEM } from \"../interfaces/kemInterface.js\";\nimport { concat, i2Osp, isCryptoKeyPair } from \"../utils/misc.js\";\n// b\"eae_prk\"\nconst LABEL_EAE_PRK = new Uint8Array([101, 97, 101, 95, 112, 114, 107]);\n// b\"shared_secret\"\n// deno-fmt-ignore\nconst LABEL_SHARED_SECRET = new Uint8Array([\n 115, 104, 97, 114, 101, 100, 95, 115, 101, 99,\n 114, 101, 116,\n]);\nfunction concat3(a, b, c) {\n const ret = new Uint8Array(a.length + b.length + c.length);\n ret.set(a, 0);\n ret.set(b, a.length);\n ret.set(c, a.length + b.length);\n return ret;\n}\nexport class Dhkem {\n constructor(id, prim, kdf) {\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"_prim\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.id = id;\n this._prim = prim;\n this._kdf = kdf;\n const suiteId = new Uint8Array(SUITE_ID_HEADER_KEM);\n suiteId.set(i2Osp(this.id, 2), 3);\n this._kdf.init(suiteId);\n }\n async serializePublicKey(key) {\n return await this._prim.serializePublicKey(key);\n }\n async deserializePublicKey(key) {\n return await this._prim.deserializePublicKey(key);\n }\n async serializePrivateKey(key) {\n return await this._prim.serializePrivateKey(key);\n }\n async deserializePrivateKey(key) {\n return await this._prim.deserializePrivateKey(key);\n }\n async importKey(format, key, isPublic = true) {\n return await this._prim.importKey(format, key, isPublic);\n }\n async generateKeyPair() {\n return await this._prim.generateKeyPair();\n }\n async deriveKeyPair(ikm) {\n if (ikm.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long ikm\");\n }\n return await this._prim.deriveKeyPair(ikm);\n }\n async encap(params) {\n let ke;\n if (params.ekm === undefined) {\n ke = await this.generateKeyPair();\n }\n else if (isCryptoKeyPair(params.ekm)) {\n // params.ekm is only used for testing.\n ke = params.ekm;\n }\n else {\n // params.ekm is only used for testing.\n ke = await this.deriveKeyPair(params.ekm);\n }\n const enc = await this._prim.serializePublicKey(ke.publicKey);\n const pkrm = await this._prim.serializePublicKey(params.recipientPublicKey);\n try {\n let dh;\n if (params.senderKey === undefined) {\n dh = new Uint8Array(await this._prim.dh(ke.privateKey, params.recipientPublicKey));\n }\n else {\n const sks = isCryptoKeyPair(params.senderKey)\n ? params.senderKey.privateKey\n : params.senderKey;\n const dh1 = new Uint8Array(await this._prim.dh(ke.privateKey, params.recipientPublicKey));\n const dh2 = new Uint8Array(await this._prim.dh(sks, params.recipientPublicKey));\n dh = concat(dh1, dh2);\n }\n let kemContext;\n if (params.senderKey === undefined) {\n kemContext = concat(new Uint8Array(enc), new Uint8Array(pkrm));\n }\n else {\n const pks = isCryptoKeyPair(params.senderKey)\n ? params.senderKey.publicKey\n : await this._prim.derivePublicKey(params.senderKey);\n const pksm = await this._prim.serializePublicKey(pks);\n kemContext = concat3(new Uint8Array(enc), new Uint8Array(pkrm), new Uint8Array(pksm));\n }\n const sharedSecret = await this._generateSharedSecret(dh, kemContext);\n return {\n enc: enc,\n sharedSecret: sharedSecret,\n };\n }\n catch (e) {\n throw new EncapError(e);\n }\n }\n async decap(params) {\n const pke = await this._prim.deserializePublicKey(params.enc);\n const skr = isCryptoKeyPair(params.recipientKey)\n ? params.recipientKey.privateKey\n : params.recipientKey;\n const pkr = isCryptoKeyPair(params.recipientKey)\n ? params.recipientKey.publicKey\n : await this._prim.derivePublicKey(params.recipientKey);\n const pkrm = await this._prim.serializePublicKey(pkr);\n try {\n let dh;\n if (params.senderPublicKey === undefined) {\n dh = new Uint8Array(await this._prim.dh(skr, pke));\n }\n else {\n const dh1 = new Uint8Array(await this._prim.dh(skr, pke));\n const dh2 = new Uint8Array(await this._prim.dh(skr, params.senderPublicKey));\n dh = concat(dh1, dh2);\n }\n let kemContext;\n if (params.senderPublicKey === undefined) {\n kemContext = concat(new Uint8Array(params.enc), new Uint8Array(pkrm));\n }\n else {\n const pksm = await this._prim.serializePublicKey(params.senderPublicKey);\n kemContext = new Uint8Array(params.enc.byteLength + pkrm.byteLength + pksm.byteLength);\n kemContext.set(new Uint8Array(params.enc), 0);\n kemContext.set(new Uint8Array(pkrm), params.enc.byteLength);\n kemContext.set(new Uint8Array(pksm), params.enc.byteLength + pkrm.byteLength);\n }\n return await this._generateSharedSecret(dh, kemContext);\n }\n catch (e) {\n throw new DecapError(e);\n }\n }\n async _generateSharedSecret(dh, kemContext) {\n const labeledIkm = this._kdf.buildLabeledIkm(LABEL_EAE_PRK, dh);\n const labeledInfo = this._kdf.buildLabeledInfo(LABEL_SHARED_SECRET, kemContext, this.secretSize);\n return await this._kdf.extractAndExpand(EMPTY.buffer, labeledIkm.buffer, labeledInfo.buffer, this.secretSize);\n }\n}\n","// The key usages for KEM.\nexport const KEM_USAGES = [\"deriveBits\"];\n// b\"dkp_prk\"\nexport const LABEL_DKP_PRK = new Uint8Array([\n 100,\n 107,\n 112,\n 95,\n 112,\n 114,\n 107,\n]);\n// b\"sk\"\nexport const LABEL_SK = new Uint8Array([115, 107]);\n","/**\n * The minimum inplementation of bignum to derive an EC key pair.\n */\nexport class Bignum {\n constructor(size) {\n Object.defineProperty(this, \"_num\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._num = new Uint8Array(size);\n }\n val() {\n return this._num;\n }\n reset() {\n this._num.fill(0);\n }\n set(src) {\n if (src.length !== this._num.length) {\n throw new Error(\"Bignum.set: invalid argument\");\n }\n this._num.set(src);\n }\n isZero() {\n for (let i = 0; i < this._num.length; i++) {\n if (this._num[i] !== 0) {\n return false;\n }\n }\n return true;\n }\n lessThan(v) {\n if (v.length !== this._num.length) {\n throw new Error(\"Bignum.lessThan: invalid argument\");\n }\n for (let i = 0; i < this._num.length; i++) {\n if (this._num[i] < v[i]) {\n return true;\n }\n if (this._num[i] > v[i]) {\n return false;\n }\n }\n return false;\n }\n}\n","import { NativeAlgorithm } from \"../../algorithm.js\";\nimport { EMPTY } from \"../../consts.js\";\nimport { DeriveKeyPairError, DeserializeError, NotSupportedError, SerializeError, } from \"../../errors.js\";\nimport { KemId } from \"../../identifiers.js\";\nimport { KEM_USAGES, LABEL_DKP_PRK } from \"../../interfaces/dhkemPrimitives.js\";\nimport { Bignum } from \"../../utils/bignum.js\";\nimport { base64UrlToBytes, i2Osp } from \"../../utils/misc.js\";\n// b\"candidate\"\n// deno-fmt-ignore\nconst LABEL_CANDIDATE = new Uint8Array([\n 99, 97, 110, 100, 105, 100, 97, 116, 101,\n]);\n// the order of the curve being used.\n// deno-fmt-ignore\nconst ORDER_P_256 = new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84,\n 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,\n]);\n// deno-fmt-ignore\nconst ORDER_P_384 = new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf,\n 0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a,\n 0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x73,\n]);\n// deno-fmt-ignore\nconst ORDER_P_521 = new Uint8Array([\n 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xfa, 0x51, 0x86, 0x87, 0x83, 0xbf, 0x2f,\n 0x96, 0x6b, 0x7f, 0xcc, 0x01, 0x48, 0xf7, 0x09,\n 0xa5, 0xd0, 0x3b, 0xb5, 0xc9, 0xb8, 0x89, 0x9c,\n 0x47, 0xae, 0xbb, 0x6f, 0xb7, 0x1e, 0x91, 0x38,\n 0x64, 0x09,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_256 = new Uint8Array([\n 48, 65, 2, 1, 0, 48, 19, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 8, 42, 134,\n 72, 206, 61, 3, 1, 7, 4, 39, 48, 37,\n 2, 1, 1, 4, 32,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_384 = new Uint8Array([\n 48, 78, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 34, 4, 55, 48, 53, 2, 1, 1,\n 4, 48,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_521 = new Uint8Array([\n 48, 96, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 35, 4, 73, 48, 71, 2, 1, 1,\n 4, 66,\n]);\nexport class Ec extends NativeAlgorithm {\n constructor(kem, hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // EC specific arguments for deriving key pair.\n Object.defineProperty(this, \"_order\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_bitmask\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._hkdf = hkdf;\n switch (kem) {\n case KemId.DhkemP256HkdfSha256:\n this._alg = { name: \"ECDH\", namedCurve: \"P-256\" };\n this._nPk = 65;\n this._nSk = 32;\n this._nDh = 32;\n this._order = ORDER_P_256;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_256;\n break;\n case KemId.DhkemP384HkdfSha384:\n this._alg = { name: \"ECDH\", namedCurve: \"P-384\" };\n this._nPk = 97;\n this._nSk = 48;\n this._nDh = 48;\n this._order = ORDER_P_384;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_384;\n break;\n default:\n // case KemId.DhkemP521HkdfSha512:\n this._alg = { name: \"ECDH\", namedCurve: \"P-521\" };\n this._nPk = 133;\n this._nSk = 66;\n this._nDh = 66;\n this._order = ORDER_P_521;\n this._bitmask = 0x01;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_521;\n break;\n }\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(this._alg, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY.buffer, LABEL_DKP_PRK, new Uint8Array(ikm));\n const bn = new Bignum(this._nSk);\n for (let counter = 0; bn.isZero() || !bn.lessThan(this._order); counter++) {\n if (counter > 255) {\n throw new Error(\"Faild to derive a key pair\");\n }\n const bytes = new Uint8Array(await this._hkdf.labeledExpand(dkpPrk, LABEL_CANDIDATE, i2Osp(counter, 1), this._nSk));\n bytes[0] = bytes[0] & this._bitmask;\n bn.set(bytes);\n }\n const sk = await this._deserializePkcs8Key(bn.val());\n bn.reset();\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async dh(sk, pk) {\n try {\n await this._setup();\n const bits = await this._api.deriveBits({\n name: \"ECDH\",\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.crv === \"undefined\" || key.crv !== this._alg.namedCurve) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import { EMPTY } from \"../consts.js\";\nimport { InvalidParamError } from \"../errors.js\";\nimport { KdfId } from \"../identifiers.js\";\nimport { NativeAlgorithm } from \"../algorithm.js\";\n// b\"HPKE-v1\"\nconst HPKE_VERSION = new Uint8Array([72, 80, 75, 69, 45, 118, 49]);\nexport class HkdfNative extends NativeAlgorithm {\n constructor() {\n super();\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha256\n });\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: EMPTY\n });\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-256\",\n length: 256,\n }\n });\n }\n init(suiteId) {\n this._suiteId = suiteId;\n }\n buildLabeledIkm(label, ikm) {\n this._checkInit();\n const ret = new Uint8Array(7 + this._suiteId.byteLength + label.byteLength + ikm.byteLength);\n ret.set(HPKE_VERSION, 0);\n ret.set(this._suiteId, 7);\n ret.set(label, 7 + this._suiteId.byteLength);\n ret.set(ikm, 7 + this._suiteId.byteLength + label.byteLength);\n return ret;\n }\n buildLabeledInfo(label, info, len) {\n this._checkInit();\n const ret = new Uint8Array(9 + this._suiteId.byteLength + label.byteLength + info.byteLength);\n ret.set(new Uint8Array([0, len]), 0);\n ret.set(HPKE_VERSION, 2);\n ret.set(this._suiteId, 9);\n ret.set(label, 9 + this._suiteId.byteLength);\n ret.set(info, 9 + this._suiteId.byteLength + label.byteLength);\n return ret;\n }\n async extract(salt, ikm) {\n await this._setup();\n if (salt.byteLength === 0) {\n salt = new ArrayBuffer(this.hashSize);\n }\n if (salt.byteLength !== this.hashSize) {\n throw new InvalidParamError(\"The salt length must be the same as the hashSize\");\n }\n const key = await this._api.importKey(\"raw\", salt, this.algHash, false, [\n \"sign\",\n ]);\n return await this._api.sign(\"HMAC\", key, ikm);\n }\n async expand(prk, info, len) {\n await this._setup();\n const key = await this._api.importKey(\"raw\", prk, this.algHash, false, [\n \"sign\",\n ]);\n const okm = new ArrayBuffer(len);\n const p = new Uint8Array(okm);\n let prev = EMPTY;\n const mid = new Uint8Array(info);\n const tail = new Uint8Array(1);\n if (len > 255 * this.hashSize) {\n throw new Error(\"Entropy limit reached\");\n }\n const tmp = new Uint8Array(this.hashSize + mid.length + 1);\n for (let i = 1, cur = 0; cur < p.length; i++) {\n tail[0] = i;\n tmp.set(prev, 0);\n tmp.set(mid, prev.length);\n tmp.set(tail, prev.length + mid.length);\n prev = new Uint8Array(await this._api.sign(\"HMAC\", key, tmp.slice(0, prev.length + mid.length + 1)));\n if (p.length - cur >= prev.length) {\n p.set(prev, cur);\n cur += prev.length;\n }\n else {\n p.set(prev.slice(0, p.length - cur), cur);\n cur += p.length - cur;\n }\n }\n return okm;\n }\n async extractAndExpand(salt, ikm, info, len) {\n await this._setup();\n const baseKey = await this._api.importKey(\"raw\", ikm, \"HKDF\", false, [\"deriveBits\"]);\n return await this._api.deriveBits({\n name: \"HKDF\",\n hash: this.algHash.hash,\n salt: salt,\n info: info,\n }, baseKey, len * 8);\n }\n async labeledExtract(salt, label, ikm) {\n return await this.extract(salt, this.buildLabeledIkm(label, ikm).buffer);\n }\n async labeledExpand(prk, label, info, len) {\n return await this.expand(prk, this.buildLabeledInfo(label, info, len).buffer, len);\n }\n _checkInit() {\n if (this._suiteId === EMPTY) {\n throw new Error(\"Not initialized. Call init()\");\n }\n }\n}\nexport class HkdfSha256Native extends HkdfNative {\n constructor() {\n super(...arguments);\n /** KdfId.HkdfSha256 (0x0001) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha256\n });\n /** 32 */\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n /** The parameters for Web Cryptography API */\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-256\",\n length: 256,\n }\n });\n }\n}\nexport class HkdfSha384Native extends HkdfNative {\n constructor() {\n super(...arguments);\n /** KdfId.HkdfSha384 (0x0002) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha384\n });\n /** 48 */\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 48\n });\n /** The parameters for Web Cryptography API */\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-384\",\n length: 384,\n }\n });\n }\n}\nexport class HkdfSha512Native extends HkdfNative {\n constructor() {\n super(...arguments);\n /** KdfId.HkdfSha512 (0x0003) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha512\n });\n /** 64 */\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 64\n });\n /** The parameters for Web Cryptography API */\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-512\",\n length: 512,\n }\n });\n }\n}\n","// The key usages for AEAD.\nexport const AEAD_USAGES = [\"encrypt\", \"decrypt\"];\n","/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/abstract/montgomery.ts\n */\n/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytesAsync, validateObject, } from \"../utils/noble.js\";\nimport { createKeygen } from \"./curve.js\";\nimport { mod } from \"./modular.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nfunction validateOpts(curve) {\n validateObject(curve, {\n adjustScalarBytes: \"function\",\n powPminus2: \"function\",\n });\n return Object.freeze({ ...curve });\n}\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;\n const is25519 = type === \"x25519\";\n if (!is25519 && type !== \"x448\")\n throw new Error(\"invalid type\");\n const randomBytes_ = rand || randomBytesAsync;\n const montgomeryBits = is25519 ? 255 : 448;\n const fieldLen = is25519 ? 32 : 56;\n const Gu = is25519 ? BigInt(9) : BigInt(5);\n // RFC 7748 #5:\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and\n // (156326 - 2) / 4 = 39081 for curve448/X448\n // const a = is25519 ? 156326n : 486662n;\n const a24 = is25519 ? BigInt(121665) : BigInt(39081);\n // RFC: x25519 \"the resulting integer is of the form 2^254 plus\n // eight times a value between 0 and 2^251 - 1 (inclusive)\"\n // x448: \"2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)\"\n const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);\n const maxAdded = is25519\n ? BigInt(8) * _2n ** BigInt(251) - _1n\n : BigInt(4) * _2n ** BigInt(445) - _1n;\n const maxScalar = minScalar + maxAdded + _1n; // (inclusive)\n const modP = (n) => mod(n, P);\n const GuBytes = encodeU(Gu);\n function encodeU(u) {\n return numberToBytesLE(modP(u), fieldLen);\n }\n function decodeU(u) {\n const _u = copyBytes(abytes(u, fieldLen, \"uCoordinate\"));\n // RFC: When receiving such an array, implementations of X25519\n // (but not X448) MUST mask the most significant bit in the final byte.\n if (is25519)\n _u[31] &= 127; // 0b0111_1111\n // RFC: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime. The non-canonical\n // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224\n // - 1 through 2^448 - 1 for X448.\n return modP(bytesToNumberLE(_u));\n }\n function decodeScalar(scalar) {\n return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, \"scalar\"))));\n }\n function scalarMult(scalar, u) {\n const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));\n // Some public keys are useless, of low-order. Curve author doesn't think\n // it needs to be validated, but we do it nonetheless.\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error(\"invalid private or public key received\");\n return encodeU(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n const getPublicKey = scalarMultBase;\n const getSharedSecret = scalarMult;\n // cswap from RFC7748 \"example code\"\n function cswap(swap, x_2, x_3) {\n // dummy = mask(swap) AND (x_2 XOR x_3)\n // Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n // and x_3, computed, e.g., as mask(swap) = 0 - swap.\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy\n x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy\n return { x_2, x_3 };\n }\n /**\n * Montgomery x-only multiplication ladder.\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange(\"u\", u, _0n, P);\n aInRange(\"scalar\", scalar, minScalar, maxScalar);\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent\n return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))\n }\n const lengths = {\n secretKey: fieldLen,\n publicKey: fieldLen,\n seed: fieldLen,\n };\n const randomSecretKey = async (seed) => {\n if (seed === undefined) {\n seed = await randomBytes_(fieldLen);\n }\n abytes(seed, lengths.seed, \"seed\");\n return seed;\n };\n const utils = { randomSecretKey };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getSharedSecret,\n getPublicKey,\n scalarMult,\n scalarMultBase,\n utils,\n GuBytes: GuBytes.slice(),\n lengths,\n });\n}\n","import { AEAD_USAGES, AeadId, NativeAlgorithm } from \"@hpke/common\";\nexport class AesGcmContext extends NativeAlgorithm {\n constructor(key) {\n super();\n Object.defineProperty(this, \"_rawKey\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_key\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: undefined\n });\n this._rawKey = key;\n }\n async seal(iv, data, aad) {\n await this._setupKey();\n const alg = {\n name: \"AES-GCM\",\n iv: iv,\n additionalData: aad,\n };\n const ct = await this._api.encrypt(alg, this._key, data);\n return ct;\n }\n async open(iv, data, aad) {\n await this._setupKey();\n const alg = {\n name: \"AES-GCM\",\n iv: iv,\n additionalData: aad,\n };\n const pt = await this._api.decrypt(alg, this._key, data);\n return pt;\n }\n async _setupKey() {\n if (this._key !== undefined) {\n return;\n }\n await this._setup();\n const key = await this._importKey(this._rawKey);\n (new Uint8Array(this._rawKey)).fill(0);\n this._key = key;\n return;\n }\n async _importKey(key) {\n return await this._api.importKey(\"raw\", key, { name: \"AES-GCM\" }, true, AEAD_USAGES);\n }\n}\n/**\n * The AES-128-GCM for HPKE AEAD implementing {@link AeadInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `aead` parameter of {@link CipherSuiteParams} instead of `AeadId.Aes128Gcm`.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class Aes128Gcm {\n constructor() {\n /** AeadId.Aes128Gcm (0x0001) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: AeadId.Aes128Gcm\n });\n /** 16 */\n Object.defineProperty(this, \"keySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n /** 12 */\n Object.defineProperty(this, \"nonceSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 12\n });\n /** 16 */\n Object.defineProperty(this, \"tagSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n }\n createEncryptionContext(key) {\n return new AesGcmContext(key);\n }\n}\n/**\n * The AES-256-GCM for HPKE AEAD implementing {@link AeadInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `aead` parameter of {@link CipherSuiteParams} instead of `AeadId.Aes256Gcm`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes256Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes256Gcm(),\n * });\n * ```\n */\nexport class Aes256Gcm extends Aes128Gcm {\n constructor() {\n super(...arguments);\n /** AeadId.Aes256Gcm (0x0002) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: AeadId.Aes256Gcm\n });\n /** 32 */\n Object.defineProperty(this, \"keySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n /** 12 */\n Object.defineProperty(this, \"nonceSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 12\n });\n /** 16 */\n Object.defineProperty(this, \"tagSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n }\n}\n","import { NotSupportedError } from \"@hpke/common\";\nexport function emitNotSupported() {\n return new Promise((_resolve, reject) => {\n reject(new NotSupportedError(\"Not supported\"));\n });\n}\n","import { ExportError, INPUT_LENGTH_LIMIT, InvalidParamError, } from \"@hpke/common\";\nimport { emitNotSupported } from \"./utils/emitNotSupported.js\";\n// b\"sec\"\nconst LABEL_SEC = new Uint8Array([115, 101, 99]);\nexport class ExporterContextImpl {\n constructor(api, kdf, exporterSecret) {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"exporterSecret\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._api = api;\n this._kdf = kdf;\n this.exporterSecret = exporterSecret;\n }\n async seal(_data, _aad) {\n return await emitNotSupported();\n }\n async open(_data, _aad) {\n return await emitNotSupported();\n }\n async export(exporterContext, len) {\n if (exporterContext.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long exporter context\");\n }\n try {\n return await this._kdf.labeledExpand(this.exporterSecret, LABEL_SEC, new Uint8Array(exporterContext), len);\n }\n catch (e) {\n throw new ExportError(e);\n }\n }\n}\nexport class RecipientExporterContextImpl extends ExporterContextImpl {\n}\nexport class SenderExporterContextImpl extends ExporterContextImpl {\n constructor(api, kdf, exporterSecret, enc) {\n super(api, kdf, exporterSecret);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.enc = enc;\n return;\n }\n}\n","import { i2Osp, MessageLimitReachedError, xor } from \"@hpke/common\";\nimport { ExporterContextImpl } from \"./exporterContext.js\";\nexport class EncryptionContextImpl extends ExporterContextImpl {\n constructor(api, kdf, params) {\n super(api, kdf, params.exporterSecret);\n // AEAD id.\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The length in bytes of a key for the algorithm.\n Object.defineProperty(this, \"_nK\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The length in bytes of a nonce for the algorithm.\n Object.defineProperty(this, \"_nN\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The length in bytes of an authentication tag for the algorithm.\n Object.defineProperty(this, \"_nT\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The end-to-end encryption key information.\n Object.defineProperty(this, \"_ctx\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n if (params.key === undefined || params.baseNonce === undefined ||\n params.seq === undefined) {\n throw new Error(\"Required parameters are missing\");\n }\n this._aead = params.aead;\n this._nK = this._aead.keySize;\n this._nN = this._aead.nonceSize;\n this._nT = this._aead.tagSize;\n const key = this._aead.createEncryptionContext(params.key);\n this._ctx = {\n key: key,\n baseNonce: params.baseNonce,\n seq: params.seq,\n };\n }\n computeNonce(k) {\n const seqBytes = i2Osp(k.seq, k.baseNonce.byteLength);\n return xor(k.baseNonce, seqBytes).buffer;\n }\n incrementSeq(k) {\n // if (this.seq >= (1 << (8 * this.baseNonce.byteLength)) - 1) {\n if (k.seq > Number.MAX_SAFE_INTEGER) {\n throw new MessageLimitReachedError(\"Message limit reached\");\n }\n k.seq += 1;\n return;\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _Mutex_locked;\nexport class Mutex {\n constructor() {\n _Mutex_locked.set(this, Promise.resolve());\n }\n async lock() {\n let releaseLock;\n const nextLock = new Promise((resolve) => {\n releaseLock = resolve;\n });\n const previousLock = __classPrivateFieldGet(this, _Mutex_locked, \"f\");\n __classPrivateFieldSet(this, _Mutex_locked, nextLock, \"f\");\n await previousLock;\n return releaseLock;\n }\n}\n_Mutex_locked = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _RecipientContextImpl_mutex;\nimport { EMPTY, OpenError } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class RecipientContextImpl extends EncryptionContextImpl {\n constructor() {\n super(...arguments);\n _RecipientContextImpl_mutex.set(this, void 0);\n }\n async open(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _RecipientContextImpl_mutex, __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\").lock();\n let pt;\n try {\n pt = await this._ctx.key.open(this.computeNonce(this._ctx), data, aad);\n }\n catch (e) {\n throw new OpenError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return pt;\n }\n}\n_RecipientContextImpl_mutex = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _SenderContextImpl_mutex;\nimport { EMPTY, SealError } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class SenderContextImpl extends EncryptionContextImpl {\n constructor(api, kdf, params, enc) {\n super(api, kdf, params);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n _SenderContextImpl_mutex.set(this, void 0);\n this.enc = enc;\n }\n async seal(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _SenderContextImpl_mutex, __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\").lock();\n let ct;\n try {\n ct = await this._ctx.key.seal(this.computeNonce(this._ctx), data, aad);\n }\n catch (e) {\n throw new SealError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return ct;\n }\n}\n_SenderContextImpl_mutex = new WeakMap();\n","import { AeadId, EMPTY, i2Osp, INFO_LENGTH_LIMIT, INPUT_LENGTH_LIMIT, InvalidParamError, MINIMUM_PSK_LENGTH, Mode, NativeAlgorithm, } from \"@hpke/common\";\nimport { RecipientExporterContextImpl, SenderExporterContextImpl, } from \"./exporterContext.js\";\nimport { RecipientContextImpl } from \"./recipientContext.js\";\nimport { SenderContextImpl } from \"./senderContext.js\";\n// b\"base_nonce\"\n// deno-fmt-ignore\nconst LABEL_BASE_NONCE = new Uint8Array([\n 98, 97, 115, 101, 95, 110, 111, 110, 99, 101,\n]);\n// b\"exp\"\nconst LABEL_EXP = new Uint8Array([101, 120, 112]);\n// b\"info_hash\"\n// deno-fmt-ignore\nconst LABEL_INFO_HASH = new Uint8Array([\n 105, 110, 102, 111, 95, 104, 97, 115, 104,\n]);\n// b\"key\"\nconst LABEL_KEY = new Uint8Array([107, 101, 121]);\n// b\"psk_id_hash\"\n// deno-fmt-ignore\nconst LABEL_PSK_ID_HASH = new Uint8Array([\n 112, 115, 107, 95, 105, 100, 95, 104, 97, 115, 104,\n]);\n// b\"secret\"\nconst LABEL_SECRET = new Uint8Array([115, 101, 99, 114, 101, 116]);\n// b\"HPKE\"\n// deno-fmt-ignore\nconst SUITE_ID_HEADER_HPKE = new Uint8Array([\n 72, 80, 75, 69, 0, 0, 0, 0, 0, 0,\n]);\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This is the super class of {@link CipherSuite} and the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuite | @hpke/core#CipherSuite} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - DHKEM(X25519, HKDF-SHA256)\n * - DHKEM(X448, HKDF-SHA512)\n * - ChaCha20Poly1305\n *\n * In addtion, the HKDF functions contained in this class can only derive\n * keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * // Use an extension module.\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuiteNative extends NativeAlgorithm {\n /**\n * @param params A set of parameters for building a cipher suite.\n *\n * If the error occurred, throws {@link InvalidParamError}.\n *\n * @throws {@link InvalidParamError}\n */\n constructor(params) {\n super();\n Object.defineProperty(this, \"_kem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // KEM\n if (typeof params.kem === \"number\") {\n throw new InvalidParamError(\"KemId cannot be used\");\n }\n this._kem = params.kem;\n // KDF\n if (typeof params.kdf === \"number\") {\n throw new InvalidParamError(\"KdfId cannot be used\");\n }\n this._kdf = params.kdf;\n // AEAD\n if (typeof params.aead === \"number\") {\n throw new InvalidParamError(\"AeadId cannot be used\");\n }\n this._aead = params.aead;\n this._suiteId = new Uint8Array(SUITE_ID_HEADER_HPKE);\n this._suiteId.set(i2Osp(this._kem.id, 2), 4);\n this._suiteId.set(i2Osp(this._kdf.id, 2), 6);\n this._suiteId.set(i2Osp(this._aead.id, 2), 8);\n this._kdf.init(this._suiteId);\n }\n /**\n * Gets the KEM context of the ciphersuite.\n */\n get kem() {\n return this._kem;\n }\n /**\n * Gets the KDF context of the ciphersuite.\n */\n get kdf() {\n return this._kdf;\n }\n /**\n * Gets the AEAD context of the ciphersuite.\n */\n get aead() {\n return this._aead;\n }\n /**\n * Creates an encryption context for a sender.\n *\n * If the error occurred, throws {@link DecapError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the sender encryption context.\n * @returns A sender encryption context.\n * @throws {@link EncapError}, {@link ValidationError}\n */\n async createSenderContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const dh = await this._kem.encap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleS(mode, dh.sharedSecret, dh.enc, params);\n }\n /**\n * Creates an encryption context for a recipient.\n *\n * If the error occurred, throws {@link DecapError}\n * | {@link DeserializeError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the recipient encryption context.\n * @returns A recipient encryption context.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link ValidationError}\n */\n async createRecipientContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const sharedSecret = await this._kem.decap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderPublicKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderPublicKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleR(mode, sharedSecret, params);\n }\n /**\n * Encrypts a message to a recipient.\n *\n * If the error occurred, throws `EncapError` | `MessageLimitReachedError` | `SealError` | `ValidationError`.\n *\n * @param params A set of parameters for building a sender encryption context.\n * @param pt A plain text as bytes to be encrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A cipher text and an encapsulated key as bytes.\n * @throws {@link EncapError}, {@link MessageLimitReachedError}, {@link SealError}, {@link ValidationError}\n */\n async seal(params, pt, aad = EMPTY.buffer) {\n const ctx = await this.createSenderContext(params);\n return {\n ct: await ctx.seal(pt, aad),\n enc: ctx.enc,\n };\n }\n /**\n * Decrypts a message from a sender.\n *\n * If the error occurred, throws `DecapError` | `DeserializeError` | `OpenError` | `ValidationError`.\n *\n * @param params A set of parameters for building a recipient encryption context.\n * @param ct An encrypted text as bytes to be decrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A decrypted plain text as bytes.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link OpenError}, {@link ValidationError}\n */\n async open(params, ct, aad = EMPTY.buffer) {\n const ctx = await this.createRecipientContext(params);\n return await ctx.open(ct, aad);\n }\n // private verifyPskInputs(mode: Mode, params: KeyScheduleParams) {\n // const gotPsk = (params.psk !== undefined);\n // const gotPskId = (params.psk !== undefined && params.psk.id.byteLength > 0);\n // if (gotPsk !== gotPskId) {\n // throw new Error('Inconsistent PSK inputs');\n // }\n // if (gotPsk && (mode === Mode.Base || mode === Mode.Auth)) {\n // throw new Error('PSK input provided when not needed');\n // }\n // if (!gotPsk && (mode === Mode.Psk || mode === Mode.AuthPsk)) {\n // throw new Error('Missing required PSK input');\n // }\n // return;\n // }\n async _keySchedule(mode, sharedSecret, params) {\n // Currently, there is no point in executing this function\n // because this hpke library does not allow users to explicitly specify the mode.\n //\n // this.verifyPskInputs(mode, params);\n const pskId = params.psk === undefined\n ? EMPTY\n : new Uint8Array(params.psk.id);\n const pskIdHash = await this._kdf.labeledExtract(EMPTY.buffer, LABEL_PSK_ID_HASH, pskId);\n const info = params.info === undefined\n ? EMPTY\n : new Uint8Array(params.info);\n const infoHash = await this._kdf.labeledExtract(EMPTY.buffer, LABEL_INFO_HASH, info);\n const keyScheduleContext = new Uint8Array(1 + pskIdHash.byteLength + infoHash.byteLength);\n keyScheduleContext.set(new Uint8Array([mode]), 0);\n keyScheduleContext.set(new Uint8Array(pskIdHash), 1);\n keyScheduleContext.set(new Uint8Array(infoHash), 1 + pskIdHash.byteLength);\n const psk = params.psk === undefined\n ? EMPTY\n : new Uint8Array(params.psk.key);\n const ikm = this._kdf.buildLabeledIkm(LABEL_SECRET, psk)\n .buffer;\n const exporterSecretInfo = this._kdf.buildLabeledInfo(LABEL_EXP, keyScheduleContext, this._kdf.hashSize).buffer;\n const exporterSecret = await this._kdf.extractAndExpand(sharedSecret, ikm, exporterSecretInfo, this._kdf.hashSize);\n if (this._aead.id === AeadId.ExportOnly) {\n return { aead: this._aead, exporterSecret: exporterSecret };\n }\n const keyInfo = this._kdf.buildLabeledInfo(LABEL_KEY, keyScheduleContext, this._aead.keySize).buffer;\n const key = await this._kdf.extractAndExpand(sharedSecret, ikm, keyInfo, this._aead.keySize);\n const baseNonceInfo = this._kdf.buildLabeledInfo(LABEL_BASE_NONCE, keyScheduleContext, this._aead.nonceSize).buffer;\n const baseNonce = await this._kdf.extractAndExpand(sharedSecret, ikm, baseNonceInfo, this._aead.nonceSize);\n return {\n aead: this._aead,\n exporterSecret: exporterSecret,\n key: key,\n baseNonce: new Uint8Array(baseNonce),\n seq: 0,\n };\n }\n async _keyScheduleS(mode, sharedSecret, enc, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new SenderExporterContextImpl(this._api, this._kdf, res.exporterSecret, enc);\n }\n return new SenderContextImpl(this._api, this._kdf, res, enc);\n }\n async _keyScheduleR(mode, sharedSecret, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new RecipientExporterContextImpl(this._api, this._kdf, res.exporterSecret);\n }\n return new RecipientContextImpl(this._api, this._kdf, res);\n }\n _validateInputLength(params) {\n if (params.info !== undefined &&\n params.info.byteLength > INFO_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long info\");\n }\n if (params.psk !== undefined) {\n if (params.psk.key.byteLength < MINIMUM_PSK_LENGTH) {\n throw new InvalidParamError(`PSK must have at least ${MINIMUM_PSK_LENGTH} bytes`);\n }\n if (params.psk.key.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.key\");\n }\n if (params.psk.id.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.id\");\n }\n }\n return;\n }\n}\n","import { Dhkem, Ec, HkdfSha256Native, HkdfSha384Native, HkdfSha512Native, KemId, } from \"@hpke/common\";\nexport class DhkemP256HkdfSha256Native extends Dhkem {\n constructor() {\n const kdf = new HkdfSha256Native();\n const prim = new Ec(KemId.DhkemP256HkdfSha256, kdf);\n super(KemId.DhkemP256HkdfSha256, prim, kdf);\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KemId.DhkemP256HkdfSha256\n });\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 65\n });\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 65\n });\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n }\n}\nexport class DhkemP384HkdfSha384Native extends Dhkem {\n constructor() {\n const kdf = new HkdfSha384Native();\n const prim = new Ec(KemId.DhkemP384HkdfSha384, kdf);\n super(KemId.DhkemP384HkdfSha384, prim, kdf);\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KemId.DhkemP384HkdfSha384\n });\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 48\n });\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 97\n });\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 97\n });\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 48\n });\n }\n}\nexport class DhkemP521HkdfSha512Native extends Dhkem {\n constructor() {\n const kdf = new HkdfSha512Native();\n const prim = new Ec(KemId.DhkemP521HkdfSha512, kdf);\n super(KemId.DhkemP521HkdfSha512, prim, kdf);\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KemId.DhkemP521HkdfSha512\n });\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 64\n });\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 133\n });\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 133\n });\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 64\n });\n }\n}\n","import { HkdfSha256Native, HkdfSha384Native, HkdfSha512Native, } from \"@hpke/common\";\nimport { CipherSuiteNative } from \"./cipherSuiteNative.js\";\nimport { DhkemP256HkdfSha256Native, DhkemP384HkdfSha384Native, DhkemP521HkdfSha512Native, } from \"./kems/dhkemNative.js\";\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This class is the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuiteNative | @hpke/core#CipherSuiteNative} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - `DHKEM(X25519, HKDF-SHA256)`\n * - `DHKEM(X448, HKDF-SHA512)`\n * - `ChaCha20Poly1305`\n *\n * In addtion, the HKDF functions contained in this `CipherSuiteNative`\n * class can only derive keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuite extends CipherSuiteNative {\n}\n/**\n * The DHKEM(P-256, HKDF-SHA256) for HPKE KEM implementing {@link KemInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KemId.DhkemP256HkdfSha256`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class DhkemP256HkdfSha256 extends DhkemP256HkdfSha256Native {\n}\n/**\n * The DHKEM(P-384, HKDF-SHA384) for HPKE KEM implementing {@link KemInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KemId.DhkemP384HkdfSha384`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP384HkdfSha384,\n * HkdfSha384,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP384HkdfSha384(),\n * kdf: new HkdfSha384(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class DhkemP384HkdfSha384 extends DhkemP384HkdfSha384Native {\n}\n/**\n * The DHKEM(P-521, HKDF-SHA512) for HPKE KEM implementing {@link KemInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KemId.DhkemP521HkdfSha512`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes256Gcm,\n * CipherSuite,\n * DhkemP521HkdfSha512,\n * HkdfSha512,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP521HkdfSha512(),\n * kdf: new HkdfSha512(),\n * aead: new Aes256Gcm(),\n * });\n * ```\n */\nexport class DhkemP521HkdfSha512 extends DhkemP521HkdfSha512Native {\n}\n/**\n * The HKDF-SHA256 for HPKE KDF implementing {@link KdfInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha256`.\n *\n * The KDF class can only derive keys of the same length as the `hashSize`.\n * If you want to derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class HkdfSha256 extends HkdfSha256Native {\n}\n/**\n * The HKDF-SHA384 for HPKE KDF implementing {@link KdfInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha384`.\n *\n * The KDF class can only derive keys of the same length as the `hashSize`.\n * If you want to derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP384HkdfSha384,\n * HkdfSha384,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP384HkdfSha384(),\n * kdf: new HkdfSha384(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class HkdfSha384 extends HkdfSha384Native {\n}\n/**\n * The HKDF-SHA512 for HPKE KDF implementing {@link KdfInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha512`.\n *\n * The KDF class can only derive keys of the same length as the `hashSize`.\n * If you want to derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes256Gcm,\n * CipherSuite,\n * DhkemP521HkdfSha512,\n * HkdfSha512,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP521HkdfSha512(),\n * kdf: new HkdfSha512(),\n * aead: new Aes256Gcm(),\n * });\n * ```\n */\nexport class HkdfSha512 extends HkdfSha512Native {\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, } from \"@hpke/common\";\nconst ALG_NAME = \"X25519\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X25519 = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,\n]);\nexport class X25519 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 32;\n this._nSk = 32;\n this._nDh = 32;\n this._pkcs8AlgId = PKCS8_ALG_ID_X25519;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY.buffer, LABEL_DKP_PRK, new Uint8Array(ikm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, } from \"@hpke/common\";\nconst ALG_NAME = \"X448\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X448 = new Uint8Array([\n 0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38,\n]);\nexport class X448 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 56;\n this._nSk = 56;\n this._nDh = 56;\n this._pkcs8AlgId = PKCS8_ALG_ID_X448;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(key, false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY.buffer, LABEL_DKP_PRK, new Uint8Array(ikm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","'use strict';\n\n// This is free and unencumbered software released into the public domain.\n// See LICENSE.md for more information.\n\n//\n// Utilities\n//\n\n/**\n * @param {number} a The number to test.\n * @param {number} min The minimum value in the range, inclusive.\n * @param {number} max The maximum value in the range, inclusive.\n * @return {boolean} True if a >= min and a <= max.\n */\nfunction inRange(a, min, max) {\n return min <= a && a <= max;\n}\n\n/**\n * @param {*} o\n * @return {Object}\n */\nfunction ToDictionary(o) {\n if (o === undefined) return {};\n if (o === Object(o)) return o;\n throw TypeError('Could not convert argument to dictionary');\n}\n\n/**\n * @param {string} string Input string of UTF-16 code units.\n * @return {!Array.} Code points.\n */\nfunction stringToCodePoints(string) {\n // https://heycam.github.io/webidl/#dfn-obtain-unicode\n\n // 1. Let S be the DOMString value.\n var s = String(string);\n\n // 2. Let n be the length of S.\n var n = s.length;\n\n // 3. Initialize i to 0.\n var i = 0;\n\n // 4. Initialize U to be an empty sequence of Unicode characters.\n var u = [];\n\n // 5. While i < n:\n while (i < n) {\n\n // 1. Let c be the code unit in S at index i.\n var c = s.charCodeAt(i);\n\n // 2. Depending on the value of c:\n\n // c < 0xD800 or c > 0xDFFF\n if (c < 0xD800 || c > 0xDFFF) {\n // Append to U the Unicode character with code point c.\n u.push(c);\n }\n\n // 0xDC00 ≤ c ≤ 0xDFFF\n else if (0xDC00 <= c && c <= 0xDFFF) {\n // Append to U a U+FFFD REPLACEMENT CHARACTER.\n u.push(0xFFFD);\n }\n\n // 0xD800 ≤ c ≤ 0xDBFF\n else if (0xD800 <= c && c <= 0xDBFF) {\n // 1. If i = n−1, then append to U a U+FFFD REPLACEMENT\n // CHARACTER.\n if (i === n - 1) {\n u.push(0xFFFD);\n }\n // 2. Otherwise, i < n−1:\n else {\n // 1. Let d be the code unit in S at index i+1.\n var d = string.charCodeAt(i + 1);\n\n // 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:\n if (0xDC00 <= d && d <= 0xDFFF) {\n // 1. Let a be c & 0x3FF.\n var a = c & 0x3FF;\n\n // 2. Let b be d & 0x3FF.\n var b = d & 0x3FF;\n\n // 3. Append to U the Unicode character with code point\n // 2^16+2^10*a+b.\n u.push(0x10000 + (a << 10) + b);\n\n // 4. Set i to i+1.\n i += 1;\n }\n\n // 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a\n // U+FFFD REPLACEMENT CHARACTER.\n else {\n u.push(0xFFFD);\n }\n }\n }\n\n // 3. Set i to i+1.\n i += 1;\n }\n\n // 6. Return U.\n return u;\n}\n\n/**\n * @param {!Array.} code_points Array of code points.\n * @return {string} string String of UTF-16 code units.\n */\nfunction codePointsToString(code_points) {\n var s = '';\n for (var i = 0; i < code_points.length; ++i) {\n var cp = code_points[i];\n if (cp <= 0xFFFF) {\n s += String.fromCharCode(cp);\n } else {\n cp -= 0x10000;\n s += String.fromCharCode((cp >> 10) + 0xD800,\n (cp & 0x3FF) + 0xDC00);\n }\n }\n return s;\n}\n\n\n//\n// Implementation of Encoding specification\n// https://encoding.spec.whatwg.org/\n//\n\n//\n// 3. Terminology\n//\n\n/**\n * End-of-stream is a special token that signifies no more tokens\n * are in the stream.\n * @const\n */ var end_of_stream = -1;\n\n/**\n * A stream represents an ordered sequence of tokens.\n *\n * @constructor\n * @param {!(Array.|Uint8Array)} tokens Array of tokens that provide the\n * stream.\n */\nfunction Stream(tokens) {\n /** @type {!Array.} */\n this.tokens = [].slice.call(tokens);\n}\n\nStream.prototype = {\n /**\n * @return {boolean} True if end-of-stream has been hit.\n */\n endOfStream: function() {\n return !this.tokens.length;\n },\n\n /**\n * When a token is read from a stream, the first token in the\n * stream must be returned and subsequently removed, and\n * end-of-stream must be returned otherwise.\n *\n * @return {number} Get the next token from the stream, or\n * end_of_stream.\n */\n read: function() {\n if (!this.tokens.length)\n return end_of_stream;\n return this.tokens.shift();\n },\n\n /**\n * When one or more tokens are prepended to a stream, those tokens\n * must be inserted, in given order, before the first token in the\n * stream.\n *\n * @param {(number|!Array.)} token The token(s) to prepend to the stream.\n */\n prepend: function(token) {\n if (Array.isArray(token)) {\n var tokens = /**@type {!Array.}*/(token);\n while (tokens.length)\n this.tokens.unshift(tokens.pop());\n } else {\n this.tokens.unshift(token);\n }\n },\n\n /**\n * When one or more tokens are pushed to a stream, those tokens\n * must be inserted, in given order, after the last token in the\n * stream.\n *\n * @param {(number|!Array.)} token The tokens(s) to prepend to the stream.\n */\n push: function(token) {\n if (Array.isArray(token)) {\n var tokens = /**@type {!Array.}*/(token);\n while (tokens.length)\n this.tokens.push(tokens.shift());\n } else {\n this.tokens.push(token);\n }\n }\n};\n\n//\n// 4. Encodings\n//\n\n// 4.1 Encoders and decoders\n\n/** @const */\nvar finished = -1;\n\n/**\n * @param {boolean} fatal If true, decoding errors raise an exception.\n * @param {number=} opt_code_point Override the standard fallback code point.\n * @return {number} The code point to insert on a decoding error.\n */\nfunction decoderError(fatal, opt_code_point) {\n if (fatal)\n throw TypeError('Decoder error');\n return opt_code_point || 0xFFFD;\n}\n\n//\n// 7. API\n//\n\n/** @const */ var DEFAULT_ENCODING = 'utf-8';\n\n// 7.1 Interface TextDecoder\n\n/**\n * @constructor\n * @param {string=} encoding The label of the encoding;\n * defaults to 'utf-8'.\n * @param {Object=} options\n */\nfunction TextDecoder(encoding, options) {\n if (!(this instanceof TextDecoder)) {\n return new TextDecoder(encoding, options);\n }\n encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;\n if (encoding !== DEFAULT_ENCODING) {\n throw new Error('Encoding not supported. Only utf-8 is supported');\n }\n options = ToDictionary(options);\n\n /** @private @type {boolean} */\n this._streaming = false;\n /** @private @type {boolean} */\n this._BOMseen = false;\n /** @private @type {?Decoder} */\n this._decoder = null;\n /** @private @type {boolean} */\n this._fatal = Boolean(options['fatal']);\n /** @private @type {boolean} */\n this._ignoreBOM = Boolean(options['ignoreBOM']);\n\n Object.defineProperty(this, 'encoding', {value: 'utf-8'});\n Object.defineProperty(this, 'fatal', {value: this._fatal});\n Object.defineProperty(this, 'ignoreBOM', {value: this._ignoreBOM});\n}\n\nTextDecoder.prototype = {\n /**\n * @param {ArrayBufferView=} input The buffer of bytes to decode.\n * @param {Object=} options\n * @return {string} The decoded string.\n */\n decode: function decode(input, options) {\n var bytes;\n if (typeof input === 'object' && input instanceof ArrayBuffer) {\n bytes = new Uint8Array(input);\n } else if (typeof input === 'object' && 'buffer' in input &&\n input.buffer instanceof ArrayBuffer) {\n bytes = new Uint8Array(input.buffer,\n input.byteOffset,\n input.byteLength);\n } else {\n bytes = new Uint8Array(0);\n }\n\n options = ToDictionary(options);\n\n if (!this._streaming) {\n this._decoder = new UTF8Decoder({fatal: this._fatal});\n this._BOMseen = false;\n }\n this._streaming = Boolean(options['stream']);\n\n var input_stream = new Stream(bytes);\n\n var code_points = [];\n\n /** @type {?(number|!Array.)} */\n var result;\n\n while (!input_stream.endOfStream()) {\n result = this._decoder.handler(input_stream, input_stream.read());\n if (result === finished)\n break;\n if (result === null)\n continue;\n if (Array.isArray(result))\n code_points.push.apply(code_points, /**@type {!Array.}*/(result));\n else\n code_points.push(result);\n }\n if (!this._streaming) {\n do {\n result = this._decoder.handler(input_stream, input_stream.read());\n if (result === finished)\n break;\n if (result === null)\n continue;\n if (Array.isArray(result))\n code_points.push.apply(code_points, /**@type {!Array.}*/(result));\n else\n code_points.push(result);\n } while (!input_stream.endOfStream());\n this._decoder = null;\n }\n\n if (code_points.length) {\n // If encoding is one of utf-8, utf-16be, and utf-16le, and\n // ignore BOM flag and BOM seen flag are unset, run these\n // subsubsteps:\n if (['utf-8'].indexOf(this.encoding) !== -1 &&\n !this._ignoreBOM && !this._BOMseen) {\n // If token is U+FEFF, set BOM seen flag.\n if (code_points[0] === 0xFEFF) {\n this._BOMseen = true;\n code_points.shift();\n } else {\n // Otherwise, if token is not end-of-stream, set BOM seen\n // flag and append token to output.\n this._BOMseen = true;\n }\n }\n }\n\n return codePointsToString(code_points);\n }\n};\n\n// 7.2 Interface TextEncoder\n\n/**\n * @constructor\n * @param {string=} encoding The label of the encoding;\n * defaults to 'utf-8'.\n * @param {Object=} options\n */\nfunction TextEncoder(encoding, options) {\n if (!(this instanceof TextEncoder))\n return new TextEncoder(encoding, options);\n encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;\n if (encoding !== DEFAULT_ENCODING) {\n throw new Error('Encoding not supported. Only utf-8 is supported');\n }\n options = ToDictionary(options);\n\n /** @private @type {boolean} */\n this._streaming = false;\n /** @private @type {?Encoder} */\n this._encoder = null;\n /** @private @type {{fatal: boolean}} */\n this._options = {fatal: Boolean(options['fatal'])};\n\n Object.defineProperty(this, 'encoding', {value: 'utf-8'});\n}\n\nTextEncoder.prototype = {\n /**\n * @param {string=} opt_string The string to encode.\n * @param {Object=} options\n * @return {Uint8Array} Encoded bytes, as a Uint8Array.\n */\n encode: function encode(opt_string, options) {\n opt_string = opt_string ? String(opt_string) : '';\n options = ToDictionary(options);\n\n // NOTE: This option is nonstandard. None of the encodings\n // permitted for encoding (i.e. UTF-8, UTF-16) are stateful,\n // so streaming is not necessary.\n if (!this._streaming)\n this._encoder = new UTF8Encoder(this._options);\n this._streaming = Boolean(options['stream']);\n\n var bytes = [];\n var input_stream = new Stream(stringToCodePoints(opt_string));\n /** @type {?(number|!Array.)} */\n var result;\n while (!input_stream.endOfStream()) {\n result = this._encoder.handler(input_stream, input_stream.read());\n if (result === finished)\n break;\n if (Array.isArray(result))\n bytes.push.apply(bytes, /**@type {!Array.}*/(result));\n else\n bytes.push(result);\n }\n if (!this._streaming) {\n while (true) {\n result = this._encoder.handler(input_stream, input_stream.read());\n if (result === finished)\n break;\n if (Array.isArray(result))\n bytes.push.apply(bytes, /**@type {!Array.}*/(result));\n else\n bytes.push(result);\n }\n this._encoder = null;\n }\n return new Uint8Array(bytes);\n }\n};\n\n//\n// 8. The encoding\n//\n\n// 8.1 utf-8\n\n/**\n * @constructor\n * @implements {Decoder}\n * @param {{fatal: boolean}} options\n */\nfunction UTF8Decoder(options) {\n var fatal = options.fatal;\n\n // utf-8's decoder's has an associated utf-8 code point, utf-8\n // bytes seen, and utf-8 bytes needed (all initially 0), a utf-8\n // lower boundary (initially 0x80), and a utf-8 upper boundary\n // (initially 0xBF).\n var /** @type {number} */ utf8_code_point = 0,\n /** @type {number} */ utf8_bytes_seen = 0,\n /** @type {number} */ utf8_bytes_needed = 0,\n /** @type {number} */ utf8_lower_boundary = 0x80,\n /** @type {number} */ utf8_upper_boundary = 0xBF;\n\n /**\n * @param {Stream} stream The stream of bytes being decoded.\n * @param {number} bite The next byte read from the stream.\n * @return {?(number|!Array.)} The next code point(s)\n * decoded, or null if not enough data exists in the input\n * stream to decode a complete code point.\n */\n this.handler = function(stream, bite) {\n // 1. If byte is end-of-stream and utf-8 bytes needed is not 0,\n // set utf-8 bytes needed to 0 and return error.\n if (bite === end_of_stream && utf8_bytes_needed !== 0) {\n utf8_bytes_needed = 0;\n return decoderError(fatal);\n }\n\n // 2. If byte is end-of-stream, return finished.\n if (bite === end_of_stream)\n return finished;\n\n // 3. If utf-8 bytes needed is 0, based on byte:\n if (utf8_bytes_needed === 0) {\n\n // 0x00 to 0x7F\n if (inRange(bite, 0x00, 0x7F)) {\n // Return a code point whose value is byte.\n return bite;\n }\n\n // 0xC2 to 0xDF\n if (inRange(bite, 0xC2, 0xDF)) {\n // Set utf-8 bytes needed to 1 and utf-8 code point to byte\n // − 0xC0.\n utf8_bytes_needed = 1;\n utf8_code_point = bite - 0xC0;\n }\n\n // 0xE0 to 0xEF\n else if (inRange(bite, 0xE0, 0xEF)) {\n // 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.\n if (bite === 0xE0)\n utf8_lower_boundary = 0xA0;\n // 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.\n if (bite === 0xED)\n utf8_upper_boundary = 0x9F;\n // 3. Set utf-8 bytes needed to 2 and utf-8 code point to\n // byte − 0xE0.\n utf8_bytes_needed = 2;\n utf8_code_point = bite - 0xE0;\n }\n\n // 0xF0 to 0xF4\n else if (inRange(bite, 0xF0, 0xF4)) {\n // 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.\n if (bite === 0xF0)\n utf8_lower_boundary = 0x90;\n // 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.\n if (bite === 0xF4)\n utf8_upper_boundary = 0x8F;\n // 3. Set utf-8 bytes needed to 3 and utf-8 code point to\n // byte − 0xF0.\n utf8_bytes_needed = 3;\n utf8_code_point = bite - 0xF0;\n }\n\n // Otherwise\n else {\n // Return error.\n return decoderError(fatal);\n }\n\n // Then (byte is in the range 0xC2 to 0xF4) set utf-8 code\n // point to utf-8 code point << (6 × utf-8 bytes needed) and\n // return continue.\n utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed);\n return null;\n }\n\n // 4. If byte is not in the range utf-8 lower boundary to utf-8\n // upper boundary, run these substeps:\n if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {\n\n // 1. Set utf-8 code point, utf-8 bytes needed, and utf-8\n // bytes seen to 0, set utf-8 lower boundary to 0x80, and set\n // utf-8 upper boundary to 0xBF.\n utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;\n utf8_lower_boundary = 0x80;\n utf8_upper_boundary = 0xBF;\n\n // 2. Prepend byte to stream.\n stream.prepend(bite);\n\n // 3. Return error.\n return decoderError(fatal);\n }\n\n // 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary\n // to 0xBF.\n utf8_lower_boundary = 0x80;\n utf8_upper_boundary = 0xBF;\n\n // 6. Increase utf-8 bytes seen by one and set utf-8 code point\n // to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes\n // needed − utf-8 bytes seen)).\n utf8_bytes_seen += 1;\n utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen));\n\n // 7. If utf-8 bytes seen is not equal to utf-8 bytes needed,\n // continue.\n if (utf8_bytes_seen !== utf8_bytes_needed)\n return null;\n\n // 8. Let code point be utf-8 code point.\n var code_point = utf8_code_point;\n\n // 9. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes\n // seen to 0.\n utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;\n\n // 10. Return a code point whose value is code point.\n return code_point;\n };\n}\n\n/**\n * @constructor\n * @implements {Encoder}\n * @param {{fatal: boolean}} options\n */\nfunction UTF8Encoder(options) {\n var fatal = options.fatal;\n /**\n * @param {Stream} stream Input stream.\n * @param {number} code_point Next code point read from the stream.\n * @return {(number|!Array.)} Byte(s) to emit.\n */\n this.handler = function(stream, code_point) {\n // 1. If code point is end-of-stream, return finished.\n if (code_point === end_of_stream)\n return finished;\n\n // 2. If code point is in the range U+0000 to U+007F, return a\n // byte whose value is code point.\n if (inRange(code_point, 0x0000, 0x007f))\n return code_point;\n\n // 3. Set count and offset based on the range code point is in:\n var count, offset;\n // U+0080 to U+07FF: 1 and 0xC0\n if (inRange(code_point, 0x0080, 0x07FF)) {\n count = 1;\n offset = 0xC0;\n }\n // U+0800 to U+FFFF: 2 and 0xE0\n else if (inRange(code_point, 0x0800, 0xFFFF)) {\n count = 2;\n offset = 0xE0;\n }\n // U+10000 to U+10FFFF: 3 and 0xF0\n else if (inRange(code_point, 0x10000, 0x10FFFF)) {\n count = 3;\n offset = 0xF0;\n }\n\n // 4.Let bytes be a byte sequence whose first byte is (code\n // point >> (6 × count)) + offset.\n var bytes = [(code_point >> (6 * count)) + offset];\n\n // 5. Run these substeps while count is greater than 0:\n while (count > 0) {\n\n // 1. Set temp to code point >> (6 × (count − 1)).\n var temp = code_point >> (6 * (count - 1));\n\n // 2. Append to bytes 0x80 | (temp & 0x3F).\n bytes.push(0x80 | (temp & 0x3F));\n\n // 3. Decrease count by one.\n count -= 1;\n }\n\n // 6. Return bytes bytes, in order.\n return bytes;\n };\n}\n\nexports.TextEncoder = TextEncoder;\nexports.TextDecoder = TextDecoder;","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n","'use strict';\n\nconst uuid = require('uuid').v4;\n\n/**\n * Generates a JSON-RPC 1.0 or 2.0 request\n * @param {String} method Name of method to call\n * @param {Array|Object} params Array of parameters passed to the method as specified, or an object of parameter names and corresponding value\n * @param {String|Number|null} [id] Request ID can be a string, number, null for explicit notification or left out for automatic generation\n * @param {Object} [options]\n * @param {Number} [options.version=2] JSON-RPC version to use (1 or 2)\n * @param {Boolean} [options.notificationIdNull=false] When true, version 2 requests will set id to null instead of omitting it\n * @param {Function} [options.generator] Passed the request, and the options object and is expected to return a request ID\n * @throws {TypeError} If any of the parameters are invalid\n * @return {Object} A JSON-RPC 1.0 or 2.0 request\n * @memberOf Utils\n */\nconst generateRequest = function(method, params, id, options) {\n if(typeof method !== 'string') {\n throw new TypeError(method + ' must be a string');\n }\n\n options = options || {};\n\n // check valid version provided\n const version = typeof options.version === 'number' ? options.version : 2;\n if (version !== 1 && version !== 2) {\n throw new TypeError(version + ' must be 1 or 2');\n }\n\n const request = {\n method: method\n };\n\n if(version === 2) {\n request.jsonrpc = '2.0';\n }\n\n if(params) {\n // params given, but invalid?\n if(typeof params !== 'object' && !Array.isArray(params)) {\n throw new TypeError(params + ' must be an object, array or omitted');\n }\n request.params = params;\n }\n\n // if id was left out, generate one (null means explicit notification)\n if(typeof(id) === 'undefined') {\n const generator = typeof options.generator === 'function' ? options.generator : function() { return uuid(); };\n request.id = generator(request, options);\n } else if (version === 2 && id === null) {\n // we have a version 2 notification\n if (options.notificationIdNull) {\n request.id = null; // id will not be set at all unless option provided\n }\n } else {\n request.id = id;\n }\n\n return request;\n};\n\nmodule.exports = generateRequest;\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","export default /^(?:[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;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var 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(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","'use strict'\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n// @ts-ignore\nvar _Buffer = require('safe-buffer').Buffer\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256)\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i)\n var xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n var BASE = ALPHABET.length\n var LEADER = ALPHABET.charAt(0)\n var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }\n if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0\n var length = 0\n var pbegin = 0\n var pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n var b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return _Buffer.alloc(0) }\n var psz = 0\n // Skip and count leading '1's.\n var zeroes = 0\n var length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size)\n // Process the characters.\n while (psz < source.length) {\n // Find code of next character\n var charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n var carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n var i = 0\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n var it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n var vch = _Buffer.allocUnsafe(zeroes + (size - it4))\n vch.fill(0x00, 0, zeroes)\n var j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nmodule.exports = base\n","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [number & 0x3ffffff];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [0];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this._strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // '0' - '9'\n if (c >= 48 && c <= 57) {\n return c - 48;\n // 'A' - 'F'\n } else if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n } else {\n assert(false, 'Invalid character in ' + string);\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this._strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var b = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n b = c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n b = c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n b = c;\n }\n assert(c >= 0 && b < mul, 'Invalid character');\n r += b;\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [0];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this._strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n function move (dest, src) {\n dest.words = src.words;\n dest.length = src.length;\n dest.negative = src.negative;\n dest.red = src.red;\n }\n\n BN.prototype._move = function _move (dest) {\n move(dest, this);\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype._strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n // Check Symbol.for because not everywhere where Symbol defined\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility\n if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {\n try {\n BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;\n } catch (e) {\n BN.prototype.inspect = inspect;\n }\n } else {\n BN.prototype.inspect = inspect;\n }\n\n function inspect () {\n return (this.red ? '';\n }\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modrn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16, 2);\n };\n\n if (Buffer) {\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n return this.toArrayLike(Buffer, endian, length);\n };\n }\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n var allocate = function allocate (ArrayType, size) {\n if (ArrayType.allocUnsafe) {\n return ArrayType.allocUnsafe(size);\n }\n return new ArrayType(size);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n this._strip();\n\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n var res = allocate(ArrayType, reqLength);\n var postfix = endian === 'le' ? 'LE' : 'BE';\n this['_toArrayLike' + postfix](res, byteLength);\n return res;\n };\n\n BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {\n var position = 0;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position++] = word & 0xff;\n if (position < res.length) {\n res[position++] = (word >> 8) & 0xff;\n }\n if (position < res.length) {\n res[position++] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position < res.length) {\n res[position++] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position < res.length) {\n res[position++] = carry;\n\n while (position < res.length) {\n res[position++] = 0;\n }\n }\n };\n\n BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {\n var position = res.length - 1;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position--] = word & 0xff;\n if (position >= 0) {\n res[position--] = (word >> 8) & 0xff;\n }\n if (position >= 0) {\n res[position--] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position >= 0) {\n res[position--] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position >= 0) {\n res[position--] = carry;\n\n while (position >= 0) {\n res[position--] = 0;\n }\n }\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] >>> wbit) & 0x01;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this._strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this._strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this._strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this._strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this._strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this._strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n function jumboMulTo (self, num, out) {\n // Temporary disable, see https://github.com/indutny/bn.js/issues/211\n // var fftm = new FFTM();\n // return fftm.mulp(self, num, out);\n return bigMulTo(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out._strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n this.length = num === 0 ? 1 : this.length;\n\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this._strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) <= num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this._strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this._strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this._strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q._strip();\n }\n a._strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modrn = function modrn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return isNegNum ? -acc : acc;\n };\n\n // WARNING: DEPRECATED\n BN.prototype.modn = function modn (num) {\n return this.modrn(num);\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n this._strip();\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this._strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is a BN v4 instance\n r.strip();\n } else {\n // r is a BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n\n move(a, a.umod(this.m)._forceRed(this));\n return a;\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\nconst P = 2n ** 255n - 19n; // ed25519 is twisted edwards curve\nconst N = 2n ** 252n + 27742317777372353535851937790883648493n; // curve's (group) order\nconst Gx = 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an; // base point x\nconst Gy = 0x6666666666666666666666666666666666666666666666666666666666666658n; // base point y\nconst CURVE = {\n a: -1n,\n d: 37095705934669439343138083508754565189542113879843219016388785533085940283555n,\n p: P, n: N, h: 8, Gx, Gy // field prime, curve (group) order, cofactor\n};\nconst err = (m = '') => { throw new Error(m); }; // error helper, messes-up stack trace\nconst str = (s) => typeof s === 'string'; // is string\nconst au8 = (a, l) => // is Uint8Array (of specific length)\n !(a instanceof Uint8Array) || (typeof l === 'number' && l > 0 && a.length !== l) ?\n err('Uint8Array expected') : a;\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst toU8 = (a, len) => au8(str(a) ? h2b(a) : u8n(a), len); // norm(hex/u8a) to u8a\nconst mod = (a, b = P) => { let r = a % b; return r >= 0n ? r : b + r; }; // mod division\nconst isPoint = (p) => (p instanceof Point ? p : err('Point expected')); // is xyzt point\nlet Gpows = undefined; // precomputes for base point G\nclass Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n }\n static fromAffine(p) { return new Point(p.x, p.y, 1n, mod(p.x * p.y)); }\n static fromHex(hex, strict = true) {\n const { d } = CURVE;\n hex = toU8(hex, 32);\n const normed = hex.slice(); // copy the array to not mess it up\n normed[31] = hex[31] & ~0x80; // adjust first LE byte = last BE byte\n const y = b2n_LE(normed); // decode as little-endian, convert to num\n if (y === 0n) { // y=0 is valid, proceed\n }\n else {\n if (strict && !(0n < y && y < P))\n err('bad y coord 1'); // strict=true [1..P-1]\n if (!strict && !(0n < y && y < 2n ** 256n))\n err('bad y coord 2'); // strict=false [1..2^256-1]\n }\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(d * y2 + 1n); // v=dy²+1\n let { isValid, value: x } = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (!isValid)\n err('bad y coordinate 3'); // not square root: bad point\n const isXOdd = (x & 1n) === 1n; // adjust sign of x coordinate\n const isHeadOdd = (hex[31] & 0x80) !== 0;\n if (isHeadOdd !== isXOdd)\n x = mod(-x);\n return new Point(x, y, 1n, mod(x * y)); // Z=1, T=xy\n }\n get x() { return this.toAffine().x; } // .x, .y will call expensive toAffine.\n get y() { return this.toAffine().y; } // Should be used with care.\n equals(other) {\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = isPoint(other); // isPoint() checks class equality\n const X1Z2 = mod(X1 * Z2), X2Z1 = mod(X2 * Z1);\n const Y1Z2 = mod(Y1 * Z2), Y2Z1 = mod(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() { return this.equals(I); }\n negate() {\n return new Point(mod(-this.ex), this.ey, this.ez, mod(-this.et));\n }\n double() {\n const { ex: X1, ey: Y1, ez: Z1 } = this; // Cost: 4M + 4S + 1*a + 6add + 1*2\n const { a } = CURVE; // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n const A = mod(X1 * X1);\n const B = mod(Y1 * Y1);\n const C = mod(2n * mod(Z1 * Z1));\n const D = mod(a * A);\n const x1y1 = X1 + Y1;\n const E = mod(mod(x1y1 * x1y1) - A - B);\n const G = D + B;\n const F = G - C;\n const H = D - B;\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n add(other) {\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; // Cost: 8M + 1*k + 8add + 1*2.\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = isPoint(other); // doesn't check if other on-curve\n const { a, d } = CURVE; // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3\n const A = mod(X1 * X2);\n const B = mod(Y1 * Y2);\n const C = mod(T1 * d * T2);\n const D = mod(Z1 * Z2);\n const E = mod((X1 + Y1) * (X2 + Y2) - A - B);\n const F = mod(D - C);\n const G = mod(D + C);\n const H = mod(B - a * A);\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n mul(n, safe = true) {\n if (n === 0n)\n return safe === true ? err('cannot multiply by 0') : I;\n if (!(typeof n === 'bigint' && 0n < n && n < N))\n err('invalid scalar, must be < L');\n if (!safe && this.is0() || n === 1n)\n return this; // safe=true bans 0. safe=false allows 0.\n if (this.equals(G))\n return wNAF(n).p; // use wNAF precomputes for base points\n let p = I, f = G; // init result point & fake point\n for (let d = this; n > 0n; d = d.double(), n >>= 1n) { // double-and-add ladder\n if (n & 1n)\n p = p.add(d); // if bit is present, add to point\n else if (safe)\n f = f.add(d); // if not, add to fake for timing safety\n }\n return p;\n }\n multiply(scalar) { return this.mul(scalar); } // Aliases for compatibilty\n clearCofactor() { return this.mul(BigInt(CURVE.h), false); } // multiply by cofactor\n isSmallOrder() { return this.clearCofactor().is0(); } // check if P is small order\n isTorsionFree() {\n let p = this.mul(N / 2n, false).double(); // ensures the point is not \"bad\".\n if (N % 2n)\n p = p.add(this); // P^(N+1) // P*N == (P*(N/2))*2+P\n return p.is0();\n }\n toAffine() {\n const { ex: x, ey: y, ez: z } = this; // (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy)\n if (this.is0())\n return { x: 0n, y: 0n }; // fast-path for zero point\n const iz = invert(z); // z^-1: invert z\n if (mod(z * iz) !== 1n)\n err('invalid inverse'); // (z * z^-1) must be 1, otherwise bad math\n return { x: mod(x * iz), y: mod(y * iz) }; // x = x*z^-1; y = y*z^-1\n }\n toRawBytes() {\n const { x, y } = this.toAffine(); // convert to affine 2d point\n const b = n2b_32LE(y); // encode number to 32 bytes\n b[31] |= x & 1n ? 0x80 : 0; // store sign in first LE byte\n return b;\n }\n toHex() { return b2h(this.toRawBytes()); } // encode to hex string\n}\nPoint.BASE = new Point(Gx, Gy, 1n, mod(Gx * Gy)); // Generator / Base point\nPoint.ZERO = new Point(0n, 1n, 1n, 0n); // Identity / Zero point\nconst { BASE: G, ZERO: I } = Point; // Generator, identity points\nconst padh = (num, pad) => num.toString(16).padStart(pad, '0');\nconst b2h = (b) => Array.from(b).map(e => padh(e, 2)).join(''); // bytes to hex\nconst h2b = (hex) => {\n const l = hex.length; // error if not string,\n if (!str(hex) || l % 2)\n err('hex invalid 1'); // or has odd length like 3, 5.\n const arr = u8n(l / 2); // create result array\n for (let i = 0; i < arr.length; i++) {\n const j = i * 2;\n const h = hex.slice(j, j + 2); // hexByte. slice is faster than substr\n const b = Number.parseInt(h, 16); // byte, created from string part\n if (Number.isNaN(b) || b < 0)\n err('hex invalid 2'); // byte must be valid 0 <= byte < 256\n arr[i] = b;\n }\n return arr;\n};\nconst n2b_32LE = (num) => h2b(padh(num, 32 * 2)).reverse(); // number to bytes LE\nconst b2n_LE = (b) => BigInt('0x' + b2h(u8n(au8(b)).reverse())); // bytes LE to num\nconst concatB = (...arrs) => {\n const r = u8n(arrs.reduce((sum, a) => sum + au8(a).length, 0)); // create u8a of summed length\n let pad = 0; // walk through each array,\n arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type\n return r;\n};\nconst invert = (num, md = P) => {\n if (num === 0n || md <= 0n)\n err('no inverse n=' + num + ' mod=' + md); // no neg exponent for now\n let a = mod(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n while (a !== 0n) { // uses euclidean gcd algorithm\n const q = b / a, r = b % a; // not constant-time\n const m = x - u * q, n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n return b === 1n ? mod(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst pow2 = (x, power) => {\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n};\nconst pow_2_252_3 = (x) => {\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n};\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\nconst uvRatio = (u, v) => {\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7).pow_p_5_8; // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n)\n x = mod(-x); // edIsNegative\n return { isValid: useRoot1 || useRoot2, value: x };\n};\nconst modL_LE = (hash) => mod(b2n_LE(hash), N); // modulo L; but little-endian\nlet _shaS;\nconst sha512a = (...m) => etc.sha512Async(...m); // Async SHA512\nconst sha512s = (...m) => // Sync SHA512, not set by default\n typeof _shaS === 'function' ? _shaS(...m) : err('etc.sha512Sync not set');\nconst hash2extK = (hashed) => {\n const head = hashed.slice(0, 32); // slice creates a copy, unlike subarray\n head[0] &= 248; // Clamp bits: 0b1111_1000,\n head[31] &= 127; // 0b0111_1111,\n head[31] |= 64; // 0b0100_0000\n const prefix = hashed.slice(32, 64); // private key \"prefix\"\n const scalar = modL_LE(head); // modular division over curve order\n const point = G.mul(scalar); // public key point\n const pointBytes = point.toRawBytes(); // point serialized to Uint8Array\n return { head, prefix, scalar, point, pointBytes };\n};\n// RFC8032 5.1.5; getPublicKey async, sync. Hash priv key and extract point.\nconst getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, 32)).then(hash2extK);\nconst getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, 32)));\nconst getPublicKeyAsync = (priv) => getExtendedPublicKeyAsync(priv).then(p => p.pointBytes);\nconst getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;\nfunction hashFinish(asynchronous, res) {\n if (asynchronous)\n return sha512a(res.hashable).then(res.finish);\n return res.finish(sha512s(res.hashable));\n}\nconst _sign = (e, rBytes, msg) => {\n const { pointBytes: P, scalar: s } = e;\n const r = modL_LE(rBytes); // r was created outside, reduce it modulo L\n const R = G.mul(r).toRawBytes(); // R = [r]B\n const hashable = concatB(R, P, msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n const S = mod(r + modL_LE(hashed) * s, N); // S = (r + k * s) mod L; 0 <= s < l\n return au8(concatB(R, n2b_32LE(S)), 64); // 64-byte sig: 32b R.x + 32b LE(S)\n };\n return { hashable, finish };\n};\nconst signAsync = async (msg, privKey) => {\n const m = toU8(msg); // RFC8032 5.1.6: sign msg with key async\n const e = await getExtendedPublicKeyAsync(privKey); // pub,prfx\n const rBytes = await sha512a(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinish(true, _sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\nconst sign = (msg, privKey) => {\n const m = toU8(msg); // RFC8032 5.1.6: sign msg with key sync\n const e = getExtendedPublicKey(privKey); // pub,prfx\n const rBytes = sha512s(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinish(false, _sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\nconst _verify = (sig, msg, pub) => {\n msg = toU8(msg); // Message hex str/Bytes\n sig = toU8(sig, 64); // Signature hex str/Bytes, must be 64 bytes\n const A = Point.fromHex(pub, false); // public key A decoded\n const R = Point.fromHex(sig.slice(0, 32), false); // 0 <= R < 2^256: ZIP215 R can be >= P\n const s = b2n_LE(sig.slice(32, 64)); // Decode second half as an integer S\n const SB = G.mul(s, false); // in the range 0 <= s < L\n const hashable = concatB(R.toRawBytes(), A.toRawBytes(), msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n const k = modL_LE(hashed); // decode in little-endian, modulo L\n const RkA = R.add(A.mul(k, false)); // [8]R + [8][k]A'\n return RkA.add(SB.negate()).clearCofactor().is0(); // [8][S]B = [8]R + [8][k]A'\n };\n return { hashable, finish };\n};\n// RFC8032 5.1.7: verification async, sync\nconst verifyAsync = async (s, m, p) => hashFinish(true, _verify(s, m, p));\nconst verify = (s, m, p) => hashFinish(false, _verify(s, m, p));\nconst cr = () => // We support: 1) browsers 2) node.js 19+\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\nconst etc = {\n bytesToHex: b2h, hexToBytes: h2b, concatBytes: concatB,\n mod, invert,\n randomBytes: (len) => {\n const crypto = cr(); // Can be shimmed in node.js <= 18 to prevent error:\n // import { webcrypto } from 'node:crypto';\n // if (!globalThis.crypto) globalThis.crypto = webcrypto;\n if (!crypto)\n err('crypto.getRandomValues must be defined');\n return crypto.getRandomValues(u8n(len));\n },\n sha512Async: async (...messages) => {\n const crypto = cr();\n if (!crypto)\n err('crypto.subtle or etc.sha512Async must be defined');\n const m = concatB(...messages);\n return u8n(await crypto.subtle.digest('SHA-512', m.buffer));\n },\n sha512Sync: undefined, // Actual logic below\n};\nObject.defineProperties(etc, { sha512Sync: {\n configurable: false, get() { return _shaS; }, set(f) { if (!_shaS)\n _shaS = f; },\n } });\nconst utils = {\n getExtendedPublicKeyAsync, getExtendedPublicKey,\n randomPrivateKey: () => etc.randomBytes(32),\n precompute(w = 8, p = G) { p.multiply(3n); return p; }, // no-op\n};\nconst W = 8; // Precomputes-related code. W = window size\nconst precompute = () => {\n const points = []; // 10x sign(), 2x verify(). To achieve this,\n const windows = 256 / W + 1; // app needs to spend 40ms+ to calculate\n let p = G, b = p; // a lot of points related to base point G.\n for (let w = 0; w < windows; w++) { // Points are stored in array and used\n b = p; // any time Gx multiplication is done.\n points.push(b); // They consume 16-32 MiB of RAM.\n for (let i = 1; i < 2 ** (W - 1); i++) {\n b = b.add(p);\n points.push(b);\n }\n p = b.double(); // Precomputes don't speed-up getSharedKey,\n } // which multiplies user point by scalar,\n return points; // when precomputes are using base point\n};\nconst wNAF = (n) => {\n // Compared to other point mult methods,\n const comp = Gpows || (Gpows = precompute()); // stores 2x less points using subtraction\n const neg = (cnd, p) => { let n = p.negate(); return cnd ? n : p; }; // negate\n let p = I, f = G; // f must be G, or could become I in the end\n const windows = 1 + 256 / W; // W=8 17 windows\n const wsize = 2 ** (W - 1); // W=8 128 window size\n const mask = BigInt(2 ** W - 1); // W=8 will create mask 0b11111111\n const maxNum = 2 ** W; // W=8 256\n const shiftBy = BigInt(W); // W=8 8\n for (let w = 0; w < windows; w++) {\n const off = w * wsize;\n let wbits = Number(n & mask); // extract W bits.\n n >>= shiftBy; // shift number by W bits.\n if (wbits > wsize) {\n wbits -= maxNum;\n n += 1n;\n } // split if bits > max: +224 => 256-32\n const off1 = off, off2 = off + Math.abs(wbits) - 1; // offsets, evaluate both\n const cnd1 = w % 2 !== 0, cnd2 = wbits < 0; // conditions, evaluate both\n if (wbits === 0) {\n f = f.add(neg(cnd1, comp[off1])); // bits are 0: add garbage to fake point\n }\n else { // ^ can't add off2, off2 = I\n p = p.add(neg(cnd2, comp[off2])); // bits are 1: add to result point\n }\n }\n return { p, f }; // return both real and fake points for JIT\n}; // !! you can disable precomputes by commenting-out call of the wNAF() inside Point#mul()\nexport { getPublicKey, getPublicKeyAsync, sign, verify, // Remove the export to easily use in REPL\nsignAsync, verifyAsync, CURVE, etc, utils, Point as ExtendedPoint }; // envs like browser console\n","/* The MIT License (MIT)\n *\n * Copyright 2015-2018 Peter A. Bigot\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n/**\n * Support for translating between Uint8Array instances and JavaScript\n * native types.\n *\n * {@link module:Layout~Layout|Layout} is the basis of a class\n * hierarchy that associates property names with sequences of encoded\n * bytes.\n *\n * Layouts are supported for these scalar (numeric) types:\n * * {@link module:Layout~UInt|Unsigned integers in little-endian\n * format} with {@link module:Layout.u8|8-bit}, {@link\n * module:Layout.u16|16-bit}, {@link module:Layout.u24|24-bit},\n * {@link module:Layout.u32|32-bit}, {@link\n * module:Layout.u40|40-bit}, and {@link module:Layout.u48|48-bit}\n * representation ranges;\n * * {@link module:Layout~UIntBE|Unsigned integers in big-endian\n * format} with {@link module:Layout.u16be|16-bit}, {@link\n * module:Layout.u24be|24-bit}, {@link module:Layout.u32be|32-bit},\n * {@link module:Layout.u40be|40-bit}, and {@link\n * module:Layout.u48be|48-bit} representation ranges;\n * * {@link module:Layout~Int|Signed integers in little-endian\n * format} with {@link module:Layout.s8|8-bit}, {@link\n * module:Layout.s16|16-bit}, {@link module:Layout.s24|24-bit},\n * {@link module:Layout.s32|32-bit}, {@link\n * module:Layout.s40|40-bit}, and {@link module:Layout.s48|48-bit}\n * representation ranges;\n * * {@link module:Layout~IntBE|Signed integers in big-endian format}\n * with {@link module:Layout.s16be|16-bit}, {@link\n * module:Layout.s24be|24-bit}, {@link module:Layout.s32be|32-bit},\n * {@link module:Layout.s40be|40-bit}, and {@link\n * module:Layout.s48be|48-bit} representation ranges;\n * * 64-bit integral values that decode to an exact (if magnitude is\n * less than 2^53) or nearby integral Number in {@link\n * module:Layout.nu64|unsigned little-endian}, {@link\n * module:Layout.nu64be|unsigned big-endian}, {@link\n * module:Layout.ns64|signed little-endian}, and {@link\n * module:Layout.ns64be|unsigned big-endian} encodings;\n * * 32-bit floating point values with {@link\n * module:Layout.f32|little-endian} and {@link\n * module:Layout.f32be|big-endian} representations;\n * * 64-bit floating point values with {@link\n * module:Layout.f64|little-endian} and {@link\n * module:Layout.f64be|big-endian} representations;\n * * {@link module:Layout.const|Constants} that take no space in the\n * encoded expression.\n *\n * and for these aggregate types:\n * * {@link module:Layout.seq|Sequence}s of instances of a {@link\n * module:Layout~Layout|Layout}, with JavaScript representation as\n * an Array and constant or data-dependent {@link\n * module:Layout~Sequence#count|length};\n * * {@link module:Layout.struct|Structure}s that aggregate a\n * heterogeneous sequence of {@link module:Layout~Layout|Layout}\n * instances, with JavaScript representation as an Object;\n * * {@link module:Layout.union|Union}s that support multiple {@link\n * module:Layout~VariantLayout|variant layouts} over a fixed\n * (padded) or variable (not padded) span of bytes, using an\n * unsigned integer at the start of the data or a separate {@link\n * module:Layout.unionLayoutDiscriminator|layout element} to\n * determine which layout to use when interpreting the buffer\n * contents;\n * * {@link module:Layout.bits|BitStructure}s that contain a sequence\n * of individual {@link\n * module:Layout~BitStructure#addField|BitField}s packed into an 8,\n * 16, 24, or 32-bit unsigned integer starting at the least- or\n * most-significant bit;\n * * {@link module:Layout.cstr|C strings} of varying length;\n * * {@link module:Layout.blob|Blobs} of fixed- or variable-{@link\n * module:Layout~Blob#length|length} raw data.\n *\n * All {@link module:Layout~Layout|Layout} instances are immutable\n * after construction, to prevent internal state from becoming\n * inconsistent.\n *\n * @local Layout\n * @local ExternalLayout\n * @local GreedyCount\n * @local OffsetLayout\n * @local UInt\n * @local UIntBE\n * @local Int\n * @local IntBE\n * @local NearUInt64\n * @local NearUInt64BE\n * @local NearInt64\n * @local NearInt64BE\n * @local Float\n * @local FloatBE\n * @local Double\n * @local DoubleBE\n * @local Sequence\n * @local Structure\n * @local UnionDiscriminator\n * @local UnionLayoutDiscriminator\n * @local Union\n * @local VariantLayout\n * @local BitStructure\n * @local BitField\n * @local Boolean\n * @local Blob\n * @local CString\n * @local Constant\n * @local bindConstructorLayout\n * @module Layout\n * @license MIT\n * @author Peter A. Bigot\n * @see {@link https://github.com/pabigot/buffer-layout|buffer-layout on GitHub}\n */\n'use strict';\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.s16 = exports.s8 = exports.nu64be = exports.u48be = exports.u40be = exports.u32be = exports.u24be = exports.u16be = exports.nu64 = exports.u48 = exports.u40 = exports.u32 = exports.u24 = exports.u16 = exports.u8 = exports.offset = exports.greedy = exports.Constant = exports.UTF8 = exports.CString = exports.Blob = exports.Boolean = exports.BitField = exports.BitStructure = exports.VariantLayout = exports.Union = exports.UnionLayoutDiscriminator = exports.UnionDiscriminator = exports.Structure = exports.Sequence = exports.DoubleBE = exports.Double = exports.FloatBE = exports.Float = exports.NearInt64BE = exports.NearInt64 = exports.NearUInt64BE = exports.NearUInt64 = exports.IntBE = exports.Int = exports.UIntBE = exports.UInt = exports.OffsetLayout = exports.GreedyCount = exports.ExternalLayout = exports.bindConstructorLayout = exports.nameWithProperty = exports.Layout = exports.uint8ArrayToBuffer = exports.checkUint8Array = void 0;\nexports.constant = exports.utf8 = exports.cstr = exports.blob = exports.unionLayoutDiscriminator = exports.union = exports.seq = exports.bits = exports.struct = exports.f64be = exports.f64 = exports.f32be = exports.f32 = exports.ns64be = exports.s48be = exports.s40be = exports.s32be = exports.s24be = exports.s16be = exports.ns64 = exports.s48 = exports.s40 = exports.s32 = exports.s24 = void 0;\nconst buffer_1 = require(\"buffer\");\n/* Check if a value is a Uint8Array.\n *\n * @ignore */\nfunction checkUint8Array(b) {\n if (!(b instanceof Uint8Array)) {\n throw new TypeError('b must be a Uint8Array');\n }\n}\nexports.checkUint8Array = checkUint8Array;\n/* Create a Buffer instance from a Uint8Array.\n *\n * @ignore */\nfunction uint8ArrayToBuffer(b) {\n checkUint8Array(b);\n return buffer_1.Buffer.from(b.buffer, b.byteOffset, b.length);\n}\nexports.uint8ArrayToBuffer = uint8ArrayToBuffer;\n/**\n * Base class for layout objects.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * Layout#encode|encode} or {@link Layout#decode|decode} functions.\n *\n * @param {Number} span - Initializer for {@link Layout#span|span}. The\n * parameter must be an integer; a negative value signifies that the\n * span is {@link Layout#getSpan|value-specific}.\n *\n * @param {string} [property] - Initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n */\nclass Layout {\n constructor(span, property) {\n if (!Number.isInteger(span)) {\n throw new TypeError('span must be an integer');\n }\n /** The span of the layout in bytes.\n *\n * Positive values are generally expected.\n *\n * Zero will only appear in {@link Constant}s and in {@link\n * Sequence}s where the {@link Sequence#count|count} is zero.\n *\n * A negative value indicates that the span is value-specific, and\n * must be obtained using {@link Layout#getSpan|getSpan}. */\n this.span = span;\n /** The property name used when this layout is represented in an\n * Object.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances. If left undefined the span of the unnamed layout will\n * be treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n /** Function to create an Object into which decoded properties will\n * be written.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances, which means:\n * * {@link Structure}\n * * {@link Union}\n * * {@link VariantLayout}\n * * {@link BitStructure}\n *\n * If left undefined the JavaScript representation of these layouts\n * will be Object instances.\n *\n * See {@link bindConstructorLayout}.\n */\n makeDestinationObject() {\n return {};\n }\n /**\n * Calculate the span of a specific instance of a layout.\n *\n * @param {Uint8Array} b - the buffer that contains an encoded instance.\n *\n * @param {Number} [offset] - the offset at which the encoded instance\n * starts. If absent a zero offset is inferred.\n *\n * @return {Number} - the number of bytes covered by the layout\n * instance. If this method is not overridden in a subclass the\n * definition-time constant {@link Layout#span|span} will be\n * returned.\n *\n * @throws {RangeError} - if the length of the value cannot be\n * determined.\n */\n getSpan(b, offset) {\n if (0 > this.span) {\n throw new RangeError('indeterminate span');\n }\n return this.span;\n }\n /**\n * Replicate the layout using a new property.\n *\n * This function must be used to get a structurally-equivalent layout\n * with a different name since all {@link Layout} instances are\n * immutable.\n *\n * **NOTE** This is a shallow copy. All fields except {@link\n * Layout#property|property} are strictly equal to the origin layout.\n *\n * @param {String} property - the value for {@link\n * Layout#property|property} in the replica.\n *\n * @returns {Layout} - the copy with {@link Layout#property|property}\n * set to `property`.\n */\n replicate(property) {\n const rv = Object.create(this.constructor.prototype);\n Object.assign(rv, this);\n rv.property = property;\n return rv;\n }\n /**\n * Create an object from layout properties and an array of values.\n *\n * **NOTE** This function returns `undefined` if invoked on a layout\n * that does not return its value as an Object. Objects are\n * returned for things that are a {@link Structure}, which includes\n * {@link VariantLayout|variant layouts} if they are structures, and\n * excludes {@link Union}s. If you want this feature for a union\n * you must use {@link Union.getVariant|getVariant} to select the\n * desired layout.\n *\n * @param {Array} values - an array of values that correspond to the\n * default order for properties. As with {@link Layout#decode|decode}\n * layout elements that have no property name are skipped when\n * iterating over the array values. Only the top-level properties are\n * assigned; arguments are not assigned to properties of contained\n * layouts. Any unused values are ignored.\n *\n * @return {(Object|undefined)}\n */\n fromArray(values) {\n return undefined;\n }\n}\nexports.Layout = Layout;\n/* Provide text that carries a name (such as for a function that will\n * be throwing an error) annotated with the property of a given layout\n * (such as one for which the value was unacceptable).\n *\n * @ignore */\nfunction nameWithProperty(name, lo) {\n if (lo.property) {\n return name + '[' + lo.property + ']';\n }\n return name;\n}\nexports.nameWithProperty = nameWithProperty;\n/**\n * Augment a class so that instances can be encoded/decoded using a\n * given layout.\n *\n * Calling this function couples `Class` with `layout` in several ways:\n *\n * * `Class.layout_` becomes a static member property equal to `layout`;\n * * `layout.boundConstructor_` becomes a static member property equal\n * to `Class`;\n * * The {@link Layout#makeDestinationObject|makeDestinationObject()}\n * property of `layout` is set to a function that returns a `new\n * Class()`;\n * * `Class.decode(b, offset)` becomes a static member function that\n * delegates to {@link Layout#decode|layout.decode}. The\n * synthesized function may be captured and extended.\n * * `Class.prototype.encode(b, offset)` provides an instance member\n * function that delegates to {@link Layout#encode|layout.encode}\n * with `src` set to `this`. The synthesized function may be\n * captured and extended, but when the extension is invoked `this`\n * must be explicitly bound to the instance.\n *\n * @param {class} Class - a JavaScript class with a nullary\n * constructor.\n *\n * @param {Layout} layout - the {@link Layout} instance used to encode\n * instances of `Class`.\n */\n// `Class` must be a constructor Function, but the assignment of a `layout_` property to it makes it difficult to type\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction bindConstructorLayout(Class, layout) {\n if ('function' !== typeof Class) {\n throw new TypeError('Class must be constructor');\n }\n if (Object.prototype.hasOwnProperty.call(Class, 'layout_')) {\n throw new Error('Class is already bound to a layout');\n }\n if (!(layout && (layout instanceof Layout))) {\n throw new TypeError('layout must be a Layout');\n }\n if (Object.prototype.hasOwnProperty.call(layout, 'boundConstructor_')) {\n throw new Error('layout is already bound to a constructor');\n }\n Class.layout_ = layout;\n layout.boundConstructor_ = Class;\n layout.makeDestinationObject = (() => new Class());\n Object.defineProperty(Class.prototype, 'encode', {\n value(b, offset) {\n return layout.encode(this, b, offset);\n },\n writable: true,\n });\n Object.defineProperty(Class, 'decode', {\n value(b, offset) {\n return layout.decode(b, offset);\n },\n writable: true,\n });\n}\nexports.bindConstructorLayout = bindConstructorLayout;\n/**\n * An object that behaves like a layout but does not consume space\n * within its containing layout.\n *\n * This is primarily used to obtain metadata about a member, such as a\n * {@link OffsetLayout} that can provide data about a {@link\n * Layout#getSpan|value-specific span}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support {@link\n * ExternalLayout#isCount|isCount} or other {@link Layout} functions.\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n * @augments {Layout}\n */\nclass ExternalLayout extends Layout {\n /**\n * Return `true` iff the external layout decodes to an unsigned\n * integer layout.\n *\n * In that case it can be used as the source of {@link\n * Sequence#count|Sequence counts}, {@link Blob#length|Blob lengths},\n * or as {@link UnionLayoutDiscriminator#layout|external union\n * discriminators}.\n *\n * @abstract\n */\n isCount() {\n throw new Error('ExternalLayout is abstract');\n }\n}\nexports.ExternalLayout = ExternalLayout;\n/**\n * An {@link ExternalLayout} that determines its {@link\n * Layout#decode|value} based on offset into and length of the buffer\n * on which it is invoked.\n *\n * *Factory*: {@link module:Layout.greedy|greedy}\n *\n * @param {Number} [elementSpan] - initializer for {@link\n * GreedyCount#elementSpan|elementSpan}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {ExternalLayout}\n */\nclass GreedyCount extends ExternalLayout {\n constructor(elementSpan = 1, property) {\n if ((!Number.isInteger(elementSpan)) || (0 >= elementSpan)) {\n throw new TypeError('elementSpan must be a (positive) integer');\n }\n super(-1, property);\n /** The layout for individual elements of the sequence. The value\n * must be a positive integer. If not provided, the value will be\n * 1. */\n this.elementSpan = elementSpan;\n }\n /** @override */\n isCount() {\n return true;\n }\n /** @override */\n decode(b, offset = 0) {\n checkUint8Array(b);\n const rem = b.length - offset;\n return Math.floor(rem / this.elementSpan);\n }\n /** @override */\n encode(src, b, offset) {\n return 0;\n }\n}\nexports.GreedyCount = GreedyCount;\n/**\n * An {@link ExternalLayout} that supports accessing a {@link Layout}\n * at a fixed offset from the start of another Layout. The offset may\n * be before, within, or after the base layout.\n *\n * *Factory*: {@link module:Layout.offset|offset}\n *\n * @param {Layout} layout - initializer for {@link\n * OffsetLayout#layout|layout}, modulo `property`.\n *\n * @param {Number} [offset] - Initializes {@link\n * OffsetLayout#offset|offset}. Defaults to zero.\n *\n * @param {string} [property] - Optional new property name for a\n * {@link Layout#replicate| replica} of `layout` to be used as {@link\n * OffsetLayout#layout|layout}. If not provided the `layout` is used\n * unchanged.\n *\n * @augments {Layout}\n */\nclass OffsetLayout extends ExternalLayout {\n constructor(layout, offset = 0, property) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n if (!Number.isInteger(offset)) {\n throw new TypeError('offset must be integer or undefined');\n }\n super(layout.span, property || layout.property);\n /** The subordinated layout. */\n this.layout = layout;\n /** The location of {@link OffsetLayout#layout} relative to the\n * start of another layout.\n *\n * The value may be positive or negative, but an error will thrown\n * if at the point of use it goes outside the span of the Uint8Array\n * being accessed. */\n this.offset = offset;\n }\n /** @override */\n isCount() {\n return ((this.layout instanceof UInt)\n || (this.layout instanceof UIntBE));\n }\n /** @override */\n decode(b, offset = 0) {\n return this.layout.decode(b, offset + this.offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n return this.layout.encode(src, b, offset + this.offset);\n }\n}\nexports.OffsetLayout = OffsetLayout;\n/**\n * Represent an unsigned integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.u8|u8}, {@link\n * module:Layout.u16|u16}, {@link module:Layout.u24|u24}, {@link\n * module:Layout.u32|u32}, {@link module:Layout.u40|u40}, {@link\n * module:Layout.u48|u48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UInt extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readUIntLE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeUIntLE(src, offset, this.span);\n return this.span;\n }\n}\nexports.UInt = UInt;\n/**\n * Represent an unsigned integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.u8be|u8be}, {@link\n * module:Layout.u16be|u16be}, {@link module:Layout.u24be|u24be},\n * {@link module:Layout.u32be|u32be}, {@link\n * module:Layout.u40be|u40be}, {@link module:Layout.u48be|u48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UIntBE extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readUIntBE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeUIntBE(src, offset, this.span);\n return this.span;\n }\n}\nexports.UIntBE = UIntBE;\n/**\n * Represent a signed integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.s8|s8}, {@link\n * module:Layout.s16|s16}, {@link module:Layout.s24|s24}, {@link\n * module:Layout.s32|s32}, {@link module:Layout.s40|s40}, {@link\n * module:Layout.s48|s48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Int extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readIntLE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeIntLE(src, offset, this.span);\n return this.span;\n }\n}\nexports.Int = Int;\n/**\n * Represent a signed integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.s8be|s8be}, {@link\n * module:Layout.s16be|s16be}, {@link module:Layout.s24be|s24be},\n * {@link module:Layout.s32be|s32be}, {@link\n * module:Layout.s40be|s40be}, {@link module:Layout.s48be|s48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass IntBE extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readIntBE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeIntBE(src, offset, this.span);\n return this.span;\n }\n}\nexports.IntBE = IntBE;\nconst V2E32 = Math.pow(2, 32);\n/* True modulus high and low 32-bit words, where low word is always\n * non-negative. */\nfunction divmodInt64(src) {\n const hi32 = Math.floor(src / V2E32);\n const lo32 = src - (hi32 * V2E32);\n return { hi32, lo32 };\n}\n/* Reconstruct Number from quotient and non-negative remainder */\nfunction roundedInt64(hi32, lo32) {\n return hi32 * V2E32 + lo32;\n}\n/**\n * Represent an unsigned 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64|nu64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const lo32 = buffer.readUInt32LE(offset);\n const hi32 = buffer.readUInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeUInt32LE(split.lo32, offset);\n buffer.writeUInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\nexports.NearUInt64 = NearUInt64;\n/**\n * Represent an unsigned 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64be|nu64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const hi32 = buffer.readUInt32BE(offset);\n const lo32 = buffer.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeUInt32BE(split.hi32, offset);\n buffer.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\nexports.NearUInt64BE = NearUInt64BE;\n/**\n * Represent a signed 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64|ns64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const lo32 = buffer.readUInt32LE(offset);\n const hi32 = buffer.readInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeUInt32LE(split.lo32, offset);\n buffer.writeInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\nexports.NearInt64 = NearInt64;\n/**\n * Represent a signed 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64be|ns64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const hi32 = buffer.readInt32BE(offset);\n const lo32 = buffer.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeInt32BE(split.hi32, offset);\n buffer.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\nexports.NearInt64BE = NearInt64BE;\n/**\n * Represent a 32-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f32|f32}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Float extends Layout {\n constructor(property) {\n super(4, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readFloatLE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeFloatLE(src, offset);\n return 4;\n }\n}\nexports.Float = Float;\n/**\n * Represent a 32-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f32be|f32be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass FloatBE extends Layout {\n constructor(property) {\n super(4, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readFloatBE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeFloatBE(src, offset);\n return 4;\n }\n}\nexports.FloatBE = FloatBE;\n/**\n * Represent a 64-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f64|f64}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Double extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readDoubleLE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeDoubleLE(src, offset);\n return 8;\n }\n}\nexports.Double = Double;\n/**\n * Represent a 64-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f64be|f64be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass DoubleBE extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readDoubleBE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeDoubleBE(src, offset);\n return 8;\n }\n}\nexports.DoubleBE = DoubleBE;\n/**\n * Represent a contiguous sequence of a specific layout as an Array.\n *\n * *Factory*: {@link module:Layout.seq|seq}\n *\n * @param {Layout} elementLayout - initializer for {@link\n * Sequence#elementLayout|elementLayout}.\n *\n * @param {(Number|ExternalLayout)} count - initializer for {@link\n * Sequence#count|count}. The parameter must be either a positive\n * integer or an instance of {@link ExternalLayout}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Sequence extends Layout {\n constructor(elementLayout, count, property) {\n if (!(elementLayout instanceof Layout)) {\n throw new TypeError('elementLayout must be a Layout');\n }\n if (!(((count instanceof ExternalLayout) && count.isCount())\n || (Number.isInteger(count) && (0 <= count)))) {\n throw new TypeError('count must be non-negative integer '\n + 'or an unsigned integer ExternalLayout');\n }\n let span = -1;\n if ((!(count instanceof ExternalLayout))\n && (0 < elementLayout.span)) {\n span = count * elementLayout.span;\n }\n super(span, property);\n /** The layout for individual elements of the sequence. */\n this.elementLayout = elementLayout;\n /** The number of elements in the sequence.\n *\n * This will be either a non-negative integer or an instance of\n * {@link ExternalLayout} for which {@link\n * ExternalLayout#isCount|isCount()} is `true`. */\n this.count = count;\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n return this.span;\n }\n let span = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n if (0 < this.elementLayout.span) {\n span = count * this.elementLayout.span;\n }\n else {\n let idx = 0;\n while (idx < count) {\n span += this.elementLayout.getSpan(b, offset + span);\n ++idx;\n }\n }\n return span;\n }\n /** @override */\n decode(b, offset = 0) {\n const rv = [];\n let i = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n while (i < count) {\n rv.push(this.elementLayout.decode(b, offset));\n offset += this.elementLayout.getSpan(b, offset);\n i += 1;\n }\n return rv;\n }\n /** Implement {@link Layout#encode|encode} for {@link Sequence}.\n *\n * **NOTE** If `src` is shorter than {@link Sequence#count|count} then\n * the unused space in the buffer is left unchanged. If `src` is\n * longer than {@link Sequence#count|count} the unneeded elements are\n * ignored.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset = 0) {\n const elo = this.elementLayout;\n const span = src.reduce((span, v) => {\n return span + elo.encode(v, b, offset + span);\n }, 0);\n if (this.count instanceof ExternalLayout) {\n this.count.encode(src.length, b, offset);\n }\n return span;\n }\n}\nexports.Sequence = Sequence;\n/**\n * Represent a contiguous sequence of arbitrary layout elements as an\n * Object.\n *\n * *Factory*: {@link module:Layout.struct|struct}\n *\n * **NOTE** The {@link Layout#span|span} of the structure is variable\n * if any layout in {@link Structure#fields|fields} has a variable\n * span. When {@link Layout#encode|encoding} we must have a value for\n * all variable-length fields, or we wouldn't be able to figure out\n * how much space to use for storage. We can only identify the value\n * for a field when it has a {@link Layout#property|property}. As\n * such, although a structure may contain both unnamed fields and\n * variable-length fields, it cannot contain an unnamed\n * variable-length field.\n *\n * @param {Layout[]} fields - initializer for {@link\n * Structure#fields|fields}. An error is raised if this contains a\n * variable-length field for which a {@link Layout#property|property}\n * is not defined.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @param {Boolean} [decodePrefixes] - initializer for {@link\n * Structure#decodePrefixes|property}.\n *\n * @throws {Error} - if `fields` contains an unnamed variable-length\n * layout.\n *\n * @augments {Layout}\n */\nclass Structure extends Layout {\n constructor(fields, property, decodePrefixes) {\n if (!(Array.isArray(fields)\n && fields.reduce((acc, v) => acc && (v instanceof Layout), true))) {\n throw new TypeError('fields must be array of Layout instances');\n }\n if (('boolean' === typeof property)\n && (undefined === decodePrefixes)) {\n decodePrefixes = property;\n property = undefined;\n }\n /* Verify absence of unnamed variable-length fields. */\n for (const fd of fields) {\n if ((0 > fd.span)\n && (undefined === fd.property)) {\n throw new Error('fields cannot contain unnamed variable-length layout');\n }\n }\n let span = -1;\n try {\n span = fields.reduce((span, fd) => span + fd.getSpan(), 0);\n }\n catch (e) {\n // ignore error\n }\n super(span, property);\n /** The sequence of {@link Layout} values that comprise the\n * structure.\n *\n * The individual elements need not be the same type, and may be\n * either scalar or aggregate layouts. If a member layout leaves\n * its {@link Layout#property|property} undefined the\n * corresponding region of the buffer associated with the element\n * will not be mutated.\n *\n * @type {Layout[]} */\n this.fields = fields;\n /** Control behavior of {@link Layout#decode|decode()} given short\n * buffers.\n *\n * In some situations a structure many be extended with additional\n * fields over time, with older installations providing only a\n * prefix of the full structure. If this property is `true`\n * decoding will accept those buffers and leave subsequent fields\n * undefined, as long as the buffer ends at a field boundary.\n * Defaults to `false`. */\n this.decodePrefixes = !!decodePrefixes;\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n return this.span;\n }\n let span = 0;\n try {\n span = this.fields.reduce((span, fd) => {\n const fsp = fd.getSpan(b, offset);\n offset += fsp;\n return span + fsp;\n }, 0);\n }\n catch (e) {\n throw new RangeError('indeterminate span');\n }\n return span;\n }\n /** @override */\n decode(b, offset = 0) {\n checkUint8Array(b);\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(b, offset);\n }\n offset += fd.getSpan(b, offset);\n if (this.decodePrefixes\n && (b.length === offset)) {\n break;\n }\n }\n return dest;\n }\n /** Implement {@link Layout#encode|encode} for {@link Structure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the buffer is\n * left unmodified. */\n encode(src, b, offset = 0) {\n const firstOffset = offset;\n let lastOffset = 0;\n let lastWrote = 0;\n for (const fd of this.fields) {\n let span = fd.span;\n lastWrote = (0 < span) ? span : 0;\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n lastWrote = fd.encode(fv, b, offset);\n if (0 > span) {\n /* Read the as-encoded span, which is not necessarily the\n * same as what we wrote. */\n span = fd.getSpan(b, offset);\n }\n }\n }\n lastOffset = offset;\n offset += span;\n }\n /* Use (lastOffset + lastWrote) instead of offset because the last\n * item may have had a dynamic length and we don't want to include\n * the padding between it and the end of the space reserved for\n * it. */\n return (lastOffset + lastWrote) - firstOffset;\n }\n /** @override */\n fromArray(values) {\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if ((undefined !== fd.property)\n && (0 < values.length)) {\n dest[fd.property] = values.shift();\n }\n }\n return dest;\n }\n /**\n * Get access to the layout of a given property.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Layout} - the layout associated with `property`, or\n * undefined if there is no such property.\n */\n layoutFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n return undefined;\n }\n /**\n * Get the offset of a structure member.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Number} - the offset in bytes to the start of `property`\n * within the structure, or undefined if `property` is not a field\n * within the structure. If the property is a member but follows a\n * variable-length structure member a negative number will be\n * returned.\n */\n offsetOf(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n let offset = 0;\n for (const fd of this.fields) {\n if (fd.property === property) {\n return offset;\n }\n if (0 > fd.span) {\n offset = -1;\n }\n else if (0 <= offset) {\n offset += fd.span;\n }\n }\n return undefined;\n }\n}\nexports.Structure = Structure;\n/**\n * An object that can provide a {@link\n * Union#discriminator|discriminator} API for {@link Union}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * UnionDiscriminator#encode|encode} or {@link\n * UnionDiscriminator#decode|decode} functions.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}.\n *\n * @abstract\n */\nclass UnionDiscriminator {\n constructor(property) {\n /** The {@link Layout#property|property} to be used when the\n * discriminator is referenced in isolation (generally when {@link\n * Union#decode|Union decode} cannot delegate to a specific\n * variant). */\n this.property = property;\n }\n /** Analog to {@link Layout#decode|Layout decode} for union discriminators.\n *\n * The implementation of this method need not reference the buffer if\n * variant information is available through other means. */\n decode(b, offset) {\n throw new Error('UnionDiscriminator is abstract');\n }\n /** Analog to {@link Layout#decode|Layout encode} for union discriminators.\n *\n * The implementation of this method need not store the value if\n * variant information is maintained through other means. */\n encode(src, b, offset) {\n throw new Error('UnionDiscriminator is abstract');\n }\n}\nexports.UnionDiscriminator = UnionDiscriminator;\n/**\n * An object that can provide a {@link\n * UnionDiscriminator|discriminator API} for {@link Union} using an\n * unsigned integral {@link Layout} instance located either inside or\n * outside the union.\n *\n * @param {ExternalLayout} layout - initializes {@link\n * UnionLayoutDiscriminator#layout|layout}. Must satisfy {@link\n * ExternalLayout#isCount|isCount()}.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}, superseding the property\n * from `layout`, but defaulting to `variant` if neither `property`\n * nor layout provide a property name.\n *\n * @augments {UnionDiscriminator}\n */\nclass UnionLayoutDiscriminator extends UnionDiscriminator {\n constructor(layout, property) {\n if (!((layout instanceof ExternalLayout)\n && layout.isCount())) {\n throw new TypeError('layout must be an unsigned integer ExternalLayout');\n }\n super(property || layout.property || 'variant');\n /** The {@link ExternalLayout} used to access the discriminator\n * value. */\n this.layout = layout;\n }\n /** Delegate decoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n decode(b, offset) {\n return this.layout.decode(b, offset);\n }\n /** Delegate encoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n encode(src, b, offset) {\n return this.layout.encode(src, b, offset);\n }\n}\nexports.UnionLayoutDiscriminator = UnionLayoutDiscriminator;\n/**\n * Represent any number of span-compatible layouts.\n *\n * *Factory*: {@link module:Layout.union|union}\n *\n * If the union has a {@link Union#defaultLayout|default layout} that\n * layout must have a non-negative {@link Layout#span|span}. The span\n * of a fixed-span union includes its {@link\n * Union#discriminator|discriminator} if the variant is a {@link\n * Union#usesPrefixDiscriminator|prefix of the union}, plus the span\n * of its {@link Union#defaultLayout|default layout}.\n *\n * If the union does not have a default layout then the encoded span\n * of the union depends on the encoded span of its variant (which may\n * be fixed or variable).\n *\n * {@link VariantLayout#layout|Variant layout}s are added through\n * {@link Union#addVariant|addVariant}. If the union has a default\n * layout, the span of the {@link VariantLayout#layout|layout\n * contained by the variant} must not exceed the span of the {@link\n * Union#defaultLayout|default layout} (minus the span of a {@link\n * Union#usesPrefixDiscriminator|prefix disriminator}, if used). The\n * span of the variant will equal the span of the union itself.\n *\n * The variant for a buffer can only be identified from the {@link\n * Union#discriminator|discriminator} {@link\n * UnionDiscriminator#property|property} (in the case of the {@link\n * Union#defaultLayout|default layout}), or by using {@link\n * Union#getVariant|getVariant} and examining the resulting {@link\n * VariantLayout} instance.\n *\n * A variant compatible with a JavaScript object can be identified\n * using {@link Union#getSourceVariant|getSourceVariant}.\n *\n * @param {(UnionDiscriminator|ExternalLayout|Layout)} discr - How to\n * identify the layout used to interpret the union contents. The\n * parameter must be an instance of {@link UnionDiscriminator}, an\n * {@link ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}, or {@link UInt} (or {@link\n * UIntBE}). When a non-external layout element is passed the layout\n * appears at the start of the union. In all cases the (synthesized)\n * {@link UnionDiscriminator} instance is recorded as {@link\n * Union#discriminator|discriminator}.\n *\n * @param {(Layout|null)} defaultLayout - initializer for {@link\n * Union#defaultLayout|defaultLayout}. If absent defaults to `null`.\n * If `null` there is no default layout: the union has data-dependent\n * length and attempts to decode or encode unrecognized variants will\n * throw an exception. A {@link Layout} instance must have a\n * non-negative {@link Layout#span|span}, and if it lacks a {@link\n * Layout#property|property} the {@link\n * Union#defaultLayout|defaultLayout} will be a {@link\n * Layout#replicate|replica} with property `content`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Union extends Layout {\n constructor(discr, defaultLayout, property) {\n let discriminator;\n if ((discr instanceof UInt)\n || (discr instanceof UIntBE)) {\n discriminator = new UnionLayoutDiscriminator(new OffsetLayout(discr));\n }\n else if ((discr instanceof ExternalLayout)\n && discr.isCount()) {\n discriminator = new UnionLayoutDiscriminator(discr);\n }\n else if (!(discr instanceof UnionDiscriminator)) {\n throw new TypeError('discr must be a UnionDiscriminator '\n + 'or an unsigned integer layout');\n }\n else {\n discriminator = discr;\n }\n if (undefined === defaultLayout) {\n defaultLayout = null;\n }\n if (!((null === defaultLayout)\n || (defaultLayout instanceof Layout))) {\n throw new TypeError('defaultLayout must be null or a Layout');\n }\n if (null !== defaultLayout) {\n if (0 > defaultLayout.span) {\n throw new Error('defaultLayout must have constant span');\n }\n if (undefined === defaultLayout.property) {\n defaultLayout = defaultLayout.replicate('content');\n }\n }\n /* The union span can be estimated only if there's a default\n * layout. The union spans its default layout, plus any prefix\n * variant layout. By construction both layouts, if present, have\n * non-negative span. */\n let span = -1;\n if (defaultLayout) {\n span = defaultLayout.span;\n if ((0 <= span) && ((discr instanceof UInt)\n || (discr instanceof UIntBE))) {\n span += discriminator.layout.span;\n }\n }\n super(span, property);\n /** The interface for the discriminator value in isolation.\n *\n * This a {@link UnionDiscriminator} either passed to the\n * constructor or synthesized from the `discr` constructor\n * argument. {@link\n * Union#usesPrefixDiscriminator|usesPrefixDiscriminator} will be\n * `true` iff the `discr` parameter was a non-offset {@link\n * Layout} instance. */\n this.discriminator = discriminator;\n /** `true` if the {@link Union#discriminator|discriminator} is the\n * first field in the union.\n *\n * If `false` the discriminator is obtained from somewhere\n * else. */\n this.usesPrefixDiscriminator = (discr instanceof UInt)\n || (discr instanceof UIntBE);\n /** The layout for non-discriminator content when the value of the\n * discriminator is not recognized.\n *\n * This is the value passed to the constructor. It is\n * structurally equivalent to the second component of {@link\n * Union#layout|layout} but may have a different property\n * name. */\n this.defaultLayout = defaultLayout;\n /** A registry of allowed variants.\n *\n * The keys are unsigned integers which should be compatible with\n * {@link Union.discriminator|discriminator}. The property value\n * is the corresponding {@link VariantLayout} instances assigned\n * to this union by {@link Union#addVariant|addVariant}.\n *\n * **NOTE** The registry remains mutable so that variants can be\n * {@link Union#addVariant|added} at any time. Users should not\n * manipulate the content of this property. */\n this.registry = {};\n /* Private variable used when invoking getSourceVariant */\n let boundGetSourceVariant = this.defaultGetSourceVariant.bind(this);\n /** Function to infer the variant selected by a source object.\n *\n * Defaults to {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant} but may\n * be overridden using {@link\n * Union#configGetSourceVariant|configGetSourceVariant}.\n *\n * @param {Object} src - as with {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * @returns {(undefined|VariantLayout)} The default variant\n * (`undefined`) or first registered variant that uses a property\n * available in `src`. */\n this.getSourceVariant = function (src) {\n return boundGetSourceVariant(src);\n };\n /** Function to override the implementation of {@link\n * Union#getSourceVariant|getSourceVariant}.\n *\n * Use this if the desired variant cannot be identified using the\n * algorithm of {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * **NOTE** The provided function will be invoked bound to this\n * Union instance, providing local access to {@link\n * Union#registry|registry}.\n *\n * @param {Function} gsv - a function that follows the API of\n * {@link Union#defaultGetSourceVariant|defaultGetSourceVariant}. */\n this.configGetSourceVariant = function (gsv) {\n boundGetSourceVariant = gsv.bind(this);\n };\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n return this.span;\n }\n /* Default layouts always have non-negative span, so we don't have\n * one and we have to recognize the variant which will in turn\n * determine the span. */\n const vlo = this.getVariant(b, offset);\n if (!vlo) {\n throw new Error('unable to determine span for unrecognized variant');\n }\n return vlo.getSpan(b, offset);\n }\n /**\n * Method to infer a registered Union variant compatible with `src`.\n *\n * The first satisfied rule in the following sequence defines the\n * return value:\n * * If `src` has properties matching the Union discriminator and\n * the default layout, `undefined` is returned regardless of the\n * value of the discriminator property (this ensures the default\n * layout will be used);\n * * If `src` has a property matching the Union discriminator, the\n * value of the discriminator identifies a registered variant, and\n * either (a) the variant has no layout, or (b) `src` has the\n * variant's property, then the variant is returned (because the\n * source satisfies the constraints of the variant it identifies);\n * * If `src` does not have a property matching the Union\n * discriminator, but does have a property matching a registered\n * variant, then the variant is returned (because the source\n * matches a variant without an explicit conflict);\n * * An error is thrown (because we either can't identify a variant,\n * or we were explicitly told the variant but can't satisfy it).\n *\n * @param {Object} src - an object presumed to be compatible with\n * the content of the Union.\n *\n * @return {(undefined|VariantLayout)} - as described above.\n *\n * @throws {Error} - if `src` cannot be associated with a default or\n * registered variant.\n */\n defaultGetSourceVariant(src) {\n if (Object.prototype.hasOwnProperty.call(src, this.discriminator.property)) {\n if (this.defaultLayout && this.defaultLayout.property\n && Object.prototype.hasOwnProperty.call(src, this.defaultLayout.property)) {\n return undefined;\n }\n const vlo = this.registry[src[this.discriminator.property]];\n if (vlo\n && ((!vlo.layout)\n || (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)))) {\n return vlo;\n }\n }\n else {\n for (const tag in this.registry) {\n const vlo = this.registry[tag];\n if (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)) {\n return vlo;\n }\n }\n }\n throw new Error('unable to infer src variant');\n }\n /** Implement {@link Layout#decode|decode} for {@link Union}.\n *\n * If the variant is {@link Union#addVariant|registered} the return\n * value is an instance of that variant, with no explicit\n * discriminator. Otherwise the {@link Union#defaultLayout|default\n * layout} is used to decode the content. */\n decode(b, offset = 0) {\n let dest;\n const dlo = this.discriminator;\n const discr = dlo.decode(b, offset);\n const clo = this.registry[discr];\n if (undefined === clo) {\n const defaultLayout = this.defaultLayout;\n let contentOffset = 0;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dest = this.makeDestinationObject();\n dest[dlo.property] = discr;\n // defaultLayout.property can be undefined, but this is allowed by buffer-layout\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n dest[defaultLayout.property] = defaultLayout.decode(b, offset + contentOffset);\n }\n else {\n dest = clo.decode(b, offset);\n }\n return dest;\n }\n /** Implement {@link Layout#encode|encode} for {@link Union}.\n *\n * This API assumes the `src` object is consistent with the union's\n * {@link Union#defaultLayout|default layout}. To encode variants\n * use the appropriate variant-specific {@link VariantLayout#encode}\n * method. */\n encode(src, b, offset = 0) {\n const vlo = this.getSourceVariant(src);\n if (undefined === vlo) {\n const dlo = this.discriminator;\n // this.defaultLayout is not undefined when vlo is undefined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const clo = this.defaultLayout;\n let contentOffset = 0;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dlo.encode(src[dlo.property], b, offset);\n // clo.property is not undefined when vlo is undefined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return contentOffset + clo.encode(src[clo.property], b, offset + contentOffset);\n }\n return vlo.encode(src, b, offset);\n }\n /** Register a new variant structure within a union. The newly\n * created variant is returned.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} layout - initializer for {@link\n * VariantLayout#layout|layout}.\n *\n * @param {String} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {VariantLayout} */\n addVariant(variant, layout, property) {\n const rv = new VariantLayout(this, variant, layout, property);\n this.registry[variant] = rv;\n return rv;\n }\n /**\n * Get the layout associated with a registered variant.\n *\n * If `vb` does not produce a registered variant the function returns\n * `undefined`.\n *\n * @param {(Number|Uint8Array)} vb - either the variant number, or a\n * buffer from which the discriminator is to be read.\n *\n * @param {Number} offset - offset into `vb` for the start of the\n * union. Used only when `vb` is an instance of {Uint8Array}.\n *\n * @return {({VariantLayout}|undefined)}\n */\n getVariant(vb, offset = 0) {\n let variant;\n if (vb instanceof Uint8Array) {\n variant = this.discriminator.decode(vb, offset);\n }\n else {\n variant = vb;\n }\n return this.registry[variant];\n }\n}\nexports.Union = Union;\n/**\n * Represent a specific variant within a containing union.\n *\n * **NOTE** The {@link Layout#span|span} of the variant may include\n * the span of the {@link Union#discriminator|discriminator} used to\n * identify it, but values read and written using the variant strictly\n * conform to the content of {@link VariantLayout#layout|layout}.\n *\n * **NOTE** User code should not invoke this constructor directly. Use\n * the union {@link Union#addVariant|addVariant} helper method.\n *\n * @param {Union} union - initializer for {@link\n * VariantLayout#union|union}.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} [layout] - initializer for {@link\n * VariantLayout#layout|layout}. If absent the variant carries no\n * data.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}. Unlike many other layouts, variant\n * layouts normally include a property name so they can be identified\n * within their containing {@link Union}. The property identifier may\n * be absent only if `layout` is is absent.\n *\n * @augments {Layout}\n */\nclass VariantLayout extends Layout {\n constructor(union, variant, layout, property) {\n if (!(union instanceof Union)) {\n throw new TypeError('union must be a Union');\n }\n if ((!Number.isInteger(variant)) || (0 > variant)) {\n throw new TypeError('variant must be a (non-negative) integer');\n }\n if (('string' === typeof layout)\n && (undefined === property)) {\n property = layout;\n layout = null;\n }\n if (layout) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n if ((null !== union.defaultLayout)\n && (0 <= layout.span)\n && (layout.span > union.defaultLayout.span)) {\n throw new Error('variant span exceeds span of containing union');\n }\n if ('string' !== typeof property) {\n throw new TypeError('variant must have a String property');\n }\n }\n let span = union.span;\n if (0 > union.span) {\n span = layout ? layout.span : 0;\n if ((0 <= span) && union.usesPrefixDiscriminator) {\n span += union.discriminator.layout.span;\n }\n }\n super(span, property);\n /** The {@link Union} to which this variant belongs. */\n this.union = union;\n /** The unsigned integral value identifying this variant within\n * the {@link Union#discriminator|discriminator} of the containing\n * union. */\n this.variant = variant;\n /** The {@link Layout} to be used when reading/writing the\n * non-discriminator part of the {@link\n * VariantLayout#union|union}. If `null` the variant carries no\n * data. */\n this.layout = layout || null;\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n /* Will be equal to the containing union span if that is not\n * variable. */\n return this.span;\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n /* Span is defined solely by the variant (and prefix discriminator) */\n let span = 0;\n if (this.layout) {\n span = this.layout.getSpan(b, offset + contentOffset);\n }\n return contentOffset + span;\n }\n /** @override */\n decode(b, offset = 0) {\n const dest = this.makeDestinationObject();\n if (this !== this.union.getVariant(b, offset)) {\n throw new Error('variant mismatch');\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout) {\n dest[this.property] = this.layout.decode(b, offset + contentOffset);\n }\n else if (this.property) {\n dest[this.property] = true;\n }\n else if (this.union.usesPrefixDiscriminator) {\n dest[this.union.discriminator.property] = this.variant;\n }\n return dest;\n }\n /** @override */\n encode(src, b, offset = 0) {\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout\n && (!Object.prototype.hasOwnProperty.call(src, this.property))) {\n throw new TypeError('variant lacks property ' + this.property);\n }\n this.union.discriminator.encode(this.variant, b, offset);\n let span = contentOffset;\n if (this.layout) {\n this.layout.encode(src[this.property], b, offset + contentOffset);\n span += this.layout.getSpan(b, offset + contentOffset);\n if ((0 <= this.union.span)\n && (span > this.union.span)) {\n throw new Error('encoded variant overruns containing union');\n }\n }\n return span;\n }\n /** Delegate {@link Layout#fromArray|fromArray} to {@link\n * VariantLayout#layout|layout}. */\n fromArray(values) {\n if (this.layout) {\n return this.layout.fromArray(values);\n }\n return undefined;\n }\n}\nexports.VariantLayout = VariantLayout;\n/** JavaScript chose to define bitwise operations as operating on\n * signed 32-bit values in 2's complement form, meaning any integer\n * with bit 31 set is going to look negative. For right shifts that's\n * not a problem, because `>>>` is a logical shift, but for every\n * other bitwise operator we have to compensate for possible negative\n * results. */\nfunction fixBitwiseResult(v) {\n if (0 > v) {\n v += 0x100000000;\n }\n return v;\n}\n/**\n * Contain a sequence of bit fields as an unsigned integer.\n *\n * *Factory*: {@link module:Layout.bits|bits}\n *\n * This is a container element; within it there are {@link BitField}\n * instances that provide the extracted properties. The container\n * simply defines the aggregate representation and its bit ordering.\n * The representation is an object containing properties with numeric\n * or {@link Boolean} values.\n *\n * {@link BitField}s are added with the {@link\n * BitStructure#addField|addField} and {@link\n * BitStructure#addBoolean|addBoolean} methods.\n\n * @param {Layout} word - initializer for {@link\n * BitStructure#word|word}. The parameter must be an instance of\n * {@link UInt} (or {@link UIntBE}) that is no more than 4 bytes wide.\n *\n * @param {bool} [msb] - `true` if the bit numbering starts at the\n * most significant bit of the containing word; `false` (default) if\n * it starts at the least significant bit of the containing word. If\n * the parameter at this position is a string and `property` is\n * `undefined` the value of this argument will instead be used as the\n * value of `property`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass BitStructure extends Layout {\n constructor(word, msb, property) {\n if (!((word instanceof UInt)\n || (word instanceof UIntBE))) {\n throw new TypeError('word must be a UInt or UIntBE layout');\n }\n if (('string' === typeof msb)\n && (undefined === property)) {\n property = msb;\n msb = false;\n }\n if (4 < word.span) {\n throw new RangeError('word cannot exceed 32 bits');\n }\n super(word.span, property);\n /** The layout used for the packed value. {@link BitField}\n * instances are packed sequentially depending on {@link\n * BitStructure#msb|msb}. */\n this.word = word;\n /** Whether the bit sequences are packed starting at the most\n * significant bit growing down (`true`), or the least significant\n * bit growing up (`false`).\n *\n * **NOTE** Regardless of this value, the least significant bit of\n * any {@link BitField} value is the least significant bit of the\n * corresponding section of the packed value. */\n this.msb = !!msb;\n /** The sequence of {@link BitField} layouts that comprise the\n * packed structure.\n *\n * **NOTE** The array remains mutable to allow fields to be {@link\n * BitStructure#addField|added} after construction. Users should\n * not manipulate the content of this property.*/\n this.fields = [];\n /* Storage for the value. Capture a variable instead of using an\n * instance property because we don't want anything to change the\n * value without going through the mutator. */\n let value = 0;\n this._packedSetValue = function (v) {\n value = fixBitwiseResult(v);\n return this;\n };\n this._packedGetValue = function () {\n return value;\n };\n }\n /** @override */\n decode(b, offset = 0) {\n const dest = this.makeDestinationObject();\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(b);\n }\n }\n return dest;\n }\n /** Implement {@link Layout#encode|encode} for {@link BitStructure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the packed\n * value is left unmodified. Unused bits are also left unmodified. */\n encode(src, b, offset = 0) {\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n fd.encode(fv);\n }\n }\n }\n return this.word.encode(this._packedGetValue(), b, offset);\n }\n /** Register a new bitfield with a containing bit structure. The\n * resulting bitfield is returned.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {BitField} */\n addField(bits, property) {\n const bf = new BitField(this, bits, property);\n this.fields.push(bf);\n return bf;\n }\n /** As with {@link BitStructure#addField|addField} for single-bit\n * fields with `boolean` value representation.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {Boolean} */\n // `Boolean` conflicts with the native primitive type\n // eslint-disable-next-line @typescript-eslint/ban-types\n addBoolean(property) {\n // This is my Boolean, not the Javascript one.\n const bf = new Boolean(this, property);\n this.fields.push(bf);\n return bf;\n }\n /**\n * Get access to the bit field for a given property.\n *\n * @param {String} property - the bit field of interest.\n *\n * @return {BitField} - the field associated with `property`, or\n * undefined if there is no such property.\n */\n fieldFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n return undefined;\n }\n}\nexports.BitStructure = BitStructure;\n/**\n * Represent a sequence of bits within a {@link BitStructure}.\n *\n * All bit field values are represented as unsigned integers.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addField|addField} helper\n * method.\n *\n * **NOTE** BitField instances are not instances of {@link Layout}\n * since {@link Layout#span|span} measures 8-bit units.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n */\nclass BitField {\n constructor(container, bits, property) {\n if (!(container instanceof BitStructure)) {\n throw new TypeError('container must be a BitStructure');\n }\n if ((!Number.isInteger(bits)) || (0 >= bits)) {\n throw new TypeError('bits must be positive integer');\n }\n const totalBits = 8 * container.span;\n const usedBits = container.fields.reduce((sum, fd) => sum + fd.bits, 0);\n if ((bits + usedBits) > totalBits) {\n throw new Error('bits too long for span remainder ('\n + (totalBits - usedBits) + ' of '\n + totalBits + ' remain)');\n }\n /** The {@link BitStructure} instance to which this bit field\n * belongs. */\n this.container = container;\n /** The span of this value in bits. */\n this.bits = bits;\n /** A mask of {@link BitField#bits|bits} bits isolating value bits\n * that fit within the field.\n *\n * That is, it masks a value that has not yet been shifted into\n * position within its containing packed integer. */\n this.valueMask = (1 << bits) - 1;\n if (32 === bits) { // shifted value out of range\n this.valueMask = 0xFFFFFFFF;\n }\n /** The offset of the value within the containing packed unsigned\n * integer. The least significant bit of the packed value is at\n * offset zero, regardless of bit ordering used. */\n this.start = usedBits;\n if (this.container.msb) {\n this.start = totalBits - usedBits - bits;\n }\n /** A mask of {@link BitField#bits|bits} isolating the field value\n * within the containing packed unsigned integer. */\n this.wordMask = fixBitwiseResult(this.valueMask << this.start);\n /** The property name used when this bitfield is represented in an\n * Object.\n *\n * Intended to be functionally equivalent to {@link\n * Layout#property}.\n *\n * If left undefined the corresponding span of bits will be\n * treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n /** Store a value into the corresponding subsequence of the containing\n * bit field. */\n decode(b, offset) {\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(word & this.wordMask);\n const value = wordValue >>> this.start;\n return value;\n }\n /** Store a value into the corresponding subsequence of the containing\n * bit field.\n *\n * **NOTE** This is not a specialization of {@link\n * Layout#encode|Layout.encode} and there is no return value. */\n encode(value) {\n if ('number' !== typeof value\n || !Number.isInteger(value)\n || (value !== fixBitwiseResult(value & this.valueMask))) {\n throw new TypeError(nameWithProperty('BitField.encode', this)\n + ' value must be integer not exceeding ' + this.valueMask);\n }\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(value << this.start);\n this.container._packedSetValue(fixBitwiseResult(word & ~this.wordMask)\n | wordValue);\n }\n}\nexports.BitField = BitField;\n/**\n * Represent a single bit within a {@link BitStructure} as a\n * JavaScript boolean.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addBoolean|addBoolean} helper\n * method.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {BitField}\n */\n/* eslint-disable no-extend-native */\nclass Boolean extends BitField {\n constructor(container, property) {\n super(container, 1, property);\n }\n /** Override {@link BitField#decode|decode} for {@link Boolean|Boolean}.\n *\n * @returns {boolean} */\n decode(b, offset) {\n return !!super.decode(b, offset);\n }\n /** @override */\n encode(value) {\n if ('boolean' === typeof value) {\n // BitField requires integer values\n value = +value;\n }\n super.encode(value);\n }\n}\nexports.Boolean = Boolean;\n/* eslint-enable no-extend-native */\n/**\n * Contain a fixed-length block of arbitrary data, represented as a\n * Uint8Array.\n *\n * *Factory*: {@link module:Layout.blob|blob}\n *\n * @param {(Number|ExternalLayout)} length - initializes {@link\n * Blob#length|length}.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Blob extends Layout {\n constructor(length, property) {\n if (!(((length instanceof ExternalLayout) && length.isCount())\n || (Number.isInteger(length) && (0 <= length)))) {\n throw new TypeError('length must be positive integer '\n + 'or an unsigned integer ExternalLayout');\n }\n let span = -1;\n if (!(length instanceof ExternalLayout)) {\n span = length;\n }\n super(span, property);\n /** The number of bytes in the blob.\n *\n * This may be a non-negative integer, or an instance of {@link\n * ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}. */\n this.length = length;\n }\n /** @override */\n getSpan(b, offset) {\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return span;\n }\n /** @override */\n decode(b, offset = 0) {\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return uint8ArrayToBuffer(b).slice(offset, offset + span);\n }\n /** Implement {@link Layout#encode|encode} for {@link Blob}.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset) {\n let span = this.length;\n if (this.length instanceof ExternalLayout) {\n span = src.length;\n }\n if (!(src instanceof Uint8Array && span === src.length)) {\n throw new TypeError(nameWithProperty('Blob.encode', this)\n + ' requires (length ' + span + ') Uint8Array as src');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Uint8Array');\n }\n const srcBuffer = uint8ArrayToBuffer(src);\n uint8ArrayToBuffer(b).write(srcBuffer.toString('hex'), offset, span, 'hex');\n if (this.length instanceof ExternalLayout) {\n this.length.encode(span, b, offset);\n }\n return span;\n }\n}\nexports.Blob = Blob;\n/**\n * Contain a `NUL`-terminated UTF8 string.\n *\n * *Factory*: {@link module:Layout.cstr|cstr}\n *\n * **NOTE** Any UTF8 string that incorporates a zero-valued byte will\n * not be correctly decoded by this layout.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass CString extends Layout {\n constructor(property) {\n super(-1, property);\n }\n /** @override */\n getSpan(b, offset = 0) {\n checkUint8Array(b);\n let idx = offset;\n while ((idx < b.length) && (0 !== b[idx])) {\n idx += 1;\n }\n return 1 + idx - offset;\n }\n /** @override */\n decode(b, offset = 0) {\n const span = this.getSpan(b, offset);\n return uint8ArrayToBuffer(b).slice(offset, offset + span - 1).toString('utf-8');\n }\n /** @override */\n encode(src, b, offset = 0) {\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = String(src);\n }\n const srcb = buffer_1.Buffer.from(src, 'utf8');\n const span = srcb.length;\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n const buffer = uint8ArrayToBuffer(b);\n srcb.copy(buffer, offset);\n buffer[offset + span] = 0;\n return span + 1;\n }\n}\nexports.CString = CString;\n/**\n * Contain a UTF8 string with implicit length.\n *\n * *Factory*: {@link module:Layout.utf8|utf8}\n *\n * **NOTE** Because the length is implicit in the size of the buffer\n * this layout should be used only in isolation, or in a situation\n * where the length can be expressed by operating on a slice of the\n * containing buffer.\n *\n * @param {Number} [maxSpan] - the maximum length allowed for encoded\n * string content. If not provided there is no bound on the allowed\n * content.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UTF8 extends Layout {\n constructor(maxSpan, property) {\n if (('string' === typeof maxSpan) && (undefined === property)) {\n property = maxSpan;\n maxSpan = undefined;\n }\n if (undefined === maxSpan) {\n maxSpan = -1;\n }\n else if (!Number.isInteger(maxSpan)) {\n throw new TypeError('maxSpan must be an integer');\n }\n super(-1, property);\n /** The maximum span of the layout in bytes.\n *\n * Positive values are generally expected. Zero is abnormal.\n * Attempts to encode or decode a value that exceeds this length\n * will throw a `RangeError`.\n *\n * A negative value indicates that there is no bound on the length\n * of the content. */\n this.maxSpan = maxSpan;\n }\n /** @override */\n getSpan(b, offset = 0) {\n checkUint8Array(b);\n return b.length - offset;\n }\n /** @override */\n decode(b, offset = 0) {\n const span = this.getSpan(b, offset);\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n return uint8ArrayToBuffer(b).slice(offset, offset + span).toString('utf-8');\n }\n /** @override */\n encode(src, b, offset = 0) {\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = String(src);\n }\n const srcb = buffer_1.Buffer.from(src, 'utf8');\n const span = srcb.length;\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n srcb.copy(uint8ArrayToBuffer(b), offset);\n return span;\n }\n}\nexports.UTF8 = UTF8;\n/**\n * Contain a constant value.\n *\n * This layout may be used in cases where a JavaScript value can be\n * inferred without an expression in the binary encoding. An example\n * would be a {@link VariantLayout|variant layout} where the content\n * is implied by the union {@link Union#discriminator|discriminator}.\n *\n * @param {Object|Number|String} value - initializer for {@link\n * Constant#value|value}. If the value is an object (or array) and\n * the application intends the object to remain unchanged regardless\n * of what is done to values decoded by this layout, the value should\n * be frozen prior passing it to this constructor.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Constant extends Layout {\n constructor(value, property) {\n super(0, property);\n /** The value produced by this constant when the layout is {@link\n * Constant#decode|decoded}.\n *\n * Any JavaScript value including `null` and `undefined` is\n * permitted.\n *\n * **WARNING** If `value` passed in the constructor was not\n * frozen, it is possible for users of decoded values to change\n * the content of the value. */\n this.value = value;\n }\n /** @override */\n decode(b, offset) {\n return this.value;\n }\n /** @override */\n encode(src, b, offset) {\n /* Constants take no space */\n return 0;\n }\n}\nexports.Constant = Constant;\n/** Factory for {@link GreedyCount}. */\nexports.greedy = ((elementSpan, property) => new GreedyCount(elementSpan, property));\n/** Factory for {@link OffsetLayout}. */\nexports.offset = ((layout, offset, property) => new OffsetLayout(layout, offset, property));\n/** Factory for {@link UInt|unsigned int layouts} spanning one\n * byte. */\nexports.u8 = ((property) => new UInt(1, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16 = ((property) => new UInt(2, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24 = ((property) => new UInt(3, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32 = ((property) => new UInt(4, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40 = ((property) => new UInt(5, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48 = ((property) => new UInt(6, property));\n/** Factory for {@link NearUInt64|little-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64 = ((property) => new NearUInt64(property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16be = ((property) => new UIntBE(2, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24be = ((property) => new UIntBE(3, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32be = ((property) => new UIntBE(4, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40be = ((property) => new UIntBE(5, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48be = ((property) => new UIntBE(6, property));\n/** Factory for {@link NearUInt64BE|big-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64be = ((property) => new NearUInt64BE(property));\n/** Factory for {@link Int|signed int layouts} spanning one\n * byte. */\nexports.s8 = ((property) => new Int(1, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning two bytes. */\nexports.s16 = ((property) => new Int(2, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning three bytes. */\nexports.s24 = ((property) => new Int(3, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning four bytes. */\nexports.s32 = ((property) => new Int(4, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning five bytes. */\nexports.s40 = ((property) => new Int(5, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning six bytes. */\nexports.s48 = ((property) => new Int(6, property));\n/** Factory for {@link NearInt64|little-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64 = ((property) => new NearInt64(property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning two bytes. */\nexports.s16be = ((property) => new IntBE(2, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning three bytes. */\nexports.s24be = ((property) => new IntBE(3, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning four bytes. */\nexports.s32be = ((property) => new IntBE(4, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning five bytes. */\nexports.s40be = ((property) => new IntBE(5, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning six bytes. */\nexports.s48be = ((property) => new IntBE(6, property));\n/** Factory for {@link NearInt64BE|big-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64be = ((property) => new NearInt64BE(property));\n/** Factory for {@link Float|little-endian 32-bit floating point} values. */\nexports.f32 = ((property) => new Float(property));\n/** Factory for {@link FloatBE|big-endian 32-bit floating point} values. */\nexports.f32be = ((property) => new FloatBE(property));\n/** Factory for {@link Double|little-endian 64-bit floating point} values. */\nexports.f64 = ((property) => new Double(property));\n/** Factory for {@link DoubleBE|big-endian 64-bit floating point} values. */\nexports.f64be = ((property) => new DoubleBE(property));\n/** Factory for {@link Structure} values. */\nexports.struct = ((fields, property, decodePrefixes) => new Structure(fields, property, decodePrefixes));\n/** Factory for {@link BitStructure} values. */\nexports.bits = ((word, msb, property) => new BitStructure(word, msb, property));\n/** Factory for {@link Sequence} values. */\nexports.seq = ((elementLayout, count, property) => new Sequence(elementLayout, count, property));\n/** Factory for {@link Union} values. */\nexports.union = ((discr, defaultLayout, property) => new Union(discr, defaultLayout, property));\n/** Factory for {@link UnionLayoutDiscriminator} values. */\nexports.unionLayoutDiscriminator = ((layout, property) => new UnionLayoutDiscriminator(layout, property));\n/** Factory for {@link Blob} values. */\nexports.blob = ((length, property) => new Blob(length, property));\n/** Factory for {@link CString} values. */\nexports.cstr = ((property) => new CString(property));\n/** Factory for {@link UTF8} values. */\nexports.utf8 = ((maxSpan, property) => new UTF8(maxSpan, property));\n/** Factory for {@link Constant} values. */\nexports.constant = ((value, property) => new Constant(value, property));\n//# sourceMappingURL=Layout.js.map","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.deserializeUnchecked = exports.deserialize = exports.serialize = exports.BinaryReader = exports.BinaryWriter = exports.BorshError = exports.baseDecode = exports.baseEncode = void 0;\nconst bn_js_1 = __importDefault(require(\"bn.js\"));\nconst bs58_1 = __importDefault(require(\"bs58\"));\n// TODO: Make sure this polyfill not included when not required\nconst encoding = __importStar(require(\"text-encoding-utf-8\"));\nconst ResolvedTextDecoder = typeof TextDecoder !== \"function\" ? encoding.TextDecoder : TextDecoder;\nconst textDecoder = new ResolvedTextDecoder(\"utf-8\", { fatal: true });\nfunction baseEncode(value) {\n if (typeof value === \"string\") {\n value = Buffer.from(value, \"utf8\");\n }\n return bs58_1.default.encode(Buffer.from(value));\n}\nexports.baseEncode = baseEncode;\nfunction baseDecode(value) {\n return Buffer.from(bs58_1.default.decode(value));\n}\nexports.baseDecode = baseDecode;\nconst INITIAL_LENGTH = 1024;\nclass BorshError extends Error {\n constructor(message) {\n super(message);\n this.fieldPath = [];\n this.originalMessage = message;\n }\n addToFieldPath(fieldName) {\n this.fieldPath.splice(0, 0, fieldName);\n // NOTE: Modifying message directly as jest doesn't use .toString()\n this.message = this.originalMessage + \": \" + this.fieldPath.join(\".\");\n }\n}\nexports.BorshError = BorshError;\n/// Binary encoder.\nclass BinaryWriter {\n constructor() {\n this.buf = Buffer.alloc(INITIAL_LENGTH);\n this.length = 0;\n }\n maybeResize() {\n if (this.buf.length < 16 + this.length) {\n this.buf = Buffer.concat([this.buf, Buffer.alloc(INITIAL_LENGTH)]);\n }\n }\n writeU8(value) {\n this.maybeResize();\n this.buf.writeUInt8(value, this.length);\n this.length += 1;\n }\n writeU16(value) {\n this.maybeResize();\n this.buf.writeUInt16LE(value, this.length);\n this.length += 2;\n }\n writeU32(value) {\n this.maybeResize();\n this.buf.writeUInt32LE(value, this.length);\n this.length += 4;\n }\n writeU64(value) {\n this.maybeResize();\n this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray(\"le\", 8)));\n }\n writeU128(value) {\n this.maybeResize();\n this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray(\"le\", 16)));\n }\n writeU256(value) {\n this.maybeResize();\n this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray(\"le\", 32)));\n }\n writeU512(value) {\n this.maybeResize();\n this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray(\"le\", 64)));\n }\n writeBuffer(buffer) {\n // Buffer.from is needed as this.buf.subarray can return plain Uint8Array in browser\n this.buf = Buffer.concat([\n Buffer.from(this.buf.subarray(0, this.length)),\n buffer,\n Buffer.alloc(INITIAL_LENGTH),\n ]);\n this.length += buffer.length;\n }\n writeString(str) {\n this.maybeResize();\n const b = Buffer.from(str, \"utf8\");\n this.writeU32(b.length);\n this.writeBuffer(b);\n }\n writeFixedArray(array) {\n this.writeBuffer(Buffer.from(array));\n }\n writeArray(array, fn) {\n this.maybeResize();\n this.writeU32(array.length);\n for (const elem of array) {\n this.maybeResize();\n fn(elem);\n }\n }\n toArray() {\n return this.buf.subarray(0, this.length);\n }\n}\nexports.BinaryWriter = BinaryWriter;\nfunction handlingRangeError(target, propertyKey, propertyDescriptor) {\n const originalMethod = propertyDescriptor.value;\n propertyDescriptor.value = function (...args) {\n try {\n return originalMethod.apply(this, args);\n }\n catch (e) {\n if (e instanceof RangeError) {\n const code = e.code;\n if ([\"ERR_BUFFER_OUT_OF_BOUNDS\", \"ERR_OUT_OF_RANGE\"].indexOf(code) >= 0) {\n throw new BorshError(\"Reached the end of buffer when deserializing\");\n }\n }\n throw e;\n }\n };\n}\nclass BinaryReader {\n constructor(buf) {\n this.buf = buf;\n this.offset = 0;\n }\n readU8() {\n const value = this.buf.readUInt8(this.offset);\n this.offset += 1;\n return value;\n }\n readU16() {\n const value = this.buf.readUInt16LE(this.offset);\n this.offset += 2;\n return value;\n }\n readU32() {\n const value = this.buf.readUInt32LE(this.offset);\n this.offset += 4;\n return value;\n }\n readU64() {\n const buf = this.readBuffer(8);\n return new bn_js_1.default(buf, \"le\");\n }\n readU128() {\n const buf = this.readBuffer(16);\n return new bn_js_1.default(buf, \"le\");\n }\n readU256() {\n const buf = this.readBuffer(32);\n return new bn_js_1.default(buf, \"le\");\n }\n readU512() {\n const buf = this.readBuffer(64);\n return new bn_js_1.default(buf, \"le\");\n }\n readBuffer(len) {\n if (this.offset + len > this.buf.length) {\n throw new BorshError(`Expected buffer length ${len} isn't within bounds`);\n }\n const result = this.buf.slice(this.offset, this.offset + len);\n this.offset += len;\n return result;\n }\n readString() {\n const len = this.readU32();\n const buf = this.readBuffer(len);\n try {\n // NOTE: Using TextDecoder to fail on invalid UTF-8\n return textDecoder.decode(buf);\n }\n catch (e) {\n throw new BorshError(`Error decoding UTF-8 string: ${e}`);\n }\n }\n readFixedArray(len) {\n return new Uint8Array(this.readBuffer(len));\n }\n readArray(fn) {\n const len = this.readU32();\n const result = Array();\n for (let i = 0; i < len; ++i) {\n result.push(fn());\n }\n return result;\n }\n}\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU8\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU16\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU32\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU64\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU128\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU256\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readU512\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readString\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readFixedArray\", null);\n__decorate([\n handlingRangeError\n], BinaryReader.prototype, \"readArray\", null);\nexports.BinaryReader = BinaryReader;\nfunction capitalizeFirstLetter(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\nfunction serializeField(schema, fieldName, value, fieldType, writer) {\n try {\n // TODO: Handle missing values properly (make sure they never result in just skipped write)\n if (typeof fieldType === \"string\") {\n writer[`write${capitalizeFirstLetter(fieldType)}`](value);\n }\n else if (fieldType instanceof Array) {\n if (typeof fieldType[0] === \"number\") {\n if (value.length !== fieldType[0]) {\n throw new BorshError(`Expecting byte array of length ${fieldType[0]}, but got ${value.length} bytes`);\n }\n writer.writeFixedArray(value);\n }\n else if (fieldType.length === 2 && typeof fieldType[1] === \"number\") {\n if (value.length !== fieldType[1]) {\n throw new BorshError(`Expecting byte array of length ${fieldType[1]}, but got ${value.length} bytes`);\n }\n for (let i = 0; i < fieldType[1]; i++) {\n serializeField(schema, null, value[i], fieldType[0], writer);\n }\n }\n else {\n writer.writeArray(value, (item) => {\n serializeField(schema, fieldName, item, fieldType[0], writer);\n });\n }\n }\n else if (fieldType.kind !== undefined) {\n switch (fieldType.kind) {\n case \"option\": {\n if (value === null || value === undefined) {\n writer.writeU8(0);\n }\n else {\n writer.writeU8(1);\n serializeField(schema, fieldName, value, fieldType.type, writer);\n }\n break;\n }\n case \"map\": {\n writer.writeU32(value.size);\n value.forEach((val, key) => {\n serializeField(schema, fieldName, key, fieldType.key, writer);\n serializeField(schema, fieldName, val, fieldType.value, writer);\n });\n break;\n }\n default:\n throw new BorshError(`FieldType ${fieldType} unrecognized`);\n }\n }\n else {\n serializeStruct(schema, value, writer);\n }\n }\n catch (error) {\n if (error instanceof BorshError) {\n error.addToFieldPath(fieldName);\n }\n throw error;\n }\n}\nfunction serializeStruct(schema, obj, writer) {\n if (typeof obj.borshSerialize === \"function\") {\n obj.borshSerialize(writer);\n return;\n }\n const structSchema = schema.get(obj.constructor);\n if (!structSchema) {\n throw new BorshError(`Class ${obj.constructor.name} is missing in schema`);\n }\n if (structSchema.kind === \"struct\") {\n structSchema.fields.map(([fieldName, fieldType]) => {\n serializeField(schema, fieldName, obj[fieldName], fieldType, writer);\n });\n }\n else if (structSchema.kind === \"enum\") {\n const name = obj[structSchema.field];\n for (let idx = 0; idx < structSchema.values.length; ++idx) {\n const [fieldName, fieldType] = structSchema.values[idx];\n if (fieldName === name) {\n writer.writeU8(idx);\n serializeField(schema, fieldName, obj[fieldName], fieldType, writer);\n break;\n }\n }\n }\n else {\n throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${obj.constructor.name}`);\n }\n}\n/// Serialize given object using schema of the form:\n/// { class_name -> [ [field_name, field_type], .. ], .. }\nfunction serialize(schema, obj, Writer = BinaryWriter) {\n const writer = new Writer();\n serializeStruct(schema, obj, writer);\n return writer.toArray();\n}\nexports.serialize = serialize;\nfunction deserializeField(schema, fieldName, fieldType, reader) {\n try {\n if (typeof fieldType === \"string\") {\n return reader[`read${capitalizeFirstLetter(fieldType)}`]();\n }\n if (fieldType instanceof Array) {\n if (typeof fieldType[0] === \"number\") {\n return reader.readFixedArray(fieldType[0]);\n }\n else if (typeof fieldType[1] === \"number\") {\n const arr = [];\n for (let i = 0; i < fieldType[1]; i++) {\n arr.push(deserializeField(schema, null, fieldType[0], reader));\n }\n return arr;\n }\n else {\n return reader.readArray(() => deserializeField(schema, fieldName, fieldType[0], reader));\n }\n }\n if (fieldType.kind === \"option\") {\n const option = reader.readU8();\n if (option) {\n return deserializeField(schema, fieldName, fieldType.type, reader);\n }\n return undefined;\n }\n if (fieldType.kind === \"map\") {\n let map = new Map();\n const length = reader.readU32();\n for (let i = 0; i < length; i++) {\n const key = deserializeField(schema, fieldName, fieldType.key, reader);\n const val = deserializeField(schema, fieldName, fieldType.value, reader);\n map.set(key, val);\n }\n return map;\n }\n return deserializeStruct(schema, fieldType, reader);\n }\n catch (error) {\n if (error instanceof BorshError) {\n error.addToFieldPath(fieldName);\n }\n throw error;\n }\n}\nfunction deserializeStruct(schema, classType, reader) {\n if (typeof classType.borshDeserialize === \"function\") {\n return classType.borshDeserialize(reader);\n }\n const structSchema = schema.get(classType);\n if (!structSchema) {\n throw new BorshError(`Class ${classType.name} is missing in schema`);\n }\n if (structSchema.kind === \"struct\") {\n const result = {};\n for (const [fieldName, fieldType] of schema.get(classType).fields) {\n result[fieldName] = deserializeField(schema, fieldName, fieldType, reader);\n }\n return new classType(result);\n }\n if (structSchema.kind === \"enum\") {\n const idx = reader.readU8();\n if (idx >= structSchema.values.length) {\n throw new BorshError(`Enum index: ${idx} is out of range`);\n }\n const [fieldName, fieldType] = structSchema.values[idx];\n const fieldValue = deserializeField(schema, fieldName, fieldType, reader);\n return new classType({ [fieldName]: fieldValue });\n }\n throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${classType.constructor.name}`);\n}\n/// Deserializes object from bytes using schema.\nfunction deserialize(schema, classType, buffer, Reader = BinaryReader) {\n const reader = new Reader(buffer);\n const result = deserializeStruct(schema, classType, reader);\n if (reader.offset < buffer.length) {\n throw new BorshError(`Unexpected ${buffer.length - reader.offset} bytes after deserialized data`);\n }\n return result;\n}\nexports.deserialize = deserialize;\n/// Deserializes object from bytes using schema, without checking the length read\nfunction deserializeUnchecked(schema, classType, buffer, Reader = BinaryReader) {\n const reader = new Reader(buffer);\n return deserializeStruct(schema, classType, reader);\n}\nexports.deserializeUnchecked = deserializeUnchecked;\n","var basex = require('base-x')\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`Wrong positive integer: ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`Expected boolean, not ${b}`);\n}\nfunction bytes(b, ...lengths) {\n if (!(b instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nconst u8a = (a) => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n if (!u8a(data))\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Base SHA2 class (RFC 6234)\nexport class SHA2 extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_sha2.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { SHA2 } from './_sha2.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends SHA2 {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n"],"names":["uuid","generateRequest","ClientBrowser","callServer","options","this","reviver","replacer","generator","version","notificationIdNull","module","exports","prototype","request","method","params","id","callback","self","isBatch","Array","isArray","TypeError","undefined","hasCallback","err","message","JSON","stringify","response","_parseResponse","responseText","parse","length","isError","res","error","isNotError","filter","result","globalThis","crypto","isBytes","a","Uint8Array","ArrayBuffer","isView","constructor","name","anumber","n","Number","isSafeInteger","Error","b","lengths","includes","ahash","h","create","outputLen","blockLen","aexists","instance","checkFinished","destroyed","finished","clean","arrays","i","fill","createView","arr","DataView","buffer","byteOffset","byteLength","rotr","word","shift","hasHexBuiltin","from","toHex","fromHex","hexes","_","toString","padStart","bytesToHex","bytes","hex","asciiToBase16","ch","hexToBytes","hl","al","array","ai","hi","n1","charCodeAt","n2","char","str","TextEncoder","encode","toBytes","data","sum","pad","set","Hash","hashCons","hashC","msg","update","digest","tmp","bytesLength","getRandomValues","randomBytes","Chi","c","Maj","HashMD","padOffset","isLE","super","pos","view","len","take","Math","min","dataView","process","subarray","roundClean","digestInto","out","aoutput","value","setBigUint64","_32n","BigInt","_u32_max","wh","wl","l","setUint32","oview","outLen","state","get","slice","destroy","_cloneInto","to","clone","SHA256_IV","Uint32Array","SHA512_IV","U32_MASK64","fromBig","le","shrSH","_l","s","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","add","Ah","Al","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5L","El","add5H","Eh","SHA256_K","SHA256_W","SHA256","A","B","C","D","E","F","G","H","offset","getUint32","W15","W2","s0","s1","T1","T2","K512","lst","map","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","_0n","_1n","_abool2","title","_abytes2","needsLen","numberToHexUnpadded","num","hexToNumber","reverse","numberToBytesLE","expectedLength","e","copyBytes","isPosBig","aInRange","max","bitLen","object","fields","optFields","checkField","fieldName","expectedType","isOpt","val","current","Object","entries","forEach","k","v","notImplemented","memoized","fn","WeakMap","arg","args","computed","_2n","_3n","_4n","_5n","_7n","_8n","_9n","_16n","x","power","modulo","invert","number","y","u","q","r","m","assertIsSquare","Fp","root","eql","sqr","sqrt3mod4","p1div4","ORDER","pow","sqrt5mod8","p5div8","mul","nv","sub","ONE","tonelliShanks","P","Q","S","Z","_Fp","Field","FpLegendre","cc","Q1div2","is0","M","t","R","ZERO","t_tmp","exponent","isNegativeLE","FIELD_FIELDS","nums","passZero","inverted","multipliedAcc","reduce","acc","invertedAcc","inv","reduceRight","p1mod2","powered","yes","zero","no","neg","nBitLength","_nBitLength","nByteLength","ceil","bitLenOrOpts","opts","_nbitLength","_sqrt","allowedLengths","modFromBytes","sqrt","_opts","BITS","BYTES","sqrtP","f","freeze","MASK","isValid","isValidNot0","isOdd","lhs","rhs","p","d","FpPow","div","sqrN","addN","subN","mulN","Fp_","tn","c1","c2","c3","c4","tv1","tv2","tv3","tv4","e1","e2","cmov","e3","sqrt9mod16","fromBytes","skipValidation","padded","scalar","invertBatch","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","negateCt","condition","item","negate","normalizeZ","points","invertedZs","fromAffine","toAffine","validateW","W","bits","calcWOpts","scalarBits","maxNumber","windows","windowSize","mask","shiftBy","calcOffsets","window","wOpts","wbits","nextN","offsetStart","abs","isZero","isNeg","isNegF","offsetF","pointPrecomputes","pointWindowSizes","getW","assert0","wNAF","Point","BASE","Fn","_unsafeLadder","elm","double","precomputeWindow","point","base","push","precomputes","wo","wNAFUnsafe","getPrecomputes","transform","comp","cached","unsafe","prev","createCache","delete","hasCache","pippenger","fieldN","scalars","validateMSMPoints","field","validateMSMScalars","plength","slength","buckets","floor","j","resI","sumI","createField","order","_createCurveFields","type","CURVE","curveOpts","FpFnLE","assign","PrimeEdwardsPoint","ep","_bytes","_hex","clearCofactor","assertValidity","invertedZ","isTorsionFree","isSmallOrder","other","assertSame","init","subtract","multiply","multiplyUnsafe","precompute","isLazy","toRawBytes","hash","eddsaOpts","Gx","Gy","uvRatio","adjustScalarBytes","domain","prehash","mapToCurve","_eddsa_legacy_opts_to_new","extraOpts","validated","cofactor","modP","x2","y2","left","right","isEdValidXY","acoord","banZero","aextpoint","toAffineMemo","iz","X","Y","zz","assertValidMemo","T","X2","Y2","Z2","Z4","aX2","zip215","normed","lastByte","isXOdd","isLastByteOdd","wnaf","equals","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","X3","Y3","T3","Z3","ex","ey","ez","et","msm","_setWindowSize","edwards","eddsa","ExtendedPoint","_eddsa_new_output_to_legacy","cHash","ctx","phflag","modN_LE","getExtendedPublicKey","secretKey","head","prefix","key","hashed","getPrivateScalar","pointBytes","getPublicKey","hashDomainToScalar","context","of","msgs","verifyOpts","_size","publicKey","signature","seed","randomSecretKey","utils","isValidSecretKey","isValidPublicKey","toMontgomery","size","is25519","toMontgomerySecret","randomPrivateKey","keygen","sign","verify","sig","mid","SB","ed25519_CURVE_p","ed25519_CURVE","ED25519_SQRT_M1","v3","v7","_10n","_20n","_40n","_80n","b2","b4","b5","b10","b20","b40","b80","b160","b240","b250","pow_p_5_8","ed25519_pow_2_252_3","vx2","root1","root2","useRoot1","useRoot2","noRoot","ed25519Defaults","ed25519","SQRT_M1","SQRT_AD_MINUS_ONE","INVSQRT_A_MINUS_D","ONE_MINUS_D_SQ","D_MINUS_ONE_SQ","invertSqrt","MAX_255B","bytes255ToNumberLE","calcElligatorRistrettoMap","r0","mod","Ns","Ns_D_is_sq","s_","Nt","s2","W0","W1","W3","_RistrettoPoint","ap","hashToCurve","R1","R2","ristretto255_map","diff","equalBytes","u1","u2","u1_2","u2_2","I","Dx","Dy","u2sq","invsqrt","D1","D2","zInv","_x","_y","one","two","encodeValue","join","encodeURIComponent","String","getPrototypeOf","encodeObjectContextEntry","cause","code","contextAndErrorOptions","errorOptions","contextRest","keys","decodingAdviceMessage","searchParamsString","btoa","encodeContextObject","getErrorMessage","__code","isFixedSize","codec","fixedSize","isLittleEndian","config","endian","numberEncoderFactory","input","encoder","write","range","codecDescription","assertNumberIsBetweenForCodec","arrayBuffer","getSizeFromValue","getEncodedSize","numberDecoderFactory","decoder","read","assertByteArrayIsNotEmptyForCodec","expected","assertByteArrayHasEnoughBytesForCodec","bytesOffset","toArrayBuffer","decode","getU64Encoder","getU64Codec","decoderFixedSize","encoderFixedSize","maxSize","decoderMaxSize","encoderMaxSize","getBigUint64","getU64Decoder","StructError","failure","failures","explanation","rest","path","isObject","isNonArrayObject","print","toFailure","struct","branch","refinement","toFailures","Symbol","iterator","run","coerce","coercer","status","validator","ts","Map","Set","refiner","Struct","props","schema","assert","validate","is","tuples","tuple","done","next","shiftIterator","Element","Class","literal","constant","description","isNaN","optional","record","Key","Value","Structs","Never","union","coerced","first","unknown","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","IOTAS","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","Keccak","suffix","enableXOF","rounds","posOut","state32","keccak","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","keccakP","finish","writeInto","bufferOut","xofInto","xof","keccak_256","gen","HMAC","_key","iHash","oHash","buf","divNearest","den","validateSigFormat","format","validateSigOpts","def","optsn","optName","lowS","DERErr","DER","Err","_tlv","tag","dataLen","lenLen","lengthBytes","_int","parseInt","toSig","int","tlv","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","seq","pprefix","hasEvenY","getWLengths","publicKeyUncompressed","publicKeyHasPrefix","ecdsa","ecdsaOpts","hmac","bits2int","bits2int_modN","CURVE_ORDER","fnBits","getSharedSecret","ecdhOpts","randomBytes_","fieldLen","minLen","reduced","isCompressed","isProbPub","isValidPrivateKey","normPrivateKeyToScalar","secretKeyA","publicKeyB","ecdh","defaultSigOpts","extraEntropy","defaultSigOpts_format","isBiggerThanHalfOrder","validateRS","Signature","recovery","recid","validateSigLength","L","addRecoveryBit","recoverPublicKey","messageHash","FIELD_ORDER","rec","radj","ir","hasHighS","fromCompact","fromDER","normalizeS","toDERRawBytes","toDERHex","toCompactRawBytes","toCompactHex","delta","ORDER_MASK","int2octets","validateMsgAndHash","k2sig","privateKey","some","h1int","seedArgs","kBytes","ik","normS","prepSig","drbg","hashLen","qByteLen","hmacFn","u8n","u8of","byte","reset","reseed","sl","pred","createHmacDrbg","sg","isHex","isObj","derError","tryParsingSig","weierstrass","allowedPrivateKeyLengths","wrapPrivateKey","allowInfinityPoint","endo","_weierstrass_legacy_opts_to_new","_ecdsa_legacy_opts_to_new","_ecdsa","ProjectivePoint","_ecdsa_new_output_to_legacy","beta","basises","assertCompressionIsSupported","encodePoint","_c","bx","decodePoint","uncomp","tail","isValidXY","weierstrassEquation","sqrtError","x3","_4a3","_27b2","aprjpoint","splitEndoScalarN","basis","a1","b1","a2","k1","k2","k1neg","k2neg","MAX_NUM","_splitEndoScalar","finishEndo","endoBeta","k1p","k2p","U1","U2","b3","t0","t1","t2","t3","t4","t5","fake","k1f","k2f","sc","p1","p2","mulEndoUnsafe","multiplyAndAddUnsafe","px","py","pz","fromPrivateKey","weierstrassN","secp256k1_CURVE","secp256k1_ENDO","Fpk1","_6n","_11n","_22n","_23n","_44n","_88n","b6","b9","b11","b22","b44","b88","b176","b220","b223","secp256k1","curveDef","defHash","createCurve","generateKeypair","privateScalar","isOnCurve","toBuffer","Buffer","isBuffer","properties","serialize","SOLANA_SCHEMA","deserialize","decodeUnchecked","deserializeUnchecked","_PublicKey","PUBLIC_KEY_LENGTH","uniquePublicKeyCounter","PublicKey","_bn","isPublicKeyData","decoded","unique","eq","toBase58","toJSON","toArrayLike","zeroPad","alloc","copy","toStringTag","createWithSeed","fromPublicKey","programId","concat","publicKeyBytes","createProgramAddressSync","seeds","createProgramAddress","findProgramAddressSync","address","nonce","seedsWithNonce","findProgramAddress","pubkeyData","default","kind","PACKET_DATA_SIZE","TransactionExpiredBlockheightExceededError","defineProperty","TransactionExpiredTimeoutError","timeoutSeconds","toFixed","TransactionExpiredNonceInvalidError","MessageAccountKeys","staticAccountKeys","accountKeysFromLookups","keySegments","writable","readonly","index","keySegment","flat","compileInstructions","instructions","U8_MAX","keyIndexMap","findKeyIndex","keyIndex","instruction","programIdIndex","accountKeyIndexes","meta","pubkey","property","rustString","rsl","_decode","bind","_encode","rslShim","chars","span","getAlloc","getItemAlloc","elementLayout","layout","decodeLength","elem","encodeLength","rem_len","CompiledKeys","payer","keyMetaMap","compile","getOrInsertDefault","keyMeta","isSigner","isWritable","isInvoked","payerKeyMeta","ix","accountMeta","getMessageComponents","mapEntries","writableSigners","readonlySigners","writableNonSigners","readonlyNonSigners","header","numRequiredSignatures","numReadonlySignedAccounts","numReadonlyUnsignedAccounts","payerAddress","extractTableLookup","lookupTable","writableIndexes","drainedWritableKeys","drainKeysFoundInLookupTable","addresses","readonlyIndexes","drainedReadonlyKeys","accountKey","lookupTableEntries","keyMetaFilter","lookupTableIndexes","drainedKeys","lookupTableIndex","findIndex","entry","END_OF_BUFFER_ERROR_MESSAGE","guardedShift","byteArray","guardedSplice","start","splice","Message","accountKeys","recentBlockhash","indexToProgramIds","account","compiledInstructions","accounts","addressTableLookups","getAccountKeys","compiledKeys","payerKey","isAccountSigner","isAccountWritable","numSignedAccounts","isProgramId","has","programIds","values","nonProgramIds","numKeys","keyCount","keyIndicesCount","dataCount","keyIndices","dataLength","instructionCount","instructionBuffer","instructionBufferLength","signDataLayout","transaction","signData","accountCount","dataSlice","messageArgs","MessageV0","numAccountKeysFromLookups","count","lookup","addressLookupTableAccounts","resolveAddressTableLookups","numStaticAccountKeys","tableLookup","tableAccount","find","lookupTableAccounts","extractResult","addressTableLookup","encodedStaticAccountKeysLength","serializedInstructions","serializeInstructions","encodedInstructionsLength","serializedAddressTableLookups","serializeAddressTableLookups","encodedAddressTableLookupsLength","messageLayout","serializedMessage","serializedMessageLength","staticAccountKeysLength","instructionsLength","addressTableLookupsLength","serializedLength","encodedAccountKeyIndexesLength","encodedDataLength","encodedWritableIndexesLength","encodedReadonlyIndexesLength","maskedPrefix","addressTableLookupsCount","VersionedMessage","deserializeMessageVersion","DEFAULT_SIGNATURE","TransactionInstruction","Transaction","signatures","feePayer","lastValidBlockHeight","nonceInfo","minNonceContextSlot","_message","_json","hasOwnProperty","call","minContextSlot","blockhash","nonceInstruction","signers","items","compileMessage","console","warn","accountMetas","uniqueMetas","pubkeyString","uniqueIndex","sort","localeCompare","localeMatcher","usage","sensitivity","ignorePunctuation","numeric","caseFirst","feePayerIndex","payerMeta","unshift","signedKeys","unsignedKeys","indexOf","_compile","every","pair","serializeMessage","getEstimatedFee","connection","getFeeForMessage","setSigners","seen","uniqueSigners","signer","_partialSign","partialSign","_addSignature","addSignature","sigpair","verifySignatures","requireAllSignatures","_getMessageSignednessErrors","errors","missing","invalid","sigErrors","errorMessage","_serialize","signatureCount","transactionLength","wireTransaction","keyObj","populate","sigPubkeyPair","VersionedTransaction","defaultSignatures","encodedSignaturesLength","transactionLayout","serializedTransaction","serializedTransactionLength","signaturesLength","messageData","signerPubkeys","signerIndex","SYSVAR_CLOCK_PUBKEY","SYSVAR_RECENT_BLOCKHASHES_PUBKEY","SYSVAR_RENT_PUBKEY","SYSVAR_STAKE_HISTORY_PUBKEY","SendTransactionError","action","transactionMessage","logs","maybeLogsOutput","guideText","transactionLogs","transactionError","cachedLogs","getLogs","Promise","resolve","reject","getTransaction","then","tx","logMessages","catch","async","sendAndConfirmTransaction","sendOptions","skipPreflight","preflightCommitment","commitment","maxRetries","sendTransaction","confirmTransaction","abortSignal","nonceAccountPubkey","nonceValue","sleep","ms","setTimeout","encodeData","allocLength","layoutFields","FeeCalculatorLayout","NONCE_ACCOUNT_LENGTH","bigIntLayout","src","bigInt","SYSTEM_INSTRUCTION_LAYOUTS","Create","Assign","Transfer","CreateWithSeed","AdvanceNonceAccount","WithdrawNonceAccount","InitializeNonceAccount","AuthorizeNonceAccount","Allocate","AllocateWithSeed","AssignWithSeed","TransferWithSeed","UpgradeNonceAccount","SystemProgram","createAccount","lamports","space","fromPubkey","newAccountPubkey","transfer","basePubkey","toPubkey","accountPubkey","createAccountWithSeed","createNonceAccount","noncePubkey","initParams","authorizedPubkey","nonceInitialize","authorized","instructionData","nonceAdvance","nonceWithdraw","nonceAuthorize","newAuthorizedPubkey","allocate","Loader","getMinNumSignatures","chunkSize","load","program","balanceNeeded","getMinimumBalanceForRentExemption","programInfo","getAccountInfo","executable","owner","dataLayout","transactions","bytesLengthPadding","_rpcEndpoint","REQUESTS_PER_SECOND","all","deployCommitment","finalizeSignature","getSlot","slot","MS_PER_SLOT","fetch","PublicKeyFromString","RawAccountDataResult","BufferFromRawAccountData","createRpcResult","jsonrpc","UnknownRpcResult","jsonRpcResult","jsonRpcResultAndContext","notificationResultAndContext","GetInflationGovernorResult","foundation","foundationTerm","initial","taper","terminal","GetRecentPrioritizationFeesResult","epoch","effectiveSlot","amount","postBalance","commission","prioritizationFee","GetInflationRateResult","total","GetEpochInfoResult","slotIndex","slotsInEpoch","absoluteSlot","blockHeight","transactionCount","GetEpochScheduleResult","slotsPerEpoch","leaderScheduleSlotOffset","warmup","firstNormalEpoch","firstNormalSlot","GetLeaderScheduleResult","TransactionErrorResult","SignatureStatusResult","SignatureReceivedResult","ParsedInstructionStruct","parsed","PartiallyDecodedInstructionStruct","rentEpoch","unitsConsumed","returnData","innerInstructions","byIdentity","firstSlot","lastSlot","circulating","nonCirculating","nonCirculatingAccounts","TokenAmountResult","uiAmount","decimals","uiAmountString","ParsedAccountDataResult","AccountInfoResult","ParsedOrRawAccountData","ParsedAccountInfoResult","ProgramAccountInfoResult","active","inactive","memo","blockTime","subscription","SlotInfoResult","parent","SlotUpdateResult","timestamp","stats","numTransactionEntries","numSuccessfulTransactions","numFailedTransactions","maxTransactionsPerEntry","VoteAccountInfoResult","gossip","tpu","rpc","votePubkey","nodePubkey","activatedStake","epochVoteAccount","epochCredits","lastVote","rootSlot","ConfirmationStatus","delinquent","SignatureStatusResponse","confirmations","confirmationStatus","AddressTableLookupStruct","ConfirmedTransactionResult","AnnotatedAccountKey","source","ConfirmedTransactionAccountsModeResult","ParsedInstructionResult","RawInstructionResult","ParsedOrRawInstruction","ParsedConfirmedTransactionResult","TokenBalanceResult","accountIndex","mint","uiTokenAmount","LoadedAddressesResult","ConfirmedTransactionMetaResult","fee","preBalances","postBalances","preTokenBalances","postTokenBalances","loadedAddresses","computeUnitsConsumed","costUnits","ParsedConfirmedTransactionMetaResult","TransactionVersionStruct","RewardsResult","rewardType","LogsResult","previousBlockhash","parentSlot","rewards","numTransactions","numSlots","samplePeriodSecs","feeCalculator","lamportsPerSignature","Keypair","keypair","_keypair","generate","fromSecretKey","computedPublicKey","ii","fromSeed","CreateLookupTable","FreezeLookupTable","ExtendLookupTable","DeactivateLookupTable","CloseLookupTable","RequestUnits","RequestHeapFrame","SetComputeUnitLimit","SetComputeUnitPrice","ED25519_INSTRUCTION_LAYOUT","Ed25519Program","createInstructionWithPublicKey","instructionIndex","publicKeyOffset","signatureOffset","messageDataOffset","numSignatures","padding","signatureInstructionIndex","publicKeyInstructionIndex","messageDataSize","messageInstructionIndex","createInstructionWithPrivateKey","publicKeyCreate","SECP256K1_INSTRUCTION_LAYOUT","Secp256k1Program","publicKeyToEthAddress","recoveryId","createInstructionWithEthAddress","ethAddress","rawAddress","startsWith","substr","ethAddressOffset","ethAddressInstructionIndex","pkey","msgHash","privKey","ecdsaSign","_Lockup","STAKE_CONFIG_ID","Lockup","unixTimestamp","custodian","STAKE_INSTRUCTION_LAYOUTS","Initialize","lockup","Authorize","Delegate","Split","Withdraw","Deactivate","Merge","AuthorizeWithSeed","Staker","Withdrawer","StakeProgram","initialize","stakePubkey","maybeLockup","staker","withdrawer","delegate","authorize","stakeAuthorizationType","custodianPubkey","newAuthorized","authorizeWithSeed","authorityBase","authoritySeed","authorityOwner","splitInstruction","splitStakePubkey","split","rentExemptReserve","splitWithSeed","merge","sourceStakePubKey","withdraw","deactivate","VOTE_INSTRUCTION_LAYOUTS","InitializeAccount","voteInit","UpdateValidatorIdentity","voteAuthorizeWithSeedArgs","Voter","VoteProgram","initializeAccount","authorizedVoter","authorizedWithdrawer","voteAuthorizationType","currentAuthorityDerivedKeyBasePubkey","currentAuthorityDerivedKeyOwnerPubkey","currentAuthorityDerivedKeySeed","authorizedWithdrawerPubkey","safeWithdraw","currentVoteAccountBalance","rentExemptMinimum","updateValidatorIdentity","website","details","iconUrl","keybaseUsername","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","Infinity","rt","log","LN2","HpkeError","EncapError","DecapError","ExportError","SealError","OpenError","MessageLimitReachedError","DeriveKeyPairError","dntGlobalThis","baseObj","extObj","Proxy","_target","prop","_receiver","deleteProperty","success","ownKeys","baseKeys","Reflect","extKeys","extKeysSet","desc","getOwnPropertyDescriptor","NativeAlgorithm","enumerable","configurable","_setup","_api","subtle","webcrypto","loadSubtleCrypto","INPUT_LENGTH_LIMIT","w","ret","LABEL_EAE_PRK","LABEL_SHARED_SECRET","Dhkem","prim","kdf","_prim","_kdf","suiteId","serializePublicKey","deserializePublicKey","serializePrivateKey","deserializePrivateKey","importKey","isPublic","generateKeyPair","deriveKeyPair","ikm","encap","ke","ekm","enc","pkrm","recipientPublicKey","dh","kemContext","senderKey","sks","pks","derivePublicKey","pksm","concat3","sharedSecret","_generateSharedSecret","decap","pke","skr","recipientKey","pkr","senderPublicKey","labeledIkm","buildLabeledIkm","labeledInfo","buildLabeledInfo","secretSize","extractAndExpand","KEM_USAGES","Bignum","_num","lessThan","LABEL_CANDIDATE","ORDER_P_256","ORDER_P_384","ORDER_P_521","PKCS8_ALG_ID_P_256","PKCS8_ALG_ID_P_384","PKCS8_ALG_ID_P_521","Ec","kem","hkdf","_hkdf","_alg","namedCurve","_nPk","_nSk","_nDh","_order","_bitmask","_pkcs8AlgId","exportKey","_importRawKey","jwk","base64","replace","byteString","atob","base64UrlToBytes","_importJWK","generateKey","dkpPrk","labeledExtract","bn","counter","labeledExpand","sk","_deserializePkcs8Key","pk","deriveBits","public","crv","pkcs8Key","HPKE_VERSION","HkdfNative","_suiteId","label","_checkInit","info","extract","salt","hashSize","algHash","expand","prk","okm","cur","baseKey","HkdfSha256Native","arguments","AEAD_USAGES","AesGcmContext","_rawKey","seal","iv","aad","_setupKey","alg","additionalData","encrypt","open","decrypt","_importKey","Aes128Gcm","createEncryptionContext","Aes256Gcm","emitNotSupported","_resolve","LABEL_SEC","ExporterContextImpl","api","exporterSecret","_data","_aad","exporterContext","RecipientExporterContextImpl","SenderExporterContextImpl","EncryptionContextImpl","baseNonce","_aead","aead","_nK","keySize","_nN","nonceSize","_nT","tagSize","_ctx","computeNonce","xor","incrementSeq","MAX_SAFE_INTEGER","_Mutex_locked","Mutex","lock","releaseLock","nextLock","previousLock","receiver","__classPrivateFieldGet","__classPrivateFieldSet","_RecipientContextImpl_mutex","RecipientContextImpl","release","pt","_SenderContextImpl_mutex","SenderContextImpl","ct","LABEL_BASE_NONCE","LABEL_EXP","LABEL_INFO_HASH","LABEL_KEY","LABEL_PSK_ID_HASH","LABEL_SECRET","SUITE_ID_HEADER_HPKE","CipherSuiteNative","_kem","createSenderContext","_validateInputLength","mode","psk","_keyScheduleS","createRecipientContext","_keyScheduleR","_keySchedule","pskId","pskIdHash","infoHash","keyScheduleContext","exporterSecretInfo","keyInfo","baseNonceInfo","DhkemP256HkdfSha256Native","CipherSuite","DhkemP256HkdfSha256","HkdfSha256","inRange","ToDictionary","o","Stream","tokens","endOfStream","prepend","token","pop","decoderError","fatal","opt_code_point","DEFAULT_ENCODING","TextDecoder","encoding","toLowerCase","_streaming","_BOMseen","_decoder","_fatal","Boolean","_ignoreBOM","_encoder","_options","UTF8Decoder","utf8_code_point","utf8_bytes_seen","utf8_bytes_needed","utf8_lower_boundary","utf8_upper_boundary","handler","stream","bite","code_point","UTF8Encoder","temp","input_stream","code_points","apply","cp","fromCharCode","codePointsToString","opt_string","string","stringToCodePoints","ieee754","customInspectSymbol","SlowBuffer","INSPECT_MAX_BYTES","K_MAX_LENGTH","createBuffer","RangeError","setPrototypeOf","encodingOrOffset","allocUnsafe","isEncoding","actual","fromString","arrayView","isInstance","fromArrayBuffer","fromArrayLike","fromArrayView","SharedArrayBuffer","valueOf","obj","checked","numberIsNaN","fromObject","toPrimitive","assertSize","mustMatch","loweredCase","utf8ToBytes","base64ToBytes","slowToString","end","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","readUInt16BE","foundIndex","found","hexWrite","remaining","strLen","utf8Write","blitBuffer","asciiWrite","asciiToBytes","base64Write","ucs2Write","units","lo","utf16leToBytes","fromByteArray","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","codePoints","MAX_ARGUMENTS_LENGTH","decodeCodePointsArray","kMaxLength","TYPED_ARRAY_SUPPORT","proto","foo","typedArraySupport","poolSize","allocUnsafeSlow","_isBuffer","compare","list","swap16","swap32","swap64","toLocaleString","inspect","trim","target","thisStart","thisEnd","thisCopy","targetCopy","isFinite","_arr","hexSliceLookupTable","checkOffset","ext","checkInt","wrtBigUInt64LE","checkIntBI","wrtBigUInt64BE","checkIEEE754","writeFloat","littleEndian","noAssert","writeDouble","newBuf","readUintLE","readUIntLE","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readUInt32BE","readBigUInt64LE","defineBigIntMethod","validateNumber","last","boundsError","readBigUInt64BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readBigInt64LE","readBigInt64BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUintLE","writeUIntLE","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeUInt32BE","writeBigUInt64LE","writeBigUInt64BE","writeIntLE","limit","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeBigInt64LE","writeBigInt64BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","sym","getMessage","Base","stack","addNumericalSeparator","ERR_OUT_OF_RANGE","checkBounds","ERR_INVALID_ARG_TYPE","ERR_BUFFER_OUT_OF_BOUNDS","received","isInteger","INVALID_BASE64_RE","leadSurrogate","toByteArray","base64clean","dst","alphabet","table","i16","BufferBigIntNotDefined","rnds8","rng","msCrypto","byteToHex","test","rnds","random","_Buffer","ALPHABET","BASE_MAP","charAt","xc","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","charCode","carry","it3","it4","vch","pbegin","pend","b58","it1","it2","repeat","inherits","ctor","superCtor","super_","TempCtor","BN","isBN","negative","words","red","_init","wordSize","parseHex4Bits","parseHexByte","lowerBound","parseBase","move","dest","cmp","_initNumber","_initArray","_parseHex","_parseBase","toArray","off","_strip","limbLen","limbPow","imuln","_iaddn","_move","_expand","_normSign","for","zeros","groupSizes","groupBases","smallMulTo","ncarry","rword","maxJ","groupSize","groupBase","modrn","idivn","toNumber","ArrayType","reqLength","_toArrayLikeLE","position","_toArrayLikeBE","clz32","_countBits","_zeroBits","zeroBits","toTwos","width","inotn","iaddn","fromTwos","testn","notn","ineg","iuor","ior","or","uor","iuand","iand","and","uand","iuxor","ixor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","iadd","isub","comb10MulTo","a0","al0","ah0","al1","ah1","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","b0","bl0","bh0","bl1","bh1","bl2","bh2","bl3","bh3","bl4","bh4","bl5","bh5","bl6","bh6","b7","bl7","bh7","b8","bl8","bh8","bl9","bh9","w0","imul","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","bigMulTo","hncarry","jumboMulTo","FFTM","mulTo","makeRBT","N","revBin","rb","permute","rbt","rws","iws","rtws","itws","rtwdf","cos","itwdf","sin","rtwdf_","itwdf_","re","ie","ro","io","rx","guessLen13b","odd","conjugate","normalize13b","ws","convert13b","stub","ph","mulp","rwst","iwst","nrws","nrwst","niwst","rmws","mulf","isNegNum","muln","isqr","toBitArray","iushln","carryMask","newCarry","ishln","iushrn","hint","extended","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","subn","iabs","_ishlnsubmul","_wordDiv","bhi","qj","divmod","positive","divn","umod","divRound","dm","half","r2","andln","modn","egcd","g","isEven","yp","xp","im","jm","gcd","_invmp","x1","cmpn","invm","bincn","ucmp","gtn","gt","gten","gte","ltn","lt","lten","lte","eqn","Red","toRed","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","_tmp","K256","P224","P192","P25519","prime","_prime","Mont","imod","rinv","minv","ireduce","rlen","imulK","strip","output","mod3","nOne","lpow","z","wnd","currentLen","mont","b64","lens","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","parts","maxChunkLength","len2","encodeChunk","tripletToBase64","au8","toU8","h2b","isPoint","Gpows","strict","b2n_LE","safe","n2b_32LE","b2h","padh","concatB","arrs","md","pow2","RM1","pow_2_252_3","modL_LE","_shaS","sha512s","priv","hash2extK","hashFinish","asynchronous","etc","sha512Async","sha512a","hashable","_sign","cr","concatBytes","messages","sha512Sync","defineProperties","cnd","off1","off2","cnd1","cnd2","u8","buffer_1","checkUint8Array","uint8ArrayToBuffer","Layout","makeDestinationObject","getSpan","replicate","rv","fromArray","nameWithProperty","ExternalLayout","isCount","OffsetLayout","UInt","UIntBE","V2E32","divmodInt64","hi32","lo32","roundedInt64","NearUInt64","NearInt64","Sequence","idx","elo","Structure","decodePrefixes","fd","fsp","firstOffset","lastOffset","lastWrote","fv","layoutFor","offsetOf","Blob","srcBuffer","Events","EE","once","addListener","emitter","event","listener","evt","_events","_eventsCount","clearEvent","EventEmitter","__proto__","eventNames","events","names","getOwnPropertySymbols","listeners","handlers","ee","listenerCount","emit","removeListener","on","removeAllListeners","prefixed","__createBinding","__setModuleDefault","__decorate","decorators","decorate","__importStar","__esModule","__importDefault","BinaryReader","BinaryWriter","BorshError","baseDecode","baseEncode","bn_js_1","bs58_1","textDecoder","INITIAL_LENGTH","fieldPath","originalMessage","addToFieldPath","maybeResize","writeU8","writeU16","writeU32","writeU64","writeBuffer","writeU128","writeU256","writeU512","writeString","writeFixedArray","writeArray","handlingRangeError","propertyKey","propertyDescriptor","originalMethod","readU8","readU16","readU32","readU64","readBuffer","readU128","readU256","readU512","readString","readFixedArray","readArray","capitalizeFirstLetter","toUpperCase","serializeField","fieldType","writer","serializeStruct","borshSerialize","structSchema","deserializeField","reader","deserializeStruct","classType","borshDeserialize","fieldValue","Writer","Reader","basex","exists","SHA2","sha512","copyProps","SafeBuffer"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/bundle.f14f48a41b2945673e48.js b/export-and-sign/dist/bundle.f14f48a41b2945673e48.js new file mode 100644 index 0000000..dfaedfc --- /dev/null +++ b/export-and-sign/dist/bundle.f14f48a41b2945673e48.js @@ -0,0 +1,3 @@ +/*! For license information please see bundle.f14f48a41b2945673e48.js.LICENSE.txt */ +(()=>{var e,t,r,n,o,a={758:(e,t,r)=>{"use strict";var n=r(598),o=r(810);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(a(e)+" is not iterable")}function l(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}}function p(e,t,r,n,o){var a=d(e,t,r,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})}function d(e,t,r,n,o){return new y(v().w(e,t,r,n),o||Promise)}function y(e,t){function r(n,o,a,i){try{var u=e[n](o),c=u.value;return c instanceof b?t.resolve(c.v).then(function(e){r("next",e,a,i)},function(e){r("throw",e,a,i)}):t.resolve(c).then(function(e){u.value=e,a(u)},function(e){return r("throw",e,a,i)})}catch(e){i(e)}}var n;this.next||(m(y.prototype),m(y.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),m(this,"_invoke",function(e,o,a){function i(){return new t(function(t,n){r(e,a,t,n)})}return n=n?n.then(i,i):i()},!0)}function v(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var c=n&&n.prototype instanceof u?n:u,s=Object.create(c.prototype);return m(s,"_invoke",function(r,n,o){var a,u,c,s=0,f=o||[],l=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return a=t,u=0,c=e,p.n=r,i}};function d(r,n){for(u=r,c=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(c=a[(u=a[4])?5:(u=3,3)],a[4]=a[5]=e):a[0]<=d&&((o=r<2&&dn||n>y)&&(a[4]=r,a[5]=n,p.n=y,u=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,y),u=f,c=y;(t=u<2?e:c)||!l;){a||(u?u<3?(u>1&&(p.n=-1),d(u,c)):p.n=c:p.v=c);try{if(s=2,a){if(u||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,u<2&&(u=0)}else 1===u&&(t=a.return)&&t.call(a),u<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),u=1);a=e}else if((t=(l=p.n<0)?c:r.call(n,p))!==i)break}catch(t){a=e,u=1,c=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function u(){}function c(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(m(t={},n,function(){return this}),t),l=s.prototype=u.prototype=Object.create(f);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,m(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return c.prototype=s,m(l,"constructor",s),m(s,"constructor",c),c.displayName="GeneratorFunction",m(s,o,"GeneratorFunction"),m(l),m(l,o,"Generator"),m(l,n,function(){return this}),m(l,"toString",function(){return"[object Generator]"}),(v=function(){return{w:a,m:p}})()}function m(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}m=function(e,t,r,n){function a(t,r){m(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},m(e,t,r,n)}function b(e,t){this.v=e,this.k=t}function h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(e){s=!0,o=e}finally{try{if(!c&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw o}}return u}}(e,t)||w(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e){return function(e){if(Array.isArray(e))return x(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||w(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function w(e,t){if(e){if("string"==typeof e)return x(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?x(e,t):void 0}}function x(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function j(e){return I.apply(this,arguments)}function I(){return(I=S(s().mark(function e(t){return s().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,crypto.subtle.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}},e)}))).apply(this,arguments)}function N(){return(N=S(s().mark(function e(){return s().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!_()){e.next=2;break}throw new Error("Doubly iframed");case 2:return e.next=4,D();case 4:if(null!==e.sent){e.next=10;break}return e.next=8,T();case 8:R(e.sent);case 10:case"end":return e.stop()}},e)}))).apply(this,arguments)}function T(){return A.apply(this,arguments)}function A(){return(A=S(s().mark(function e(){var t;return s().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return t=e.sent,e.next=5,crypto.subtle.exportKey("jwk",t.privateKey);case 5:return e.abrupt("return",e.sent);case 6:case"end":return e.stop()}},e)}))).apply(this,arguments)}function D(){var e=M(O);return e?JSON.parse(e):null}function R(e){K(O,JSON.stringify(e),1728e5)}function K(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function M(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return r.hasOwnProperty("expiry")&&r.hasOwnProperty("value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function U(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function G(e){return g(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function C(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(g(n),g(e)))}if(r<0){for(var o=-1*r,a=0,i=0;i0;)r.push(o%58),o=o/58|0}for(var i=0;i0;){var u=r[i];a=(u=void 0===u?a:58*u+a)>>8,r[i]=u%256,i++}}var c=n.concat(r.reverse());return new Uint8Array(c)}function z(){return(z=S(s().mark(function e(t,r,n){var o;return s().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.t0=r,e.next="SOLANA"===e.t0?3:"HEXADECIMAL"===e.t0?13:14;break;case 3:if(n){e.next=5;break}throw new Error("public key must be specified for SOLANA key format");case 5:if(32===t.length){e.next=7;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 7:if(32===n.length){e.next=9;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 9:return(o=new Uint8Array(64)).set(t,0),o.set(n,32),e.abrupt("return",H(o));case 13:return e.abrupt("return","0x"+G(t));case 14:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.abrupt("return","0x"+G(t));case 16:case"end":return e.stop()}},e)}))).apply(this,arguments)}function $(e,t){var r={},n={padding:"^(\\d+(px|em|%|rem) ?){1,4}$",margin:"^(\\d+(px|em|%|rem) ?){1,4}$",borderWidth:"^(\\d+(px|em|rem) ?){1,4}$",borderStyle:"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$",borderColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",borderRadius:"^(\\d+(px|em|%|rem) ?){1,4}$",fontSize:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$",fontWeight:"^(normal|bold|bolder|lighter|\\d{3})$",fontFamily:'^[^";<>]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t=h(e,2),o=t[0],a=t[1],i=o.trim();if(0===i.length)throw new Error("css style property cannot be empty");var u=n[i];if(!u)throw new Error('invalid or unsupported css style property: "'.concat(i,'"'));var c=new RegExp(u),s=a.trim();if(0==s.length)throw new Error('css style for "'.concat(i,'" is empty'));if(!c.test(s))throw new Error('invalid css style value for property "'.concat(i,'"'));r[i]=s}),r}var q={initEmbeddedKey:function(){return N.apply(this,arguments)},generateTargetKey:T,setItemWithExpiry:K,getItemWithExpiry:M,getEmbeddedKey:D,setEmbeddedKey:R,onResetEmbeddedKey:function(){window.localStorage.removeItem(O),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:function(e){return Y.apply(this,arguments)},base58Encode:H,base58Decode:J,encodeKey:function(e,t,r){return z.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),P?P.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),F("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:F,uint8arrayFromHexString:U,uint8arrayToHexString:G,setParentFrameMessageChannelPort:function(e){P=e},normalizePadding:C,fromDerSignature:B,additionalAssociatedData:function(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))},verifyEnclaveSignature:function(e,t,r){return L.apply(this,arguments)},getEd25519PublicKey:function(e){return n.jn.sha512Sync=function(){var e;return o.Zf((e=n.jn).concatBytes.apply(e,arguments))},n.lG(e)},applySettings:function(e){var t={};if(!e)return JSON.stringify(t);var r=JSON.parse(e);if(r.styles){var n=document.getElementById("key-div");if(!n)throw new Error("no key-div HTML element found to apply settings to.");var o=$(r.styles);Object.entries(o).forEach(function(e){var t=h(e,2),r=t[0],o=t[1];n.style[r]=o}),t.styles=o}return JSON.stringify(t)},validateStyles:$,getSettings:function(){var e=window.localStorage.getItem(k);return e?JSON.parse(e):null},setSettings:function(e){window.localStorage.setItem(k,JSON.stringify(e))},parsePrivateKey:function(e){if(Array.isArray(e))return new Uint8Array(e);if("string"==typeof e){if(e.startsWith("0x")&&(e=e.slice(2)),64===e.length&&/^[0-9a-fA-F]+$/.test(e))return U(e);try{return J(e)}catch(e){throw new Error("Invalid private key format. Use hex (64 chars) or base58 format.")}}throw new Error("Private key must be a string (hex/base58) or number array")}},W=r(112),X=r(255);function V(e){return V="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},V(e)}function Q(){var e=oe(),t=e.m(Q),r=(Object.getPrototypeOf?Object.getPrototypeOf(t):t.__proto__).constructor;function n(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===r||"GeneratorFunction"===(t.displayName||t.name))}var o={throw:1,return:2,break:3,continue:3};function a(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,o[e],t)},delegateYield:function(e,o,a){return t.resultName=o,r(n.d,Z(e),a)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(Q=function(){return{wrap:function(t,r,n,o){return e.w(a(t),r,n,o&&o.reverse())},isGeneratorFunction:n,mark:e.m,awrap:function(e,t){return new ie(e,t)},AsyncIterator:ne,async:function(e,t,r,o,i){return(n(t)?re:te)(a(e),t,r,o,i)},keys:ee,values:Z}})()}function Z(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(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(V(e)+" is not iterable")}function ee(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}}function te(e,t,r,n,o){var a=re(e,t,r,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})}function re(e,t,r,n,o){return new ne(oe().w(e,t,r,n),o||Promise)}function ne(e,t){function r(n,o,a,i){try{var u=e[n](o),c=u.value;return c instanceof ie?t.resolve(c.v).then(function(e){r("next",e,a,i)},function(e){r("throw",e,a,i)}):t.resolve(c).then(function(e){u.value=e,a(u)},function(e){return r("throw",e,a,i)})}catch(e){i(e)}}var n;this.next||(ae(ne.prototype),ae(ne.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),ae(this,"_invoke",function(e,o,a){function i(){return new t(function(t,n){r(e,a,t,n)})}return n=n?n.then(i,i):i()},!0)}function oe(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var c=n&&n.prototype instanceof u?n:u,s=Object.create(c.prototype);return ae(s,"_invoke",function(r,n,o){var a,u,c,s=0,f=o||[],l=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return a=t,u=0,c=e,p.n=r,i}};function d(r,n){for(u=r,c=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(c=a[(u=a[4])?5:(u=3,3)],a[4]=a[5]=e):a[0]<=d&&((o=r<2&&dn||n>y)&&(a[4]=r,a[5]=n,p.n=y,u=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,y),u=f,c=y;(t=u<2?e:c)||!l;){a||(u?u<3?(u>1&&(p.n=-1),d(u,c)):p.n=c:p.v=c);try{if(s=2,a){if(u||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,u<2&&(u=0)}else 1===u&&(t=a.return)&&t.call(a),u<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),u=1);a=e}else if((t=(l=p.n<0)?c:r.call(n,p))!==i)break}catch(t){a=e,u=1,c=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function u(){}function c(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ae(t={},n,function(){return this}),t),l=s.prototype=u.prototype=Object.create(f);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ae(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return c.prototype=s,ae(l,"constructor",s),ae(s,"constructor",c),c.displayName="GeneratorFunction",ae(s,o,"GeneratorFunction"),ae(l),ae(l,o,"Generator"),ae(l,n,function(){return this}),ae(l,"toString",function(){return"[object Generator]"}),(oe=function(){return{w:a,m:p}})()}function ae(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}ae=function(e,t,r,n){function a(t,r){ae(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},ae(e,t,r,n)}function ie(e,t){this.v=e,this.k=t}function ue(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function ce(e){for(var t=1;t=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(ye(e)+" is not iterable")}function we(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}}function xe(e,t,r,n,o){var a=Ee(e,t,r,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})}function Ee(e,t,r,n,o){return new Se(Oe().w(e,t,r,n),o||Promise)}function Se(e,t){function r(n,o,a,i){try{var u=e[n](o),c=u.value;return c instanceof Pe?t.resolve(c.v).then(function(e){r("next",e,a,i)},function(e){r("throw",e,a,i)}):t.resolve(c).then(function(e){u.value=e,a(u)},function(e){return r("throw",e,a,i)})}catch(e){i(e)}}var n;this.next||(ke(Se.prototype),ke(Se.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),ke(this,"_invoke",function(e,o,a){function i(){return new t(function(t,n){r(e,a,t,n)})}return n=n?n.then(i,i):i()},!0)}function Oe(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var c=n&&n.prototype instanceof u?n:u,s=Object.create(c.prototype);return ke(s,"_invoke",function(r,n,o){var a,u,c,s=0,f=o||[],l=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return a=t,u=0,c=e,p.n=r,i}};function d(r,n){for(u=r,c=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(c=a[(u=a[4])?5:(u=3,3)],a[4]=a[5]=e):a[0]<=d&&((o=r<2&&dn||n>y)&&(a[4]=r,a[5]=n,p.n=y,u=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,y),u=f,c=y;(t=u<2?e:c)||!l;){a||(u?u<3?(u>1&&(p.n=-1),d(u,c)):p.n=c:p.v=c);try{if(s=2,a){if(u||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,u<2&&(u=0)}else 1===u&&(t=a.return)&&t.call(a),u<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),u=1);a=e}else if((t=(l=p.n<0)?c:r.call(n,p))!==i)break}catch(t){a=e,u=1,c=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function u(){}function c(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ke(t={},n,function(){return this}),t),l=s.prototype=u.prototype=Object.create(f);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ke(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return c.prototype=s,ke(l,"constructor",s),ke(s,"constructor",c),c.displayName="GeneratorFunction",ke(s,o,"GeneratorFunction"),ke(l),ke(l,o,"Generator"),ke(l,n,function(){return this}),ke(l,"toString",function(){return"[object Generator]"}),(Oe=function(){return{w:a,m:p}})()}function ke(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}ke=function(e,t,r,n){function a(t,r){ke(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},ke(e,t,r,n)}function Pe(e,t){this.v=e,this.k=t}function _e(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,u=[],c=!0,s=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);c=!0);}catch(e){s=!0,o=e}finally{try{if(!c&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw o}}return u}}(e,t)||function(e,t){if(e){if("string"==typeof e)return je(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?je(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function je(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 22:if(u.organizationId&&u.organizationId===r){e.next=24;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(u.organizationId,"."));case 24:if(u.encappedPublic){e.next=26;break}throw new Error('missing "encappedPublic" in bundle signed data');case 26:if(u.ciphertext){e.next=28;break}throw new Error('missing "ciphertext" in bundle signed data');case 28:return o=q.uint8arrayFromHexString(u.encappedPublic),a=q.uint8arrayFromHexString(u.ciphertext),e.abrupt("break",32);case 31:throw new Error("unsupported version: ".concat(i.version));case 32:return e.next=34,q.getEmbeddedKey();case 34:return c=e.sent,e.next=37,n({ciphertextBuf:a,encappedKeyBuf:o,receiverPrivJwk:c});case 37:return e.abrupt("return",e.sent);case 38:case"end":return e.stop()}},e)})),Ke.apply(this,arguments)}function Me(e){return Ue.apply(this,arguments)}function Ue(){return(Ue=Ne(he().mark(function e(t){var r,n,o;return he().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=q.getEmbeddedKey()){e.next=4;break}return q.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.abrupt("return");case 4:return e.next=6,q.p256JWKPrivateToPublic(r);case 6:n=e.sent,o=q.uint8arrayToHexString(n),q.sendMessageUp("EMBEDDED_PUBLIC_KEY",o,t);case 9:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Ge(e,t,r,n,o,a){return Ce.apply(this,arguments)}function Ce(){return Ce=Ne(he().mark(function e(t,r,n,o,a,i){var u,c,s,f,l,p,d;return he().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Re(n,r,i);case 2:if(u=e.sent,s=new Uint8Array(u),"SOLANA"!==o){e.next=12;break}return f=q.uint8arrayToHexString(s.subarray(0,32)),l=q.getEd25519PublicKey(f),e.next=9,q.encodeKey(s,o,l);case 9:c=e.sent,e.next=15;break;case 12:return e.next=14,q.encodeKey(s,o);case 14:c=e.sent;case 15:if(p=a||"default","SOLANA"!==o){e.next=20;break}d=W.AX.fromSecretKey(q.base58Decode(c)),e.next=24;break;case 20:if("HEXADECIMAL"!==o){e.next=24;break}return e.next=23,qe(Array.from(q.uint8arrayFromHexString(c)));case 23:d=e.sent;case 24:Te=me(me({},Te),{},be({},p,{organizationId:r,privateKey:c,format:o,expiry:(new Date).getTime()+864e5,keypair:d})),q.sendMessageUp("BUNDLE_INJECTED",!0,t);case 26:case"end":return e.stop()}},e)})),Ce.apply(this,arguments)}function Be(e,t){return Le.apply(this,arguments)}function Le(){return(Le=Ne(he().mark(function e(t,r){var n;return he().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=q.applySettings(t),q.setSettings(n),q.sendMessageUp("SETTINGS_APPLIED",!0,r);case 3:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Fe(e,t,r){return Ye.apply(this,arguments)}function Ye(){return(Ye=Ne(he().mark(function e(t,r,n){var o,a,i,u,c,s,f,l,p;return he().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(Ve(a=Te[o=n||"default"],o)){e.next=4;break}return e.abrupt("return");case 4:return e.next=6,Qe(a);case 6:if(i=e.sent,u=JSON.parse(r),c=u.transaction,"SOLANA"!==u.type){e.next=17;break}f=q.uint8arrayFromHexString(c),(l=W.Kt.deserialize(f)).sign([i]),s=l.serialize(),e.next=18;break;case 17:throw new Error("unsupported transaction type");case 18:p=q.uint8arrayToHexString(s),q.sendMessageUp("TRANSACTION_SIGNED",p,t);case 20:case"end":return e.stop()}},e)}))).apply(this,arguments)}function He(e,t,r){return Je.apply(this,arguments)}function Je(){return Je=Ne(he().mark(function e(t,r,a){var i,u,c,s,f,l,p,d,y,v;return he().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(Ve(u=Te[i=a||"default"],i)){e.next=4;break}return e.abrupt("return");case 4:return c=JSON.parse(r),s=c.message,f=c.type,l=Ae.encode(s),e.next=10,Qe(u);case 10:if(d=e.sent,"SOLANA"!==f){e.next=18;break}n.jn.sha512Sync=function(){var e;return o.Zf((e=n.jn).concatBytes.apply(e,arguments))},y=d.secretKey.slice(0,32),v=n._S(l,y),p=q.uint8arrayToHexString(v),e.next=20;break;case 18:return q.sendMessageUp("ERROR","unsupported message type",t),e.abrupt("return");case 20:q.sendMessageUp("MESSAGE_SIGNED",p,t);case 21:case"end":return e.stop()}},e)})),Je.apply(this,arguments)}function ze(e,t){return $e.apply(this,arguments)}function $e(){return($e=Ne(he().mark(function e(t,r){return he().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r){e.next=4;break}return Te={},q.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.abrupt("return");case 4:if(Te[r]){e.next=7;break}return q.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.abrupt("return");case 7:delete Te[r],q.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 9:case"end":return e.stop()}},e)}))).apply(this,arguments)}function qe(e){return We.apply(this,arguments)}function We(){return(We=Ne(he().mark(function e(t){var r,n;return he().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(32!==(r=q.parsePrivateKey(t)).length){e.next=5;break}n=W.AX.fromSeed(r),e.next=10;break;case 5:if(64!==r.length){e.next=9;break}n=W.AX.fromSecretKey(r),e.next=10;break;case 9:throw new Error("Invalid private key length: ".concat(r.length,". Expected 32 or 64 bytes."));case 10:return e.abrupt("return",n);case 11:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Xe(e){Te[e]&&delete Te[e]}function Ve(e,t){if(!e)throw new Error("key bytes not found. Please re-inject export bundle for address ".concat(t," into iframe. Note that address is case sensitive.")).toString();if((new Date).getTime()>=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(Te);r=i.expiry&&t.push(a)}for(var u=0,c=t;u=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(tt(e)+" is not iterable")}function ot(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}}function at(e,t,r,n,o){var a=it(e,t,r,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})}function it(e,t,r,n,o){return new ut(ct().w(e,t,r,n),o||Promise)}function ut(e,t){function r(n,o,a,i){try{var u=e[n](o),c=u.value;return c instanceof ft?t.resolve(c.v).then(function(e){r("next",e,a,i)},function(e){r("throw",e,a,i)}):t.resolve(c).then(function(e){u.value=e,a(u)},function(e){return r("throw",e,a,i)})}catch(e){i(e)}}var n;this.next||(st(ut.prototype),st(ut.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),st(this,"_invoke",function(e,o,a){function i(){return new t(function(t,n){r(e,a,t,n)})}return n=n?n.then(i,i):i()},!0)}function ct(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var c=n&&n.prototype instanceof u?n:u,s=Object.create(c.prototype);return st(s,"_invoke",function(r,n,o){var a,u,c,s=0,f=o||[],l=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return a=t,u=0,c=e,p.n=r,i}};function d(r,n){for(u=r,c=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(c=a[(u=a[4])?5:(u=3,3)],a[4]=a[5]=e):a[0]<=d&&((o=r<2&&dn||n>y)&&(a[4]=r,a[5]=n,p.n=y,u=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,y),u=f,c=y;(t=u<2?e:c)||!l;){a||(u?u<3?(u>1&&(p.n=-1),d(u,c)):p.n=c:p.v=c);try{if(s=2,a){if(u||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,u<2&&(u=0)}else 1===u&&(t=a.return)&&t.call(a),u<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),u=1);a=e}else if((t=(l=p.n<0)?c:r.call(n,p))!==i)break}catch(t){a=e,u=1,c=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function u(){}function c(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(st(t={},n,function(){return this}),t),l=s.prototype=u.prototype=Object.create(f);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,st(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return c.prototype=s,st(l,"constructor",s),st(s,"constructor",c),c.displayName="GeneratorFunction",st(s,o,"GeneratorFunction"),st(l),st(l,o,"Generator"),st(l,n,function(){return this}),st(l,"toString",function(){return"[object Generator]"}),(ct=function(){return{w:a,m:p}})()}function st(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}st=function(e,t,r,n){function a(t,r){st(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},st(e,t,r,n)}function ft(e,t){this.v=e,this.k=t}function lt(e,t,r,n,o,a,i){try{var u=e[a](i),c=u.value}catch(e){return void r(e)}u.done?t(c):Promise.resolve(c).then(n,o)}function pt(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var a=e.apply(t,r);function i(e){lt(a,n,o,i,u,"next",e)}function u(e){lt(a,n,o,i,u,"throw",e)}i(void 0)})}}window.TKHQ=q,document.addEventListener("DOMContentLoaded",pt(rt().mark(function e(){var t,r,n,o;return rt().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,q.initEmbeddedKey();case 2:return e.next=4,q.getEmbeddedKey();case 4:return t=e.sent,e.next=7,q.p256JWKPrivateToPublic(t);case 7:r=e.sent,n=q.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,et(pe),(o=q.getSettings())&&q.applySettings(o),q.sendMessageUp("PUBLIC_KEY_READY",n);case 14:case"end":return e.stop()}},e)}))),window.addEventListener("message",function(){var e=pt(rt().mark(function e(t){var r,n,o,a,i;return rt().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.data||"TURNKEY_INIT_MESSAGE_CHANNEL"!=t.data.type||null===(r=t.ports)||void 0===r||!r[0]){e.next=15;break}return(n=t.ports[0]).onmessage=et(pe).messageEventListener,q.setParentFrameMessageChannelPort(n),e.next=6,q.initEmbeddedKey();case 6:return e.next=8,q.getEmbeddedKey();case 8:return o=e.sent,e.next=11,q.p256JWKPrivateToPublic(o);case 11:a=e.sent,i=q.uint8arrayToHexString(a),document.getElementById("embedded-key").value=i,q.sendMessageUp("PUBLIC_KEY_READY",i);case 15:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}())},790:()=>{}},i={};function u(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return a[e].call(r.exports,r,r.exports,u),r.loaded=!0,r.exports}u.m=a,e=[],u.O=(t,r,n,o)=>{if(!r){var a=1/0;for(f=0;f=o)&&Object.keys(u.O).every(e=>u.O[e](r[c]))?r.splice(c--,1):(i=!1,o0&&e[f-1][2]>o;f--)e[f]=e[f-1];e[f]=[r,n,o]},u.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return u.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,u.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var o=Object.create(null);u.r(o);var a={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>a[t]=()=>e[t]);return a.default=()=>e,u.d(o,a),o},u.d=(e,t)=>{for(var r in t)u.o(t,r)&&!u.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},u.f={},u.e=e=>Promise.all(Object.keys(u.f).reduce((t,r)=>(u.f[r](e,t),t),[])),u.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",u.miniCssF=e=>{},u.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},o="export-and-sign:",u.l=(e,t,r,a)=>{if(n[e])n[e].push(t);else{var i,c;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(d);var o=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),o&&o.forEach(e=>e(r)),t)return t(r)},d=setTimeout(p.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=p.bind(null,i.onerror),i.onload=p.bind(null,i.onload),c&&document.head.appendChild(i)}},u.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},u.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),u.p="/",(()=>{var e={792:0};u.f.j=(t,r)=>{var n=u.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var o=new Promise((r,o)=>n=e[t]=[r,o]);r.push(n[2]=o);var a=u.p+u.u(t),i=new Error;u.l(a,r=>{if(u.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var o=r&&("load"===r.type?"missing":r.type),a=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+o+": "+a+")",i.name="ChunkLoadError",i.type=o,i.request=a,n[1](i)}},"chunk-"+t,t)}},u.O.j=t=>0===e[t];var t=(t,r)=>{var n,o,[a,i,c]=r,s=0;if(a.some(t=>0!==e[t])){for(n in i)u.o(i,n)&&(u.m[n]=i[n]);if(c)var f=c(u)}for(t&&t(r);su(758));c=u.O(c)})(); +//# sourceMappingURL=bundle.f14f48a41b2945673e48.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.78c912c0211a44421f40.js.LICENSE.txt b/export-and-sign/dist/bundle.f14f48a41b2945673e48.js.LICENSE.txt similarity index 100% rename from export-and-sign/dist/bundle.78c912c0211a44421f40.js.LICENSE.txt rename to export-and-sign/dist/bundle.f14f48a41b2945673e48.js.LICENSE.txt diff --git a/export-and-sign/dist/bundle.f14f48a41b2945673e48.js.map b/export-and-sign/dist/bundle.f14f48a41b2945673e48.js.map new file mode 100644 index 0000000..54c025a --- /dev/null +++ b/export-and-sign/dist/bundle.f14f48a41b2945673e48.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundle.f14f48a41b2945673e48.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,81GCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,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DwhB,EAAmB5f,KAAOuf,EAAqBnhB,KAAK,KAAMwhB,EAAmB5f,KAAK5B,KAAKwhB,G,KClFvF,IAAIE,EAAsBxE,EAAoBQ,OAAEla,EAAW,CAAC,IAAK,IAAO0Z,EAAoB,MAC5FwE,EAAsBxE,EAAoBQ,EAAEgE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/crypto-utils.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","/**\n * Turnkey Core Module\n * Contains all the core cryptographic and utility functions\n */\n\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n/** constant for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n return await crypto.subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const p256key = await crypto.subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (!item.hasOwnProperty(\"expiry\") || !item.hasOwnProperty(\"value\")) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decoded = BigInt(0);\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await TKHQ.p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = TKHQ.additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\nimport { HpkeDecrypt } from \"./crypto-utils.js\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n let encappedKeyBuf;\n let ciphertextBuf;\n let verified;\n\n // Parse the import bundle\n const bundleObj = JSON.parse(bundle);\n switch (bundleObj.version) {\n case \"v1.0.0\":\n // Validate fields exist\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n // Verify enclave signature\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(`failed to verify enclave signature: ${bundle}`);\n }\n\n // Parse the signed data. The data is produced by JSON encoding followed by hex encoding. We reverse this here.\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n // Validate fields match\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n encappedKeyBuf = TKHQ.uint8arrayFromHexString(signedData.encappedPublic);\n ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n break;\n default:\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Parse the decrypted key bytes\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n // Set in memory\n // If no address provided, use a default key\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair, // Cache the keypair for performance\n },\n };\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n \n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n \n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error( `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectWalletBundle(\n event.data[\"value\"],\n event.data[\"organizationId\"],\n event.data[\"requestId\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n};\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"./crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n\n// Init MessageChannel for communication between iframe <> parent page\nwindow.addEventListener(\"message\", async function (event) {\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage =\n initEventHandlers(HpkeDecrypt).messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n }\n});\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(758)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_slicedToArray","Array","isArray","_arrayWithHoles","next","push","_iterableToArrayLimit","_unsupportedIterableToArray","_nonIterableRest","_toConsumableArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","isDoublyIframed","undefined","window","location","ancestorOrigins","parent","top","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","crypto","subtle","importKey","namedCurve","abrupt","sent","stop","_initEmbeddedKey","_callee2","_context2","Error","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee3","p256key","_context3","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","key","ttl","item","expiry","Date","getTime","localStorage","setItem","itemStr","getItem","hasOwnProperty","removeItem","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","s","rPadded","sPadded","_verifyEnclaveSignature","_callee4","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context4","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","verify","hash","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","_p256JWKPrivateToPublic","_callee5","jwkPrivate","jwkPrivateCopy","publicKey","_context5","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","base58Decode","alphabet","decodedBytes","BigInt","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee6","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_context6","t0","set","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","TKHQ","initEmbeddedKey","onResetEmbeddedKey","p256JWKPrivateToPublic","_x5","encodeKey","_x6","_x7","_x8","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","additionalAssociatedData","senderPubBuf","receiverPubBuf","verifyEnclaveSignature","_x2","_x3","_x4","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","_ref3","_ref4","style","getSettings","setSettings","parsePrivateKey","error","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeDecrypt","_HpkeDecrypt","ciphertextBuf","encappedKeyBuf","receiverPrivJwk","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","inMemoryKeys","textEncoder","textDecoder","TextDecoder","decryptBundle","_decryptBundle","_callee8","bundle","organizationId","bundleObj","embeddedKeyJwk","_context8","version","data","dataSignature","decode","encappedPublic","ciphertext","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee9","targetPubBuf","targetPubHex","_context9","onInjectKeyBundle","_x9","_x10","_onInjectKeyBundle","_callee10","address","keyBytes","keyAddress","cachedKeypair","_context10","subarray","Keypair","fromSecretKey","createSolanaKeypair","format","keypair","onApplySettings","_x11","_x12","_onApplySettings","_callee11","_context11","onSignTransaction","_x13","_x14","_x15","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x16","_x17","_x18","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","secretKey","onClearEmbeddedPrivateKey","_x19","_x20","_onClearEmbeddedPrivateKey","_callee14","_context14","_x21","_createSolanaKeypair","_callee15","_context15","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x22","_getOrCreateKeypair","_callee16","_context16","initEventHandlers","messageEventListener","_messageEventListener","event","onInjectWalletBundle","t1","t2","t3","t4","t5","t6","_x28","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","preventDefault","_x23","_x24","_x25","_x26","injectWalletBtn","_ref5","_x27","addDOMEventListeners","capture","signal","_ref6","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x29","styleSettings","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","module","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","onScriptComplete","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/index.html b/export-and-sign/dist/index.html index 1536888..b39d23d 100644 --- a/export-and-sign/dist/index.html +++ b/export-and-sign/dist/index.html @@ -1 +1 @@ -Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file +Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file diff --git a/export-and-sign/package-lock.json b/export-and-sign/package-lock.json index 3e48b8e..2f9febd 100644 --- a/export-and-sign/package-lock.json +++ b/export-and-sign/package-lock.json @@ -12,9 +12,7 @@ "@hpke/core": "1.7.5", "@noble/ed25519": "2.0.0", "@noble/hashes": "1.3.2", - "@solana/web3.js": "1.98.4", - "tweetnacl": "1.0.3", - "tweetnacl-util": "0.15.1" + "@solana/web3.js": "1.98.4" }, "devDependencies": { "@babel/core": "7.23.0", @@ -12293,18 +12291,6 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, - "node_modules/tweetnacl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", - "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", - "license": "Unlicense" - }, - "node_modules/tweetnacl-util": { - "version": "0.15.1", - "resolved": "https://registry.npmjs.org/tweetnacl-util/-/tweetnacl-util-0.15.1.tgz", - "integrity": "sha512-RKJBIj8lySrShN4w6i/BonWp2Z/uxwC3h4y7xsRrpP59ZboCd0GpEVsOnMDYLMmKBpYhb5TgHzZXy7wTfYFBRw==", - "license": "Unlicense" - }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -21950,16 +21936,6 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==" }, - "tweetnacl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", - "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==" - }, - "tweetnacl-util": { - "version": "0.15.1", - "resolved": "https://registry.npmjs.org/tweetnacl-util/-/tweetnacl-util-0.15.1.tgz", - "integrity": "sha512-RKJBIj8lySrShN4w6i/BonWp2Z/uxwC3h4y7xsRrpP59ZboCd0GpEVsOnMDYLMmKBpYhb5TgHzZXy7wTfYFBRw==" - }, "type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", diff --git a/export-and-sign/package.json b/export-and-sign/package.json index c55d590..4280bb8 100644 --- a/export-and-sign/package.json +++ b/export-and-sign/package.json @@ -19,9 +19,7 @@ "@hpke/core": "1.7.5", "@noble/ed25519": "2.0.0", "@noble/hashes": "1.3.2", - "@solana/web3.js": "1.98.4", - "tweetnacl": "1.0.3", - "tweetnacl-util": "0.15.1" + "@solana/web3.js": "1.98.4" }, "devDependencies": { "@babel/core": "7.23.0", diff --git a/export-and-sign/src/event-handlers.js b/export-and-sign/src/event-handlers.js index ab9f25d..9dc9af6 100644 --- a/export-and-sign/src/event-handlers.js +++ b/export-and-sign/src/event-handlers.js @@ -1,6 +1,8 @@ import { TKHQ } from "./turnkey-core.js"; import { Keypair, VersionedTransaction } from "@solana/web3.js"; -import nacl from "tweetnacl"; +import * as nobleEd25519 from "@noble/ed25519"; +import * as nobleHashes from "@noble/hashes/sha512"; + import { HpkeDecrypt } from "./crypto-utils.js"; // Persist keys in memory via mapping of { address --> pk } @@ -264,9 +266,16 @@ async function onSignMessage(requestId, serializedMessage, address) { const keypair = await getOrCreateKeypair(key); if (messageType === "SOLANA") { - // Sign the message - const signature = nacl.sign.detached(messageBytes, keypair.secretKey); - + // Set up sha512 for nobleEd25519 (required for signing) + nobleEd25519.etc.sha512Sync = (...m) => + nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m)); + + // Extract the 32-byte private key from the 64-byte secretKey + // Solana keypair.secretKey format: [32-byte private key][32-byte public key] + const privateKey = keypair.secretKey.slice(0, 32); + // Sign the message using nobleEd25519 + const signature = nobleEd25519.sign(messageBytes, privateKey); + // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair. // Clients can verify the signature returned.