@solana/web3.js 1.35.1 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,7 +27,7 @@ var solanaWeb3=function(exports){"use strict";var commonjsGlobal=typeof globalTh
27
27
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28
28
  THE SOFTWARE.
29
29
 
30
- */var specialChar="~",safeSpecialChar="\\x"+("0"+specialChar.charCodeAt(0).toString(16)).slice(-2),escapedSafeSpecialChar="\\"+safeSpecialChar,specialCharRG=new RegExp(safeSpecialChar,"g"),safeSpecialCharRG=new RegExp(escapedSafeSpecialChar,"g"),safeStartWithSpecialCharRG=new RegExp("(?:^|([^\\\\]))"+escapedSafeSpecialChar),indexOf=[].indexOf||function(v){for(var i=this.length;i--&&this[i]!==v;);return i},$String=String;function generateReplacer(value,replacer,resolve){var doNotIgnore=false,inspect=!!replacer,path=[],all=[value],seen=[value],mapp=[resolve?specialChar:"[Circular]"],last=value,lvl=1,i,fn;if(inspect){fn=typeof replacer==="object"?function(key,value){return key!==""&&replacer.indexOf(key)<0?void 0:value}:replacer}return function(key,value){if(inspect)value=fn.call(this,key,value);if(doNotIgnore){if(last!==this){i=lvl-indexOf.call(all,this)-1;lvl-=i;all.splice(lvl,all.length);path.splice(lvl-1,path.length);last=this}if(typeof value==="object"&&value){if(indexOf.call(all,value)<0){all.push(last=value)}lvl=all.length;i=indexOf.call(seen,value);if(i<0){i=seen.push(value)-1;if(resolve){path.push((""+key).replace(specialCharRG,safeSpecialChar));mapp[i]=specialChar+path.join(specialChar)}else{mapp[i]=mapp[0]}}else{value=mapp[i]}}else{if(typeof value==="string"&&resolve){value=value.replace(safeSpecialChar,escapedSafeSpecialChar).replace(specialChar,safeSpecialChar)}}}else{doNotIgnore=true}return value}}function retrieveFromPath(current,keys){for(var i=0,length=keys.length;i<length;current=current[keys[i++].replace(safeSpecialCharRG,specialChar)]);return current}function generateReviver(reviver){return function(key,value){var isString=typeof value==="string";if(isString&&value.charAt(0)===specialChar){return new $String(value.slice(1))}if(key==="")value=regenerate(value,value,{});if(isString)value=value.replace(safeStartWithSpecialCharRG,"$1"+specialChar).replace(escapedSafeSpecialChar,safeSpecialChar);return reviver?reviver.call(this,key,value):value}}function regenerateArray(root,current,retrieve){for(var i=0,length=current.length;i<length;i++){current[i]=regenerate(root,current[i],retrieve)}return current}function regenerateObject(root,current,retrieve){for(var key in current){if(current.hasOwnProperty(key)){current[key]=regenerate(root,current[key],retrieve)}}return current}function regenerate(root,current,retrieve){return current instanceof Array?regenerateArray(root,current,retrieve):current instanceof $String?current.length?retrieve.hasOwnProperty(current)?retrieve[current]:retrieve[current]=retrieveFromPath(root,current.split(specialChar)):root:current instanceof Object?regenerateObject(root,current,retrieve):current}var CircularJSON={stringify:function stringify(value,replacer,space,doNotResolve){return CircularJSON.parser.stringify(value,generateReplacer(value,replacer,!doNotResolve),space)},parse:function parse(text,reviver){return CircularJSON.parser.parse(text,generateReviver(reviver))},parser:JSON};var circularJson_node=CircularJSON;(function(exports){var _interopRequireDefault=interopRequireDefault.exports;Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _regenerator=_interopRequireDefault(regenerator);var _asyncToGenerator2=_interopRequireDefault(asyncToGenerator.exports);var _typeof2=_interopRequireDefault(_typeof.exports);var _classCallCheck2=_interopRequireDefault(classCallCheck.exports);var _createClass2=_interopRequireDefault(createClass.exports);var _inherits2=_interopRequireDefault(inherits$3.exports);var _possibleConstructorReturn2=_interopRequireDefault(possibleConstructorReturn.exports);var _getPrototypeOf2=_interopRequireDefault(getPrototypeOf.exports);var _eventemitter=eventemitter3.exports;var _circularJson=_interopRequireDefault(circularJson_node);function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=(0,_getPrototypeOf2["default"])(Derived),result;if(hasNativeReflectConstruct){var NewTarget=(0,_getPrototypeOf2["default"])(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return(0,_possibleConstructorReturn2["default"])(this,result)}}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}var __rest=function(s,e){var t={};for(var p in s){if(Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0)t[p]=s[p]}if(s!=null&&typeof Object.getOwnPropertySymbols==="function")for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++){if(e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i]))t[p[i]]=s[p[i]]}return t};var CommonClient=function(_EventEmitter){(0,_inherits2["default"])(CommonClient,_EventEmitter);var _super=_createSuper(CommonClient);function CommonClient(webSocketFactory){var _this;var address=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"ws://localhost:8080";var _a=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var generate_request_id=arguments.length>3?arguments[3]:undefined;(0,_classCallCheck2["default"])(this,CommonClient);var _a$autoconnect=_a.autoconnect,autoconnect=_a$autoconnect===void 0?true:_a$autoconnect,_a$reconnect=_a.reconnect,reconnect=_a$reconnect===void 0?true:_a$reconnect,_a$reconnect_interval=_a.reconnect_interval,reconnect_interval=_a$reconnect_interval===void 0?1e3:_a$reconnect_interval,_a$max_reconnects=_a.max_reconnects,max_reconnects=_a$max_reconnects===void 0?5:_a$max_reconnects,rest_options=__rest(_a,["autoconnect","reconnect","reconnect_interval","max_reconnects"]);_this=_super.call(this);_this.webSocketFactory=webSocketFactory;_this.queue={};_this.rpc_id=0;_this.address=address;_this.autoconnect=autoconnect;_this.ready=false;_this.reconnect=reconnect;_this.reconnect_interval=reconnect_interval;_this.max_reconnects=max_reconnects;_this.rest_options=rest_options;_this.current_reconnects=0;_this.generate_request_id=generate_request_id||function(){return++_this.rpc_id};if(_this.autoconnect)_this._connect(_this.address,Object.assign({autoconnect:_this.autoconnect,reconnect:_this.reconnect,reconnect_interval:_this.reconnect_interval,max_reconnects:_this.max_reconnects},_this.rest_options));return _this}(0,_createClass2["default"])(CommonClient,[{key:"connect",value:function connect(){if(this.socket)return;this._connect(this.address,Object.assign({autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects},this.rest_options))}},{key:"call",value:function call(method,params,timeout,ws_opts){var _this2=this;if(!ws_opts&&"object"===(0,_typeof2["default"])(timeout)){ws_opts=timeout;timeout=null}return new Promise((function(resolve,reject){if(!_this2.ready)return reject(new Error("socket not ready"));var rpc_id=_this2.generate_request_id(method,params);var message={jsonrpc:"2.0",method:method,params:params||null,id:rpc_id};_this2.socket.send(JSON.stringify(message),ws_opts,(function(error){if(error)return reject(error);_this2.queue[rpc_id]={promise:[resolve,reject]};if(timeout){_this2.queue[rpc_id].timeout=setTimeout((function(){delete _this2.queue[rpc_id];reject(new Error("reply timeout"))}),timeout)}}))}))}},{key:"login",value:function(){var _login=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark((function _callee(params){var resp;return _regenerator["default"].wrap((function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return this.call("rpc.login",params);case 2:resp=_context.sent;if(resp){_context.next=5;break}throw new Error("authentication failed");case 5:return _context.abrupt("return",resp);case 6:case"end":return _context.stop()}}}),_callee,this)})));function login(_x){return _login.apply(this,arguments)}return login}()},{key:"listMethods",value:function(){var _listMethods=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark((function _callee2(){return _regenerator["default"].wrap((function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return this.call("__listMethods");case 2:return _context2.abrupt("return",_context2.sent);case 3:case"end":return _context2.stop()}}}),_callee2,this)})));function listMethods(){return _listMethods.apply(this,arguments)}return listMethods}()},{key:"notify",value:function notify(method,params){var _this3=this;return new Promise((function(resolve,reject){if(!_this3.ready)return reject(new Error("socket not ready"));var message={jsonrpc:"2.0",method:method,params:params||null};_this3.socket.send(JSON.stringify(message),(function(error){if(error)return reject(error);resolve()}))}))}},{key:"subscribe",value:function(){var _subscribe=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark((function _callee3(event){var result;return _regenerator["default"].wrap((function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:if(typeof event==="string")event=[event];_context3.next=3;return this.call("rpc.on",event);case 3:result=_context3.sent;if(!(typeof event==="string"&&result[event]!=="ok")){_context3.next=6;break}throw new Error("Failed subscribing to an event '"+event+"' with: "+result[event]);case 6:return _context3.abrupt("return",result);case 7:case"end":return _context3.stop()}}}),_callee3,this)})));function subscribe(_x2){return _subscribe.apply(this,arguments)}return subscribe}()},{key:"unsubscribe",value:function(){var _unsubscribe=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark((function _callee4(event){var result;return _regenerator["default"].wrap((function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:if(typeof event==="string")event=[event];_context4.next=3;return this.call("rpc.off",event);case 3:result=_context4.sent;if(!(typeof event==="string"&&result[event]!=="ok")){_context4.next=6;break}throw new Error("Failed unsubscribing from an event with: "+result);case 6:return _context4.abrupt("return",result);case 7:case"end":return _context4.stop()}}}),_callee4,this)})));function unsubscribe(_x3){return _unsubscribe.apply(this,arguments)}return unsubscribe}()},{key:"close",value:function close(code,data){this.socket.close(code||1e3,data)}},{key:"_connect",value:function _connect(address,options){var _this4=this;this.socket=this.webSocketFactory(address,options);this.socket.addEventListener("open",(function(){_this4.ready=true;_this4.emit("open");_this4.current_reconnects=0}));this.socket.addEventListener("message",(function(_ref){var message=_ref.data;if(message instanceof ArrayBuffer)message=Buffer.from(message).toString();try{message=_circularJson["default"].parse(message)}catch(error){return}if(message.notification&&_this4.listeners(message.notification).length){if(!Object.keys(message.params).length)return _this4.emit(message.notification);var args=[message.notification];if(message.params.constructor===Object)args.push(message.params);else for(var i=0;i<message.params.length;i++){args.push(message.params[i])}return Promise.resolve().then((function(){_this4.emit.apply(_this4,args)}))}if(!_this4.queue[message.id]){if(message.method&&message.params){return Promise.resolve().then((function(){_this4.emit(message.method,message.params)}))}return}if("error"in message==="result"in message)_this4.queue[message.id].promise[1](new Error('Server response malformed. Response must include either "result"'+' or "error", but not both.'));if(_this4.queue[message.id].timeout)clearTimeout(_this4.queue[message.id].timeout);if(message.error)_this4.queue[message.id].promise[1](message.error);else _this4.queue[message.id].promise[0](message.result);delete _this4.queue[message.id]}));this.socket.addEventListener("error",(function(error){return _this4.emit("error",error)}));this.socket.addEventListener("close",(function(_ref2){var code=_ref2.code,reason=_ref2.reason;if(_this4.ready)setTimeout((function(){return _this4.emit("close",code,reason)}),0);_this4.ready=false;_this4.socket=undefined;if(code===1e3)return;_this4.current_reconnects++;if(_this4.reconnect&&(_this4.max_reconnects>_this4.current_reconnects||_this4.max_reconnects===0))setTimeout((function(){return _this4._connect(address,options)}),_this4.reconnect_interval)}))}}]);return CommonClient}(_eventemitter.EventEmitter);exports["default"]=CommonClient})(client);var _interopRequireDefault=interopRequireDefault.exports;Object.defineProperty(index_browser,"__esModule",{value:true});var Client_1=index_browser.Client=void 0;var _classCallCheck2=_interopRequireDefault(classCallCheck.exports);var _inherits2=_interopRequireDefault(inherits$3.exports);var _possibleConstructorReturn2=_interopRequireDefault(possibleConstructorReturn.exports);var _getPrototypeOf2=_interopRequireDefault(getPrototypeOf.exports);var _websocket=_interopRequireDefault(websocket_browser);var _client=_interopRequireDefault(client);function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=(0,_getPrototypeOf2["default"])(Derived),result;if(hasNativeReflectConstruct){var NewTarget=(0,_getPrototypeOf2["default"])(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return(0,_possibleConstructorReturn2["default"])(this,result)}}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}var Client=function(_CommonClient){(0,_inherits2["default"])(Client,_CommonClient);var _super=_createSuper(Client);function Client(){var address=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"ws://localhost:8080";var _ref=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},_ref$autoconnect=_ref.autoconnect,autoconnect=_ref$autoconnect===void 0?true:_ref$autoconnect,_ref$reconnect=_ref.reconnect,reconnect=_ref$reconnect===void 0?true:_ref$reconnect,_ref$reconnect_interv=_ref.reconnect_interval,reconnect_interval=_ref$reconnect_interv===void 0?1e3:_ref$reconnect_interv,_ref$max_reconnects=_ref.max_reconnects,max_reconnects=_ref$max_reconnects===void 0?5:_ref$max_reconnects;var generate_request_id=arguments.length>2?arguments[2]:undefined;(0,_classCallCheck2["default"])(this,Client);return _super.call(this,_websocket["default"],address,{autoconnect:autoconnect,reconnect:reconnect,reconnect_interval:reconnect_interval,max_reconnects:max_reconnects},generate_request_id)}return Client}(_client["default"]);Client_1=index_browser.Client=Client;var rngBrowser={exports:{}};var getRandomValues=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof window.msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);if(getRandomValues){var rnds8=new Uint8Array(16);rngBrowser.exports=function whatwgRNG(){getRandomValues(rnds8);return rnds8}}else{var rnds=new Array(16);rngBrowser.exports=function mathRNG(){for(var i=0,r;i<16;i++){if((i&3)===0)r=Math.random()*4294967296;rnds[i]=r>>>((i&3)<<3)&255}return rnds}}var byteToHex=[];for(var i=0;i<256;++i){byteToHex[i]=(i+256).toString(16).substr(1)}function bytesToUuid$1(buf,offset){var i=offset||0;var bth=byteToHex;return[bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]]].join("")}var bytesToUuid_1=bytesToUuid$1;var rng=rngBrowser.exports;var bytesToUuid=bytesToUuid_1;function v4(options,buf,offset){var i=buf&&offset||0;if(typeof options=="string"){buf=options==="binary"?new Array(16):null;options=null}options=options||{};var rnds=options.random||(options.rng||rng)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){for(var ii=0;ii<16;++ii){buf[i+ii]=rnds[ii]}}return buf||bytesToUuid(rnds)}var v4_1=v4;const uuid$1=v4_1;const generateRequest$1=function(method,params,id,options){if(typeof method!=="string"){throw new TypeError(method+" must be a string")}options=options||{};const version=typeof options.version==="number"?options.version:2;if(version!==1&&version!==2){throw new TypeError(version+" must be 1 or 2")}const request={method:method};if(version===2){request.jsonrpc="2.0"}if(params){if(typeof params!=="object"&&!Array.isArray(params)){throw new TypeError(params+" must be an object, array or omitted")}request.params=params}if(typeof id==="undefined"){const generator=typeof options.generator==="function"?options.generator:function(){return uuid$1()};request.id=generator(request,options)}else if(version===2&&id===null){if(options.notificationIdNull){request.id=null}}else{request.id=id}return request};var generateRequest_1=generateRequest$1;const uuid=v4_1;const generateRequest=generateRequest_1;const ClientBrowser=function(callServer,options){if(!(this instanceof ClientBrowser)){return new ClientBrowser(callServer,options)}if(!options){options={}}this.options={reviver:typeof options.reviver!=="undefined"?options.reviver:null,replacer:typeof options.replacer!=="undefined"?options.replacer:null,generator:typeof options.generator!=="undefined"?options.generator:function(){return uuid()},version:typeof options.version!=="undefined"?options.version:2,notificationIdNull:typeof options.notificationIdNull==="boolean"?options.notificationIdNull:false};this.callServer=callServer};var browser=ClientBrowser;ClientBrowser.prototype.request=function(method,params,id,callback){const self=this;let request=null;const isBatch=Array.isArray(method)&&typeof params==="function";if(this.options.version===1&&isBatch){throw new TypeError("JSON-RPC 1.0 does not support batching")}const isRaw=!isBatch&&method&&typeof method==="object"&&typeof params==="function";if(isBatch||isRaw){callback=params;request=method}else{if(typeof id==="function"){callback=id;id=undefined}const hasCallback=typeof callback==="function";try{request=generateRequest(method,params,id,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(err){if(hasCallback){return callback(err)}throw err}if(!hasCallback){return request}}let message;try{message=JSON.stringify(request,this.options.replacer)}catch(err){return callback(err)}this.callServer(message,(function(err,response){self._parseResponse(err,response,callback)}));return request};ClientBrowser.prototype._parseResponse=function(err,responseText,callback){if(err){callback(err);return}if(!responseText){return callback()}let response;try{response=JSON.parse(responseText,this.options.reviver)}catch(err){return callback(err)}if(callback.length===3){if(Array.isArray(response)){const isError=function(res){return typeof res.error!=="undefined"};const isNotError=function(res){return!isError(res)};return callback(null,response.filter(isError),response.filter(isNotError))}else{return callback(null,response.error,response.result)}}callback(null,response)};var RpcClient=browser;const MINIMUM_SLOT_PER_EPOCH=32;function trailingZeros(n){let trailingZeros=0;while(n>1){n/=2;trailingZeros++}return trailingZeros}function nextPowerOfTwo(n){if(n===0)return 1;n--;n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;return n+1}class EpochSchedule{constructor(slotsPerEpoch,leaderScheduleSlotOffset,warmup,firstNormalEpoch,firstNormalSlot){this.slotsPerEpoch=void 0;this.leaderScheduleSlotOffset=void 0;this.warmup=void 0;this.firstNormalEpoch=void 0;this.firstNormalSlot=void 0;this.slotsPerEpoch=slotsPerEpoch;this.leaderScheduleSlotOffset=leaderScheduleSlotOffset;this.warmup=warmup;this.firstNormalEpoch=firstNormalEpoch;this.firstNormalSlot=firstNormalSlot}getEpoch(slot){return this.getEpochAndSlotIndex(slot)[0]}getEpochAndSlotIndex(slot){if(slot<this.firstNormalSlot){const epoch=trailingZeros(nextPowerOfTwo(slot+MINIMUM_SLOT_PER_EPOCH+1))-trailingZeros(MINIMUM_SLOT_PER_EPOCH)-1;const epochLen=this.getSlotsInEpoch(epoch);const slotIndex=slot-(epochLen-MINIMUM_SLOT_PER_EPOCH);return[epoch,slotIndex]}else{const normalSlotIndex=slot-this.firstNormalSlot;const normalEpochIndex=Math.floor(normalSlotIndex/this.slotsPerEpoch);const epoch=this.firstNormalEpoch+normalEpochIndex;const slotIndex=normalSlotIndex%this.slotsPerEpoch;return[epoch,slotIndex]}}getFirstSlotInEpoch(epoch){if(epoch<=this.firstNormalEpoch){return(Math.pow(2,epoch)-1)*MINIMUM_SLOT_PER_EPOCH}else{return(epoch-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}}getLastSlotInEpoch(epoch){return this.getFirstSlotInEpoch(epoch)+this.getSlotsInEpoch(epoch)-1}getSlotsInEpoch(epoch){if(epoch<this.firstNormalEpoch){return Math.pow(2,epoch+trailingZeros(MINIMUM_SLOT_PER_EPOCH))}else{return this.slotsPerEpoch}}}class SendTransactionError extends Error{constructor(message,logs){super(message);this.logs=void 0;this.logs=logs}}const NUM_TICKS_PER_SECOND=160;const DEFAULT_TICKS_PER_SLOT=64;const NUM_SLOTS_PER_SECOND=NUM_TICKS_PER_SECOND/DEFAULT_TICKS_PER_SLOT;const MS_PER_SLOT=1e3/NUM_SLOTS_PER_SECOND;function promiseTimeout(promise,timeoutMs){let timeoutId;const timeoutPromise=new Promise((resolve=>{timeoutId=setTimeout((()=>resolve(null)),timeoutMs)}));return Promise.race([promise,timeoutPromise]).then((result=>{clearTimeout(timeoutId);return result}))}function makeWebsocketUrl(endpoint){let url=new URL(endpoint);const useHttps=url.protocol==="https:";url.protocol=useHttps?"wss:":"ws:";url.host="";if(url.port!==""){url.port=String(Number(url.port)+1)}return url.toString()}const PublicKeyFromString=coerce(instance(PublicKey),string(),(value=>new PublicKey(value)));const RawAccountDataResult=tuple([string(),literal("base64")]);const BufferFromRawAccountData=coerce(instance(buffer.Buffer),RawAccountDataResult,(value=>buffer.Buffer.from(value[0],"base64")));const BLOCKHASH_CACHE_TIMEOUT_MS=30*1e3;function createRpcResult(result){return union([type({jsonrpc:literal("2.0"),id:string(),result:result}),type({jsonrpc:literal("2.0"),id:string(),error:type({code:unknown(),message:string(),data:optional(any())})})])}const UnknownRpcResult=createRpcResult(unknown());function jsonRpcResult(schema){return coerce(createRpcResult(schema),UnknownRpcResult,(value=>{if("error"in value){return value}else{return{...value,result:create(value.result,schema)}}}))}function jsonRpcResultAndContext(value){return jsonRpcResult(type({context:type({slot:number()}),value:value}))}function notificationResultAndContext(value){return type({context:type({slot:number()}),value:value})}const GetInflationGovernorResult=type({foundation:number(),foundationTerm:number(),initial:number(),taper:number(),terminal:number()});const GetInflationRewardResult=jsonRpcResult(array(nullable(type({epoch:number(),effectiveSlot:number(),amount:number(),postBalance:number()}))));const GetEpochInfoResult=type({epoch:number(),slotIndex:number(),slotsInEpoch:number(),absoluteSlot:number(),blockHeight:optional(number()),transactionCount:optional(number())});const GetEpochScheduleResult=type({slotsPerEpoch:number(),leaderScheduleSlotOffset:number(),warmup:boolean(),firstNormalEpoch:number(),firstNormalSlot:number()});const GetLeaderScheduleResult=record(string(),array(number()));const TransactionErrorResult=nullable(union([type({}),string()]));const SignatureStatusResult=type({err:TransactionErrorResult});const SignatureReceivedResult=literal("receivedSignature");const VersionResult=type({"solana-core":string(),"feature-set":optional(number())});const SimulatedTransactionResponseStruct=jsonRpcResultAndContext(type({err:nullable(union([type({}),string()])),logs:nullable(array(string())),accounts:optional(nullable(array(nullable(type({executable:boolean(),owner:string(),lamports:number(),data:array(string()),rentEpoch:optional(number())}))))),unitsConsumed:optional(number())}));function createRpcClient(url,useHttps,httpHeaders,fetchMiddleware,disableRetryOnRateLimit){let fetchWithMiddleware;if(fetchMiddleware){fetchWithMiddleware=async(url,options)=>{const modifiedFetchArgs=await new Promise(((resolve,reject)=>{try{fetchMiddleware(url,options,((modifiedUrl,modifiedOptions)=>resolve([modifiedUrl,modifiedOptions])))}catch(error){reject(error)}}));return await fetch(...modifiedFetchArgs)}}const clientBrowser=new RpcClient((async(request,callback)=>{const agent=undefined;const options={method:"POST",body:request,agent:agent,headers:Object.assign({"Content-Type":"application/json"},httpHeaders||{})};try{let too_many_requests_retries=5;let res;let waitTime=500;for(;;){if(fetchWithMiddleware){res=await fetchWithMiddleware(url,options)}else{res=await fetch(url,options)}if(res.status!==429){break}if(disableRetryOnRateLimit===true){break}too_many_requests_retries-=1;if(too_many_requests_retries===0){break}console.log(`Server responded with ${res.status} ${res.statusText}. Retrying after ${waitTime}ms delay...`);await sleep(waitTime);waitTime*=2}const text=await res.text();if(res.ok){callback(null,text)}else{callback(new Error(`${res.status} ${res.statusText}: ${text}`))}}catch(err){if(err instanceof Error)callback(err)}finally{}}),{});return clientBrowser}function createRpcRequest(client){return(method,args)=>new Promise(((resolve,reject)=>{client.request(method,args,((err,response)=>{if(err){reject(err);return}resolve(response)}))}))}function createRpcBatchRequest(client){return requests=>new Promise(((resolve,reject)=>{if(requests.length===0)resolve([]);const batch=requests.map((params=>client.request(params.methodName,params.args)));client.request(batch,((err,response)=>{if(err){reject(err);return}resolve(response)}))}))}const GetInflationGovernorRpcResult=jsonRpcResult(GetInflationGovernorResult);const GetEpochInfoRpcResult=jsonRpcResult(GetEpochInfoResult);const GetEpochScheduleRpcResult=jsonRpcResult(GetEpochScheduleResult);const GetLeaderScheduleRpcResult=jsonRpcResult(GetLeaderScheduleResult);const SlotRpcResult=jsonRpcResult(number());const GetSupplyRpcResult=jsonRpcResultAndContext(type({total:number(),circulating:number(),nonCirculating:number(),nonCirculatingAccounts:array(PublicKeyFromString)}));const TokenAmountResult=type({amount:string(),uiAmount:nullable(number()),decimals:number(),uiAmountString:optional(string())});const GetTokenLargestAccountsResult=jsonRpcResultAndContext(array(type({address:PublicKeyFromString,amount:string(),uiAmount:nullable(number()),decimals:number(),uiAmountString:optional(string())})));const GetTokenAccountsByOwner=jsonRpcResultAndContext(array(type({pubkey:PublicKeyFromString,account:type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:BufferFromRawAccountData,rentEpoch:number()})})));const ParsedAccountDataResult=type({program:string(),parsed:unknown(),space:number()});const GetParsedTokenAccountsByOwner=jsonRpcResultAndContext(array(type({pubkey:PublicKeyFromString,account:type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:ParsedAccountDataResult,rentEpoch:number()})})));const GetLargestAccountsRpcResult=jsonRpcResultAndContext(array(type({lamports:number(),address:PublicKeyFromString})));const AccountInfoResult=type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:BufferFromRawAccountData,rentEpoch:number()});const KeyedAccountInfoResult=type({pubkey:PublicKeyFromString,account:AccountInfoResult});const ParsedOrRawAccountData=coerce(union([instance(buffer.Buffer),ParsedAccountDataResult]),union([RawAccountDataResult,ParsedAccountDataResult]),(value=>{if(Array.isArray(value)){return create(value,BufferFromRawAccountData)}else{return value}}));const ParsedAccountInfoResult=type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:ParsedOrRawAccountData,rentEpoch:number()});const KeyedParsedAccountInfoResult=type({pubkey:PublicKeyFromString,account:ParsedAccountInfoResult});const StakeActivationResult=type({state:union([literal("active"),literal("inactive"),literal("activating"),literal("deactivating")]),active:number(),inactive:number()});const GetConfirmedSignaturesForAddress2RpcResult=jsonRpcResult(array(type({signature:string(),slot:number(),err:TransactionErrorResult,memo:nullable(string()),blockTime:optional(nullable(number()))})));const GetSignaturesForAddressRpcResult=jsonRpcResult(array(type({signature:string(),slot:number(),err:TransactionErrorResult,memo:nullable(string()),blockTime:optional(nullable(number()))})));const AccountNotificationResult=type({subscription:number(),result:notificationResultAndContext(AccountInfoResult)});const ProgramAccountInfoResult=type({pubkey:PublicKeyFromString,account:AccountInfoResult});const ProgramAccountNotificationResult=type({subscription:number(),result:notificationResultAndContext(ProgramAccountInfoResult)});const SlotInfoResult=type({parent:number(),slot:number(),root:number()});const SlotNotificationResult=type({subscription:number(),result:SlotInfoResult});const SlotUpdateResult=union([type({type:union([literal("firstShredReceived"),literal("completed"),literal("optimisticConfirmation"),literal("root")]),slot:number(),timestamp:number()}),type({type:literal("createdBank"),parent:number(),slot:number(),timestamp:number()}),type({type:literal("frozen"),slot:number(),timestamp:number(),stats:type({numTransactionEntries:number(),numSuccessfulTransactions:number(),numFailedTransactions:number(),maxTransactionsPerEntry:number()})}),type({type:literal("dead"),slot:number(),timestamp:number(),err:string()})]);const SlotUpdateNotificationResult=type({subscription:number(),result:SlotUpdateResult});const SignatureNotificationResult=type({subscription:number(),result:notificationResultAndContext(union([SignatureStatusResult,SignatureReceivedResult]))});const RootNotificationResult=type({subscription:number(),result:number()});const ContactInfoResult=type({pubkey:string(),gossip:nullable(string()),tpu:nullable(string()),rpc:nullable(string()),version:nullable(string())});const VoteAccountInfoResult=type({votePubkey:string(),nodePubkey:string(),activatedStake:number(),epochVoteAccount:boolean(),epochCredits:array(tuple([number(),number(),number()])),commission:number(),lastVote:number(),rootSlot:nullable(number())});const GetVoteAccounts=jsonRpcResult(type({current:array(VoteAccountInfoResult),delinquent:array(VoteAccountInfoResult)}));const ConfirmationStatus=union([literal("processed"),literal("confirmed"),literal("finalized")]);const SignatureStatusResponse=type({slot:number(),confirmations:nullable(number()),err:TransactionErrorResult,confirmationStatus:optional(ConfirmationStatus)});const GetSignatureStatusesRpcResult=jsonRpcResultAndContext(array(nullable(SignatureStatusResponse)));const GetMinimumBalanceForRentExemptionRpcResult=jsonRpcResult(number());const ConfirmedTransactionResult=type({signatures:array(string()),message:type({accountKeys:array(string()),header:type({numRequiredSignatures:number(),numReadonlySignedAccounts:number(),numReadonlyUnsignedAccounts:number()}),instructions:array(type({accounts:array(number()),data:string(),programIdIndex:number()})),recentBlockhash:string()})});const ParsedInstructionResult=type({parsed:unknown(),program:string(),programId:PublicKeyFromString});const RawInstructionResult=type({accounts:array(PublicKeyFromString),data:string(),programId:PublicKeyFromString});const InstructionResult=union([RawInstructionResult,ParsedInstructionResult]);const UnknownInstructionResult=union([type({parsed:unknown(),program:string(),programId:string()}),type({accounts:array(string()),data:string(),programId:string()})]);const ParsedOrRawInstruction=coerce(InstructionResult,UnknownInstructionResult,(value=>{if("accounts"in value){return create(value,RawInstructionResult)}else{return create(value,ParsedInstructionResult)}}));const ParsedConfirmedTransactionResult=type({signatures:array(string()),message:type({accountKeys:array(type({pubkey:PublicKeyFromString,signer:boolean(),writable:boolean()})),instructions:array(ParsedOrRawInstruction),recentBlockhash:string()})});const TokenBalanceResult=type({accountIndex:number(),mint:string(),owner:optional(string()),uiTokenAmount:TokenAmountResult});const ConfirmedTransactionMetaResult=type({err:TransactionErrorResult,fee:number(),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(type({accounts:array(number()),data:string(),programIdIndex:number()}))})))),preBalances:array(number()),postBalances:array(number()),logMessages:optional(nullable(array(string()))),preTokenBalances:optional(nullable(array(TokenBalanceResult))),postTokenBalances:optional(nullable(array(TokenBalanceResult)))});const ParsedConfirmedTransactionMetaResult=type({err:TransactionErrorResult,fee:number(),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(ParsedOrRawInstruction)})))),preBalances:array(number()),postBalances:array(number()),logMessages:optional(nullable(array(string()))),preTokenBalances:optional(nullable(array(TokenBalanceResult))),postTokenBalances:optional(nullable(array(TokenBalanceResult)))});const GetBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionResult,meta:nullable(ConfirmedTransactionMetaResult)})),rewards:optional(array(type({pubkey:string(),lamports:number(),postBalance:nullable(number()),rewardType:nullable(string())}))),blockTime:nullable(number()),blockHeight:nullable(number())})));const GetConfirmedBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionResult,meta:nullable(ConfirmedTransactionMetaResult)})),rewards:optional(array(type({pubkey:string(),lamports:number(),postBalance:nullable(number()),rewardType:nullable(string())}))),blockTime:nullable(number())})));const GetBlockSignaturesRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),signatures:array(string()),blockTime:nullable(number())})));const GetTransactionRpcResult=jsonRpcResult(nullable(type({slot:number(),meta:ConfirmedTransactionMetaResult,blockTime:optional(nullable(number())),transaction:ConfirmedTransactionResult})));const GetParsedTransactionRpcResult=jsonRpcResult(nullable(type({slot:number(),transaction:ParsedConfirmedTransactionResult,meta:nullable(ParsedConfirmedTransactionMetaResult),blockTime:optional(nullable(number()))})));const GetRecentBlockhashAndContextRpcResult=jsonRpcResultAndContext(type({blockhash:string(),feeCalculator:type({lamportsPerSignature:number()})}));const GetLatestBlockhashRpcResult=jsonRpcResultAndContext(type({blockhash:string(),lastValidBlockHeight:number()}));const PerfSampleResult=type({slot:number(),numTransactions:number(),numSlots:number(),samplePeriodSecs:number()});const GetRecentPerformanceSamplesRpcResult=jsonRpcResult(array(PerfSampleResult));const GetFeeCalculatorRpcResult=jsonRpcResultAndContext(nullable(type({feeCalculator:type({lamportsPerSignature:number()})})));const RequestAirdropRpcResult=jsonRpcResult(string());const SendTransactionRpcResult=jsonRpcResult(string());const LogsResult=type({err:TransactionErrorResult,logs:array(string()),signature:string()});const LogsNotificationResult=type({result:notificationResultAndContext(LogsResult),subscription:number()});class Connection{constructor(endpoint,commitmentOrConfig){this._commitment=void 0;this._confirmTransactionInitialTimeout=void 0;this._rpcEndpoint=void 0;this._rpcWsEndpoint=void 0;this._rpcClient=void 0;this._rpcRequest=void 0;this._rpcBatchRequest=void 0;this._rpcWebSocket=void 0;this._rpcWebSocketConnected=false;this._rpcWebSocketHeartbeat=null;this._rpcWebSocketIdleTimeout=null;this._disableBlockhashCaching=false;this._pollingBlockhash=false;this._blockhashInfo={recentBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]};this._accountChangeSubscriptionCounter=0;this._accountChangeSubscriptions={};this._programAccountChangeSubscriptionCounter=0;this._programAccountChangeSubscriptions={};this._rootSubscriptionCounter=0;this._rootSubscriptions={};this._signatureSubscriptionCounter=0;this._signatureSubscriptions={};this._slotSubscriptionCounter=0;this._slotSubscriptions={};this._logsSubscriptionCounter=0;this._logsSubscriptions={};this._slotUpdateSubscriptionCounter=0;this._slotUpdateSubscriptions={};let url=new URL(endpoint);const useHttps=url.protocol==="https:";let wsEndpoint;let httpHeaders;let fetchMiddleware;let disableRetryOnRateLimit;if(commitmentOrConfig&&typeof commitmentOrConfig==="string"){this._commitment=commitmentOrConfig}else if(commitmentOrConfig){this._commitment=commitmentOrConfig.commitment;this._confirmTransactionInitialTimeout=commitmentOrConfig.confirmTransactionInitialTimeout;wsEndpoint=commitmentOrConfig.wsEndpoint;httpHeaders=commitmentOrConfig.httpHeaders;fetchMiddleware=commitmentOrConfig.fetchMiddleware;disableRetryOnRateLimit=commitmentOrConfig.disableRetryOnRateLimit}this._rpcEndpoint=endpoint;this._rpcWsEndpoint=wsEndpoint||makeWebsocketUrl(endpoint);this._rpcClient=createRpcClient(url.toString(),useHttps,httpHeaders,fetchMiddleware,disableRetryOnRateLimit);this._rpcRequest=createRpcRequest(this._rpcClient);this._rpcBatchRequest=createRpcBatchRequest(this._rpcClient);this._rpcWebSocket=new Client_1(this._rpcWsEndpoint,{autoconnect:false,max_reconnects:Infinity});this._rpcWebSocket.on("open",this._wsOnOpen.bind(this));this._rpcWebSocket.on("error",this._wsOnError.bind(this));this._rpcWebSocket.on("close",this._wsOnClose.bind(this));this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this));this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this));this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this));this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this));this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this));this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this));this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}async getBalanceAndContext(publicKey,commitment){const args=this._buildArgs([publicKey.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getBalance",args);const res=create(unsafeRes,jsonRpcResultAndContext(number()));if("error"in res){throw new Error("failed to get balance for "+publicKey.toBase58()+": "+res.error.message)}return res.result}async getBalance(publicKey,commitment){return await this.getBalanceAndContext(publicKey,commitment).then((x=>x.value)).catch((e=>{throw new Error("failed to get balance of account "+publicKey.toBase58()+": "+e)}))}async getBlockTime(slot){const unsafeRes=await this._rpcRequest("getBlockTime",[slot]);const res=create(unsafeRes,jsonRpcResult(nullable(number())));if("error"in res){throw new Error("failed to get block time for slot "+slot+": "+res.error.message)}return res.result}async getMinimumLedgerSlot(){const unsafeRes=await this._rpcRequest("minimumLedgerSlot",[]);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new Error("failed to get minimum ledger slot: "+res.error.message)}return res.result}async getFirstAvailableBlock(){const unsafeRes=await this._rpcRequest("getFirstAvailableBlock",[]);const res=create(unsafeRes,SlotRpcResult);if("error"in res){throw new Error("failed to get first available block: "+res.error.message)}return res.result}async getSupply(config){let configArg={};if(typeof config==="string"){configArg={commitment:config}}else if(config){configArg={...config,commitment:config&&config.commitment||this.commitment}}else{configArg={commitment:this.commitment}}const unsafeRes=await this._rpcRequest("getSupply",[configArg]);const res=create(unsafeRes,GetSupplyRpcResult);if("error"in res){throw new Error("failed to get supply: "+res.error.message)}return res.result}async getTokenSupply(tokenMintAddress,commitment){const args=this._buildArgs([tokenMintAddress.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getTokenSupply",args);const res=create(unsafeRes,jsonRpcResultAndContext(TokenAmountResult));if("error"in res){throw new Error("failed to get token supply: "+res.error.message)}return res.result}async getTokenAccountBalance(tokenAddress,commitment){const args=this._buildArgs([tokenAddress.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getTokenAccountBalance",args);const res=create(unsafeRes,jsonRpcResultAndContext(TokenAmountResult));if("error"in res){throw new Error("failed to get token account balance: "+res.error.message)}return res.result}async getTokenAccountsByOwner(ownerAddress,filter,commitment){let _args=[ownerAddress.toBase58()];if("mint"in filter){_args.push({mint:filter.mint.toBase58()})}else{_args.push({programId:filter.programId.toBase58()})}const args=this._buildArgs(_args,commitment,"base64");const unsafeRes=await this._rpcRequest("getTokenAccountsByOwner",args);const res=create(unsafeRes,GetTokenAccountsByOwner);if("error"in res){throw new Error("failed to get token accounts owned by account "+ownerAddress.toBase58()+": "+res.error.message)}return res.result}async getParsedTokenAccountsByOwner(ownerAddress,filter,commitment){let _args=[ownerAddress.toBase58()];if("mint"in filter){_args.push({mint:filter.mint.toBase58()})}else{_args.push({programId:filter.programId.toBase58()})}const args=this._buildArgs(_args,commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getTokenAccountsByOwner",args);const res=create(unsafeRes,GetParsedTokenAccountsByOwner);if("error"in res){throw new Error("failed to get token accounts owned by account "+ownerAddress.toBase58()+": "+res.error.message)}return res.result}async getLargestAccounts(config){const arg={...config,commitment:config&&config.commitment||this.commitment};const args=arg.filter||arg.commitment?[arg]:[];const unsafeRes=await this._rpcRequest("getLargestAccounts",args);const res=create(unsafeRes,GetLargestAccountsRpcResult);if("error"in res){throw new Error("failed to get largest accounts: "+res.error.message)}return res.result}async getTokenLargestAccounts(mintAddress,commitment){const args=this._buildArgs([mintAddress.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getTokenLargestAccounts",args);const res=create(unsafeRes,GetTokenLargestAccountsResult);if("error"in res){throw new Error("failed to get token largest accounts: "+res.error.message)}return res.result}async getAccountInfoAndContext(publicKey,commitment){const args=this._buildArgs([publicKey.toBase58()],commitment,"base64");const unsafeRes=await this._rpcRequest("getAccountInfo",args);const res=create(unsafeRes,jsonRpcResultAndContext(nullable(AccountInfoResult)));if("error"in res){throw new Error("failed to get info about account "+publicKey.toBase58()+": "+res.error.message)}return res.result}async getParsedAccountInfo(publicKey,commitment){const args=this._buildArgs([publicKey.toBase58()],commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getAccountInfo",args);const res=create(unsafeRes,jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)));if("error"in res){throw new Error("failed to get info about account "+publicKey.toBase58()+": "+res.error.message)}return res.result}async getAccountInfo(publicKey,commitment){try{const res=await this.getAccountInfoAndContext(publicKey,commitment);return res.value}catch(e){throw new Error("failed to get info about account "+publicKey.toBase58()+": "+e)}}async getMultipleAccountsInfo(publicKeys,configOrCommitment){const keys=publicKeys.map((key=>key.toBase58()));let commitment;let encoding="base64";if(configOrCommitment){if(typeof configOrCommitment==="string"){commitment=configOrCommitment;encoding="base64"}else{commitment=configOrCommitment.commitment;encoding=configOrCommitment.encoding||"base64"}}const args=this._buildArgs([keys],commitment,encoding);const unsafeRes=await this._rpcRequest("getMultipleAccounts",args);const res=create(unsafeRes,jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult))));if("error"in res){throw new Error("failed to get info for accounts "+keys+": "+res.error.message)}return res.result.value}async getStakeActivation(publicKey,commitment,epoch){const args=this._buildArgs([publicKey.toBase58()],commitment,undefined,epoch!==undefined?{epoch:epoch}:undefined);const unsafeRes=await this._rpcRequest("getStakeActivation",args);const res=create(unsafeRes,jsonRpcResult(StakeActivationResult));if("error"in res){throw new Error(`failed to get Stake Activation ${publicKey.toBase58()}: ${res.error.message}`)}return res.result}async getProgramAccounts(programId,configOrCommitment){const extra={};let commitment;let encoding;if(configOrCommitment){if(typeof configOrCommitment==="string"){commitment=configOrCommitment}else{commitment=configOrCommitment.commitment;encoding=configOrCommitment.encoding;if(configOrCommitment.dataSlice){extra.dataSlice=configOrCommitment.dataSlice}if(configOrCommitment.filters){extra.filters=configOrCommitment.filters}}}const args=this._buildArgs([programId.toBase58()],commitment,encoding||"base64",extra);const unsafeRes=await this._rpcRequest("getProgramAccounts",args);const res=create(unsafeRes,jsonRpcResult(array(KeyedAccountInfoResult)));if("error"in res){throw new Error("failed to get accounts owned by program "+programId.toBase58()+": "+res.error.message)}return res.result}async getParsedProgramAccounts(programId,configOrCommitment){const extra={};let commitment;if(configOrCommitment){if(typeof configOrCommitment==="string"){commitment=configOrCommitment}else{commitment=configOrCommitment.commitment;if(configOrCommitment.filters){extra.filters=configOrCommitment.filters}}}const args=this._buildArgs([programId.toBase58()],commitment,"jsonParsed",extra);const unsafeRes=await this._rpcRequest("getProgramAccounts",args);const res=create(unsafeRes,jsonRpcResult(array(KeyedParsedAccountInfoResult)));if("error"in res){throw new Error("failed to get accounts owned by program "+programId.toBase58()+": "+res.error.message)}return res.result}async confirmTransaction(signature,commitment){let decodedSignature;try{decodedSignature=bs58$1.decode(signature)}catch(err){throw new Error("signature must be base58 encoded: "+signature)}assert$c(decodedSignature.length===64,"signature has invalid length");const start=Date.now();const subscriptionCommitment=commitment||this.commitment;let subscriptionId;let response=null;const confirmPromise=new Promise(((resolve,reject)=>{try{subscriptionId=this.onSignature(signature,((result,context)=>{subscriptionId=undefined;response={context:context,value:result};resolve(null)}),subscriptionCommitment)}catch(err){reject(err)}}));let timeoutMs=this._confirmTransactionInitialTimeout||60*1e3;switch(subscriptionCommitment){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":{timeoutMs=this._confirmTransactionInitialTimeout||30*1e3;break}}try{await promiseTimeout(confirmPromise,timeoutMs)}finally{if(subscriptionId){this.removeSignatureListener(subscriptionId)}}if(response===null){const duration=(Date.now()-start)/1e3;throw new Error(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`)}return response}async getClusterNodes(){const unsafeRes=await this._rpcRequest("getClusterNodes",[]);const res=create(unsafeRes,jsonRpcResult(array(ContactInfoResult)));if("error"in res){throw new Error("failed to get cluster nodes: "+res.error.message)}return res.result}async getVoteAccounts(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getVoteAccounts",args);const res=create(unsafeRes,GetVoteAccounts);if("error"in res){throw new Error("failed to get vote accounts: "+res.error.message)}return res.result}async getSlot(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getSlot",args);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new Error("failed to get slot: "+res.error.message)}return res.result}async getSlotLeader(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getSlotLeader",args);const res=create(unsafeRes,jsonRpcResult(string()));if("error"in res){throw new Error("failed to get slot leader: "+res.error.message)}return res.result}async getSlotLeaders(startSlot,limit){const args=[startSlot,limit];const unsafeRes=await this._rpcRequest("getSlotLeaders",args);const res=create(unsafeRes,jsonRpcResult(array(PublicKeyFromString)));if("error"in res){throw new Error("failed to get slot leaders: "+res.error.message)}return res.result}async getSignatureStatus(signature,config){const{context:context,value:values}=await this.getSignatureStatuses([signature],config);assert$c(values.length===1);const value=values[0];return{context:context,value:value}}async getSignatureStatuses(signatures,config){const params=[signatures];if(config){params.push(config)}const unsafeRes=await this._rpcRequest("getSignatureStatuses",params);const res=create(unsafeRes,GetSignatureStatusesRpcResult);if("error"in res){throw new Error("failed to get signature status: "+res.error.message)}return res.result}async getTransactionCount(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getTransactionCount",args);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new Error("failed to get transaction count: "+res.error.message)}return res.result}async getTotalSupply(commitment){const result=await this.getSupply({commitment:commitment,excludeNonCirculatingAccountsList:true});return result.value.total}async getInflationGovernor(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getInflationGovernor",args);const res=create(unsafeRes,GetInflationGovernorRpcResult);if("error"in res){throw new Error("failed to get inflation: "+res.error.message)}return res.result}async getInflationReward(addresses,epoch,commitment){const args=this._buildArgs([addresses.map((pubkey=>pubkey.toBase58()))],commitment,undefined,{epoch:epoch});const unsafeRes=await this._rpcRequest("getInflationReward",args);const res=create(unsafeRes,GetInflationRewardResult);if("error"in res){throw new Error("failed to get inflation reward: "+res.error.message)}return res.result}async getEpochInfo(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getEpochInfo",args);const res=create(unsafeRes,GetEpochInfoRpcResult);if("error"in res){throw new Error("failed to get epoch info: "+res.error.message)}return res.result}async getEpochSchedule(){const unsafeRes=await this._rpcRequest("getEpochSchedule",[]);const res=create(unsafeRes,GetEpochScheduleRpcResult);if("error"in res){throw new Error("failed to get epoch schedule: "+res.error.message)}const epochSchedule=res.result;return new EpochSchedule(epochSchedule.slotsPerEpoch,epochSchedule.leaderScheduleSlotOffset,epochSchedule.warmup,epochSchedule.firstNormalEpoch,epochSchedule.firstNormalSlot)}async getLeaderSchedule(){const unsafeRes=await this._rpcRequest("getLeaderSchedule",[]);const res=create(unsafeRes,GetLeaderScheduleRpcResult);if("error"in res){throw new Error("failed to get leader schedule: "+res.error.message)}return res.result}async getMinimumBalanceForRentExemption(dataLength,commitment){const args=this._buildArgs([dataLength],commitment);const unsafeRes=await this._rpcRequest("getMinimumBalanceForRentExemption",args);const res=create(unsafeRes,GetMinimumBalanceForRentExemptionRpcResult);if("error"in res){console.warn("Unable to fetch minimum balance for rent exemption");return 0}return res.result}async getRecentBlockhashAndContext(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getRecentBlockhash",args);const res=create(unsafeRes,GetRecentBlockhashAndContextRpcResult);if("error"in res){throw new Error("failed to get recent blockhash: "+res.error.message)}return res.result}async getRecentPerformanceSamples(limit){const args=this._buildArgs(limit?[limit]:[]);const unsafeRes=await this._rpcRequest("getRecentPerformanceSamples",args);const res=create(unsafeRes,GetRecentPerformanceSamplesRpcResult);if("error"in res){throw new Error("failed to get recent performance samples: "+res.error.message)}return res.result}async getFeeCalculatorForBlockhash(blockhash,commitment){const args=this._buildArgs([blockhash],commitment);const unsafeRes=await this._rpcRequest("getFeeCalculatorForBlockhash",args);const res=create(unsafeRes,GetFeeCalculatorRpcResult);if("error"in res){throw new Error("failed to get fee calculator: "+res.error.message)}const{context:context,value:value}=res.result;return{context:context,value:value!==null?value.feeCalculator:null}}async getFeeForMessage(message,commitment){const wireMessage=message.serialize().toString("base64");const args=this._buildArgs([wireMessage],commitment);const unsafeRes=await this._rpcRequest("getFeeForMessage",args);const res=create(unsafeRes,jsonRpcResultAndContext(nullable(number())));if("error"in res){throw new Error("failed to get slot: "+res.error.message)}if(res.result===null){throw new Error("invalid blockhash")}return res.result}async getRecentBlockhash(commitment){try{const res=await this.getRecentBlockhashAndContext(commitment);return res.value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhash(commitment){try{const res=await this.getLatestBlockhashAndContext(commitment);return res.value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhashAndContext(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getLatestBlockhash",args);const res=create(unsafeRes,GetLatestBlockhashRpcResult);if("error"in res){throw new Error("failed to get latest blockhash: "+res.error.message)}return res.result}async getVersion(){const unsafeRes=await this._rpcRequest("getVersion",[]);const res=create(unsafeRes,jsonRpcResult(VersionResult));if("error"in res){throw new Error("failed to get version: "+res.error.message)}return res.result}async getGenesisHash(){const unsafeRes=await this._rpcRequest("getGenesisHash",[]);const res=create(unsafeRes,jsonRpcResult(string()));if("error"in res){throw new Error("failed to get genesis hash: "+res.error.message)}return res.result}async getBlock(slot,opts){const args=this._buildArgsAtLeastConfirmed([slot],opts&&opts.commitment);const unsafeRes=await this._rpcRequest("getBlock",args);const res=create(unsafeRes,GetBlockRpcResult);if("error"in res){throw new Error("failed to get confirmed block: "+res.error.message)}const result=res.result;if(!result)return result;return{...result,transactions:result.transactions.map((({transaction:transaction,meta:meta})=>{const message=new Message(transaction.message);return{meta:meta,transaction:{...transaction,message:message}}}))}}async getTransaction(signature,opts){const args=this._buildArgsAtLeastConfirmed([signature],opts&&opts.commitment);const unsafeRes=await this._rpcRequest("getTransaction",args);const res=create(unsafeRes,GetTransactionRpcResult);if("error"in res){throw new Error("failed to get transaction: "+res.error.message)}const result=res.result;if(!result)return result;return{...result,transaction:{...result.transaction,message:new Message(result.transaction.message)}}}async getParsedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getTransaction",args);const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new Error("failed to get transaction: "+res.error.message)}return res.result}async getParsedTransactions(signatures,commitment){const batch=signatures.map((signature=>{const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");return{methodName:"getTransaction",args:args}}));const unsafeRes=await this._rpcBatchRequest(batch);const res=unsafeRes.map((unsafeRes=>{const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new Error("failed to get transactions: "+res.error.message)}return res.result}));return res}async getConfirmedBlock(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment);const unsafeRes=await this._rpcRequest("getConfirmedBlock",args);const res=create(unsafeRes,GetConfirmedBlockRpcResult);if("error"in res){throw new Error("failed to get confirmed block: "+res.error.message)}const result=res.result;if(!result){throw new Error("Confirmed block "+slot+" not found")}const block={...result,transactions:result.transactions.map((({transaction:transaction,meta:meta})=>{const message=new Message(transaction.message);return{meta:meta,transaction:{...transaction,message:message}}}))};return{...block,transactions:block.transactions.map((({transaction:transaction,meta:meta})=>({meta:meta,transaction:Transaction.populate(transaction.message,transaction.signatures)})))}}async getBlocks(startSlot,endSlot,commitment){const args=this._buildArgsAtLeastConfirmed(endSlot!==undefined?[startSlot,endSlot]:[startSlot],commitment);const unsafeRes=await this._rpcRequest("getBlocks",args);const res=create(unsafeRes,jsonRpcResult(array(number())));if("error"in res){throw new Error("failed to get blocks: "+res.error.message)}return res.result}async getBlockSignatures(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment,undefined,{transactionDetails:"signatures",rewards:false});const unsafeRes=await this._rpcRequest("getBlock",args);const res=create(unsafeRes,GetBlockSignaturesRpcResult);if("error"in res){throw new Error("failed to get block: "+res.error.message)}const result=res.result;if(!result){throw new Error("Block "+slot+" not found")}return result}async getConfirmedBlockSignatures(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment,undefined,{transactionDetails:"signatures",rewards:false});const unsafeRes=await this._rpcRequest("getConfirmedBlock",args);const res=create(unsafeRes,GetBlockSignaturesRpcResult);if("error"in res){throw new Error("failed to get confirmed block: "+res.error.message)}const result=res.result;if(!result){throw new Error("Confirmed block "+slot+" not found")}return result}async getConfirmedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment);const unsafeRes=await this._rpcRequest("getConfirmedTransaction",args);const res=create(unsafeRes,GetTransactionRpcResult);if("error"in res){throw new Error("failed to get transaction: "+res.error.message)}const result=res.result;if(!result)return result;const message=new Message(result.transaction.message);const signatures=result.transaction.signatures;return{...result,transaction:Transaction.populate(message,signatures)}}async getParsedConfirmedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getConfirmedTransaction",args);const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new Error("failed to get confirmed transaction: "+res.error.message)}return res.result}async getParsedConfirmedTransactions(signatures,commitment){const batch=signatures.map((signature=>{const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");return{methodName:"getConfirmedTransaction",args:args}}));const unsafeRes=await this._rpcBatchRequest(batch);const res=unsafeRes.map((unsafeRes=>{const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new Error("failed to get confirmed transactions: "+res.error.message)}return res.result}));return res}async getConfirmedSignaturesForAddress(address,startSlot,endSlot){let options={};let firstAvailableBlock=await this.getFirstAvailableBlock();while(!("until"in options)){startSlot--;if(startSlot<=0||startSlot<firstAvailableBlock){break}try{const block=await this.getConfirmedBlockSignatures(startSlot,"finalized");if(block.signatures.length>0){options.until=block.signatures[block.signatures.length-1].toString()}}catch(err){if(err instanceof Error&&err.message.includes("skipped")){continue}else{throw err}}}let highestConfirmedRoot=await this.getSlot("finalized");while(!("before"in options)){endSlot++;if(endSlot>highestConfirmedRoot){break}try{const block=await this.getConfirmedBlockSignatures(endSlot);if(block.signatures.length>0){options.before=block.signatures[block.signatures.length-1].toString()}}catch(err){if(err instanceof Error&&err.message.includes("skipped")){continue}else{throw err}}}const confirmedSignatureInfo=await this.getConfirmedSignaturesForAddress2(address,options);return confirmedSignatureInfo.map((info=>info.signature))}async getConfirmedSignaturesForAddress2(address,options,commitment){const args=this._buildArgsAtLeastConfirmed([address.toBase58()],commitment,undefined,options);const unsafeRes=await this._rpcRequest("getConfirmedSignaturesForAddress2",args);const res=create(unsafeRes,GetConfirmedSignaturesForAddress2RpcResult);if("error"in res){throw new Error("failed to get confirmed signatures for address: "+res.error.message)}return res.result}async getSignaturesForAddress(address,options,commitment){const args=this._buildArgsAtLeastConfirmed([address.toBase58()],commitment,undefined,options);const unsafeRes=await this._rpcRequest("getSignaturesForAddress",args);const res=create(unsafeRes,GetSignaturesForAddressRpcResult);if("error"in res){throw new Error("failed to get signatures for address: "+res.error.message)}return res.result}async getNonceAndContext(nonceAccount,commitment){const{context:context,value:accountInfo}=await this.getAccountInfoAndContext(nonceAccount,commitment);let value=null;if(accountInfo!==null){value=NonceAccount.fromAccountData(accountInfo.data)}return{context:context,value:value}}async getNonce(nonceAccount,commitment){return await this.getNonceAndContext(nonceAccount,commitment).then((x=>x.value)).catch((e=>{throw new Error("failed to get nonce for account "+nonceAccount.toBase58()+": "+e)}))}async requestAirdrop(to,lamports){const unsafeRes=await this._rpcRequest("requestAirdrop",[to.toBase58(),lamports]);const res=create(unsafeRes,RequestAirdropRpcResult);if("error"in res){throw new Error("airdrop to "+to.toBase58()+" failed: "+res.error.message)}return res.result}async _recentBlockhash(disableCache){if(!disableCache){while(this._pollingBlockhash){await sleep(100)}const timeSinceFetch=Date.now()-this._blockhashInfo.lastFetch;const expired=timeSinceFetch>=BLOCKHASH_CACHE_TIMEOUT_MS;if(this._blockhashInfo.recentBlockhash!==null&&!expired){return this._blockhashInfo.recentBlockhash}}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=true;try{const startTime=Date.now();for(let i=0;i<50;i++){const{blockhash:blockhash}=await this.getRecentBlockhash("finalized");if(this._blockhashInfo.recentBlockhash!=blockhash){this._blockhashInfo={recentBlockhash:blockhash,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]};return blockhash}await sleep(MS_PER_SLOT/2)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-startTime}ms`)}finally{this._pollingBlockhash=false}}async simulateTransaction(transactionOrMessage,signers,includeAccounts){let transaction;if(transactionOrMessage instanceof Transaction){transaction=transactionOrMessage}else{transaction=Transaction.populate(transactionOrMessage)}if(transaction.nonceInfo&&signers){transaction.sign(...signers)}else{let disableCache=this._disableBlockhashCaching;for(;;){transaction.recentBlockhash=await this._recentBlockhash(disableCache);if(!signers)break;transaction.sign(...signers);if(!transaction.signature){throw new Error("!signature")}const signature=transaction.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(signature)&&!this._blockhashInfo.transactionSignatures.includes(signature)){this._blockhashInfo.simulatedSignatures.push(signature);break}else{disableCache=true}}}const message=transaction._compile();const signData=message.serialize();const wireTransaction=transaction._serialize(signData);const encodedTransaction=wireTransaction.toString("base64");const config={encoding:"base64",commitment:this.commitment};if(includeAccounts){const addresses=(Array.isArray(includeAccounts)?includeAccounts:message.nonProgramIds()).map((key=>key.toBase58()));config["accounts"]={encoding:"base64",addresses:addresses}}if(signers){config.sigVerify=true}const args=[encodedTransaction,config];const unsafeRes=await this._rpcRequest("simulateTransaction",args);const res=create(unsafeRes,SimulatedTransactionResponseStruct);if("error"in res){let logs;if("data"in res.error){logs=res.error.data.logs;if(logs&&Array.isArray(logs)){const traceIndent="\n ";const logTrace=traceIndent+logs.join(traceIndent);console.error(res.error.message,logTrace)}}throw new SendTransactionError("failed to simulate transaction: "+res.error.message,logs)}return res.result}async sendTransaction(transaction,signers,options){if(transaction.nonceInfo){transaction.sign(...signers)}else{let disableCache=this._disableBlockhashCaching;for(;;){transaction.recentBlockhash=await this._recentBlockhash(disableCache);transaction.sign(...signers);if(!transaction.signature){throw new Error("!signature")}const signature=transaction.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(signature)){this._blockhashInfo.transactionSignatures.push(signature);break}else{disableCache=true}}}const wireTransaction=transaction.serialize();return await this.sendRawTransaction(wireTransaction,options)}async sendRawTransaction(rawTransaction,options){const encodedTransaction=toBuffer(rawTransaction).toString("base64");const result=await this.sendEncodedTransaction(encodedTransaction,options);return result}async sendEncodedTransaction(encodedTransaction,options){const config={encoding:"base64"};const skipPreflight=options&&options.skipPreflight;const preflightCommitment=options&&options.preflightCommitment||this.commitment;if(options&&options.maxRetries){config.maxRetries=options.maxRetries}if(skipPreflight){config.skipPreflight=skipPreflight}if(preflightCommitment){config.preflightCommitment=preflightCommitment}const args=[encodedTransaction,config];const unsafeRes=await this._rpcRequest("sendTransaction",args);const res=create(unsafeRes,SendTransactionRpcResult);if("error"in res){let logs;if("data"in res.error){logs=res.error.data.logs;if(logs&&Array.isArray(logs)){const traceIndent="\n ";const logTrace=traceIndent+logs.join(traceIndent);console.error(res.error.message,logTrace)}}throw new SendTransactionError("failed to send transaction: "+res.error.message,logs)}return res.result}_wsOnOpen(){this._rpcWebSocketConnected=true;this._rpcWebSocketHeartbeat=setInterval((()=>{this._rpcWebSocket.notify("ping").catch((()=>{}))}),5e3);this._updateSubscriptions()}_wsOnError(err){console.error("ws error:",err.message)}_wsOnClose(code){if(this._rpcWebSocketHeartbeat){clearInterval(this._rpcWebSocketHeartbeat);this._rpcWebSocketHeartbeat=null}if(code===1e3){this._updateSubscriptions();return}this._resetSubscriptions()}async _subscribe(sub,rpcMethod,rpcArgs){if(sub.subscriptionId==null){sub.subscriptionId="subscribing";try{const id=await this._rpcWebSocket.call(rpcMethod,rpcArgs);if(typeof id==="number"&&sub.subscriptionId==="subscribing"){sub.subscriptionId=id}}catch(err){if(sub.subscriptionId==="subscribing"){sub.subscriptionId=null}if(err instanceof Error){console.error(`${rpcMethod} error for argument`,rpcArgs,err.message)}}}}async _unsubscribe(sub,rpcMethod){const subscriptionId=sub.subscriptionId;if(subscriptionId!=null&&typeof subscriptionId!="string"){const unsubscribeId=subscriptionId;try{await this._rpcWebSocket.call(rpcMethod,[unsubscribeId])}catch(err){if(err instanceof Error){console.error(`${rpcMethod} error:`,err.message)}}}}_resetSubscriptions(){Object.values(this._accountChangeSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._programAccountChangeSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._rootSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._signatureSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._slotSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._slotUpdateSubscriptions).forEach((s=>s.subscriptionId=null))}_updateSubscriptions(){const accountKeys=Object.keys(this._accountChangeSubscriptions).map(Number);const programKeys=Object.keys(this._programAccountChangeSubscriptions).map(Number);const slotKeys=Object.keys(this._slotSubscriptions).map(Number);const slotUpdateKeys=Object.keys(this._slotUpdateSubscriptions).map(Number);const signatureKeys=Object.keys(this._signatureSubscriptions).map(Number);const rootKeys=Object.keys(this._rootSubscriptions).map(Number);const logsKeys=Object.keys(this._logsSubscriptions).map(Number);if(accountKeys.length===0&&programKeys.length===0&&slotKeys.length===0&&slotUpdateKeys.length===0&&signatureKeys.length===0&&rootKeys.length===0&&logsKeys.length===0){if(this._rpcWebSocketConnected){this._rpcWebSocketConnected=false;this._rpcWebSocketIdleTimeout=setTimeout((()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(err){if(err instanceof Error){console.log(`Error when closing socket connection: ${err.message}`)}}}),500)}return}if(this._rpcWebSocketIdleTimeout!==null){clearTimeout(this._rpcWebSocketIdleTimeout);this._rpcWebSocketIdleTimeout=null;this._rpcWebSocketConnected=true}if(!this._rpcWebSocketConnected){this._rpcWebSocket.connect();return}for(let id of accountKeys){const sub=this._accountChangeSubscriptions[id];this._subscribe(sub,"accountSubscribe",this._buildArgs([sub.publicKey],sub.commitment,"base64"))}for(let id of programKeys){const sub=this._programAccountChangeSubscriptions[id];this._subscribe(sub,"programSubscribe",this._buildArgs([sub.programId],sub.commitment,"base64",{filters:sub.filters}))}for(let id of slotKeys){const sub=this._slotSubscriptions[id];this._subscribe(sub,"slotSubscribe",[])}for(let id of slotUpdateKeys){const sub=this._slotUpdateSubscriptions[id];this._subscribe(sub,"slotsUpdatesSubscribe",[])}for(let id of signatureKeys){const sub=this._signatureSubscriptions[id];const args=[sub.signature];if(sub.options)args.push(sub.options);this._subscribe(sub,"signatureSubscribe",args)}for(let id of rootKeys){const sub=this._rootSubscriptions[id];this._subscribe(sub,"rootSubscribe",[])}for(let id of logsKeys){const sub=this._logsSubscriptions[id];let filter;if(typeof sub.filter==="object"){filter={mentions:[sub.filter.toString()]}}else{filter=sub.filter}this._subscribe(sub,"logsSubscribe",this._buildArgs([filter],sub.commitment))}}_wsOnAccountNotification(notification){const res=create(notification,AccountNotificationResult);for(const sub of Object.values(this._accountChangeSubscriptions)){if(sub.subscriptionId===res.subscription){sub.callback(res.result.value,res.result.context);return}}}onAccountChange(publicKey,callback,commitment){const id=++this._accountChangeSubscriptionCounter;this._accountChangeSubscriptions[id]={publicKey:publicKey.toBase58(),callback:callback,commitment:commitment,subscriptionId:null};this._updateSubscriptions();return id}async removeAccountChangeListener(id){if(this._accountChangeSubscriptions[id]){const subInfo=this._accountChangeSubscriptions[id];delete this._accountChangeSubscriptions[id];await this._unsubscribe(subInfo,"accountUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown account change id: ${id}`)}}_wsOnProgramAccountNotification(notification){const res=create(notification,ProgramAccountNotificationResult);for(const sub of Object.values(this._programAccountChangeSubscriptions)){if(sub.subscriptionId===res.subscription){const{value:value,context:context}=res.result;sub.callback({accountId:value.pubkey,accountInfo:value.account},context);return}}}onProgramAccountChange(programId,callback,commitment,filters){const id=++this._programAccountChangeSubscriptionCounter;this._programAccountChangeSubscriptions[id]={programId:programId.toBase58(),callback:callback,commitment:commitment,subscriptionId:null,filters:filters};this._updateSubscriptions();return id}async removeProgramAccountChangeListener(id){if(this._programAccountChangeSubscriptions[id]){const subInfo=this._programAccountChangeSubscriptions[id];delete this._programAccountChangeSubscriptions[id];await this._unsubscribe(subInfo,"programUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown program account change id: ${id}`)}}onLogs(filter,callback,commitment){const id=++this._logsSubscriptionCounter;this._logsSubscriptions[id]={filter:filter,callback:callback,commitment:commitment,subscriptionId:null};this._updateSubscriptions();return id}async removeOnLogsListener(id){if(!this._logsSubscriptions[id]){throw new Error(`Unknown logs id: ${id}`)}const subInfo=this._logsSubscriptions[id];delete this._logsSubscriptions[id];await this._unsubscribe(subInfo,"logsUnsubscribe");this._updateSubscriptions()}_wsOnLogsNotification(notification){const res=create(notification,LogsNotificationResult);const keys=Object.keys(this._logsSubscriptions).map(Number);for(let id of keys){const sub=this._logsSubscriptions[id];if(sub.subscriptionId===res.subscription){sub.callback(res.result.value,res.result.context);return}}}_wsOnSlotNotification(notification){const res=create(notification,SlotNotificationResult);for(const sub of Object.values(this._slotSubscriptions)){if(sub.subscriptionId===res.subscription){sub.callback(res.result);return}}}onSlotChange(callback){const id=++this._slotSubscriptionCounter;this._slotSubscriptions[id]={callback:callback,subscriptionId:null};this._updateSubscriptions();return id}async removeSlotChangeListener(id){if(this._slotSubscriptions[id]){const subInfo=this._slotSubscriptions[id];delete this._slotSubscriptions[id];await this._unsubscribe(subInfo,"slotUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown slot change id: ${id}`)}}_wsOnSlotUpdatesNotification(notification){const res=create(notification,SlotUpdateNotificationResult);for(const sub of Object.values(this._slotUpdateSubscriptions)){if(sub.subscriptionId===res.subscription){sub.callback(res.result);return}}}onSlotUpdate(callback){const id=++this._slotUpdateSubscriptionCounter;this._slotUpdateSubscriptions[id]={callback:callback,subscriptionId:null};this._updateSubscriptions();return id}async removeSlotUpdateListener(id){if(this._slotUpdateSubscriptions[id]){const subInfo=this._slotUpdateSubscriptions[id];delete this._slotUpdateSubscriptions[id];await this._unsubscribe(subInfo,"slotsUpdatesUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown slot update id: ${id}`)}}_buildArgs(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment||encoding||extra){let options={};if(encoding){options.encoding=encoding}if(commitment){options.commitment=commitment}if(extra){options=Object.assign(options,extra)}args.push(options)}return args}_buildArgsAtLeastConfirmed(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment&&!["confirmed","finalized"].includes(commitment)){throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`")}return this._buildArgs(args,override,encoding,extra)}_wsOnSignatureNotification(notification){const res=create(notification,SignatureNotificationResult);for(const[id,sub]of Object.entries(this._signatureSubscriptions)){if(sub.subscriptionId===res.subscription){if(res.result.value==="receivedSignature"){sub.callback({type:"received"},res.result.context)}else{delete this._signatureSubscriptions[Number(id)];this._updateSubscriptions();sub.callback({type:"status",result:res.result.value},res.result.context)}return}}}onSignature(signature,callback,commitment){const id=++this._signatureSubscriptionCounter;this._signatureSubscriptions[id]={signature:signature,callback:(notification,context)=>{if(notification.type==="status"){callback(notification.result,context)}},options:{commitment:commitment},subscriptionId:null};this._updateSubscriptions();return id}onSignatureWithOptions(signature,callback,options){const id=++this._signatureSubscriptionCounter;this._signatureSubscriptions[id]={signature:signature,callback:callback,options:options,subscriptionId:null};this._updateSubscriptions();return id}async removeSignatureListener(id){if(this._signatureSubscriptions[id]){const subInfo=this._signatureSubscriptions[id];delete this._signatureSubscriptions[id];await this._unsubscribe(subInfo,"signatureUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown signature result id: ${id}`)}}_wsOnRootNotification(notification){const res=create(notification,RootNotificationResult);for(const sub of Object.values(this._rootSubscriptions)){if(sub.subscriptionId===res.subscription){sub.callback(res.result);return}}}onRootChange(callback){const id=++this._rootSubscriptionCounter;this._rootSubscriptions[id]={callback:callback,subscriptionId:null};this._updateSubscriptions();return id}async removeRootChangeListener(id){if(this._rootSubscriptions[id]){const subInfo=this._rootSubscriptions[id];delete this._rootSubscriptions[id];await this._unsubscribe(subInfo,"rootUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown root change id: ${id}`)}}}class Keypair{constructor(keypair){this._keypair=void 0;if(keypair){this._keypair=keypair}else{this._keypair=nacl.sign.keyPair()}}static generate(){return new Keypair(nacl.sign.keyPair())}static fromSecretKey(secretKey,options){const keypair=nacl.sign.keyPair.fromSecretKey(secretKey);if(!options||!options.skipValidation){const encoder=new TextEncoder;const signData=encoder.encode("@solana/web3.js-validation-v1");const signature=nacl.sign.detached(signData,keypair.secretKey);if(!nacl.sign.detached.verify(signData,signature,keypair.publicKey)){throw new Error("provided secretKey is invalid")}}return new Keypair(keypair)}static fromSeed(seed){return new Keypair(nacl.sign.keyPair.fromSeed(seed))}get publicKey(){return new PublicKey(this._keypair.publicKey)}get secretKey(){return this._keypair.secretKey}}const PRIVATE_KEY_BYTES$1=64;const PUBLIC_KEY_BYTES$1=32;const SIGNATURE_BYTES=64;const ED25519_INSTRUCTION_LAYOUT=struct([u8("numSignatures"),u8("padding"),u16("signatureOffset"),u16("signatureInstructionIndex"),u16("publicKeyOffset"),u16("publicKeyInstructionIndex"),u16("messageDataOffset"),u16("messageDataSize"),u16("messageInstructionIndex")]);class Ed25519Program{constructor(){}static createInstructionWithPublicKey(params){const{publicKey:publicKey,message:message,signature:signature,instructionIndex:instructionIndex}=params;assert$c(publicKey.length===PUBLIC_KEY_BYTES$1,`Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey.length} bytes`);assert$c(signature.length===SIGNATURE_BYTES,`Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);const publicKeyOffset=ED25519_INSTRUCTION_LAYOUT.span;const signatureOffset=publicKeyOffset+publicKey.length;const messageDataOffset=signatureOffset+signature.length;const numSignatures=1;const instructionData=buffer.Buffer.alloc(messageDataOffset+message.length);ED25519_INSTRUCTION_LAYOUT.encode({numSignatures:numSignatures,padding:0,signatureOffset:signatureOffset,signatureInstructionIndex:instructionIndex,publicKeyOffset:publicKeyOffset,publicKeyInstructionIndex:instructionIndex,messageDataOffset:messageDataOffset,messageDataSize:message.length,messageInstructionIndex:instructionIndex},instructionData);instructionData.fill(publicKey,publicKeyOffset);instructionData.fill(signature,signatureOffset);instructionData.fill(message,messageDataOffset);return new TransactionInstruction({keys:[],programId:Ed25519Program.programId,data:instructionData})}static createInstructionWithPrivateKey(params){const{privateKey:privateKey,message:message,instructionIndex:instructionIndex}=params;assert$c(privateKey.length===PRIVATE_KEY_BYTES$1,`Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);try{const keypair=Keypair.fromSecretKey(privateKey);const publicKey=keypair.publicKey.toBytes();const signature=nacl.sign.detached(message,keypair.secretKey);return this.createInstructionWithPublicKey({publicKey:publicKey,message:message,signature:signature,instructionIndex:instructionIndex})}catch(error){throw new Error(`Error creating instruction; ${error}`)}}}Ed25519Program.programId=new PublicKey("Ed25519SigVerify111111111111111111111111111");const STAKE_CONFIG_ID=new PublicKey("StakeConfig11111111111111111111111111111111");class Authorized{constructor(staker,withdrawer){this.staker=void 0;this.withdrawer=void 0;this.staker=staker;this.withdrawer=withdrawer}}class Lockup{constructor(unixTimestamp,epoch,custodian){this.unixTimestamp=void 0;this.epoch=void 0;this.custodian=void 0;this.unixTimestamp=unixTimestamp;this.epoch=epoch;this.custodian=custodian}}Lockup.default=new Lockup(0,0,PublicKey.default);class StakeInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=u32("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(STAKE_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a StakeInstruction")}return type}static decodeInitialize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{authorized:authorized,lockup:lockup}=decodeData(STAKE_INSTRUCTION_LAYOUTS.Initialize,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,authorized:new Authorized(new PublicKey(authorized.staker),new PublicKey(authorized.withdrawer)),lockup:new Lockup(lockup.unixTimestamp,lockup.epoch,new PublicKey(lockup.custodian))}}static decodeDelegate(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,6);decodeData(STAKE_INSTRUCTION_LAYOUTS.Delegate,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,votePubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[5].pubkey}}static decodeAuthorize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{newAuthorized:newAuthorized,stakeAuthorizationType:stakeAuthorizationType}=decodeData(STAKE_INSTRUCTION_LAYOUTS.Authorize,instruction.data);const o={stakePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey,newAuthorizedPubkey:new PublicKey(newAuthorized),stakeAuthorizationType:{index:stakeAuthorizationType}};if(instruction.keys.length>3){o.custodianPubkey=instruction.keys[3].pubkey}return o}static decodeAuthorizeWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{newAuthorized:newAuthorized,stakeAuthorizationType:stakeAuthorizationType,authoritySeed:authoritySeed,authorityOwner:authorityOwner}=decodeData(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,instruction.data);const o={stakePubkey:instruction.keys[0].pubkey,authorityBase:instruction.keys[1].pubkey,authoritySeed:authoritySeed,authorityOwner:new PublicKey(authorityOwner),newAuthorizedPubkey:new PublicKey(newAuthorized),stakeAuthorizationType:{index:stakeAuthorizationType}};if(instruction.keys.length>3){o.custodianPubkey=instruction.keys[3].pubkey}return o}static decodeSplit(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{lamports:lamports}=decodeData(STAKE_INSTRUCTION_LAYOUTS.Split,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,splitStakePubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[2].pubkey,lamports:lamports}}static decodeMerge(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);decodeData(STAKE_INSTRUCTION_LAYOUTS.Merge,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,sourceStakePubKey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey}}static decodeWithdraw(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,5);const{lamports:lamports}=decodeData(STAKE_INSTRUCTION_LAYOUTS.Withdraw,instruction.data);const o={stakePubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey,lamports:lamports};if(instruction.keys.length>5){o.custodianPubkey=instruction.keys[5].pubkey}return o}static decodeDeactivate(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);decodeData(STAKE_INSTRUCTION_LAYOUTS.Deactivate,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey}}static checkProgramId(programId){if(!programId.equals(StakeProgram.programId)){throw new Error("invalid instruction; programId is not StakeProgram")}}static checkKeyLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}const STAKE_INSTRUCTION_LAYOUTS=Object.freeze({Initialize:{index:0,layout:struct([u32("instruction"),authorized(),lockup()])},Authorize:{index:1,layout:struct([u32("instruction"),publicKey("newAuthorized"),u32("stakeAuthorizationType")])},Delegate:{index:2,layout:struct([u32("instruction")])},Split:{index:3,layout:struct([u32("instruction"),ns64("lamports")])},Withdraw:{index:4,layout:struct([u32("instruction"),ns64("lamports")])},Deactivate:{index:5,layout:struct([u32("instruction")])},Merge:{index:7,layout:struct([u32("instruction")])},AuthorizeWithSeed:{index:8,layout:struct([u32("instruction"),publicKey("newAuthorized"),u32("stakeAuthorizationType"),rustString("authoritySeed"),publicKey("authorityOwner")])}});const StakeAuthorizationLayout=Object.freeze({Staker:{index:0},Withdrawer:{index:1}});class StakeProgram{constructor(){}static initialize(params){const{stakePubkey:stakePubkey,authorized:authorized,lockup:maybeLockup}=params;const lockup=maybeLockup||Lockup.default;const type=STAKE_INSTRUCTION_LAYOUTS.Initialize;const data=encodeData(type,{authorized:{staker:toBuffer(authorized.staker.toBuffer()),withdrawer:toBuffer(authorized.withdrawer.toBuffer())},lockup:{unixTimestamp:lockup.unixTimestamp,epoch:lockup.epoch,custodian:toBuffer(lockup.custodian.toBuffer())}});const instructionData={keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static createAccountWithSeed(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccountWithSeed({fromPubkey:params.fromPubkey,newAccountPubkey:params.stakePubkey,basePubkey:params.basePubkey,seed:params.seed,lamports:params.lamports,space:this.space,programId:this.programId}));const{stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}=params;return transaction.add(this.initialize({stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}))}static createAccount(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.stakePubkey,lamports:params.lamports,space:this.space,programId:this.programId}));const{stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}=params;return transaction.add(this.initialize({stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}))}static delegate(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,votePubkey:votePubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Delegate;const data=encodeData(type);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:votePubkey,isSigner:false,isWritable:false},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:false,isWritable:false},{pubkey:STAKE_CONFIG_ID,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static authorize(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,newAuthorizedPubkey:newAuthorizedPubkey,stakeAuthorizationType:stakeAuthorizationType,custodianPubkey:custodianPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Authorize;const data=encodeData(type,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),stakeAuthorizationType:stakeAuthorizationType.index});const keys=[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:true},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}];if(custodianPubkey){keys.push({pubkey:custodianPubkey,isSigner:false,isWritable:false})}return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static authorizeWithSeed(params){const{stakePubkey:stakePubkey,authorityBase:authorityBase,authoritySeed:authoritySeed,authorityOwner:authorityOwner,newAuthorizedPubkey:newAuthorizedPubkey,stakeAuthorizationType:stakeAuthorizationType,custodianPubkey:custodianPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;const data=encodeData(type,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),stakeAuthorizationType:stakeAuthorizationType.index,authoritySeed:authoritySeed,authorityOwner:toBuffer(authorityOwner.toBuffer())});const keys=[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:authorityBase,isSigner:true,isWritable:false},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false}];if(custodianPubkey){keys.push({pubkey:custodianPubkey,isSigner:false,isWritable:false})}return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static splitInstruction(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,splitStakePubkey:splitStakePubkey,lamports:lamports}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Split;const data=encodeData(type,{lamports:lamports});return new TransactionInstruction({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:splitStakePubkey,isSigner:false,isWritable:true},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static split(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.authorizedPubkey,newAccountPubkey:params.splitStakePubkey,lamports:0,space:this.space,programId:this.programId}));return transaction.add(this.splitInstruction(params))}static splitWithSeed(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,splitStakePubkey:splitStakePubkey,basePubkey:basePubkey,seed:seed,lamports:lamports}=params;const transaction=new Transaction;transaction.add(SystemProgram.allocate({accountPubkey:splitStakePubkey,basePubkey:basePubkey,seed:seed,space:this.space,programId:this.programId}));return transaction.add(this.splitInstruction({stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,splitStakePubkey:splitStakePubkey,lamports:lamports}))}static merge(params){const{stakePubkey:stakePubkey,sourceStakePubKey:sourceStakePubKey,authorizedPubkey:authorizedPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Merge;const data=encodeData(type);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:sourceStakePubKey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static withdraw(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,toPubkey:toPubkey,lamports:lamports,custodianPubkey:custodianPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Withdraw;const data=encodeData(type,{lamports:lamports});const keys=[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:toPubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}];if(custodianPubkey){keys.push({pubkey:custodianPubkey,isSigner:false,isWritable:false})}return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static deactivate(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Deactivate;const data=encodeData(type);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}}StakeProgram.programId=new PublicKey("Stake11111111111111111111111111111111111111");StakeProgram.space=200;const errors={IMPOSSIBLE_CASE:"Impossible case. Please create issue.",TWEAK_ADD:"The tweak was out of range or the resulted private key is invalid",TWEAK_MUL:"The tweak was out of range or equal to zero",CONTEXT_RANDOMIZE_UNKNOW:"Unknow error on context randomization",SECKEY_INVALID:"Private Key is invalid",PUBKEY_PARSE:"Public Key could not be parsed",PUBKEY_SERIALIZE:"Public Key serialization error",PUBKEY_COMBINE:"The sum of the public keys is not valid",SIG_PARSE:"Signature could not be parsed",SIGN:"The nonce generation function failed, or the private key was invalid",RECOVER:"Public key could not be recover",ECDH:"Scalar was invalid (zero or overflow)"};function assert$a(cond,msg){if(!cond)throw new Error(msg)}function isUint8Array(name,value,length){assert$a(value instanceof Uint8Array,`Expected ${name} to be an Uint8Array`);if(length!==undefined){if(Array.isArray(length)){const numbers=length.join(", ");const msg=`Expected ${name} to be an Uint8Array with length [${numbers}]`;assert$a(length.includes(value.length),msg)}else{const msg=`Expected ${name} to be an Uint8Array with length ${length}`;assert$a(value.length===length,msg)}}}function isCompressed(value){assert$a(toTypeString(value)==="Boolean","Expected compressed to be a Boolean")}function getAssertedOutput(output=(len=>new Uint8Array(len)),length){if(typeof output==="function")output=output(length);isUint8Array("output",output,length);return output}function toTypeString(value){return Object.prototype.toString.call(value).slice(8,-1)}var lib=secp256k1=>({contextRandomize(seed){assert$a(seed===null||seed instanceof Uint8Array,"Expected seed to be an Uint8Array or null");if(seed!==null)isUint8Array("seed",seed,32);switch(secp256k1.contextRandomize(seed)){case 1:throw new Error(errors.CONTEXT_RANDOMIZE_UNKNOW)}},privateKeyVerify(seckey){isUint8Array("private key",seckey,32);return secp256k1.privateKeyVerify(seckey)===0},privateKeyNegate(seckey){isUint8Array("private key",seckey,32);switch(secp256k1.privateKeyNegate(seckey)){case 0:return seckey;case 1:throw new Error(errors.IMPOSSIBLE_CASE)}},privateKeyTweakAdd(seckey,tweak){isUint8Array("private key",seckey,32);isUint8Array("tweak",tweak,32);switch(secp256k1.privateKeyTweakAdd(seckey,tweak)){case 0:return seckey;case 1:throw new Error(errors.TWEAK_ADD)}},privateKeyTweakMul(seckey,tweak){isUint8Array("private key",seckey,32);isUint8Array("tweak",tweak,32);switch(secp256k1.privateKeyTweakMul(seckey,tweak)){case 0:return seckey;case 1:throw new Error(errors.TWEAK_MUL)}},publicKeyVerify(pubkey){isUint8Array("public key",pubkey,[33,65]);return secp256k1.publicKeyVerify(pubkey)===0},publicKeyCreate(seckey,compressed=true,output){isUint8Array("private key",seckey,32);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyCreate(output,seckey)){case 0:return output;case 1:throw new Error(errors.SECKEY_INVALID);case 2:throw new Error(errors.PUBKEY_SERIALIZE)}},publicKeyConvert(pubkey,compressed=true,output){isUint8Array("public key",pubkey,[33,65]);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyConvert(output,pubkey)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.PUBKEY_SERIALIZE)}},publicKeyNegate(pubkey,compressed=true,output){isUint8Array("public key",pubkey,[33,65]);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyNegate(output,pubkey)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.IMPOSSIBLE_CASE);case 3:throw new Error(errors.PUBKEY_SERIALIZE)}},publicKeyCombine(pubkeys,compressed=true,output){assert$a(Array.isArray(pubkeys),"Expected public keys to be an Array");assert$a(pubkeys.length>0,"Expected public keys array will have more than zero items");for(const pubkey of pubkeys){isUint8Array("public key",pubkey,[33,65])}isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyCombine(output,pubkeys)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.PUBKEY_COMBINE);case 3:throw new Error(errors.PUBKEY_SERIALIZE)}},publicKeyTweakAdd(pubkey,tweak,compressed=true,output){isUint8Array("public key",pubkey,[33,65]);isUint8Array("tweak",tweak,32);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyTweakAdd(output,pubkey,tweak)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.TWEAK_ADD)}},publicKeyTweakMul(pubkey,tweak,compressed=true,output){isUint8Array("public key",pubkey,[33,65]);isUint8Array("tweak",tweak,32);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyTweakMul(output,pubkey,tweak)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.TWEAK_MUL)}},signatureNormalize(sig){isUint8Array("signature",sig,64);switch(secp256k1.signatureNormalize(sig)){case 0:return sig;case 1:throw new Error(errors.SIG_PARSE)}},signatureExport(sig,output){isUint8Array("signature",sig,64);output=getAssertedOutput(output,72);const obj={output:output,outputlen:72};switch(secp256k1.signatureExport(obj,sig)){case 0:return output.slice(0,obj.outputlen);case 1:throw new Error(errors.SIG_PARSE);case 2:throw new Error(errors.IMPOSSIBLE_CASE)}},signatureImport(sig,output){isUint8Array("signature",sig);output=getAssertedOutput(output,64);switch(secp256k1.signatureImport(output,sig)){case 0:return output;case 1:throw new Error(errors.SIG_PARSE);case 2:throw new Error(errors.IMPOSSIBLE_CASE)}},ecdsaSign(msg32,seckey,options={},output){isUint8Array("message",msg32,32);isUint8Array("private key",seckey,32);assert$a(toTypeString(options)==="Object","Expected options to be an Object");if(options.data!==undefined)isUint8Array("options.data",options.data);if(options.noncefn!==undefined)assert$a(toTypeString(options.noncefn)==="Function","Expected options.noncefn to be a Function");output=getAssertedOutput(output,64);const obj={signature:output,recid:null};switch(secp256k1.ecdsaSign(obj,msg32,seckey,options.data,options.noncefn)){case 0:return obj;case 1:throw new Error(errors.SIGN);case 2:throw new Error(errors.IMPOSSIBLE_CASE)}},ecdsaVerify(sig,msg32,pubkey){isUint8Array("signature",sig,64);isUint8Array("message",msg32,32);isUint8Array("public key",pubkey,[33,65]);switch(secp256k1.ecdsaVerify(sig,msg32,pubkey)){case 0:return true;case 3:return false;case 1:throw new Error(errors.SIG_PARSE);case 2:throw new Error(errors.PUBKEY_PARSE)}},ecdsaRecover(sig,recid,msg32,compressed=true,output){isUint8Array("signature",sig,64);assert$a(toTypeString(recid)==="Number"&&recid>=0&&recid<=3,"Expected recovery id to be a Number within interval [0, 3]");isUint8Array("message",msg32,32);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.ecdsaRecover(output,sig,recid,msg32)){case 0:return output;case 1:throw new Error(errors.SIG_PARSE);case 2:throw new Error(errors.RECOVER);case 3:throw new Error(errors.IMPOSSIBLE_CASE)}},ecdh(pubkey,seckey,options={},output){isUint8Array("public key",pubkey,[33,65]);isUint8Array("private key",seckey,32);assert$a(toTypeString(options)==="Object","Expected options to be an Object");if(options.data!==undefined)isUint8Array("options.data",options.data);if(options.hashfn!==undefined){assert$a(toTypeString(options.hashfn)==="Function","Expected options.hashfn to be a Function");if(options.xbuf!==undefined)isUint8Array("options.xbuf",options.xbuf,32);if(options.ybuf!==undefined)isUint8Array("options.ybuf",options.ybuf,32);isUint8Array("output",output)}else{output=getAssertedOutput(output,32)}switch(secp256k1.ecdh(output,pubkey,seckey,options.data,options.hashfn,options.xbuf,options.ybuf)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.ECDH)}}});var elliptic$2={};var name="elliptic";var version="6.5.4";var description="EC cryptography";var main="lib/elliptic.js";var files=["lib"];var scripts={lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"};var repository={type:"git",url:"git@github.com:indutny/elliptic"};var keywords=["EC","Elliptic","curve","Cryptography"];var author="Fedor Indutny <fedor@indutny.com>";var license="MIT";var bugs={url:"https://github.com/indutny/elliptic/issues"};var homepage="https://github.com/indutny/elliptic";var devDependencies={brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"};var dependencies={"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"};var require$$0={name:name,version:version,description:description,main:main,files:files,scripts:scripts,repository:repository,keywords:keywords,author:author,license:license,bugs:bugs,homepage:homepage,devDependencies:devDependencies,dependencies:dependencies};var utils$c={};var utils$b={};(function(exports){var utils=exports;function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg!=="string"){for(var i=0;i<msg.length;i++)res[i]=msg[i]|0;return res}if(enc==="hex"){msg=msg.replace(/[^a-z0-9]+/gi,"");if(msg.length%2!==0)msg="0"+msg;for(var i=0;i<msg.length;i+=2)res.push(parseInt(msg[i]+msg[i+1],16))}else{for(var i=0;i<msg.length;i++){var c=msg.charCodeAt(i);var hi=c>>8;var lo=c&255;if(hi)res.push(hi,lo);else res.push(lo)}}return res}utils.toArray=toArray;function zero2(word){if(word.length===1)return"0"+word;else return word}utils.zero2=zero2;function toHex(msg){var res="";for(var i=0;i<msg.length;i++)res+=zero2(msg[i].toString(16));return res}utils.toHex=toHex;utils.encode=function encode(arr,enc){if(enc==="hex")return toHex(arr);else return arr}})(utils$b);(function(exports){var utils=exports;var BN=bn.exports;var minAssert=minimalisticAssert;var minUtils=utils$b;utils.assert=minAssert;utils.toArray=minUtils.toArray;utils.zero2=minUtils.zero2;utils.toHex=minUtils.toHex;utils.encode=minUtils.encode;function getNAF(num,w,bits){var naf=new Array(Math.max(num.bitLength(),bits)+1);naf.fill(0);var ws=1<<w+1;var k=num.clone();for(var i=0;i<naf.length;i++){var z;var mod=k.andln(ws-1);if(k.isOdd()){if(mod>(ws>>1)-1)z=(ws>>1)-mod;else z=mod;k.isubn(z)}else{z=0}naf[i]=z;k.iushrn(1)}return naf}utils.getNAF=getNAF;function getJSF(k1,k2){var jsf=[[],[]];k1=k1.clone();k2=k2.clone();var d1=0;var d2=0;var m8;while(k1.cmpn(-d1)>0||k2.cmpn(-d2)>0){var m14=k1.andln(3)+d1&3;var m24=k2.andln(3)+d2&3;if(m14===3)m14=-1;if(m24===3)m24=-1;var u1;if((m14&1)===0){u1=0}else{m8=k1.andln(7)+d1&7;if((m8===3||m8===5)&&m24===2)u1=-m14;else u1=m14}jsf[0].push(u1);var u2;if((m24&1)===0){u2=0}else{m8=k2.andln(7)+d2&7;if((m8===3||m8===5)&&m14===2)u2=-m24;else u2=m24}jsf[1].push(u2);if(2*d1===u1+1)d1=1-d1;if(2*d2===u2+1)d2=1-d2;k1.iushrn(1);k2.iushrn(1)}return jsf}utils.getJSF=getJSF;function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function cachedProperty(){return this[key]!==undefined?this[key]:this[key]=computer.call(this)}}utils.cachedProperty=cachedProperty;function parseBytes(bytes){return typeof bytes==="string"?utils.toArray(bytes,"hex"):bytes}utils.parseBytes=parseBytes;function intFromLE(bytes){return new BN(bytes,"hex","le")}utils.intFromLE=intFromLE})(utils$c);var brorand={exports:{}};var r;brorand.exports=function rand(len){if(!r)r=new Rand(null);return r.generate(len)};function Rand(rand){this.rand=rand}brorand.exports.Rand=Rand;Rand.prototype.generate=function generate(len){return this._rand(len)};Rand.prototype._rand=function _rand(n){if(this.rand.getBytes)return this.rand.getBytes(n);var res=new Uint8Array(n);for(var i=0;i<res.length;i++)res[i]=this.rand.getByte();return res};if(typeof self==="object"){if(self.crypto&&self.crypto.getRandomValues){Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);self.crypto.getRandomValues(arr);return arr}}else if(self.msCrypto&&self.msCrypto.getRandomValues){Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);self.msCrypto.getRandomValues(arr);return arr}}else if(typeof window==="object"){Rand.prototype._rand=function(){throw new Error("Not implemented yet")}}}else{try{var crypto$1=require("crypto");if(typeof crypto$1.randomBytes!=="function")throw new Error("Not supported");Rand.prototype._rand=function _rand(n){return crypto$1.randomBytes(n)}}catch(e){}}var curve={};var BN$8=bn.exports;var utils$a=utils$c;var getNAF=utils$a.getNAF;var getJSF=utils$a.getJSF;var assert$9=utils$a.assert;function BaseCurve(type,conf){this.type=type;this.p=new BN$8(conf.p,16);this.red=conf.prime?BN$8.red(conf.prime):BN$8.mont(this.p);this.zero=new BN$8(0).toRed(this.red);this.one=new BN$8(1).toRed(this.red);this.two=new BN$8(2).toRed(this.red);this.n=conf.n&&new BN$8(conf.n,16);this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed);this._wnafT1=new Array(4);this._wnafT2=new Array(4);this._wnafT3=new Array(4);this._wnafT4=new Array(4);this._bitLength=this.n?this.n.bitLength():0;var adjustCount=this.n&&this.p.div(this.n);if(!adjustCount||adjustCount.cmpn(100)>0){this.redN=null}else{this._maxwellTrick=true;this.redN=this.n.toRed(this.red)}}var base=BaseCurve;BaseCurve.prototype.point=function point(){throw new Error("Not implemented")};BaseCurve.prototype.validate=function validate(){throw new Error("Not implemented")};BaseCurve.prototype._fixedNafMul=function _fixedNafMul(p,k){assert$9(p.precomputed);var doubles=p._getDoubles();var naf=getNAF(k,1,this._bitLength);var I=(1<<doubles.step+1)-(doubles.step%2===0?2:1);I/=3;var repr=[];var j;var nafW;for(j=0;j<naf.length;j+=doubles.step){nafW=0;for(var l=j+doubles.step-1;l>=j;l--)nafW=(nafW<<1)+naf[l];repr.push(nafW)}var a=this.jpoint(null,null,null);var b=this.jpoint(null,null,null);for(var i=I;i>0;i--){for(j=0;j<repr.length;j++){nafW=repr[j];if(nafW===i)b=b.mixedAdd(doubles.points[j]);else if(nafW===-i)b=b.mixedAdd(doubles.points[j].neg())}a=a.add(b)}return a.toP()};BaseCurve.prototype._wnafMul=function _wnafMul(p,k){var w=4;var nafPoints=p._getNAFPoints(w);w=nafPoints.wnd;var wnd=nafPoints.points;var naf=getNAF(k,w,this._bitLength);var acc=this.jpoint(null,null,null);for(var i=naf.length-1;i>=0;i--){for(var l=0;i>=0&&naf[i]===0;i--)l++;if(i>=0)l++;acc=acc.dblp(l);if(i<0)break;var z=naf[i];assert$9(z!==0);if(p.type==="affine"){if(z>0)acc=acc.mixedAdd(wnd[z-1>>1]);else acc=acc.mixedAdd(wnd[-z-1>>1].neg())}else{if(z>0)acc=acc.add(wnd[z-1>>1]);else acc=acc.add(wnd[-z-1>>1].neg())}}return p.type==="affine"?acc.toP():acc};BaseCurve.prototype._wnafMulAdd=function _wnafMulAdd(defW,points,coeffs,len,jacobianResult){var wndWidth=this._wnafT1;var wnd=this._wnafT2;var naf=this._wnafT3;var max=0;var i;var j;var p;for(i=0;i<len;i++){p=points[i];var nafPoints=p._getNAFPoints(defW);wndWidth[i]=nafPoints.wnd;wnd[i]=nafPoints.points}for(i=len-1;i>=1;i-=2){var a=i-1;var b=i;if(wndWidth[a]!==1||wndWidth[b]!==1){naf[a]=getNAF(coeffs[a],wndWidth[a],this._bitLength);naf[b]=getNAF(coeffs[b],wndWidth[b],this._bitLength);max=Math.max(naf[a].length,max);max=Math.max(naf[b].length,max);continue}var comb=[points[a],null,null,points[b]];if(points[a].y.cmp(points[b].y)===0){comb[1]=points[a].add(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}else if(points[a].y.cmp(points[b].y.redNeg())===0){comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].add(points[b].neg())}else{comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}var index=[-3,-1,-5,-7,0,7,5,1,3];var jsf=getJSF(coeffs[a],coeffs[b]);max=Math.max(jsf[0].length,max);naf[a]=new Array(max);naf[b]=new Array(max);for(j=0;j<max;j++){var ja=jsf[0][j]|0;var jb=jsf[1][j]|0;naf[a][j]=index[(ja+1)*3+(jb+1)];naf[b][j]=0;wnd[a]=comb}}var acc=this.jpoint(null,null,null);var tmp=this._wnafT4;for(i=max;i>=0;i--){var k=0;while(i>=0){var zero=true;for(j=0;j<len;j++){tmp[j]=naf[j][i]|0;if(tmp[j]!==0)zero=false}if(!zero)break;k++;i--}if(i>=0)k++;acc=acc.dblp(k);if(i<0)break;for(j=0;j<len;j++){var z=tmp[j];if(z===0)continue;else if(z>0)p=wnd[j][z-1>>1];else if(z<0)p=wnd[j][-z-1>>1].neg();if(p.type==="affine")acc=acc.mixedAdd(p);else acc=acc.add(p)}}for(i=0;i<len;i++)wnd[i]=null;if(jacobianResult)return acc;else return acc.toP()};function BasePoint(curve,type){this.curve=curve;this.type=type;this.precomputed=null}BaseCurve.BasePoint=BasePoint;BasePoint.prototype.eq=function eq(){throw new Error("Not implemented")};BasePoint.prototype.validate=function validate(){return this.curve.validate(this)};BaseCurve.prototype.decodePoint=function decodePoint(bytes,enc){bytes=utils$a.toArray(bytes,enc);var len=this.p.byteLength();if((bytes[0]===4||bytes[0]===6||bytes[0]===7)&&bytes.length-1===2*len){if(bytes[0]===6)assert$9(bytes[bytes.length-1]%2===0);else if(bytes[0]===7)assert$9(bytes[bytes.length-1]%2===1);var res=this.point(bytes.slice(1,1+len),bytes.slice(1+len,1+2*len));return res}else if((bytes[0]===2||bytes[0]===3)&&bytes.length-1===len){return this.pointFromX(bytes.slice(1,1+len),bytes[0]===3)}throw new Error("Unknown point format")};BasePoint.prototype.encodeCompressed=function encodeCompressed(enc){return this.encode(enc,true)};BasePoint.prototype._encode=function _encode(compact){var len=this.curve.p.byteLength();var x=this.getX().toArray("be",len);if(compact)return[this.getY().isEven()?2:3].concat(x);return[4].concat(x,this.getY().toArray("be",len))};BasePoint.prototype.encode=function encode(enc,compact){return utils$a.encode(this._encode(compact),enc)};BasePoint.prototype.precompute=function precompute(power){if(this.precomputed)return this;var precomputed={doubles:null,naf:null,beta:null};precomputed.naf=this._getNAFPoints(8);precomputed.doubles=this._getDoubles(4,power);precomputed.beta=this._getBeta();this.precomputed=precomputed;return this};BasePoint.prototype._hasDoubles=function _hasDoubles(k){if(!this.precomputed)return false;var doubles=this.precomputed.doubles;if(!doubles)return false;return doubles.points.length>=Math.ceil((k.bitLength()+1)/doubles.step)};BasePoint.prototype._getDoubles=function _getDoubles(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;var doubles=[this];var acc=this;for(var i=0;i<power;i+=step){for(var j=0;j<step;j++)acc=acc.dbl();doubles.push(acc)}return{step:step,points:doubles}};BasePoint.prototype._getNAFPoints=function _getNAFPoints(wnd){if(this.precomputed&&this.precomputed.naf)return this.precomputed.naf;var res=[this];var max=(1<<wnd)-1;var dbl=max===1?null:this.dbl();for(var i=1;i<max;i++)res[i]=res[i-1].add(dbl);return{wnd:wnd,points:res}};BasePoint.prototype._getBeta=function _getBeta(){return null};BasePoint.prototype.dblp=function dblp(k){var r=this;for(var i=0;i<k;i++)r=r.dbl();return r};var inherits_browser={exports:{}};if(typeof Object.create==="function"){inherits_browser.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}}else{inherits_browser.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}var utils$9=utils$c;var BN$7=bn.exports;var inherits$2=inherits_browser.exports;var Base$2=base;var assert$8=utils$9.assert;function ShortCurve(conf){Base$2.call(this,"short",conf);this.a=new BN$7(conf.a,16).toRed(this.red);this.b=new BN$7(conf.b,16).toRed(this.red);this.tinv=this.two.redInvm();this.zeroA=this.a.fromRed().cmpn(0)===0;this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0;this.endo=this._getEndomorphism(conf);this._endoWnafT1=new Array(4);this._endoWnafT2=new Array(4)}inherits$2(ShortCurve,Base$2);var short=ShortCurve;ShortCurve.prototype._getEndomorphism=function _getEndomorphism(conf){if(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)return;var beta;var lambda;if(conf.beta){beta=new BN$7(conf.beta,16).toRed(this.red)}else{var betas=this._getEndoRoots(this.p);beta=betas[0].cmp(betas[1])<0?betas[0]:betas[1];beta=beta.toRed(this.red)}if(conf.lambda){lambda=new BN$7(conf.lambda,16)}else{var lambdas=this._getEndoRoots(this.n);if(this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta))===0){lambda=lambdas[0]}else{lambda=lambdas[1];assert$8(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta))===0)}}var basis;if(conf.basis){basis=conf.basis.map((function(vec){return{a:new BN$7(vec.a,16),b:new BN$7(vec.b,16)}}))}else{basis=this._getEndoBasis(lambda)}return{beta:beta,lambda:lambda,basis:basis}};ShortCurve.prototype._getEndoRoots=function _getEndoRoots(num){var red=num===this.p?this.red:BN$7.mont(num);var tinv=new BN$7(2).toRed(red).redInvm();var ntinv=tinv.redNeg();var s=new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv);var l1=ntinv.redAdd(s).fromRed();var l2=ntinv.redSub(s).fromRed();return[l1,l2]};ShortCurve.prototype._getEndoBasis=function _getEndoBasis(lambda){var aprxSqrt=this.n.ushrn(Math.floor(this.n.bitLength()/2));var u=lambda;var v=this.n.clone();var x1=new BN$7(1);var y1=new BN$7(0);var x2=new BN$7(0);var y2=new BN$7(1);var a0;var b0;var a1;var b1;var a2;var b2;var prevR;var i=0;var r;var x;while(u.cmpn(0)!==0){var q=v.div(u);r=v.sub(q.mul(u));x=x2.sub(q.mul(x1));var y=y2.sub(q.mul(y1));if(!a1&&r.cmp(aprxSqrt)<0){a0=prevR.neg();b0=x1;a1=r.neg();b1=x}else if(a1&&++i===2){break}prevR=r;v=u;u=r;x2=x1;x1=x;y2=y1;y1=y}a2=r.neg();b2=x;var len1=a1.sqr().add(b1.sqr());var len2=a2.sqr().add(b2.sqr());if(len2.cmp(len1)>=0){a2=a0;b2=b0}if(a1.negative){a1=a1.neg();b1=b1.neg()}if(a2.negative){a2=a2.neg();b2=b2.neg()}return[{a:a1,b:b1},{a:a2,b:b2}]};ShortCurve.prototype._endoSplit=function _endoSplit(k){var basis=this.endo.basis;var v1=basis[0];var v2=basis[1];var c1=v2.b.mul(k).divRound(this.n);var c2=v1.b.neg().mul(k).divRound(this.n);var p1=c1.mul(v1.a);var p2=c2.mul(v2.a);var q1=c1.mul(v1.b);var q2=c2.mul(v2.b);var k1=k.sub(p1).sub(p2);var k2=q1.add(q2).neg();return{k1:k1,k2:k2}};ShortCurve.prototype.pointFromX=function pointFromX(x,odd){x=new BN$7(x,16);if(!x.red)x=x.toRed(this.red);var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);var y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error("invalid point");var isOdd=y.fromRed().isOdd();if(odd&&!isOdd||!odd&&isOdd)y=y.redNeg();return this.point(x,y)};ShortCurve.prototype.validate=function validate(point){if(point.inf)return true;var x=point.x;var y=point.y;var ax=this.a.redMul(x);var rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return y.redSqr().redISub(rhs).cmpn(0)===0};ShortCurve.prototype._endoWnafMulAdd=function _endoWnafMulAdd(points,coeffs,jacobianResult){var npoints=this._endoWnafT1;var ncoeffs=this._endoWnafT2;for(var i=0;i<points.length;i++){var split=this._endoSplit(coeffs[i]);var p=points[i];var beta=p._getBeta();if(split.k1.negative){split.k1.ineg();p=p.neg(true)}if(split.k2.negative){split.k2.ineg();beta=beta.neg(true)}npoints[i*2]=p;npoints[i*2+1]=beta;ncoeffs[i*2]=split.k1;ncoeffs[i*2+1]=split.k2}var res=this._wnafMulAdd(1,npoints,ncoeffs,i*2,jacobianResult);for(var j=0;j<i*2;j++){npoints[j]=null;ncoeffs[j]=null}return res};function Point$2(curve,x,y,isRed){Base$2.BasePoint.call(this,curve,"affine");if(x===null&&y===null){this.x=null;this.y=null;this.inf=true}else{this.x=new BN$7(x,16);this.y=new BN$7(y,16);if(isRed){this.x.forceRed(this.curve.red);this.y.forceRed(this.curve.red)}if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);this.inf=false}}inherits$2(Point$2,Base$2.BasePoint);ShortCurve.prototype.point=function point(x,y,isRed){return new Point$2(this,x,y,isRed)};ShortCurve.prototype.pointFromJSON=function pointFromJSON(obj,red){return Point$2.fromJSON(this,obj,red)};Point$2.prototype._getBeta=function _getBeta(){if(!this.curve.endo)return;var pre=this.precomputed;if(pre&&pre.beta)return pre.beta;var beta=this.curve.point(this.x.redMul(this.curve.endo.beta),this.y);if(pre){var curve=this.curve;var endoMul=function(p){return curve.point(p.x.redMul(curve.endo.beta),p.y)};pre.beta=beta;beta.precomputed={beta:null,naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(endoMul)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(endoMul)}}}return beta};Point$2.prototype.toJSON=function toJSON(){if(!this.precomputed)return[this.x,this.y];return[this.x,this.y,this.precomputed&&{doubles:this.precomputed.doubles&&{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf&&{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}]};Point$2.fromJSON=function fromJSON(curve,obj,red){if(typeof obj==="string")obj=JSON.parse(obj);var res=curve.point(obj[0],obj[1],red);if(!obj[2])return res;function obj2point(obj){return curve.point(obj[0],obj[1],red)}var pre=obj[2];res.precomputed={beta:null,doubles:pre.doubles&&{step:pre.doubles.step,points:[res].concat(pre.doubles.points.map(obj2point))},naf:pre.naf&&{wnd:pre.naf.wnd,points:[res].concat(pre.naf.points.map(obj2point))}};return res};Point$2.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+">"};Point$2.prototype.isInfinity=function isInfinity(){return this.inf};Point$2.prototype.add=function add(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(this.x.cmp(p.x)===0)return this.curve.point(null,null);var c=this.y.redSub(p.y);if(c.cmpn(0)!==0)c=c.redMul(this.x.redSub(p.x).redInvm());var nx=c.redSqr().redISub(this.x).redISub(p.x);var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point$2.prototype.dbl=function dbl(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(ys1.cmpn(0)===0)return this.curve.point(null,null);var a=this.curve.a;var x2=this.x.redSqr();var dyinv=ys1.redInvm();var c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);var nx=c.redSqr().redISub(this.x.redAdd(this.x));var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point$2.prototype.getX=function getX(){return this.x.fromRed()};Point$2.prototype.getY=function getY(){return this.y.fromRed()};Point$2.prototype.mul=function mul(k){k=new BN$7(k,16);if(this.isInfinity())return this;else if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else if(this.curve.endo)return this.curve._endoWnafMulAdd([this],[k]);else return this.curve._wnafMul(this,k)};Point$2.prototype.mulAdd=function mulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs);else return this.curve._wnafMulAdd(1,points,coeffs,2)};Point$2.prototype.jmulAdd=function jmulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs,true);else return this.curve._wnafMulAdd(1,points,coeffs,2,true)};Point$2.prototype.eq=function eq(p){return this===p||this.inf===p.inf&&(this.inf||this.x.cmp(p.x)===0&&this.y.cmp(p.y)===0)};Point$2.prototype.neg=function neg(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed;var negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res};Point$2.prototype.toJ=function toJ(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res};function JPoint(curve,x,y,z){Base$2.BasePoint.call(this,curve,"jacobian");if(x===null&&y===null&&z===null){this.x=this.curve.one;this.y=this.curve.one;this.z=new BN$7(0)}else{this.x=new BN$7(x,16);this.y=new BN$7(y,16);this.z=new BN$7(z,16)}if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);this.zOne=this.z===this.curve.one}inherits$2(JPoint,Base$2.BasePoint);ShortCurve.prototype.jpoint=function jpoint(x,y,z){return new JPoint(this,x,y,z)};JPoint.prototype.toP=function toP(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm();var zinv2=zinv.redSqr();var ax=this.x.redMul(zinv2);var ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)};JPoint.prototype.neg=function neg(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)};JPoint.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr();var z2=this.z.redSqr();var u1=this.x.redMul(pz2);var u2=p.x.redMul(z2);var s1=this.y.redMul(pz2.redMul(p.z));var s2=p.y.redMul(z2.redMul(this.z));var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.mixedAdd=function mixedAdd(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr();var u1=this.x;var u2=p.x.redMul(z2);var s1=this.y;var s2=p.y.redMul(z2).redMul(this.z);var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.dblp=function dblp(pow){if(pow===0)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();var i;if(this.curve.zeroA||this.curve.threeA){var r=this;for(i=0;i<pow;i++)r=r.dbl();return r}var a=this.curve.a;var tinv=this.curve.tinv;var jx=this.x;var jy=this.y;var jz=this.z;var jz4=jz.redSqr().redSqr();var jyd=jy.redAdd(jy);for(i=0;i<pow;i++){var jx2=jx.redSqr();var jyd2=jyd.redSqr();var jyd4=jyd2.redSqr();var c=jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));var t1=jx.redMul(jyd2);var nx=c.redSqr().redISub(t1.redAdd(t1));var t2=t1.redISub(nx);var dny=c.redMul(t2);dny=dny.redIAdd(dny).redISub(jyd4);var nz=jyd.redMul(jz);if(i+1<pow)jz4=jz4.redMul(jyd4);jx=nx;jz=nz;jyd=dny}return this.curve.jpoint(jx,jyd.redMul(tinv),jz)};JPoint.prototype.dbl=function dbl(){if(this.isInfinity())return this;if(this.curve.zeroA)return this._zeroDbl();else if(this.curve.threeA)return this._threeDbl();else return this._dbl()};JPoint.prototype._zeroDbl=function _zeroDbl(){var nx;var ny;var nz;if(this.zOne){var xx=this.x.redSqr();var yy=this.y.redSqr();var yyyy=yy.redSqr();var s=this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);s=s.redIAdd(s);var m=xx.redAdd(xx).redIAdd(xx);var t=m.redSqr().redISub(s).redISub(s);var yyyy8=yyyy.redIAdd(yyyy);yyyy8=yyyy8.redIAdd(yyyy8);yyyy8=yyyy8.redIAdd(yyyy8);nx=t;ny=m.redMul(s.redISub(t)).redISub(yyyy8);nz=this.y.redAdd(this.y)}else{var a=this.x.redSqr();var b=this.y.redSqr();var c=b.redSqr();var d=this.x.redAdd(b).redSqr().redISub(a).redISub(c);d=d.redIAdd(d);var e=a.redAdd(a).redIAdd(a);var f=e.redSqr();var c8=c.redIAdd(c);c8=c8.redIAdd(c8);c8=c8.redIAdd(c8);nx=f.redISub(d).redISub(d);ny=e.redMul(d.redISub(nx)).redISub(c8);nz=this.y.redMul(this.z);nz=nz.redIAdd(nz)}return this.curve.jpoint(nx,ny,nz)};JPoint.prototype._threeDbl=function _threeDbl(){var nx;var ny;var nz;if(this.zOne){var xx=this.x.redSqr();var yy=this.y.redSqr();var yyyy=yy.redSqr();var s=this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);s=s.redIAdd(s);var m=xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);var t=m.redSqr().redISub(s).redISub(s);nx=t;var yyyy8=yyyy.redIAdd(yyyy);yyyy8=yyyy8.redIAdd(yyyy8);yyyy8=yyyy8.redIAdd(yyyy8);ny=m.redMul(s.redISub(t)).redISub(yyyy8);nz=this.y.redAdd(this.y)}else{var delta=this.z.redSqr();var gamma=this.y.redSqr();var beta=this.x.redMul(gamma);var alpha=this.x.redSub(delta).redMul(this.x.redAdd(delta));alpha=alpha.redAdd(alpha).redIAdd(alpha);var beta4=beta.redIAdd(beta);beta4=beta4.redIAdd(beta4);var beta8=beta4.redAdd(beta4);nx=alpha.redSqr().redISub(beta8);nz=this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);var ggamma8=gamma.redSqr();ggamma8=ggamma8.redIAdd(ggamma8);ggamma8=ggamma8.redIAdd(ggamma8);ggamma8=ggamma8.redIAdd(ggamma8);ny=alpha.redMul(beta4.redISub(nx)).redISub(ggamma8)}return this.curve.jpoint(nx,ny,nz)};JPoint.prototype._dbl=function _dbl(){var a=this.curve.a;var jx=this.x;var jy=this.y;var jz=this.z;var jz4=jz.redSqr().redSqr();var jx2=jx.redSqr();var jy2=jy.redSqr();var c=jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));var jxd4=jx.redAdd(jx);jxd4=jxd4.redIAdd(jxd4);var t1=jxd4.redMul(jy2);var nx=c.redSqr().redISub(t1.redAdd(t1));var t2=t1.redISub(nx);var jyd8=jy2.redSqr();jyd8=jyd8.redIAdd(jyd8);jyd8=jyd8.redIAdd(jyd8);jyd8=jyd8.redIAdd(jyd8);var ny=c.redMul(t2).redISub(jyd8);var nz=jy.redAdd(jy).redMul(jz);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.trpl=function trpl(){if(!this.curve.zeroA)return this.dbl().add(this);var xx=this.x.redSqr();var yy=this.y.redSqr();var zz=this.z.redSqr();var yyyy=yy.redSqr();var m=xx.redAdd(xx).redIAdd(xx);var mm=m.redSqr();var e=this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);e=e.redIAdd(e);e=e.redAdd(e).redIAdd(e);e=e.redISub(mm);var ee=e.redSqr();var t=yyyy.redIAdd(yyyy);t=t.redIAdd(t);t=t.redIAdd(t);t=t.redIAdd(t);var u=m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);var yyu4=yy.redMul(u);yyu4=yyu4.redIAdd(yyu4);yyu4=yyu4.redIAdd(yyu4);var nx=this.x.redMul(ee).redISub(yyu4);nx=nx.redIAdd(nx);nx=nx.redIAdd(nx);var ny=this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));ny=ny.redIAdd(ny);ny=ny.redIAdd(ny);ny=ny.redIAdd(ny);var nz=this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.mul=function mul(k,kbase){k=new BN$7(k,kbase);return this.curve._wnafMul(this,k)};JPoint.prototype.eq=function eq(p){if(p.type==="affine")return this.eq(p.toJ());if(this===p)return true;var z2=this.z.redSqr();var pz2=p.z.redSqr();if(this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0)!==0)return false;var z3=z2.redMul(this.z);var pz3=pz2.redMul(p.z);return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0)===0};JPoint.prototype.eqXToP=function eqXToP(x){var zs=this.z.redSqr();var rx=x.toRed(this.curve.red).redMul(zs);if(this.x.cmp(rx)===0)return true;var xc=x.clone();var t=this.curve.redN.redMul(zs);for(;;){xc.iadd(this.curve.n);if(xc.cmp(this.curve.p)>=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}};JPoint.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC JPoint Infinity>";return"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"};JPoint.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0};var BN$6=bn.exports;var inherits$1=inherits_browser.exports;var Base$1=base;var utils$8=utils$c;function MontCurve(conf){Base$1.call(this,"mont",conf);this.a=new BN$6(conf.a,16).toRed(this.red);this.b=new BN$6(conf.b,16).toRed(this.red);this.i4=new BN$6(4).toRed(this.red).redInvm();this.two=new BN$6(2).toRed(this.red);this.a24=this.i4.redMul(this.a.redAdd(this.two))}inherits$1(MontCurve,Base$1);var mont=MontCurve;MontCurve.prototype.validate=function validate(point){var x=point.normalize().x;var x2=x.redSqr();var rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);var y=rhs.redSqrt();return y.redSqr().cmp(rhs)===0};function Point$1(curve,x,z){Base$1.BasePoint.call(this,curve,"projective");if(x===null&&z===null){this.x=this.curve.one;this.z=this.curve.zero}else{this.x=new BN$6(x,16);this.z=new BN$6(z,16);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red)}}inherits$1(Point$1,Base$1.BasePoint);MontCurve.prototype.decodePoint=function decodePoint(bytes,enc){return this.point(utils$8.toArray(bytes,enc),1)};MontCurve.prototype.point=function point(x,z){return new Point$1(this,x,z)};MontCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point$1.fromJSON(this,obj)};Point$1.prototype.precompute=function precompute(){};Point$1.prototype._encode=function _encode(){return this.getX().toArray("be",this.curve.p.byteLength())};Point$1.fromJSON=function fromJSON(curve,obj){return new Point$1(curve,obj[0],obj[1]||curve.one)};Point$1.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"};Point$1.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0};Point$1.prototype.dbl=function dbl(){var a=this.x.redAdd(this.z);var aa=a.redSqr();var b=this.x.redSub(this.z);var bb=b.redSqr();var c=aa.redSub(bb);var nx=aa.redMul(bb);var nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)};Point$1.prototype.add=function add(){throw new Error("Not supported on Montgomery curve")};Point$1.prototype.diffAdd=function diffAdd(p,diff){var a=this.x.redAdd(this.z);var b=this.x.redSub(this.z);var c=p.x.redAdd(p.z);var d=p.x.redSub(p.z);var da=d.redMul(a);var cb=c.redMul(b);var nx=diff.z.redMul(da.redAdd(cb).redSqr());var nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)};Point$1.prototype.mul=function mul(k){var t=k.clone();var a=this;var b=this.curve.point(null,null);var c=this;for(var bits=[];t.cmpn(0)!==0;t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--){if(bits[i]===0){a=a.diffAdd(b,c);b=b.dbl()}else{b=a.diffAdd(b,c);a=a.dbl()}}return b};Point$1.prototype.mulAdd=function mulAdd(){throw new Error("Not supported on Montgomery curve")};Point$1.prototype.jumlAdd=function jumlAdd(){throw new Error("Not supported on Montgomery curve")};Point$1.prototype.eq=function eq(other){return this.getX().cmp(other.getX())===0};Point$1.prototype.normalize=function normalize(){this.x=this.x.redMul(this.z.redInvm());this.z=this.curve.one;return this};Point$1.prototype.getX=function getX(){this.normalize();return this.x.fromRed()};var utils$7=utils$c;var BN$5=bn.exports;var inherits=inherits_browser.exports;var Base=base;var assert$7=utils$7.assert;function EdwardsCurve(conf){this.twisted=(conf.a|0)!==1;this.mOneA=this.twisted&&(conf.a|0)===-1;this.extended=this.mOneA;Base.call(this,"edwards",conf);this.a=new BN$5(conf.a,16).umod(this.red.m);this.a=this.a.toRed(this.red);this.c=new BN$5(conf.c,16).toRed(this.red);this.c2=this.c.redSqr();this.d=new BN$5(conf.d,16).toRed(this.red);this.dd=this.d.redAdd(this.d);assert$7(!this.twisted||this.c.fromRed().cmpn(1)===0);this.oneC=(conf.c|0)===1}inherits(EdwardsCurve,Base);var edwards=EdwardsCurve;EdwardsCurve.prototype._mulA=function _mulA(num){if(this.mOneA)return num.redNeg();else return this.a.redMul(num)};EdwardsCurve.prototype._mulC=function _mulC(num){if(this.oneC)return num;else return this.c.redMul(num)};EdwardsCurve.prototype.jpoint=function jpoint(x,y,z,t){return this.point(x,y,z,t)};EdwardsCurve.prototype.pointFromX=function pointFromX(x,odd){x=new BN$5(x,16);if(!x.red)x=x.toRed(this.red);var x2=x.redSqr();var rhs=this.c2.redSub(this.a.redMul(x2));var lhs=this.one.redSub(this.c2.redMul(this.d).redMul(x2));var y2=rhs.redMul(lhs.redInvm());var y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error("invalid point");var isOdd=y.fromRed().isOdd();if(odd&&!isOdd||!odd&&isOdd)y=y.redNeg();return this.point(x,y)};EdwardsCurve.prototype.pointFromY=function pointFromY(y,odd){y=new BN$5(y,16);if(!y.red)y=y.toRed(this.red);var y2=y.redSqr();var lhs=y2.redSub(this.c2);var rhs=y2.redMul(this.d).redMul(this.c2).redSub(this.a);var x2=lhs.redMul(rhs.redInvm());if(x2.cmp(this.zero)===0){if(odd)throw new Error("invalid point");else return this.point(this.zero,y)}var x=x2.redSqrt();if(x.redSqr().redSub(x2).cmp(this.zero)!==0)throw new Error("invalid point");if(x.fromRed().isOdd()!==odd)x=x.redNeg();return this.point(x,y)};EdwardsCurve.prototype.validate=function validate(point){if(point.isInfinity())return true;point.normalize();var x2=point.x.redSqr();var y2=point.y.redSqr();var lhs=x2.redMul(this.a).redAdd(y2);var rhs=this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));return lhs.cmp(rhs)===0};function Point(curve,x,y,z,t){Base.BasePoint.call(this,curve,"projective");if(x===null&&y===null&&z===null){this.x=this.curve.zero;this.y=this.curve.one;this.z=this.curve.one;this.t=this.curve.zero;this.zOne=true}else{this.x=new BN$5(x,16);this.y=new BN$5(y,16);this.z=z?new BN$5(z,16):this.curve.one;this.t=t&&new BN$5(t,16);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);if(this.t&&!this.t.red)this.t=this.t.toRed(this.curve.red);this.zOne=this.z===this.curve.one;if(this.curve.extended&&!this.t){this.t=this.x.redMul(this.y);if(!this.zOne)this.t=this.t.redMul(this.z.redInvm())}}}inherits(Point,Base.BasePoint);EdwardsCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point.fromJSON(this,obj)};EdwardsCurve.prototype.point=function point(x,y,z,t){return new Point(this,x,y,z,t)};Point.fromJSON=function fromJSON(curve,obj){return new Point(curve,obj[0],obj[1],obj[2])};Point.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"};Point.prototype.isInfinity=function isInfinity(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)};Point.prototype._extDbl=function _extDbl(){var a=this.x.redSqr();var b=this.y.redSqr();var c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a);var e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);var g=d.redAdd(b);var f=g.redSub(c);var h=d.redSub(b);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projDbl=function _projDbl(){var b=this.x.redAdd(this.y).redSqr();var c=this.x.redSqr();var d=this.y.redSqr();var nx;var ny;var nz;var e;var h;var j;if(this.curve.twisted){e=this.curve._mulA(c);var f=e.redAdd(d);if(this.zOne){nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));ny=f.redMul(e.redSub(d));nz=f.redSqr().redSub(f).redSub(f)}else{h=this.z.redSqr();j=f.redSub(h).redISub(h);nx=b.redSub(c).redISub(d).redMul(j);ny=f.redMul(e.redSub(d));nz=f.redMul(j)}}else{e=c.redAdd(d);h=this.curve._mulC(this.z).redSqr();j=e.redSub(h).redSub(h);nx=this.curve._mulC(b.redISub(e)).redMul(j);ny=this.curve._mulC(e).redMul(c.redISub(d));nz=e.redMul(j)}return this.curve.point(nx,ny,nz)};Point.prototype.dbl=function dbl(){if(this.isInfinity())return this;if(this.curve.extended)return this._extDbl();else return this._projDbl()};Point.prototype._extAdd=function _extAdd(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x));var b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));var c=this.t.redMul(this.curve.dd).redMul(p.t);var d=this.z.redMul(p.z.redAdd(p.z));var e=b.redSub(a);var f=d.redSub(c);var g=d.redAdd(c);var h=b.redAdd(a);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projAdd=function _projAdd(p){var a=this.z.redMul(p.z);var b=a.redSqr();var c=this.x.redMul(p.x);var d=this.y.redMul(p.y);var e=this.curve.d.redMul(c).redMul(d);var f=b.redSub(e);var g=b.redAdd(e);var tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);var nx=a.redMul(f).redMul(tmp);var ny;var nz;if(this.curve.twisted){ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));nz=f.redMul(g)}else{ny=a.redMul(g).redMul(d.redSub(c));nz=this.curve._mulC(f).redMul(g)}return this.curve.point(nx,ny,nz)};Point.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;if(this.curve.extended)return this._extAdd(p);else return this._projAdd(p)};Point.prototype.mul=function mul(k){if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else return this.curve._wnafMul(this,k)};Point.prototype.mulAdd=function mulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,false)};Point.prototype.jmulAdd=function jmulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,true)};Point.prototype.normalize=function normalize(){if(this.zOne)return this;var zi=this.z.redInvm();this.x=this.x.redMul(zi);this.y=this.y.redMul(zi);if(this.t)this.t=this.t.redMul(zi);this.z=this.curve.one;this.zOne=true;return this};Point.prototype.neg=function neg(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())};Point.prototype.getX=function getX(){this.normalize();return this.x.fromRed()};Point.prototype.getY=function getY(){this.normalize();return this.y.fromRed()};Point.prototype.eq=function eq(other){return this===other||this.getX().cmp(other.getX())===0&&this.getY().cmp(other.getY())===0};Point.prototype.eqXToP=function eqXToP(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(rx)===0)return true;var xc=x.clone();var t=this.curve.redN.redMul(this.z);for(;;){xc.iadd(this.curve.n);if(xc.cmp(this.curve.p)>=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}};Point.prototype.toP=Point.prototype.normalize;Point.prototype.mixedAdd=Point.prototype.add;(function(exports){var curve=exports;curve.base=base;curve.short=short;curve.mont=mont;curve.edwards=edwards})(curve);var curves$2={};(function(exports){var curves=exports;var hash=hash$3;var curve$1=curve;var utils=utils$c;var assert=utils.assert;function PresetCurve(options){if(options.type==="short")this.curve=new curve$1.short(options);else if(options.type==="edwards")this.curve=new curve$1.edwards(options);else this.curve=new curve$1.mont(options);this.g=this.curve.g;this.n=this.curve.n;this.hash=options.hash;assert(this.g.validate(),"Invalid curve");assert(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}curves.PresetCurve=PresetCurve;function defineCurve(name,options){Object.defineProperty(curves,name,{configurable:true,enumerable:true,get:function(){var curve=new PresetCurve(options);Object.defineProperty(curves,name,{configurable:true,enumerable:true,value:curve});return curve}})}defineCurve("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:hash.sha256,gRed:false,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]});defineCurve("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:hash.sha256,gRed:false,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]});defineCurve("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:hash.sha256,gRed:false,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]});defineCurve("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f "+"5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 "+"f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:hash.sha384,gRed:false,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 "+"5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 "+"0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]});defineCurve("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b "+"99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd "+"3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 "+"f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:hash.sha512,gRed:false,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 "+"053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 "+"a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 "+"579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 "+"3fad0761 353c7086 a272c240 88be9476 9fd16650"]});defineCurve("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["9"]});defineCurve("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var pre;try{pre=require("./precomputed/secp256k1")}catch(e){pre=undefined}defineCurve("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:hash.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:false,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",pre]})})(curves$2);var hash$1=hash$3;var utils$6=utils$b;var assert$6=minimalisticAssert;function HmacDRBG$1(options){if(!(this instanceof HmacDRBG$1))return new HmacDRBG$1(options);this.hash=options.hash;this.predResist=!!options.predResist;this.outLen=this.hash.outSize;this.minEntropy=options.minEntropy||this.hash.hmacStrength;this._reseed=null;this.reseedInterval=null;this.K=null;this.V=null;var entropy=utils$6.toArray(options.entropy,options.entropyEnc||"hex");var nonce=utils$6.toArray(options.nonce,options.nonceEnc||"hex");var pers=utils$6.toArray(options.pers,options.persEnc||"hex");assert$6(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._init(entropy,nonce,pers)}var hmacDrbg=HmacDRBG$1;HmacDRBG$1.prototype._init=function init(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8);this.V=new Array(this.outLen/8);for(var i=0;i<this.V.length;i++){this.K[i]=0;this.V[i]=1}this._update(seed);this._reseed=1;this.reseedInterval=281474976710656};HmacDRBG$1.prototype._hmac=function hmac(){return new hash$1.hmac(this.hash,this.K)};HmacDRBG$1.prototype._update=function update(seed){var kmac=this._hmac().update(this.V).update([0]);if(seed)kmac=kmac.update(seed);this.K=kmac.digest();this.V=this._hmac().update(this.V).digest();if(!seed)return;this.K=this._hmac().update(this.V).update([1]).update(seed).digest();this.V=this._hmac().update(this.V).digest()};HmacDRBG$1.prototype.reseed=function reseed(entropy,entropyEnc,add,addEnc){if(typeof entropyEnc!=="string"){addEnc=add;add=entropyEnc;entropyEnc=null}entropy=utils$6.toArray(entropy,entropyEnc);add=utils$6.toArray(add,addEnc);assert$6(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._update(entropy.concat(add||[]));this._reseed=1};HmacDRBG$1.prototype.generate=function generate(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");if(typeof enc!=="string"){addEnc=add;add=enc;enc=null}if(add){add=utils$6.toArray(add,addEnc||"hex");this._update(add)}var temp=[];while(temp.length<len){this.V=this._hmac().update(this.V).digest();temp=temp.concat(this.V)}var res=temp.slice(0,len);this._update(add);this._reseed++;return utils$6.encode(res,enc)};var BN$4=bn.exports;var utils$5=utils$c;var assert$5=utils$5.assert;function KeyPair$3(ec,options){this.ec=ec;this.priv=null;this.pub=null;if(options.priv)this._importPrivate(options.priv,options.privEnc);if(options.pub)this._importPublic(options.pub,options.pubEnc)}var key$1=KeyPair$3;KeyPair$3.fromPublic=function fromPublic(ec,pub,enc){if(pub instanceof KeyPair$3)return pub;return new KeyPair$3(ec,{pub:pub,pubEnc:enc})};KeyPair$3.fromPrivate=function fromPrivate(ec,priv,enc){if(priv instanceof KeyPair$3)return priv;return new KeyPair$3(ec,{priv:priv,privEnc:enc})};KeyPair$3.prototype.validate=function validate(){var pub=this.getPublic();if(pub.isInfinity())return{result:false,reason:"Invalid public key"};if(!pub.validate())return{result:false,reason:"Public key is not a point"};if(!pub.mul(this.ec.curve.n).isInfinity())return{result:false,reason:"Public key * N != O"};return{result:true,reason:null}};KeyPair$3.prototype.getPublic=function getPublic(compact,enc){if(typeof compact==="string"){enc=compact;compact=null}if(!this.pub)this.pub=this.ec.g.mul(this.priv);if(!enc)return this.pub;return this.pub.encode(enc,compact)};KeyPair$3.prototype.getPrivate=function getPrivate(enc){if(enc==="hex")return this.priv.toString(16,2);else return this.priv};KeyPair$3.prototype._importPrivate=function _importPrivate(key,enc){this.priv=new BN$4(key,enc||16);this.priv=this.priv.umod(this.ec.curve.n)};KeyPair$3.prototype._importPublic=function _importPublic(key,enc){if(key.x||key.y){if(this.ec.curve.type==="mont"){assert$5(key.x,"Need x coordinate")}else if(this.ec.curve.type==="short"||this.ec.curve.type==="edwards"){assert$5(key.x&&key.y,"Need both x and y coordinate")}this.pub=this.ec.curve.point(key.x,key.y);return}this.pub=this.ec.curve.decodePoint(key,enc)};KeyPair$3.prototype.derive=function derive(pub){if(!pub.validate()){assert$5(pub.validate(),"public point not validated")}return pub.mul(this.priv).getX()};KeyPair$3.prototype.sign=function sign(msg,enc,options){return this.ec.sign(msg,this,enc,options)};KeyPair$3.prototype.verify=function verify(msg,signature){return this.ec.verify(msg,signature,this)};KeyPair$3.prototype.inspect=function inspect(){return"<Key priv: "+(this.priv&&this.priv.toString(16,2))+" pub: "+(this.pub&&this.pub.inspect())+" >"};var BN$3=bn.exports;var utils$4=utils$c;var assert$4=utils$4.assert;function Signature$3(options,enc){if(options instanceof Signature$3)return options;if(this._importDER(options,enc))return;assert$4(options.r&&options.s,"Signature without r or s");this.r=new BN$3(options.r,16);this.s=new BN$3(options.s,16);if(options.recoveryParam===undefined)this.recoveryParam=null;else this.recoveryParam=options.recoveryParam}var signature$1=Signature$3;function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(initial&128)){return initial}var octetLen=initial&15;if(octetLen===0||octetLen>4){return false}var val=0;for(var i=0,off=p.place;i<octetLen;i++,off++){val<<=8;val|=buf[off];val>>>=0}if(val<=127){return false}p.place=off;return val}function rmPadding(buf){var i=0;var len=buf.length-1;while(!buf[i]&&!(buf[i+1]&128)&&i<len){i++}if(i===0){return buf}return buf.slice(i)}Signature$3.prototype._importDER=function _importDER(data,enc){data=utils$4.toArray(data,enc);var p=new Position;if(data[p.place++]!==48){return false}var len=getLength(data,p);if(len===false){return false}if(len+p.place!==data.length){return false}if(data[p.place++]!==2){return false}var rlen=getLength(data,p);if(rlen===false){return false}var r=data.slice(p.place,rlen+p.place);p.place+=rlen;if(data[p.place++]!==2){return false}var slen=getLength(data,p);if(slen===false){return false}if(data.length!==slen+p.place){return false}var s=data.slice(p.place,slen+p.place);if(r[0]===0){if(r[1]&128){r=r.slice(1)}else{return false}}if(s[0]===0){if(s[1]&128){s=s.slice(1)}else{return false}}this.r=new BN$3(r);this.s=new BN$3(s);this.recoveryParam=null;return true};function constructLength(arr,len){if(len<128){arr.push(len);return}var octets=1+(Math.log(len)/Math.LN2>>>3);arr.push(octets|128);while(--octets){arr.push(len>>>(octets<<3)&255)}arr.push(len)}Signature$3.prototype.toDER=function toDER(enc){var r=this.r.toArray();var s=this.s.toArray();if(r[0]&128)r=[0].concat(r);if(s[0]&128)s=[0].concat(s);r=rmPadding(r);s=rmPadding(s);while(!s[0]&&!(s[1]&128)){s=s.slice(1)}var arr=[2];constructLength(arr,r.length);arr=arr.concat(r);arr.push(2);constructLength(arr,s.length);var backHalf=arr.concat(s);var res=[48];constructLength(res,backHalf.length);res=res.concat(backHalf);return utils$4.encode(res,enc)};var BN$2=bn.exports;var HmacDRBG=hmacDrbg;var utils$3=utils$c;var curves$1=curves$2;var rand=brorand.exports;var assert$3=utils$3.assert;var KeyPair$2=key$1;var Signature$2=signature$1;function EC$1(options){if(!(this instanceof EC$1))return new EC$1(options);if(typeof options==="string"){assert$3(Object.prototype.hasOwnProperty.call(curves$1,options),"Unknown curve "+options);options=curves$1[options]}if(options instanceof curves$1.PresetCurve)options={curve:options};this.curve=options.curve.curve;this.n=this.curve.n;this.nh=this.n.ushrn(1);this.g=this.curve.g;this.g=options.curve.g;this.g.precompute(options.curve.n.bitLength()+1);this.hash=options.hash||options.curve.hash}var ec$1=EC$1;EC$1.prototype.keyPair=function keyPair(options){return new KeyPair$2(this,options)};EC$1.prototype.keyFromPrivate=function keyFromPrivate(priv,enc){return KeyPair$2.fromPrivate(this,priv,enc)};EC$1.prototype.keyFromPublic=function keyFromPublic(pub,enc){return KeyPair$2.fromPublic(this,pub,enc)};EC$1.prototype.genKeyPair=function genKeyPair(options){if(!options)options={};var drbg=new HmacDRBG({hash:this.hash,pers:options.pers,persEnc:options.persEnc||"utf8",entropy:options.entropy||rand(this.hash.hmacStrength),entropyEnc:options.entropy&&options.entropyEnc||"utf8",nonce:this.n.toArray()});var bytes=this.n.byteLength();var ns2=this.n.sub(new BN$2(2));for(;;){var priv=new BN$2(drbg.generate(bytes));if(priv.cmp(ns2)>0)continue;priv.iaddn(1);return this.keyFromPrivate(priv)}};EC$1.prototype._truncateToN=function _truncateToN(msg,truncOnly){var delta=msg.byteLength()*8-this.n.bitLength();if(delta>0)msg=msg.ushrn(delta);if(!truncOnly&&msg.cmp(this.n)>=0)return msg.sub(this.n);else return msg};EC$1.prototype.sign=function sign(msg,key,enc,options){if(typeof enc==="object"){options=enc;enc=null}if(!options)options={};key=this.keyFromPrivate(key,enc);msg=this._truncateToN(new BN$2(msg,16));var bytes=this.n.byteLength();var bkey=key.getPrivate().toArray("be",bytes);var nonce=msg.toArray("be",bytes);var drbg=new HmacDRBG({hash:this.hash,entropy:bkey,nonce:nonce,pers:options.pers,persEnc:options.persEnc||"utf8"});var ns1=this.n.sub(new BN$2(1));for(var iter=0;;iter++){var k=options.k?options.k(iter):new BN$2(drbg.generate(this.n.byteLength()));k=this._truncateToN(k,true);if(k.cmpn(1)<=0||k.cmp(ns1)>=0)continue;var kp=this.g.mul(k);if(kp.isInfinity())continue;var kpX=kp.getX();var r=kpX.umod(this.n);if(r.cmpn(0)===0)continue;var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));s=s.umod(this.n);if(s.cmpn(0)===0)continue;var recoveryParam=(kp.getY().isOdd()?1:0)|(kpX.cmp(r)!==0?2:0);if(options.canonical&&s.cmp(this.nh)>0){s=this.n.sub(s);recoveryParam^=1}return new Signature$2({r:r,s:s,recoveryParam:recoveryParam})}};EC$1.prototype.verify=function verify(msg,signature,key,enc){msg=this._truncateToN(new BN$2(msg,16));key=this.keyFromPublic(key,enc);signature=new Signature$2(signature,"hex");var r=signature.r;var s=signature.s;if(r.cmpn(1)<0||r.cmp(this.n)>=0)return false;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return false;var sinv=s.invm(this.n);var u1=sinv.mul(msg).umod(this.n);var u2=sinv.mul(r).umod(this.n);var p;if(!this.curve._maxwellTrick){p=this.g.mulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.getX().umod(this.n).cmp(r)===0}p=this.g.jmulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.eqXToP(r)};EC$1.prototype.recoverPubKey=function(msg,signature,j,enc){assert$3((3&j)===j,"The recovery param is more than two bits");signature=new Signature$2(signature,enc);var n=this.n;var e=new BN$2(msg);var r=signature.r;var s=signature.s;var isYOdd=j&1;var isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error("Unable to find sencond key candinate");if(isSecondKey)r=this.curve.pointFromX(r.add(this.curve.n),isYOdd);else r=this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n);var s1=n.sub(e).mul(rInv).umod(n);var s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)};EC$1.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){signature=new Signature$2(signature,enc);if(signature.recoveryParam!==null)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch(e){continue}if(Qprime.eq(Q))return i}throw new Error("Unable to find valid recovery factor")};var utils$2=utils$c;var assert$2=utils$2.assert;var parseBytes$2=utils$2.parseBytes;var cachedProperty$1=utils$2.cachedProperty;function KeyPair$1(eddsa,params){this.eddsa=eddsa;this._secret=parseBytes$2(params.secret);if(eddsa.isPoint(params.pub))this._pub=params.pub;else this._pubBytes=parseBytes$2(params.pub)}KeyPair$1.fromPublic=function fromPublic(eddsa,pub){if(pub instanceof KeyPair$1)return pub;return new KeyPair$1(eddsa,{pub:pub})};KeyPair$1.fromSecret=function fromSecret(eddsa,secret){if(secret instanceof KeyPair$1)return secret;return new KeyPair$1(eddsa,{secret:secret})};KeyPair$1.prototype.secret=function secret(){return this._secret};cachedProperty$1(KeyPair$1,"pubBytes",(function pubBytes(){return this.eddsa.encodePoint(this.pub())}));cachedProperty$1(KeyPair$1,"pub",(function pub(){if(this._pubBytes)return this.eddsa.decodePoint(this._pubBytes);return this.eddsa.g.mul(this.priv())}));cachedProperty$1(KeyPair$1,"privBytes",(function privBytes(){var eddsa=this.eddsa;var hash=this.hash();var lastIx=eddsa.encodingLength-1;var a=hash.slice(0,eddsa.encodingLength);a[0]&=248;a[lastIx]&=127;a[lastIx]|=64;return a}));cachedProperty$1(KeyPair$1,"priv",(function priv(){return this.eddsa.decodeInt(this.privBytes())}));cachedProperty$1(KeyPair$1,"hash",(function hash(){return this.eddsa.hash().update(this.secret()).digest()}));cachedProperty$1(KeyPair$1,"messagePrefix",(function messagePrefix(){return this.hash().slice(this.eddsa.encodingLength)}));KeyPair$1.prototype.sign=function sign(message){assert$2(this._secret,"KeyPair can only verify");return this.eddsa.sign(message,this)};KeyPair$1.prototype.verify=function verify(message,sig){return this.eddsa.verify(message,sig,this)};KeyPair$1.prototype.getSecret=function getSecret(enc){assert$2(this._secret,"KeyPair is public only");return utils$2.encode(this.secret(),enc)};KeyPair$1.prototype.getPublic=function getPublic(enc){return utils$2.encode(this.pubBytes(),enc)};var key=KeyPair$1;var BN$1=bn.exports;var utils$1=utils$c;var assert$1=utils$1.assert;var cachedProperty=utils$1.cachedProperty;var parseBytes$1=utils$1.parseBytes;function Signature$1(eddsa,sig){this.eddsa=eddsa;if(typeof sig!=="object")sig=parseBytes$1(sig);if(Array.isArray(sig)){sig={R:sig.slice(0,eddsa.encodingLength),S:sig.slice(eddsa.encodingLength)}}assert$1(sig.R&&sig.S,"Signature without R or S");if(eddsa.isPoint(sig.R))this._R=sig.R;if(sig.S instanceof BN$1)this._S=sig.S;this._Rencoded=Array.isArray(sig.R)?sig.R:sig.Rencoded;this._Sencoded=Array.isArray(sig.S)?sig.S:sig.Sencoded}cachedProperty(Signature$1,"S",(function S(){return this.eddsa.decodeInt(this.Sencoded())}));cachedProperty(Signature$1,"R",(function R(){return this.eddsa.decodePoint(this.Rencoded())}));cachedProperty(Signature$1,"Rencoded",(function Rencoded(){return this.eddsa.encodePoint(this.R())}));cachedProperty(Signature$1,"Sencoded",(function Sencoded(){return this.eddsa.encodeInt(this.S())}));Signature$1.prototype.toBytes=function toBytes(){return this.Rencoded().concat(this.Sencoded())};Signature$1.prototype.toHex=function toHex(){return utils$1.encode(this.toBytes(),"hex").toUpperCase()};var signature=Signature$1;var hash=hash$3;var curves=curves$2;var utils=utils$c;var assert=utils.assert;var parseBytes=utils.parseBytes;var KeyPair=key;var Signature=signature;function EDDSA(curve){assert(curve==="ed25519","only tested with ed25519 so far");if(!(this instanceof EDDSA))return new EDDSA(curve);curve=curves[curve].curve;this.curve=curve;this.g=curve.g;this.g.precompute(curve.n.bitLength()+1);this.pointClass=curve.point().constructor;this.encodingLength=Math.ceil(curve.n.bitLength()/8);this.hash=hash.sha512}var eddsa=EDDSA;EDDSA.prototype.sign=function sign(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret);var r=this.hashInt(key.messagePrefix(),message);var R=this.g.mul(r);var Rencoded=this.encodePoint(R);var s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv());var S=r.add(s_).umod(this.curve.n);return this.makeSignature({R:R,S:S,Rencoded:Rencoded})};EDDSA.prototype.verify=function verify(message,sig,pub){message=parseBytes(message);sig=this.makeSignature(sig);var key=this.keyFromPublic(pub);var h=this.hashInt(sig.Rencoded(),key.pubBytes(),message);var SG=this.g.mul(sig.S());var RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)};EDDSA.prototype.hashInt=function hashInt(){var hash=this.hash();for(var i=0;i<arguments.length;i++)hash.update(arguments[i]);return utils.intFromLE(hash.digest()).umod(this.curve.n)};EDDSA.prototype.keyFromPublic=function keyFromPublic(pub){return KeyPair.fromPublic(this,pub)};EDDSA.prototype.keyFromSecret=function keyFromSecret(secret){return KeyPair.fromSecret(this,secret)};EDDSA.prototype.makeSignature=function makeSignature(sig){if(sig instanceof Signature)return sig;return new Signature(this,sig)};EDDSA.prototype.encodePoint=function encodePoint(point){var enc=point.getY().toArray("le",this.encodingLength);enc[this.encodingLength-1]|=point.getX().isOdd()?128:0;return enc};EDDSA.prototype.decodePoint=function decodePoint(bytes){bytes=utils.parseBytes(bytes);var lastIx=bytes.length-1;var normed=bytes.slice(0,lastIx).concat(bytes[lastIx]&~128);var xIsOdd=(bytes[lastIx]&128)!==0;var y=utils.intFromLE(normed);return this.curve.pointFromY(y,xIsOdd)};EDDSA.prototype.encodeInt=function encodeInt(num){return num.toArray("le",this.encodingLength)};EDDSA.prototype.decodeInt=function decodeInt(bytes){return utils.intFromLE(bytes)};EDDSA.prototype.isPoint=function isPoint(val){return val instanceof this.pointClass};(function(exports){var elliptic=exports;elliptic.version=require$$0.version;elliptic.utils=utils$c;elliptic.rand=brorand.exports;elliptic.curve=curve;elliptic.curves=curves$2;elliptic.ec=ec$1;elliptic.eddsa=eddsa})(elliptic$2);const EC=elliptic$2.ec;const ec=new EC("secp256k1");const ecparams=ec.curve;const BN=ecparams.n.constructor;function loadCompressedPublicKey(first,xbuf){let x=new BN(xbuf);if(x.cmp(ecparams.p)>=0)return null;x=x.toRed(ecparams.red);let y=x.redSqr().redIMul(x).redIAdd(ecparams.b).redSqrt();if(first===3!==y.isOdd())y=y.redNeg();return ec.keyPair({pub:{x:x,y:y}})}function loadUncompressedPublicKey(first,xbuf,ybuf){let x=new BN(xbuf);let y=new BN(ybuf);if(x.cmp(ecparams.p)>=0||y.cmp(ecparams.p)>=0)return null;x=x.toRed(ecparams.red);y=y.toRed(ecparams.red);if((first===6||first===7)&&y.isOdd()!==(first===7))return null;const x3=x.redSqr().redIMul(x);if(!y.redSqr().redISub(x3.redIAdd(ecparams.b)).isZero())return null;return ec.keyPair({pub:{x:x,y:y}})}function loadPublicKey(pubkey){const first=pubkey[0];switch(first){case 2:case 3:if(pubkey.length!==33)return null;return loadCompressedPublicKey(first,pubkey.subarray(1,33));case 4:case 6:case 7:if(pubkey.length!==65)return null;return loadUncompressedPublicKey(first,pubkey.subarray(1,33),pubkey.subarray(33,65));default:return null}}function savePublicKey(output,point){const pubkey=point.encode(null,output.length===33);for(let i=0;i<output.length;++i)output[i]=pubkey[i]}var elliptic$1={contextRandomize(){return 0},privateKeyVerify(seckey){const bn=new BN(seckey);return bn.cmp(ecparams.n)<0&&!bn.isZero()?0:1},privateKeyNegate(seckey){const bn=new BN(seckey);const negate=ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Uint8Array,"be",32);seckey.set(negate);return 0},privateKeyTweakAdd(seckey,tweak){const bn=new BN(tweak);if(bn.cmp(ecparams.n)>=0)return 1;bn.iadd(new BN(seckey));if(bn.cmp(ecparams.n)>=0)bn.isub(ecparams.n);if(bn.isZero())return 1;const tweaked=bn.toArrayLike(Uint8Array,"be",32);seckey.set(tweaked);return 0},privateKeyTweakMul(seckey,tweak){let bn=new BN(tweak);if(bn.cmp(ecparams.n)>=0||bn.isZero())return 1;bn.imul(new BN(seckey));if(bn.cmp(ecparams.n)>=0)bn=bn.umod(ecparams.n);const tweaked=bn.toArrayLike(Uint8Array,"be",32);seckey.set(tweaked);return 0},publicKeyVerify(pubkey){const pair=loadPublicKey(pubkey);return pair===null?1:0},publicKeyCreate(output,seckey){const bn=new BN(seckey);if(bn.cmp(ecparams.n)>=0||bn.isZero())return 1;const point=ec.keyFromPrivate(seckey).getPublic();savePublicKey(output,point);return 0},publicKeyConvert(output,pubkey){const pair=loadPublicKey(pubkey);if(pair===null)return 1;const point=pair.getPublic();savePublicKey(output,point);return 0},publicKeyNegate(output,pubkey){const pair=loadPublicKey(pubkey);if(pair===null)return 1;const point=pair.getPublic();point.y=point.y.redNeg();savePublicKey(output,point);return 0},publicKeyCombine(output,pubkeys){const pairs=new Array(pubkeys.length);for(let i=0;i<pubkeys.length;++i){pairs[i]=loadPublicKey(pubkeys[i]);if(pairs[i]===null)return 1}let point=pairs[0].getPublic();for(let i=1;i<pairs.length;++i)point=point.add(pairs[i].pub);if(point.isInfinity())return 2;savePublicKey(output,point);return 0},publicKeyTweakAdd(output,pubkey,tweak){const pair=loadPublicKey(pubkey);if(pair===null)return 1;tweak=new BN(tweak);if(tweak.cmp(ecparams.n)>=0)return 2;const point=pair.getPublic().add(ecparams.g.mul(tweak));if(point.isInfinity())return 2;savePublicKey(output,point);return 0},publicKeyTweakMul(output,pubkey,tweak){const pair=loadPublicKey(pubkey);if(pair===null)return 1;tweak=new BN(tweak);if(tweak.cmp(ecparams.n)>=0||tweak.isZero())return 2;const point=pair.getPublic().mul(tweak);savePublicKey(output,point);return 0},signatureNormalize(sig){const r=new BN(sig.subarray(0,32));const s=new BN(sig.subarray(32,64));if(r.cmp(ecparams.n)>=0||s.cmp(ecparams.n)>=0)return 1;if(s.cmp(ec.nh)===1){sig.set(ecparams.n.sub(s).toArrayLike(Uint8Array,"be",32),32)}return 0},signatureExport(obj,sig){const sigR=sig.subarray(0,32);const sigS=sig.subarray(32,64);if(new BN(sigR).cmp(ecparams.n)>=0)return 1;if(new BN(sigS).cmp(ecparams.n)>=0)return 1;const{output:output}=obj;let r=output.subarray(4,4+33);r[0]=0;r.set(sigR,1);let lenR=33;let posR=0;for(;lenR>1&&r[posR]===0&&!(r[posR+1]&128);--lenR,++posR);r=r.subarray(posR);if(r[0]&128)return 1;if(lenR>1&&r[0]===0&&!(r[1]&128))return 1;let s=output.subarray(6+33,6+33+33);s[0]=0;s.set(sigS,1);let lenS=33;let posS=0;for(;lenS>1&&s[posS]===0&&!(s[posS+1]&128);--lenS,++posS);s=s.subarray(posS);if(s[0]&128)return 1;if(lenS>1&&s[0]===0&&!(s[1]&128))return 1;obj.outputlen=6+lenR+lenS;output[0]=48;output[1]=obj.outputlen-2;output[2]=2;output[3]=r.length;output.set(r,4);output[4+lenR]=2;output[5+lenR]=s.length;output.set(s,6+lenR);return 0},signatureImport(output,sig){if(sig.length<8)return 1;if(sig.length>72)return 1;if(sig[0]!==48)return 1;if(sig[1]!==sig.length-2)return 1;if(sig[2]!==2)return 1;const lenR=sig[3];if(lenR===0)return 1;if(5+lenR>=sig.length)return 1;if(sig[4+lenR]!==2)return 1;const lenS=sig[5+lenR];if(lenS===0)return 1;if(6+lenR+lenS!==sig.length)return 1;if(sig[4]&128)return 1;if(lenR>1&&sig[4]===0&&!(sig[5]&128))return 1;if(sig[lenR+6]&128)return 1;if(lenS>1&&sig[lenR+6]===0&&!(sig[lenR+7]&128))return 1;let sigR=sig.subarray(4,4+lenR);if(sigR.length===33&&sigR[0]===0)sigR=sigR.subarray(1);if(sigR.length>32)return 1;let sigS=sig.subarray(6+lenR);if(sigS.length===33&&sigS[0]===0)sigS=sigS.slice(1);if(sigS.length>32)throw new Error("S length is too long");let r=new BN(sigR);if(r.cmp(ecparams.n)>=0)r=new BN(0);let s=new BN(sig.subarray(6+lenR));if(s.cmp(ecparams.n)>=0)s=new BN(0);output.set(r.toArrayLike(Uint8Array,"be",32),0);output.set(s.toArrayLike(Uint8Array,"be",32),32);return 0},ecdsaSign(obj,message,seckey,data,noncefn){if(noncefn){const _noncefn=noncefn;noncefn=counter=>{const nonce=_noncefn(message,seckey,null,data,counter);const isValid=nonce instanceof Uint8Array&&nonce.length===32;if(!isValid)throw new Error("This is the way");return new BN(nonce)}}const d=new BN(seckey);if(d.cmp(ecparams.n)>=0||d.isZero())return 1;let sig;try{sig=ec.sign(message,seckey,{canonical:true,k:noncefn,pers:data})}catch(err){return 1}obj.signature.set(sig.r.toArrayLike(Uint8Array,"be",32),0);obj.signature.set(sig.s.toArrayLike(Uint8Array,"be",32),32);obj.recid=sig.recoveryParam;return 0},ecdsaVerify(sig,msg32,pubkey){const sigObj={r:sig.subarray(0,32),s:sig.subarray(32,64)};const sigr=new BN(sigObj.r);const sigs=new BN(sigObj.s);if(sigr.cmp(ecparams.n)>=0||sigs.cmp(ecparams.n)>=0)return 1;if(sigs.cmp(ec.nh)===1||sigr.isZero()||sigs.isZero())return 3;const pair=loadPublicKey(pubkey);if(pair===null)return 2;const point=pair.getPublic();const isValid=ec.verify(msg32,sigObj,point);return isValid?0:3},ecdsaRecover(output,sig,recid,msg32){const sigObj={r:sig.slice(0,32),s:sig.slice(32,64)};const sigr=new BN(sigObj.r);const sigs=new BN(sigObj.s);if(sigr.cmp(ecparams.n)>=0||sigs.cmp(ecparams.n)>=0)return 1;if(sigr.isZero()||sigs.isZero())return 2;let point;try{point=ec.recoverPubKey(msg32,sigObj,recid)}catch(err){return 2}savePublicKey(output,point);return 0},ecdh(output,pubkey,seckey,data,hashfn,xbuf,ybuf){const pair=loadPublicKey(pubkey);if(pair===null)return 1;const scalar=new BN(seckey);if(scalar.cmp(ecparams.n)>=0||scalar.isZero())return 2;const point=pair.getPublic().mul(scalar);if(hashfn===undefined){const data=point.encode(null,true);const sha256=ec.hash().update(data).digest();for(let i=0;i<32;++i)output[i]=sha256[i]}else{if(!xbuf)xbuf=new Uint8Array(32);const x=point.getX().toArray("be",32);for(let i=0;i<32;++i)xbuf[i]=x[i];if(!ybuf)ybuf=new Uint8Array(32);const y=point.getY().toArray("be",32);for(let i=0;i<32;++i)ybuf[i]=y[i];const hash=hashfn(xbuf,ybuf,data);const isValid=hash instanceof Uint8Array&&hash.length===output.length;if(!isValid)return 2;output.set(hash)}return 0}};var elliptic=lib(elliptic$1);var secp256k1=elliptic;var sha3$1={exports:{}};
30
+ */var specialChar="~",safeSpecialChar="\\x"+("0"+specialChar.charCodeAt(0).toString(16)).slice(-2),escapedSafeSpecialChar="\\"+safeSpecialChar,specialCharRG=new RegExp(safeSpecialChar,"g"),safeSpecialCharRG=new RegExp(escapedSafeSpecialChar,"g"),safeStartWithSpecialCharRG=new RegExp("(?:^|([^\\\\]))"+escapedSafeSpecialChar),indexOf=[].indexOf||function(v){for(var i=this.length;i--&&this[i]!==v;);return i},$String=String;function generateReplacer(value,replacer,resolve){var doNotIgnore=false,inspect=!!replacer,path=[],all=[value],seen=[value],mapp=[resolve?specialChar:"[Circular]"],last=value,lvl=1,i,fn;if(inspect){fn=typeof replacer==="object"?function(key,value){return key!==""&&replacer.indexOf(key)<0?void 0:value}:replacer}return function(key,value){if(inspect)value=fn.call(this,key,value);if(doNotIgnore){if(last!==this){i=lvl-indexOf.call(all,this)-1;lvl-=i;all.splice(lvl,all.length);path.splice(lvl-1,path.length);last=this}if(typeof value==="object"&&value){if(indexOf.call(all,value)<0){all.push(last=value)}lvl=all.length;i=indexOf.call(seen,value);if(i<0){i=seen.push(value)-1;if(resolve){path.push((""+key).replace(specialCharRG,safeSpecialChar));mapp[i]=specialChar+path.join(specialChar)}else{mapp[i]=mapp[0]}}else{value=mapp[i]}}else{if(typeof value==="string"&&resolve){value=value.replace(safeSpecialChar,escapedSafeSpecialChar).replace(specialChar,safeSpecialChar)}}}else{doNotIgnore=true}return value}}function retrieveFromPath(current,keys){for(var i=0,length=keys.length;i<length;current=current[keys[i++].replace(safeSpecialCharRG,specialChar)]);return current}function generateReviver(reviver){return function(key,value){var isString=typeof value==="string";if(isString&&value.charAt(0)===specialChar){return new $String(value.slice(1))}if(key==="")value=regenerate(value,value,{});if(isString)value=value.replace(safeStartWithSpecialCharRG,"$1"+specialChar).replace(escapedSafeSpecialChar,safeSpecialChar);return reviver?reviver.call(this,key,value):value}}function regenerateArray(root,current,retrieve){for(var i=0,length=current.length;i<length;i++){current[i]=regenerate(root,current[i],retrieve)}return current}function regenerateObject(root,current,retrieve){for(var key in current){if(current.hasOwnProperty(key)){current[key]=regenerate(root,current[key],retrieve)}}return current}function regenerate(root,current,retrieve){return current instanceof Array?regenerateArray(root,current,retrieve):current instanceof $String?current.length?retrieve.hasOwnProperty(current)?retrieve[current]:retrieve[current]=retrieveFromPath(root,current.split(specialChar)):root:current instanceof Object?regenerateObject(root,current,retrieve):current}var CircularJSON={stringify:function stringify(value,replacer,space,doNotResolve){return CircularJSON.parser.stringify(value,generateReplacer(value,replacer,!doNotResolve),space)},parse:function parse(text,reviver){return CircularJSON.parser.parse(text,generateReviver(reviver))},parser:JSON};var circularJson_node=CircularJSON;(function(exports){var _interopRequireDefault=interopRequireDefault.exports;Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _regenerator=_interopRequireDefault(regenerator);var _asyncToGenerator2=_interopRequireDefault(asyncToGenerator.exports);var _typeof2=_interopRequireDefault(_typeof.exports);var _classCallCheck2=_interopRequireDefault(classCallCheck.exports);var _createClass2=_interopRequireDefault(createClass.exports);var _inherits2=_interopRequireDefault(inherits$3.exports);var _possibleConstructorReturn2=_interopRequireDefault(possibleConstructorReturn.exports);var _getPrototypeOf2=_interopRequireDefault(getPrototypeOf.exports);var _eventemitter=eventemitter3.exports;var _circularJson=_interopRequireDefault(circularJson_node);function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=(0,_getPrototypeOf2["default"])(Derived),result;if(hasNativeReflectConstruct){var NewTarget=(0,_getPrototypeOf2["default"])(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return(0,_possibleConstructorReturn2["default"])(this,result)}}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}var __rest=function(s,e){var t={};for(var p in s){if(Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0)t[p]=s[p]}if(s!=null&&typeof Object.getOwnPropertySymbols==="function")for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++){if(e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i]))t[p[i]]=s[p[i]]}return t};var CommonClient=function(_EventEmitter){(0,_inherits2["default"])(CommonClient,_EventEmitter);var _super=_createSuper(CommonClient);function CommonClient(webSocketFactory){var _this;var address=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"ws://localhost:8080";var _a=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var generate_request_id=arguments.length>3?arguments[3]:undefined;(0,_classCallCheck2["default"])(this,CommonClient);var _a$autoconnect=_a.autoconnect,autoconnect=_a$autoconnect===void 0?true:_a$autoconnect,_a$reconnect=_a.reconnect,reconnect=_a$reconnect===void 0?true:_a$reconnect,_a$reconnect_interval=_a.reconnect_interval,reconnect_interval=_a$reconnect_interval===void 0?1e3:_a$reconnect_interval,_a$max_reconnects=_a.max_reconnects,max_reconnects=_a$max_reconnects===void 0?5:_a$max_reconnects,rest_options=__rest(_a,["autoconnect","reconnect","reconnect_interval","max_reconnects"]);_this=_super.call(this);_this.webSocketFactory=webSocketFactory;_this.queue={};_this.rpc_id=0;_this.address=address;_this.autoconnect=autoconnect;_this.ready=false;_this.reconnect=reconnect;_this.reconnect_interval=reconnect_interval;_this.max_reconnects=max_reconnects;_this.rest_options=rest_options;_this.current_reconnects=0;_this.generate_request_id=generate_request_id||function(){return++_this.rpc_id};if(_this.autoconnect)_this._connect(_this.address,Object.assign({autoconnect:_this.autoconnect,reconnect:_this.reconnect,reconnect_interval:_this.reconnect_interval,max_reconnects:_this.max_reconnects},_this.rest_options));return _this}(0,_createClass2["default"])(CommonClient,[{key:"connect",value:function connect(){if(this.socket)return;this._connect(this.address,Object.assign({autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects},this.rest_options))}},{key:"call",value:function call(method,params,timeout,ws_opts){var _this2=this;if(!ws_opts&&"object"===(0,_typeof2["default"])(timeout)){ws_opts=timeout;timeout=null}return new Promise((function(resolve,reject){if(!_this2.ready)return reject(new Error("socket not ready"));var rpc_id=_this2.generate_request_id(method,params);var message={jsonrpc:"2.0",method:method,params:params||null,id:rpc_id};_this2.socket.send(JSON.stringify(message),ws_opts,(function(error){if(error)return reject(error);_this2.queue[rpc_id]={promise:[resolve,reject]};if(timeout){_this2.queue[rpc_id].timeout=setTimeout((function(){delete _this2.queue[rpc_id];reject(new Error("reply timeout"))}),timeout)}}))}))}},{key:"login",value:function(){var _login=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark((function _callee(params){var resp;return _regenerator["default"].wrap((function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return this.call("rpc.login",params);case 2:resp=_context.sent;if(resp){_context.next=5;break}throw new Error("authentication failed");case 5:return _context.abrupt("return",resp);case 6:case"end":return _context.stop()}}}),_callee,this)})));function login(_x){return _login.apply(this,arguments)}return login}()},{key:"listMethods",value:function(){var _listMethods=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark((function _callee2(){return _regenerator["default"].wrap((function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return this.call("__listMethods");case 2:return _context2.abrupt("return",_context2.sent);case 3:case"end":return _context2.stop()}}}),_callee2,this)})));function listMethods(){return _listMethods.apply(this,arguments)}return listMethods}()},{key:"notify",value:function notify(method,params){var _this3=this;return new Promise((function(resolve,reject){if(!_this3.ready)return reject(new Error("socket not ready"));var message={jsonrpc:"2.0",method:method,params:params||null};_this3.socket.send(JSON.stringify(message),(function(error){if(error)return reject(error);resolve()}))}))}},{key:"subscribe",value:function(){var _subscribe=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark((function _callee3(event){var result;return _regenerator["default"].wrap((function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:if(typeof event==="string")event=[event];_context3.next=3;return this.call("rpc.on",event);case 3:result=_context3.sent;if(!(typeof event==="string"&&result[event]!=="ok")){_context3.next=6;break}throw new Error("Failed subscribing to an event '"+event+"' with: "+result[event]);case 6:return _context3.abrupt("return",result);case 7:case"end":return _context3.stop()}}}),_callee3,this)})));function subscribe(_x2){return _subscribe.apply(this,arguments)}return subscribe}()},{key:"unsubscribe",value:function(){var _unsubscribe=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark((function _callee4(event){var result;return _regenerator["default"].wrap((function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:if(typeof event==="string")event=[event];_context4.next=3;return this.call("rpc.off",event);case 3:result=_context4.sent;if(!(typeof event==="string"&&result[event]!=="ok")){_context4.next=6;break}throw new Error("Failed unsubscribing from an event with: "+result);case 6:return _context4.abrupt("return",result);case 7:case"end":return _context4.stop()}}}),_callee4,this)})));function unsubscribe(_x3){return _unsubscribe.apply(this,arguments)}return unsubscribe}()},{key:"close",value:function close(code,data){this.socket.close(code||1e3,data)}},{key:"_connect",value:function _connect(address,options){var _this4=this;this.socket=this.webSocketFactory(address,options);this.socket.addEventListener("open",(function(){_this4.ready=true;_this4.emit("open");_this4.current_reconnects=0}));this.socket.addEventListener("message",(function(_ref){var message=_ref.data;if(message instanceof ArrayBuffer)message=Buffer.from(message).toString();try{message=_circularJson["default"].parse(message)}catch(error){return}if(message.notification&&_this4.listeners(message.notification).length){if(!Object.keys(message.params).length)return _this4.emit(message.notification);var args=[message.notification];if(message.params.constructor===Object)args.push(message.params);else for(var i=0;i<message.params.length;i++){args.push(message.params[i])}return Promise.resolve().then((function(){_this4.emit.apply(_this4,args)}))}if(!_this4.queue[message.id]){if(message.method&&message.params){return Promise.resolve().then((function(){_this4.emit(message.method,message.params)}))}return}if("error"in message==="result"in message)_this4.queue[message.id].promise[1](new Error('Server response malformed. Response must include either "result"'+' or "error", but not both.'));if(_this4.queue[message.id].timeout)clearTimeout(_this4.queue[message.id].timeout);if(message.error)_this4.queue[message.id].promise[1](message.error);else _this4.queue[message.id].promise[0](message.result);delete _this4.queue[message.id]}));this.socket.addEventListener("error",(function(error){return _this4.emit("error",error)}));this.socket.addEventListener("close",(function(_ref2){var code=_ref2.code,reason=_ref2.reason;if(_this4.ready)setTimeout((function(){return _this4.emit("close",code,reason)}),0);_this4.ready=false;_this4.socket=undefined;if(code===1e3)return;_this4.current_reconnects++;if(_this4.reconnect&&(_this4.max_reconnects>_this4.current_reconnects||_this4.max_reconnects===0))setTimeout((function(){return _this4._connect(address,options)}),_this4.reconnect_interval)}))}}]);return CommonClient}(_eventemitter.EventEmitter);exports["default"]=CommonClient})(client);var _interopRequireDefault=interopRequireDefault.exports;Object.defineProperty(index_browser,"__esModule",{value:true});var Client_1=index_browser.Client=void 0;var _classCallCheck2=_interopRequireDefault(classCallCheck.exports);var _inherits2=_interopRequireDefault(inherits$3.exports);var _possibleConstructorReturn2=_interopRequireDefault(possibleConstructorReturn.exports);var _getPrototypeOf2=_interopRequireDefault(getPrototypeOf.exports);var _websocket=_interopRequireDefault(websocket_browser);var _client=_interopRequireDefault(client);function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=(0,_getPrototypeOf2["default"])(Derived),result;if(hasNativeReflectConstruct){var NewTarget=(0,_getPrototypeOf2["default"])(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else{result=Super.apply(this,arguments)}return(0,_possibleConstructorReturn2["default"])(this,result)}}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],(function(){})));return true}catch(e){return false}}var Client=function(_CommonClient){(0,_inherits2["default"])(Client,_CommonClient);var _super=_createSuper(Client);function Client(){var address=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"ws://localhost:8080";var _ref=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},_ref$autoconnect=_ref.autoconnect,autoconnect=_ref$autoconnect===void 0?true:_ref$autoconnect,_ref$reconnect=_ref.reconnect,reconnect=_ref$reconnect===void 0?true:_ref$reconnect,_ref$reconnect_interv=_ref.reconnect_interval,reconnect_interval=_ref$reconnect_interv===void 0?1e3:_ref$reconnect_interv,_ref$max_reconnects=_ref.max_reconnects,max_reconnects=_ref$max_reconnects===void 0?5:_ref$max_reconnects;var generate_request_id=arguments.length>2?arguments[2]:undefined;(0,_classCallCheck2["default"])(this,Client);return _super.call(this,_websocket["default"],address,{autoconnect:autoconnect,reconnect:reconnect,reconnect_interval:reconnect_interval,max_reconnects:max_reconnects},generate_request_id)}return Client}(_client["default"]);Client_1=index_browser.Client=Client;var rngBrowser={exports:{}};var getRandomValues=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof window.msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);if(getRandomValues){var rnds8=new Uint8Array(16);rngBrowser.exports=function whatwgRNG(){getRandomValues(rnds8);return rnds8}}else{var rnds=new Array(16);rngBrowser.exports=function mathRNG(){for(var i=0,r;i<16;i++){if((i&3)===0)r=Math.random()*4294967296;rnds[i]=r>>>((i&3)<<3)&255}return rnds}}var byteToHex=[];for(var i=0;i<256;++i){byteToHex[i]=(i+256).toString(16).substr(1)}function bytesToUuid$1(buf,offset){var i=offset||0;var bth=byteToHex;return[bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]]].join("")}var bytesToUuid_1=bytesToUuid$1;var rng=rngBrowser.exports;var bytesToUuid=bytesToUuid_1;function v4(options,buf,offset){var i=buf&&offset||0;if(typeof options=="string"){buf=options==="binary"?new Array(16):null;options=null}options=options||{};var rnds=options.random||(options.rng||rng)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){for(var ii=0;ii<16;++ii){buf[i+ii]=rnds[ii]}}return buf||bytesToUuid(rnds)}var v4_1=v4;const uuid$1=v4_1;const generateRequest$1=function(method,params,id,options){if(typeof method!=="string"){throw new TypeError(method+" must be a string")}options=options||{};const version=typeof options.version==="number"?options.version:2;if(version!==1&&version!==2){throw new TypeError(version+" must be 1 or 2")}const request={method:method};if(version===2){request.jsonrpc="2.0"}if(params){if(typeof params!=="object"&&!Array.isArray(params)){throw new TypeError(params+" must be an object, array or omitted")}request.params=params}if(typeof id==="undefined"){const generator=typeof options.generator==="function"?options.generator:function(){return uuid$1()};request.id=generator(request,options)}else if(version===2&&id===null){if(options.notificationIdNull){request.id=null}}else{request.id=id}return request};var generateRequest_1=generateRequest$1;const uuid=v4_1;const generateRequest=generateRequest_1;const ClientBrowser=function(callServer,options){if(!(this instanceof ClientBrowser)){return new ClientBrowser(callServer,options)}if(!options){options={}}this.options={reviver:typeof options.reviver!=="undefined"?options.reviver:null,replacer:typeof options.replacer!=="undefined"?options.replacer:null,generator:typeof options.generator!=="undefined"?options.generator:function(){return uuid()},version:typeof options.version!=="undefined"?options.version:2,notificationIdNull:typeof options.notificationIdNull==="boolean"?options.notificationIdNull:false};this.callServer=callServer};var browser=ClientBrowser;ClientBrowser.prototype.request=function(method,params,id,callback){const self=this;let request=null;const isBatch=Array.isArray(method)&&typeof params==="function";if(this.options.version===1&&isBatch){throw new TypeError("JSON-RPC 1.0 does not support batching")}const isRaw=!isBatch&&method&&typeof method==="object"&&typeof params==="function";if(isBatch||isRaw){callback=params;request=method}else{if(typeof id==="function"){callback=id;id=undefined}const hasCallback=typeof callback==="function";try{request=generateRequest(method,params,id,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(err){if(hasCallback){return callback(err)}throw err}if(!hasCallback){return request}}let message;try{message=JSON.stringify(request,this.options.replacer)}catch(err){return callback(err)}this.callServer(message,(function(err,response){self._parseResponse(err,response,callback)}));return request};ClientBrowser.prototype._parseResponse=function(err,responseText,callback){if(err){callback(err);return}if(!responseText){return callback()}let response;try{response=JSON.parse(responseText,this.options.reviver)}catch(err){return callback(err)}if(callback.length===3){if(Array.isArray(response)){const isError=function(res){return typeof res.error!=="undefined"};const isNotError=function(res){return!isError(res)};return callback(null,response.filter(isError),response.filter(isNotError))}else{return callback(null,response.error,response.result)}}callback(null,response)};var RpcClient=browser;const MINIMUM_SLOT_PER_EPOCH=32;function trailingZeros(n){let trailingZeros=0;while(n>1){n/=2;trailingZeros++}return trailingZeros}function nextPowerOfTwo(n){if(n===0)return 1;n--;n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;return n+1}class EpochSchedule{constructor(slotsPerEpoch,leaderScheduleSlotOffset,warmup,firstNormalEpoch,firstNormalSlot){this.slotsPerEpoch=void 0;this.leaderScheduleSlotOffset=void 0;this.warmup=void 0;this.firstNormalEpoch=void 0;this.firstNormalSlot=void 0;this.slotsPerEpoch=slotsPerEpoch;this.leaderScheduleSlotOffset=leaderScheduleSlotOffset;this.warmup=warmup;this.firstNormalEpoch=firstNormalEpoch;this.firstNormalSlot=firstNormalSlot}getEpoch(slot){return this.getEpochAndSlotIndex(slot)[0]}getEpochAndSlotIndex(slot){if(slot<this.firstNormalSlot){const epoch=trailingZeros(nextPowerOfTwo(slot+MINIMUM_SLOT_PER_EPOCH+1))-trailingZeros(MINIMUM_SLOT_PER_EPOCH)-1;const epochLen=this.getSlotsInEpoch(epoch);const slotIndex=slot-(epochLen-MINIMUM_SLOT_PER_EPOCH);return[epoch,slotIndex]}else{const normalSlotIndex=slot-this.firstNormalSlot;const normalEpochIndex=Math.floor(normalSlotIndex/this.slotsPerEpoch);const epoch=this.firstNormalEpoch+normalEpochIndex;const slotIndex=normalSlotIndex%this.slotsPerEpoch;return[epoch,slotIndex]}}getFirstSlotInEpoch(epoch){if(epoch<=this.firstNormalEpoch){return(Math.pow(2,epoch)-1)*MINIMUM_SLOT_PER_EPOCH}else{return(epoch-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}}getLastSlotInEpoch(epoch){return this.getFirstSlotInEpoch(epoch)+this.getSlotsInEpoch(epoch)-1}getSlotsInEpoch(epoch){if(epoch<this.firstNormalEpoch){return Math.pow(2,epoch+trailingZeros(MINIMUM_SLOT_PER_EPOCH))}else{return this.slotsPerEpoch}}}class SendTransactionError extends Error{constructor(message,logs){super(message);this.logs=void 0;this.logs=logs}}const NUM_TICKS_PER_SECOND=160;const DEFAULT_TICKS_PER_SLOT=64;const NUM_SLOTS_PER_SECOND=NUM_TICKS_PER_SECOND/DEFAULT_TICKS_PER_SLOT;const MS_PER_SLOT=1e3/NUM_SLOTS_PER_SECOND;function promiseTimeout(promise,timeoutMs){let timeoutId;const timeoutPromise=new Promise((resolve=>{timeoutId=setTimeout((()=>resolve(null)),timeoutMs)}));return Promise.race([promise,timeoutPromise]).then((result=>{clearTimeout(timeoutId);return result}))}function makeWebsocketUrl(endpoint){let url=new URL(endpoint);const useHttps=url.protocol==="https:";url.protocol=useHttps?"wss:":"ws:";url.host="";if(url.port!==""){url.port=String(Number(url.port)+1)}return url.toString()}const PublicKeyFromString=coerce(instance(PublicKey),string(),(value=>new PublicKey(value)));const RawAccountDataResult=tuple([string(),literal("base64")]);const BufferFromRawAccountData=coerce(instance(buffer.Buffer),RawAccountDataResult,(value=>buffer.Buffer.from(value[0],"base64")));const BLOCKHASH_CACHE_TIMEOUT_MS=30*1e3;function createRpcResult(result){return union([type({jsonrpc:literal("2.0"),id:string(),result:result}),type({jsonrpc:literal("2.0"),id:string(),error:type({code:unknown(),message:string(),data:optional(any())})})])}const UnknownRpcResult=createRpcResult(unknown());function jsonRpcResult(schema){return coerce(createRpcResult(schema),UnknownRpcResult,(value=>{if("error"in value){return value}else{return{...value,result:create(value.result,schema)}}}))}function jsonRpcResultAndContext(value){return jsonRpcResult(type({context:type({slot:number()}),value:value}))}function notificationResultAndContext(value){return type({context:type({slot:number()}),value:value})}const GetInflationGovernorResult=type({foundation:number(),foundationTerm:number(),initial:number(),taper:number(),terminal:number()});const GetInflationRewardResult=jsonRpcResult(array(nullable(type({epoch:number(),effectiveSlot:number(),amount:number(),postBalance:number()}))));const GetEpochInfoResult=type({epoch:number(),slotIndex:number(),slotsInEpoch:number(),absoluteSlot:number(),blockHeight:optional(number()),transactionCount:optional(number())});const GetEpochScheduleResult=type({slotsPerEpoch:number(),leaderScheduleSlotOffset:number(),warmup:boolean(),firstNormalEpoch:number(),firstNormalSlot:number()});const GetLeaderScheduleResult=record(string(),array(number()));const TransactionErrorResult=nullable(union([type({}),string()]));const SignatureStatusResult=type({err:TransactionErrorResult});const SignatureReceivedResult=literal("receivedSignature");const VersionResult=type({"solana-core":string(),"feature-set":optional(number())});const SimulatedTransactionResponseStruct=jsonRpcResultAndContext(type({err:nullable(union([type({}),string()])),logs:nullable(array(string())),accounts:optional(nullable(array(nullable(type({executable:boolean(),owner:string(),lamports:number(),data:array(string()),rentEpoch:optional(number())}))))),unitsConsumed:optional(number())}));function createRpcClient(url,useHttps,httpHeaders,fetchMiddleware,disableRetryOnRateLimit){let fetchWithMiddleware;if(fetchMiddleware){fetchWithMiddleware=async(url,options)=>{const modifiedFetchArgs=await new Promise(((resolve,reject)=>{try{fetchMiddleware(url,options,((modifiedUrl,modifiedOptions)=>resolve([modifiedUrl,modifiedOptions])))}catch(error){reject(error)}}));return await fetch(...modifiedFetchArgs)}}const clientBrowser=new RpcClient((async(request,callback)=>{const agent=undefined;const options={method:"POST",body:request,agent:agent,headers:Object.assign({"Content-Type":"application/json"},httpHeaders||{})};try{let too_many_requests_retries=5;let res;let waitTime=500;for(;;){if(fetchWithMiddleware){res=await fetchWithMiddleware(url,options)}else{res=await fetch(url,options)}if(res.status!==429){break}if(disableRetryOnRateLimit===true){break}too_many_requests_retries-=1;if(too_many_requests_retries===0){break}console.log(`Server responded with ${res.status} ${res.statusText}. Retrying after ${waitTime}ms delay...`);await sleep(waitTime);waitTime*=2}const text=await res.text();if(res.ok){callback(null,text)}else{callback(new Error(`${res.status} ${res.statusText}: ${text}`))}}catch(err){if(err instanceof Error)callback(err)}finally{}}),{});return clientBrowser}function createRpcRequest(client){return(method,args)=>new Promise(((resolve,reject)=>{client.request(method,args,((err,response)=>{if(err){reject(err);return}resolve(response)}))}))}function createRpcBatchRequest(client){return requests=>new Promise(((resolve,reject)=>{if(requests.length===0)resolve([]);const batch=requests.map((params=>client.request(params.methodName,params.args)));client.request(batch,((err,response)=>{if(err){reject(err);return}resolve(response)}))}))}const GetInflationGovernorRpcResult=jsonRpcResult(GetInflationGovernorResult);const GetEpochInfoRpcResult=jsonRpcResult(GetEpochInfoResult);const GetEpochScheduleRpcResult=jsonRpcResult(GetEpochScheduleResult);const GetLeaderScheduleRpcResult=jsonRpcResult(GetLeaderScheduleResult);const SlotRpcResult=jsonRpcResult(number());const GetSupplyRpcResult=jsonRpcResultAndContext(type({total:number(),circulating:number(),nonCirculating:number(),nonCirculatingAccounts:array(PublicKeyFromString)}));const TokenAmountResult=type({amount:string(),uiAmount:nullable(number()),decimals:number(),uiAmountString:optional(string())});const GetTokenLargestAccountsResult=jsonRpcResultAndContext(array(type({address:PublicKeyFromString,amount:string(),uiAmount:nullable(number()),decimals:number(),uiAmountString:optional(string())})));const GetTokenAccountsByOwner=jsonRpcResultAndContext(array(type({pubkey:PublicKeyFromString,account:type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:BufferFromRawAccountData,rentEpoch:number()})})));const ParsedAccountDataResult=type({program:string(),parsed:unknown(),space:number()});const GetParsedTokenAccountsByOwner=jsonRpcResultAndContext(array(type({pubkey:PublicKeyFromString,account:type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:ParsedAccountDataResult,rentEpoch:number()})})));const GetLargestAccountsRpcResult=jsonRpcResultAndContext(array(type({lamports:number(),address:PublicKeyFromString})));const AccountInfoResult=type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:BufferFromRawAccountData,rentEpoch:number()});const KeyedAccountInfoResult=type({pubkey:PublicKeyFromString,account:AccountInfoResult});const ParsedOrRawAccountData=coerce(union([instance(buffer.Buffer),ParsedAccountDataResult]),union([RawAccountDataResult,ParsedAccountDataResult]),(value=>{if(Array.isArray(value)){return create(value,BufferFromRawAccountData)}else{return value}}));const ParsedAccountInfoResult=type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:ParsedOrRawAccountData,rentEpoch:number()});const KeyedParsedAccountInfoResult=type({pubkey:PublicKeyFromString,account:ParsedAccountInfoResult});const StakeActivationResult=type({state:union([literal("active"),literal("inactive"),literal("activating"),literal("deactivating")]),active:number(),inactive:number()});const GetConfirmedSignaturesForAddress2RpcResult=jsonRpcResult(array(type({signature:string(),slot:number(),err:TransactionErrorResult,memo:nullable(string()),blockTime:optional(nullable(number()))})));const GetSignaturesForAddressRpcResult=jsonRpcResult(array(type({signature:string(),slot:number(),err:TransactionErrorResult,memo:nullable(string()),blockTime:optional(nullable(number()))})));const AccountNotificationResult=type({subscription:number(),result:notificationResultAndContext(AccountInfoResult)});const ProgramAccountInfoResult=type({pubkey:PublicKeyFromString,account:AccountInfoResult});const ProgramAccountNotificationResult=type({subscription:number(),result:notificationResultAndContext(ProgramAccountInfoResult)});const SlotInfoResult=type({parent:number(),slot:number(),root:number()});const SlotNotificationResult=type({subscription:number(),result:SlotInfoResult});const SlotUpdateResult=union([type({type:union([literal("firstShredReceived"),literal("completed"),literal("optimisticConfirmation"),literal("root")]),slot:number(),timestamp:number()}),type({type:literal("createdBank"),parent:number(),slot:number(),timestamp:number()}),type({type:literal("frozen"),slot:number(),timestamp:number(),stats:type({numTransactionEntries:number(),numSuccessfulTransactions:number(),numFailedTransactions:number(),maxTransactionsPerEntry:number()})}),type({type:literal("dead"),slot:number(),timestamp:number(),err:string()})]);const SlotUpdateNotificationResult=type({subscription:number(),result:SlotUpdateResult});const SignatureNotificationResult=type({subscription:number(),result:notificationResultAndContext(union([SignatureStatusResult,SignatureReceivedResult]))});const RootNotificationResult=type({subscription:number(),result:number()});const ContactInfoResult=type({pubkey:string(),gossip:nullable(string()),tpu:nullable(string()),rpc:nullable(string()),version:nullable(string())});const VoteAccountInfoResult=type({votePubkey:string(),nodePubkey:string(),activatedStake:number(),epochVoteAccount:boolean(),epochCredits:array(tuple([number(),number(),number()])),commission:number(),lastVote:number(),rootSlot:nullable(number())});const GetVoteAccounts=jsonRpcResult(type({current:array(VoteAccountInfoResult),delinquent:array(VoteAccountInfoResult)}));const ConfirmationStatus=union([literal("processed"),literal("confirmed"),literal("finalized")]);const SignatureStatusResponse=type({slot:number(),confirmations:nullable(number()),err:TransactionErrorResult,confirmationStatus:optional(ConfirmationStatus)});const GetSignatureStatusesRpcResult=jsonRpcResultAndContext(array(nullable(SignatureStatusResponse)));const GetMinimumBalanceForRentExemptionRpcResult=jsonRpcResult(number());const ConfirmedTransactionResult=type({signatures:array(string()),message:type({accountKeys:array(string()),header:type({numRequiredSignatures:number(),numReadonlySignedAccounts:number(),numReadonlyUnsignedAccounts:number()}),instructions:array(type({accounts:array(number()),data:string(),programIdIndex:number()})),recentBlockhash:string()})});const ParsedInstructionResult=type({parsed:unknown(),program:string(),programId:PublicKeyFromString});const RawInstructionResult=type({accounts:array(PublicKeyFromString),data:string(),programId:PublicKeyFromString});const InstructionResult=union([RawInstructionResult,ParsedInstructionResult]);const UnknownInstructionResult=union([type({parsed:unknown(),program:string(),programId:string()}),type({accounts:array(string()),data:string(),programId:string()})]);const ParsedOrRawInstruction=coerce(InstructionResult,UnknownInstructionResult,(value=>{if("accounts"in value){return create(value,RawInstructionResult)}else{return create(value,ParsedInstructionResult)}}));const ParsedConfirmedTransactionResult=type({signatures:array(string()),message:type({accountKeys:array(type({pubkey:PublicKeyFromString,signer:boolean(),writable:boolean()})),instructions:array(ParsedOrRawInstruction),recentBlockhash:string()})});const TokenBalanceResult=type({accountIndex:number(),mint:string(),owner:optional(string()),uiTokenAmount:TokenAmountResult});const ConfirmedTransactionMetaResult=type({err:TransactionErrorResult,fee:number(),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(type({accounts:array(number()),data:string(),programIdIndex:number()}))})))),preBalances:array(number()),postBalances:array(number()),logMessages:optional(nullable(array(string()))),preTokenBalances:optional(nullable(array(TokenBalanceResult))),postTokenBalances:optional(nullable(array(TokenBalanceResult)))});const ParsedConfirmedTransactionMetaResult=type({err:TransactionErrorResult,fee:number(),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(ParsedOrRawInstruction)})))),preBalances:array(number()),postBalances:array(number()),logMessages:optional(nullable(array(string()))),preTokenBalances:optional(nullable(array(TokenBalanceResult))),postTokenBalances:optional(nullable(array(TokenBalanceResult)))});const GetBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionResult,meta:nullable(ConfirmedTransactionMetaResult)})),rewards:optional(array(type({pubkey:string(),lamports:number(),postBalance:nullable(number()),rewardType:nullable(string())}))),blockTime:nullable(number()),blockHeight:nullable(number())})));const GetConfirmedBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionResult,meta:nullable(ConfirmedTransactionMetaResult)})),rewards:optional(array(type({pubkey:string(),lamports:number(),postBalance:nullable(number()),rewardType:nullable(string())}))),blockTime:nullable(number())})));const GetBlockSignaturesRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),signatures:array(string()),blockTime:nullable(number())})));const GetTransactionRpcResult=jsonRpcResult(nullable(type({slot:number(),meta:ConfirmedTransactionMetaResult,blockTime:optional(nullable(number())),transaction:ConfirmedTransactionResult})));const GetParsedTransactionRpcResult=jsonRpcResult(nullable(type({slot:number(),transaction:ParsedConfirmedTransactionResult,meta:nullable(ParsedConfirmedTransactionMetaResult),blockTime:optional(nullable(number()))})));const GetRecentBlockhashAndContextRpcResult=jsonRpcResultAndContext(type({blockhash:string(),feeCalculator:type({lamportsPerSignature:number()})}));const GetLatestBlockhashRpcResult=jsonRpcResultAndContext(type({blockhash:string(),lastValidBlockHeight:number()}));const PerfSampleResult=type({slot:number(),numTransactions:number(),numSlots:number(),samplePeriodSecs:number()});const GetRecentPerformanceSamplesRpcResult=jsonRpcResult(array(PerfSampleResult));const GetFeeCalculatorRpcResult=jsonRpcResultAndContext(nullable(type({feeCalculator:type({lamportsPerSignature:number()})})));const RequestAirdropRpcResult=jsonRpcResult(string());const SendTransactionRpcResult=jsonRpcResult(string());const LogsResult=type({err:TransactionErrorResult,logs:array(string()),signature:string()});const LogsNotificationResult=type({result:notificationResultAndContext(LogsResult),subscription:number()});class Connection{constructor(endpoint,commitmentOrConfig){this._commitment=void 0;this._confirmTransactionInitialTimeout=void 0;this._rpcEndpoint=void 0;this._rpcWsEndpoint=void 0;this._rpcClient=void 0;this._rpcRequest=void 0;this._rpcBatchRequest=void 0;this._rpcWebSocket=void 0;this._rpcWebSocketConnected=false;this._rpcWebSocketHeartbeat=null;this._rpcWebSocketIdleTimeout=null;this._disableBlockhashCaching=false;this._pollingBlockhash=false;this._blockhashInfo={recentBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]};this._accountChangeSubscriptionCounter=0;this._accountChangeSubscriptions={};this._programAccountChangeSubscriptionCounter=0;this._programAccountChangeSubscriptions={};this._rootSubscriptionCounter=0;this._rootSubscriptions={};this._signatureSubscriptionCounter=0;this._signatureSubscriptions={};this._slotSubscriptionCounter=0;this._slotSubscriptions={};this._logsSubscriptionCounter=0;this._logsSubscriptions={};this._slotUpdateSubscriptionCounter=0;this._slotUpdateSubscriptions={};let url=new URL(endpoint);const useHttps=url.protocol==="https:";let wsEndpoint;let httpHeaders;let fetchMiddleware;let disableRetryOnRateLimit;if(commitmentOrConfig&&typeof commitmentOrConfig==="string"){this._commitment=commitmentOrConfig}else if(commitmentOrConfig){this._commitment=commitmentOrConfig.commitment;this._confirmTransactionInitialTimeout=commitmentOrConfig.confirmTransactionInitialTimeout;wsEndpoint=commitmentOrConfig.wsEndpoint;httpHeaders=commitmentOrConfig.httpHeaders;fetchMiddleware=commitmentOrConfig.fetchMiddleware;disableRetryOnRateLimit=commitmentOrConfig.disableRetryOnRateLimit}this._rpcEndpoint=endpoint;this._rpcWsEndpoint=wsEndpoint||makeWebsocketUrl(endpoint);this._rpcClient=createRpcClient(url.toString(),useHttps,httpHeaders,fetchMiddleware,disableRetryOnRateLimit);this._rpcRequest=createRpcRequest(this._rpcClient);this._rpcBatchRequest=createRpcBatchRequest(this._rpcClient);this._rpcWebSocket=new Client_1(this._rpcWsEndpoint,{autoconnect:false,max_reconnects:Infinity});this._rpcWebSocket.on("open",this._wsOnOpen.bind(this));this._rpcWebSocket.on("error",this._wsOnError.bind(this));this._rpcWebSocket.on("close",this._wsOnClose.bind(this));this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this));this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this));this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this));this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this));this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this));this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this));this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}async getBalanceAndContext(publicKey,commitment){const args=this._buildArgs([publicKey.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getBalance",args);const res=create(unsafeRes,jsonRpcResultAndContext(number()));if("error"in res){throw new Error("failed to get balance for "+publicKey.toBase58()+": "+res.error.message)}return res.result}async getBalance(publicKey,commitment){return await this.getBalanceAndContext(publicKey,commitment).then((x=>x.value)).catch((e=>{throw new Error("failed to get balance of account "+publicKey.toBase58()+": "+e)}))}async getBlockTime(slot){const unsafeRes=await this._rpcRequest("getBlockTime",[slot]);const res=create(unsafeRes,jsonRpcResult(nullable(number())));if("error"in res){throw new Error("failed to get block time for slot "+slot+": "+res.error.message)}return res.result}async getMinimumLedgerSlot(){const unsafeRes=await this._rpcRequest("minimumLedgerSlot",[]);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new Error("failed to get minimum ledger slot: "+res.error.message)}return res.result}async getFirstAvailableBlock(){const unsafeRes=await this._rpcRequest("getFirstAvailableBlock",[]);const res=create(unsafeRes,SlotRpcResult);if("error"in res){throw new Error("failed to get first available block: "+res.error.message)}return res.result}async getSupply(config){let configArg={};if(typeof config==="string"){configArg={commitment:config}}else if(config){configArg={...config,commitment:config&&config.commitment||this.commitment}}else{configArg={commitment:this.commitment}}const unsafeRes=await this._rpcRequest("getSupply",[configArg]);const res=create(unsafeRes,GetSupplyRpcResult);if("error"in res){throw new Error("failed to get supply: "+res.error.message)}return res.result}async getTokenSupply(tokenMintAddress,commitment){const args=this._buildArgs([tokenMintAddress.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getTokenSupply",args);const res=create(unsafeRes,jsonRpcResultAndContext(TokenAmountResult));if("error"in res){throw new Error("failed to get token supply: "+res.error.message)}return res.result}async getTokenAccountBalance(tokenAddress,commitment){const args=this._buildArgs([tokenAddress.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getTokenAccountBalance",args);const res=create(unsafeRes,jsonRpcResultAndContext(TokenAmountResult));if("error"in res){throw new Error("failed to get token account balance: "+res.error.message)}return res.result}async getTokenAccountsByOwner(ownerAddress,filter,commitment){let _args=[ownerAddress.toBase58()];if("mint"in filter){_args.push({mint:filter.mint.toBase58()})}else{_args.push({programId:filter.programId.toBase58()})}const args=this._buildArgs(_args,commitment,"base64");const unsafeRes=await this._rpcRequest("getTokenAccountsByOwner",args);const res=create(unsafeRes,GetTokenAccountsByOwner);if("error"in res){throw new Error("failed to get token accounts owned by account "+ownerAddress.toBase58()+": "+res.error.message)}return res.result}async getParsedTokenAccountsByOwner(ownerAddress,filter,commitment){let _args=[ownerAddress.toBase58()];if("mint"in filter){_args.push({mint:filter.mint.toBase58()})}else{_args.push({programId:filter.programId.toBase58()})}const args=this._buildArgs(_args,commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getTokenAccountsByOwner",args);const res=create(unsafeRes,GetParsedTokenAccountsByOwner);if("error"in res){throw new Error("failed to get token accounts owned by account "+ownerAddress.toBase58()+": "+res.error.message)}return res.result}async getLargestAccounts(config){const arg={...config,commitment:config&&config.commitment||this.commitment};const args=arg.filter||arg.commitment?[arg]:[];const unsafeRes=await this._rpcRequest("getLargestAccounts",args);const res=create(unsafeRes,GetLargestAccountsRpcResult);if("error"in res){throw new Error("failed to get largest accounts: "+res.error.message)}return res.result}async getTokenLargestAccounts(mintAddress,commitment){const args=this._buildArgs([mintAddress.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getTokenLargestAccounts",args);const res=create(unsafeRes,GetTokenLargestAccountsResult);if("error"in res){throw new Error("failed to get token largest accounts: "+res.error.message)}return res.result}async getAccountInfoAndContext(publicKey,commitment){const args=this._buildArgs([publicKey.toBase58()],commitment,"base64");const unsafeRes=await this._rpcRequest("getAccountInfo",args);const res=create(unsafeRes,jsonRpcResultAndContext(nullable(AccountInfoResult)));if("error"in res){throw new Error("failed to get info about account "+publicKey.toBase58()+": "+res.error.message)}return res.result}async getParsedAccountInfo(publicKey,commitment){const args=this._buildArgs([publicKey.toBase58()],commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getAccountInfo",args);const res=create(unsafeRes,jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)));if("error"in res){throw new Error("failed to get info about account "+publicKey.toBase58()+": "+res.error.message)}return res.result}async getAccountInfo(publicKey,commitment){try{const res=await this.getAccountInfoAndContext(publicKey,commitment);return res.value}catch(e){throw new Error("failed to get info about account "+publicKey.toBase58()+": "+e)}}async getMultipleAccountsInfoAndContext(publicKeys,commitment){const keys=publicKeys.map((key=>key.toBase58()));const args=this._buildArgs([keys],commitment,"base64");const unsafeRes=await this._rpcRequest("getMultipleAccounts",args);const res=create(unsafeRes,jsonRpcResultAndContext(array(nullable(AccountInfoResult))));if("error"in res){throw new Error("failed to get info for accounts "+keys+": "+res.error.message)}return res.result}async getMultipleAccountsInfo(publicKeys,commitment){const res=await this.getMultipleAccountsInfoAndContext(publicKeys,commitment);return res.value}async getStakeActivation(publicKey,commitment,epoch){const args=this._buildArgs([publicKey.toBase58()],commitment,undefined,epoch!==undefined?{epoch:epoch}:undefined);const unsafeRes=await this._rpcRequest("getStakeActivation",args);const res=create(unsafeRes,jsonRpcResult(StakeActivationResult));if("error"in res){throw new Error(`failed to get Stake Activation ${publicKey.toBase58()}: ${res.error.message}`)}return res.result}async getProgramAccounts(programId,configOrCommitment){const extra={};let commitment;let encoding;if(configOrCommitment){if(typeof configOrCommitment==="string"){commitment=configOrCommitment}else{commitment=configOrCommitment.commitment;encoding=configOrCommitment.encoding;if(configOrCommitment.dataSlice){extra.dataSlice=configOrCommitment.dataSlice}if(configOrCommitment.filters){extra.filters=configOrCommitment.filters}}}const args=this._buildArgs([programId.toBase58()],commitment,encoding||"base64",extra);const unsafeRes=await this._rpcRequest("getProgramAccounts",args);const res=create(unsafeRes,jsonRpcResult(array(KeyedAccountInfoResult)));if("error"in res){throw new Error("failed to get accounts owned by program "+programId.toBase58()+": "+res.error.message)}return res.result}async getParsedProgramAccounts(programId,configOrCommitment){const extra={};let commitment;if(configOrCommitment){if(typeof configOrCommitment==="string"){commitment=configOrCommitment}else{commitment=configOrCommitment.commitment;if(configOrCommitment.filters){extra.filters=configOrCommitment.filters}}}const args=this._buildArgs([programId.toBase58()],commitment,"jsonParsed",extra);const unsafeRes=await this._rpcRequest("getProgramAccounts",args);const res=create(unsafeRes,jsonRpcResult(array(KeyedParsedAccountInfoResult)));if("error"in res){throw new Error("failed to get accounts owned by program "+programId.toBase58()+": "+res.error.message)}return res.result}async confirmTransaction(signature,commitment){let decodedSignature;try{decodedSignature=bs58$1.decode(signature)}catch(err){throw new Error("signature must be base58 encoded: "+signature)}assert$c(decodedSignature.length===64,"signature has invalid length");const start=Date.now();const subscriptionCommitment=commitment||this.commitment;let subscriptionId;let response=null;const confirmPromise=new Promise(((resolve,reject)=>{try{subscriptionId=this.onSignature(signature,((result,context)=>{subscriptionId=undefined;response={context:context,value:result};resolve(null)}),subscriptionCommitment)}catch(err){reject(err)}}));let timeoutMs=this._confirmTransactionInitialTimeout||60*1e3;switch(subscriptionCommitment){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":{timeoutMs=this._confirmTransactionInitialTimeout||30*1e3;break}}try{await promiseTimeout(confirmPromise,timeoutMs)}finally{if(subscriptionId){this.removeSignatureListener(subscriptionId)}}if(response===null){const duration=(Date.now()-start)/1e3;throw new Error(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`)}return response}async getClusterNodes(){const unsafeRes=await this._rpcRequest("getClusterNodes",[]);const res=create(unsafeRes,jsonRpcResult(array(ContactInfoResult)));if("error"in res){throw new Error("failed to get cluster nodes: "+res.error.message)}return res.result}async getVoteAccounts(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getVoteAccounts",args);const res=create(unsafeRes,GetVoteAccounts);if("error"in res){throw new Error("failed to get vote accounts: "+res.error.message)}return res.result}async getSlot(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getSlot",args);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new Error("failed to get slot: "+res.error.message)}return res.result}async getSlotLeader(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getSlotLeader",args);const res=create(unsafeRes,jsonRpcResult(string()));if("error"in res){throw new Error("failed to get slot leader: "+res.error.message)}return res.result}async getSlotLeaders(startSlot,limit){const args=[startSlot,limit];const unsafeRes=await this._rpcRequest("getSlotLeaders",args);const res=create(unsafeRes,jsonRpcResult(array(PublicKeyFromString)));if("error"in res){throw new Error("failed to get slot leaders: "+res.error.message)}return res.result}async getSignatureStatus(signature,config){const{context:context,value:values}=await this.getSignatureStatuses([signature],config);assert$c(values.length===1);const value=values[0];return{context:context,value:value}}async getSignatureStatuses(signatures,config){const params=[signatures];if(config){params.push(config)}const unsafeRes=await this._rpcRequest("getSignatureStatuses",params);const res=create(unsafeRes,GetSignatureStatusesRpcResult);if("error"in res){throw new Error("failed to get signature status: "+res.error.message)}return res.result}async getTransactionCount(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getTransactionCount",args);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new Error("failed to get transaction count: "+res.error.message)}return res.result}async getTotalSupply(commitment){const result=await this.getSupply({commitment:commitment,excludeNonCirculatingAccountsList:true});return result.value.total}async getInflationGovernor(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getInflationGovernor",args);const res=create(unsafeRes,GetInflationGovernorRpcResult);if("error"in res){throw new Error("failed to get inflation: "+res.error.message)}return res.result}async getInflationReward(addresses,epoch,commitment){const args=this._buildArgs([addresses.map((pubkey=>pubkey.toBase58()))],commitment,undefined,{epoch:epoch});const unsafeRes=await this._rpcRequest("getInflationReward",args);const res=create(unsafeRes,GetInflationRewardResult);if("error"in res){throw new Error("failed to get inflation reward: "+res.error.message)}return res.result}async getEpochInfo(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getEpochInfo",args);const res=create(unsafeRes,GetEpochInfoRpcResult);if("error"in res){throw new Error("failed to get epoch info: "+res.error.message)}return res.result}async getEpochSchedule(){const unsafeRes=await this._rpcRequest("getEpochSchedule",[]);const res=create(unsafeRes,GetEpochScheduleRpcResult);if("error"in res){throw new Error("failed to get epoch schedule: "+res.error.message)}const epochSchedule=res.result;return new EpochSchedule(epochSchedule.slotsPerEpoch,epochSchedule.leaderScheduleSlotOffset,epochSchedule.warmup,epochSchedule.firstNormalEpoch,epochSchedule.firstNormalSlot)}async getLeaderSchedule(){const unsafeRes=await this._rpcRequest("getLeaderSchedule",[]);const res=create(unsafeRes,GetLeaderScheduleRpcResult);if("error"in res){throw new Error("failed to get leader schedule: "+res.error.message)}return res.result}async getMinimumBalanceForRentExemption(dataLength,commitment){const args=this._buildArgs([dataLength],commitment);const unsafeRes=await this._rpcRequest("getMinimumBalanceForRentExemption",args);const res=create(unsafeRes,GetMinimumBalanceForRentExemptionRpcResult);if("error"in res){console.warn("Unable to fetch minimum balance for rent exemption");return 0}return res.result}async getRecentBlockhashAndContext(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getRecentBlockhash",args);const res=create(unsafeRes,GetRecentBlockhashAndContextRpcResult);if("error"in res){throw new Error("failed to get recent blockhash: "+res.error.message)}return res.result}async getRecentPerformanceSamples(limit){const args=this._buildArgs(limit?[limit]:[]);const unsafeRes=await this._rpcRequest("getRecentPerformanceSamples",args);const res=create(unsafeRes,GetRecentPerformanceSamplesRpcResult);if("error"in res){throw new Error("failed to get recent performance samples: "+res.error.message)}return res.result}async getFeeCalculatorForBlockhash(blockhash,commitment){const args=this._buildArgs([blockhash],commitment);const unsafeRes=await this._rpcRequest("getFeeCalculatorForBlockhash",args);const res=create(unsafeRes,GetFeeCalculatorRpcResult);if("error"in res){throw new Error("failed to get fee calculator: "+res.error.message)}const{context:context,value:value}=res.result;return{context:context,value:value!==null?value.feeCalculator:null}}async getFeeForMessage(message,commitment){const wireMessage=message.serialize().toString("base64");const args=this._buildArgs([wireMessage],commitment);const unsafeRes=await this._rpcRequest("getFeeForMessage",args);const res=create(unsafeRes,jsonRpcResultAndContext(nullable(number())));if("error"in res){throw new Error("failed to get slot: "+res.error.message)}if(res.result===null){throw new Error("invalid blockhash")}return res.result}async getRecentBlockhash(commitment){try{const res=await this.getRecentBlockhashAndContext(commitment);return res.value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhash(commitment){try{const res=await this.getLatestBlockhashAndContext(commitment);return res.value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhashAndContext(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getLatestBlockhash",args);const res=create(unsafeRes,GetLatestBlockhashRpcResult);if("error"in res){throw new Error("failed to get latest blockhash: "+res.error.message)}return res.result}async getVersion(){const unsafeRes=await this._rpcRequest("getVersion",[]);const res=create(unsafeRes,jsonRpcResult(VersionResult));if("error"in res){throw new Error("failed to get version: "+res.error.message)}return res.result}async getGenesisHash(){const unsafeRes=await this._rpcRequest("getGenesisHash",[]);const res=create(unsafeRes,jsonRpcResult(string()));if("error"in res){throw new Error("failed to get genesis hash: "+res.error.message)}return res.result}async getBlock(slot,opts){const args=this._buildArgsAtLeastConfirmed([slot],opts&&opts.commitment);const unsafeRes=await this._rpcRequest("getBlock",args);const res=create(unsafeRes,GetBlockRpcResult);if("error"in res){throw new Error("failed to get confirmed block: "+res.error.message)}const result=res.result;if(!result)return result;return{...result,transactions:result.transactions.map((({transaction:transaction,meta:meta})=>{const message=new Message(transaction.message);return{meta:meta,transaction:{...transaction,message:message}}}))}}async getTransaction(signature,opts){const args=this._buildArgsAtLeastConfirmed([signature],opts&&opts.commitment);const unsafeRes=await this._rpcRequest("getTransaction",args);const res=create(unsafeRes,GetTransactionRpcResult);if("error"in res){throw new Error("failed to get transaction: "+res.error.message)}const result=res.result;if(!result)return result;return{...result,transaction:{...result.transaction,message:new Message(result.transaction.message)}}}async getParsedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getTransaction",args);const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new Error("failed to get transaction: "+res.error.message)}return res.result}async getParsedTransactions(signatures,commitment){const batch=signatures.map((signature=>{const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");return{methodName:"getTransaction",args:args}}));const unsafeRes=await this._rpcBatchRequest(batch);const res=unsafeRes.map((unsafeRes=>{const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new Error("failed to get transactions: "+res.error.message)}return res.result}));return res}async getConfirmedBlock(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment);const unsafeRes=await this._rpcRequest("getConfirmedBlock",args);const res=create(unsafeRes,GetConfirmedBlockRpcResult);if("error"in res){throw new Error("failed to get confirmed block: "+res.error.message)}const result=res.result;if(!result){throw new Error("Confirmed block "+slot+" not found")}const block={...result,transactions:result.transactions.map((({transaction:transaction,meta:meta})=>{const message=new Message(transaction.message);return{meta:meta,transaction:{...transaction,message:message}}}))};return{...block,transactions:block.transactions.map((({transaction:transaction,meta:meta})=>({meta:meta,transaction:Transaction.populate(transaction.message,transaction.signatures)})))}}async getBlocks(startSlot,endSlot,commitment){const args=this._buildArgsAtLeastConfirmed(endSlot!==undefined?[startSlot,endSlot]:[startSlot],commitment);const unsafeRes=await this._rpcRequest("getBlocks",args);const res=create(unsafeRes,jsonRpcResult(array(number())));if("error"in res){throw new Error("failed to get blocks: "+res.error.message)}return res.result}async getBlockSignatures(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment,undefined,{transactionDetails:"signatures",rewards:false});const unsafeRes=await this._rpcRequest("getBlock",args);const res=create(unsafeRes,GetBlockSignaturesRpcResult);if("error"in res){throw new Error("failed to get block: "+res.error.message)}const result=res.result;if(!result){throw new Error("Block "+slot+" not found")}return result}async getConfirmedBlockSignatures(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment,undefined,{transactionDetails:"signatures",rewards:false});const unsafeRes=await this._rpcRequest("getConfirmedBlock",args);const res=create(unsafeRes,GetBlockSignaturesRpcResult);if("error"in res){throw new Error("failed to get confirmed block: "+res.error.message)}const result=res.result;if(!result){throw new Error("Confirmed block "+slot+" not found")}return result}async getConfirmedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment);const unsafeRes=await this._rpcRequest("getConfirmedTransaction",args);const res=create(unsafeRes,GetTransactionRpcResult);if("error"in res){throw new Error("failed to get transaction: "+res.error.message)}const result=res.result;if(!result)return result;const message=new Message(result.transaction.message);const signatures=result.transaction.signatures;return{...result,transaction:Transaction.populate(message,signatures)}}async getParsedConfirmedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getConfirmedTransaction",args);const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new Error("failed to get confirmed transaction: "+res.error.message)}return res.result}async getParsedConfirmedTransactions(signatures,commitment){const batch=signatures.map((signature=>{const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");return{methodName:"getConfirmedTransaction",args:args}}));const unsafeRes=await this._rpcBatchRequest(batch);const res=unsafeRes.map((unsafeRes=>{const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new Error("failed to get confirmed transactions: "+res.error.message)}return res.result}));return res}async getConfirmedSignaturesForAddress(address,startSlot,endSlot){let options={};let firstAvailableBlock=await this.getFirstAvailableBlock();while(!("until"in options)){startSlot--;if(startSlot<=0||startSlot<firstAvailableBlock){break}try{const block=await this.getConfirmedBlockSignatures(startSlot,"finalized");if(block.signatures.length>0){options.until=block.signatures[block.signatures.length-1].toString()}}catch(err){if(err instanceof Error&&err.message.includes("skipped")){continue}else{throw err}}}let highestConfirmedRoot=await this.getSlot("finalized");while(!("before"in options)){endSlot++;if(endSlot>highestConfirmedRoot){break}try{const block=await this.getConfirmedBlockSignatures(endSlot);if(block.signatures.length>0){options.before=block.signatures[block.signatures.length-1].toString()}}catch(err){if(err instanceof Error&&err.message.includes("skipped")){continue}else{throw err}}}const confirmedSignatureInfo=await this.getConfirmedSignaturesForAddress2(address,options);return confirmedSignatureInfo.map((info=>info.signature))}async getConfirmedSignaturesForAddress2(address,options,commitment){const args=this._buildArgsAtLeastConfirmed([address.toBase58()],commitment,undefined,options);const unsafeRes=await this._rpcRequest("getConfirmedSignaturesForAddress2",args);const res=create(unsafeRes,GetConfirmedSignaturesForAddress2RpcResult);if("error"in res){throw new Error("failed to get confirmed signatures for address: "+res.error.message)}return res.result}async getSignaturesForAddress(address,options,commitment){const args=this._buildArgsAtLeastConfirmed([address.toBase58()],commitment,undefined,options);const unsafeRes=await this._rpcRequest("getSignaturesForAddress",args);const res=create(unsafeRes,GetSignaturesForAddressRpcResult);if("error"in res){throw new Error("failed to get signatures for address: "+res.error.message)}return res.result}async getNonceAndContext(nonceAccount,commitment){const{context:context,value:accountInfo}=await this.getAccountInfoAndContext(nonceAccount,commitment);let value=null;if(accountInfo!==null){value=NonceAccount.fromAccountData(accountInfo.data)}return{context:context,value:value}}async getNonce(nonceAccount,commitment){return await this.getNonceAndContext(nonceAccount,commitment).then((x=>x.value)).catch((e=>{throw new Error("failed to get nonce for account "+nonceAccount.toBase58()+": "+e)}))}async requestAirdrop(to,lamports){const unsafeRes=await this._rpcRequest("requestAirdrop",[to.toBase58(),lamports]);const res=create(unsafeRes,RequestAirdropRpcResult);if("error"in res){throw new Error("airdrop to "+to.toBase58()+" failed: "+res.error.message)}return res.result}async _recentBlockhash(disableCache){if(!disableCache){while(this._pollingBlockhash){await sleep(100)}const timeSinceFetch=Date.now()-this._blockhashInfo.lastFetch;const expired=timeSinceFetch>=BLOCKHASH_CACHE_TIMEOUT_MS;if(this._blockhashInfo.recentBlockhash!==null&&!expired){return this._blockhashInfo.recentBlockhash}}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=true;try{const startTime=Date.now();for(let i=0;i<50;i++){const{blockhash:blockhash}=await this.getRecentBlockhash("finalized");if(this._blockhashInfo.recentBlockhash!=blockhash){this._blockhashInfo={recentBlockhash:blockhash,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]};return blockhash}await sleep(MS_PER_SLOT/2)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-startTime}ms`)}finally{this._pollingBlockhash=false}}async simulateTransaction(transactionOrMessage,signers,includeAccounts){let transaction;if(transactionOrMessage instanceof Transaction){transaction=transactionOrMessage}else{transaction=Transaction.populate(transactionOrMessage)}if(transaction.nonceInfo&&signers){transaction.sign(...signers)}else{let disableCache=this._disableBlockhashCaching;for(;;){transaction.recentBlockhash=await this._recentBlockhash(disableCache);if(!signers)break;transaction.sign(...signers);if(!transaction.signature){throw new Error("!signature")}const signature=transaction.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(signature)&&!this._blockhashInfo.transactionSignatures.includes(signature)){this._blockhashInfo.simulatedSignatures.push(signature);break}else{disableCache=true}}}const message=transaction._compile();const signData=message.serialize();const wireTransaction=transaction._serialize(signData);const encodedTransaction=wireTransaction.toString("base64");const config={encoding:"base64",commitment:this.commitment};if(includeAccounts){const addresses=(Array.isArray(includeAccounts)?includeAccounts:message.nonProgramIds()).map((key=>key.toBase58()));config["accounts"]={encoding:"base64",addresses:addresses}}if(signers){config.sigVerify=true}const args=[encodedTransaction,config];const unsafeRes=await this._rpcRequest("simulateTransaction",args);const res=create(unsafeRes,SimulatedTransactionResponseStruct);if("error"in res){let logs;if("data"in res.error){logs=res.error.data.logs;if(logs&&Array.isArray(logs)){const traceIndent="\n ";const logTrace=traceIndent+logs.join(traceIndent);console.error(res.error.message,logTrace)}}throw new SendTransactionError("failed to simulate transaction: "+res.error.message,logs)}return res.result}async sendTransaction(transaction,signers,options){if(transaction.nonceInfo){transaction.sign(...signers)}else{let disableCache=this._disableBlockhashCaching;for(;;){transaction.recentBlockhash=await this._recentBlockhash(disableCache);transaction.sign(...signers);if(!transaction.signature){throw new Error("!signature")}const signature=transaction.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(signature)){this._blockhashInfo.transactionSignatures.push(signature);break}else{disableCache=true}}}const wireTransaction=transaction.serialize();return await this.sendRawTransaction(wireTransaction,options)}async sendRawTransaction(rawTransaction,options){const encodedTransaction=toBuffer(rawTransaction).toString("base64");const result=await this.sendEncodedTransaction(encodedTransaction,options);return result}async sendEncodedTransaction(encodedTransaction,options){const config={encoding:"base64"};const skipPreflight=options&&options.skipPreflight;const preflightCommitment=options&&options.preflightCommitment||this.commitment;if(options&&options.maxRetries){config.maxRetries=options.maxRetries}if(skipPreflight){config.skipPreflight=skipPreflight}if(preflightCommitment){config.preflightCommitment=preflightCommitment}const args=[encodedTransaction,config];const unsafeRes=await this._rpcRequest("sendTransaction",args);const res=create(unsafeRes,SendTransactionRpcResult);if("error"in res){let logs;if("data"in res.error){logs=res.error.data.logs;if(logs&&Array.isArray(logs)){const traceIndent="\n ";const logTrace=traceIndent+logs.join(traceIndent);console.error(res.error.message,logTrace)}}throw new SendTransactionError("failed to send transaction: "+res.error.message,logs)}return res.result}_wsOnOpen(){this._rpcWebSocketConnected=true;this._rpcWebSocketHeartbeat=setInterval((()=>{this._rpcWebSocket.notify("ping").catch((()=>{}))}),5e3);this._updateSubscriptions()}_wsOnError(err){console.error("ws error:",err.message)}_wsOnClose(code){if(this._rpcWebSocketHeartbeat){clearInterval(this._rpcWebSocketHeartbeat);this._rpcWebSocketHeartbeat=null}if(code===1e3){this._updateSubscriptions();return}this._resetSubscriptions()}async _subscribe(sub,rpcMethod,rpcArgs){if(sub.subscriptionId==null){sub.subscriptionId="subscribing";try{const id=await this._rpcWebSocket.call(rpcMethod,rpcArgs);if(typeof id==="number"&&sub.subscriptionId==="subscribing"){sub.subscriptionId=id}}catch(err){if(sub.subscriptionId==="subscribing"){sub.subscriptionId=null}if(err instanceof Error){console.error(`${rpcMethod} error for argument`,rpcArgs,err.message)}}}}async _unsubscribe(sub,rpcMethod){const subscriptionId=sub.subscriptionId;if(subscriptionId!=null&&typeof subscriptionId!="string"){const unsubscribeId=subscriptionId;try{await this._rpcWebSocket.call(rpcMethod,[unsubscribeId])}catch(err){if(err instanceof Error){console.error(`${rpcMethod} error:`,err.message)}}}}_resetSubscriptions(){Object.values(this._accountChangeSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._programAccountChangeSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._rootSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._signatureSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._slotSubscriptions).forEach((s=>s.subscriptionId=null));Object.values(this._slotUpdateSubscriptions).forEach((s=>s.subscriptionId=null))}_updateSubscriptions(){const accountKeys=Object.keys(this._accountChangeSubscriptions).map(Number);const programKeys=Object.keys(this._programAccountChangeSubscriptions).map(Number);const slotKeys=Object.keys(this._slotSubscriptions).map(Number);const slotUpdateKeys=Object.keys(this._slotUpdateSubscriptions).map(Number);const signatureKeys=Object.keys(this._signatureSubscriptions).map(Number);const rootKeys=Object.keys(this._rootSubscriptions).map(Number);const logsKeys=Object.keys(this._logsSubscriptions).map(Number);if(accountKeys.length===0&&programKeys.length===0&&slotKeys.length===0&&slotUpdateKeys.length===0&&signatureKeys.length===0&&rootKeys.length===0&&logsKeys.length===0){if(this._rpcWebSocketConnected){this._rpcWebSocketConnected=false;this._rpcWebSocketIdleTimeout=setTimeout((()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(err){if(err instanceof Error){console.log(`Error when closing socket connection: ${err.message}`)}}}),500)}return}if(this._rpcWebSocketIdleTimeout!==null){clearTimeout(this._rpcWebSocketIdleTimeout);this._rpcWebSocketIdleTimeout=null;this._rpcWebSocketConnected=true}if(!this._rpcWebSocketConnected){this._rpcWebSocket.connect();return}for(let id of accountKeys){const sub=this._accountChangeSubscriptions[id];this._subscribe(sub,"accountSubscribe",this._buildArgs([sub.publicKey],sub.commitment,"base64"))}for(let id of programKeys){const sub=this._programAccountChangeSubscriptions[id];this._subscribe(sub,"programSubscribe",this._buildArgs([sub.programId],sub.commitment,"base64",{filters:sub.filters}))}for(let id of slotKeys){const sub=this._slotSubscriptions[id];this._subscribe(sub,"slotSubscribe",[])}for(let id of slotUpdateKeys){const sub=this._slotUpdateSubscriptions[id];this._subscribe(sub,"slotsUpdatesSubscribe",[])}for(let id of signatureKeys){const sub=this._signatureSubscriptions[id];const args=[sub.signature];if(sub.options)args.push(sub.options);this._subscribe(sub,"signatureSubscribe",args)}for(let id of rootKeys){const sub=this._rootSubscriptions[id];this._subscribe(sub,"rootSubscribe",[])}for(let id of logsKeys){const sub=this._logsSubscriptions[id];let filter;if(typeof sub.filter==="object"){filter={mentions:[sub.filter.toString()]}}else{filter=sub.filter}this._subscribe(sub,"logsSubscribe",this._buildArgs([filter],sub.commitment))}}_wsOnAccountNotification(notification){const res=create(notification,AccountNotificationResult);for(const sub of Object.values(this._accountChangeSubscriptions)){if(sub.subscriptionId===res.subscription){sub.callback(res.result.value,res.result.context);return}}}onAccountChange(publicKey,callback,commitment){const id=++this._accountChangeSubscriptionCounter;this._accountChangeSubscriptions[id]={publicKey:publicKey.toBase58(),callback:callback,commitment:commitment,subscriptionId:null};this._updateSubscriptions();return id}async removeAccountChangeListener(id){if(this._accountChangeSubscriptions[id]){const subInfo=this._accountChangeSubscriptions[id];delete this._accountChangeSubscriptions[id];await this._unsubscribe(subInfo,"accountUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown account change id: ${id}`)}}_wsOnProgramAccountNotification(notification){const res=create(notification,ProgramAccountNotificationResult);for(const sub of Object.values(this._programAccountChangeSubscriptions)){if(sub.subscriptionId===res.subscription){const{value:value,context:context}=res.result;sub.callback({accountId:value.pubkey,accountInfo:value.account},context);return}}}onProgramAccountChange(programId,callback,commitment,filters){const id=++this._programAccountChangeSubscriptionCounter;this._programAccountChangeSubscriptions[id]={programId:programId.toBase58(),callback:callback,commitment:commitment,subscriptionId:null,filters:filters};this._updateSubscriptions();return id}async removeProgramAccountChangeListener(id){if(this._programAccountChangeSubscriptions[id]){const subInfo=this._programAccountChangeSubscriptions[id];delete this._programAccountChangeSubscriptions[id];await this._unsubscribe(subInfo,"programUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown program account change id: ${id}`)}}onLogs(filter,callback,commitment){const id=++this._logsSubscriptionCounter;this._logsSubscriptions[id]={filter:filter,callback:callback,commitment:commitment,subscriptionId:null};this._updateSubscriptions();return id}async removeOnLogsListener(id){if(!this._logsSubscriptions[id]){throw new Error(`Unknown logs id: ${id}`)}const subInfo=this._logsSubscriptions[id];delete this._logsSubscriptions[id];await this._unsubscribe(subInfo,"logsUnsubscribe");this._updateSubscriptions()}_wsOnLogsNotification(notification){const res=create(notification,LogsNotificationResult);const keys=Object.keys(this._logsSubscriptions).map(Number);for(let id of keys){const sub=this._logsSubscriptions[id];if(sub.subscriptionId===res.subscription){sub.callback(res.result.value,res.result.context);return}}}_wsOnSlotNotification(notification){const res=create(notification,SlotNotificationResult);for(const sub of Object.values(this._slotSubscriptions)){if(sub.subscriptionId===res.subscription){sub.callback(res.result);return}}}onSlotChange(callback){const id=++this._slotSubscriptionCounter;this._slotSubscriptions[id]={callback:callback,subscriptionId:null};this._updateSubscriptions();return id}async removeSlotChangeListener(id){if(this._slotSubscriptions[id]){const subInfo=this._slotSubscriptions[id];delete this._slotSubscriptions[id];await this._unsubscribe(subInfo,"slotUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown slot change id: ${id}`)}}_wsOnSlotUpdatesNotification(notification){const res=create(notification,SlotUpdateNotificationResult);for(const sub of Object.values(this._slotUpdateSubscriptions)){if(sub.subscriptionId===res.subscription){sub.callback(res.result);return}}}onSlotUpdate(callback){const id=++this._slotUpdateSubscriptionCounter;this._slotUpdateSubscriptions[id]={callback:callback,subscriptionId:null};this._updateSubscriptions();return id}async removeSlotUpdateListener(id){if(this._slotUpdateSubscriptions[id]){const subInfo=this._slotUpdateSubscriptions[id];delete this._slotUpdateSubscriptions[id];await this._unsubscribe(subInfo,"slotsUpdatesUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown slot update id: ${id}`)}}_buildArgs(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment||encoding||extra){let options={};if(encoding){options.encoding=encoding}if(commitment){options.commitment=commitment}if(extra){options=Object.assign(options,extra)}args.push(options)}return args}_buildArgsAtLeastConfirmed(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment&&!["confirmed","finalized"].includes(commitment)){throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`")}return this._buildArgs(args,override,encoding,extra)}_wsOnSignatureNotification(notification){const res=create(notification,SignatureNotificationResult);for(const[id,sub]of Object.entries(this._signatureSubscriptions)){if(sub.subscriptionId===res.subscription){if(res.result.value==="receivedSignature"){sub.callback({type:"received"},res.result.context)}else{delete this._signatureSubscriptions[Number(id)];this._updateSubscriptions();sub.callback({type:"status",result:res.result.value},res.result.context)}return}}}onSignature(signature,callback,commitment){const id=++this._signatureSubscriptionCounter;this._signatureSubscriptions[id]={signature:signature,callback:(notification,context)=>{if(notification.type==="status"){callback(notification.result,context)}},options:{commitment:commitment},subscriptionId:null};this._updateSubscriptions();return id}onSignatureWithOptions(signature,callback,options){const id=++this._signatureSubscriptionCounter;this._signatureSubscriptions[id]={signature:signature,callback:callback,options:options,subscriptionId:null};this._updateSubscriptions();return id}async removeSignatureListener(id){if(this._signatureSubscriptions[id]){const subInfo=this._signatureSubscriptions[id];delete this._signatureSubscriptions[id];await this._unsubscribe(subInfo,"signatureUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown signature result id: ${id}`)}}_wsOnRootNotification(notification){const res=create(notification,RootNotificationResult);for(const sub of Object.values(this._rootSubscriptions)){if(sub.subscriptionId===res.subscription){sub.callback(res.result);return}}}onRootChange(callback){const id=++this._rootSubscriptionCounter;this._rootSubscriptions[id]={callback:callback,subscriptionId:null};this._updateSubscriptions();return id}async removeRootChangeListener(id){if(this._rootSubscriptions[id]){const subInfo=this._rootSubscriptions[id];delete this._rootSubscriptions[id];await this._unsubscribe(subInfo,"rootUnsubscribe");this._updateSubscriptions()}else{throw new Error(`Unknown root change id: ${id}`)}}}class Keypair{constructor(keypair){this._keypair=void 0;if(keypair){this._keypair=keypair}else{this._keypair=nacl.sign.keyPair()}}static generate(){return new Keypair(nacl.sign.keyPair())}static fromSecretKey(secretKey,options){const keypair=nacl.sign.keyPair.fromSecretKey(secretKey);if(!options||!options.skipValidation){const encoder=new TextEncoder;const signData=encoder.encode("@solana/web3.js-validation-v1");const signature=nacl.sign.detached(signData,keypair.secretKey);if(!nacl.sign.detached.verify(signData,signature,keypair.publicKey)){throw new Error("provided secretKey is invalid")}}return new Keypair(keypair)}static fromSeed(seed){return new Keypair(nacl.sign.keyPair.fromSeed(seed))}get publicKey(){return new PublicKey(this._keypair.publicKey)}get secretKey(){return this._keypair.secretKey}}const PRIVATE_KEY_BYTES$1=64;const PUBLIC_KEY_BYTES$1=32;const SIGNATURE_BYTES=64;const ED25519_INSTRUCTION_LAYOUT=struct([u8("numSignatures"),u8("padding"),u16("signatureOffset"),u16("signatureInstructionIndex"),u16("publicKeyOffset"),u16("publicKeyInstructionIndex"),u16("messageDataOffset"),u16("messageDataSize"),u16("messageInstructionIndex")]);class Ed25519Program{constructor(){}static createInstructionWithPublicKey(params){const{publicKey:publicKey,message:message,signature:signature,instructionIndex:instructionIndex}=params;assert$c(publicKey.length===PUBLIC_KEY_BYTES$1,`Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey.length} bytes`);assert$c(signature.length===SIGNATURE_BYTES,`Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);const publicKeyOffset=ED25519_INSTRUCTION_LAYOUT.span;const signatureOffset=publicKeyOffset+publicKey.length;const messageDataOffset=signatureOffset+signature.length;const numSignatures=1;const instructionData=buffer.Buffer.alloc(messageDataOffset+message.length);ED25519_INSTRUCTION_LAYOUT.encode({numSignatures:numSignatures,padding:0,signatureOffset:signatureOffset,signatureInstructionIndex:instructionIndex,publicKeyOffset:publicKeyOffset,publicKeyInstructionIndex:instructionIndex,messageDataOffset:messageDataOffset,messageDataSize:message.length,messageInstructionIndex:instructionIndex},instructionData);instructionData.fill(publicKey,publicKeyOffset);instructionData.fill(signature,signatureOffset);instructionData.fill(message,messageDataOffset);return new TransactionInstruction({keys:[],programId:Ed25519Program.programId,data:instructionData})}static createInstructionWithPrivateKey(params){const{privateKey:privateKey,message:message,instructionIndex:instructionIndex}=params;assert$c(privateKey.length===PRIVATE_KEY_BYTES$1,`Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);try{const keypair=Keypair.fromSecretKey(privateKey);const publicKey=keypair.publicKey.toBytes();const signature=nacl.sign.detached(message,keypair.secretKey);return this.createInstructionWithPublicKey({publicKey:publicKey,message:message,signature:signature,instructionIndex:instructionIndex})}catch(error){throw new Error(`Error creating instruction; ${error}`)}}}Ed25519Program.programId=new PublicKey("Ed25519SigVerify111111111111111111111111111");const STAKE_CONFIG_ID=new PublicKey("StakeConfig11111111111111111111111111111111");class Authorized{constructor(staker,withdrawer){this.staker=void 0;this.withdrawer=void 0;this.staker=staker;this.withdrawer=withdrawer}}class Lockup{constructor(unixTimestamp,epoch,custodian){this.unixTimestamp=void 0;this.epoch=void 0;this.custodian=void 0;this.unixTimestamp=unixTimestamp;this.epoch=epoch;this.custodian=custodian}}Lockup.default=new Lockup(0,0,PublicKey.default);class StakeInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=u32("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(STAKE_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a StakeInstruction")}return type}static decodeInitialize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{authorized:authorized,lockup:lockup}=decodeData(STAKE_INSTRUCTION_LAYOUTS.Initialize,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,authorized:new Authorized(new PublicKey(authorized.staker),new PublicKey(authorized.withdrawer)),lockup:new Lockup(lockup.unixTimestamp,lockup.epoch,new PublicKey(lockup.custodian))}}static decodeDelegate(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,6);decodeData(STAKE_INSTRUCTION_LAYOUTS.Delegate,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,votePubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[5].pubkey}}static decodeAuthorize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{newAuthorized:newAuthorized,stakeAuthorizationType:stakeAuthorizationType}=decodeData(STAKE_INSTRUCTION_LAYOUTS.Authorize,instruction.data);const o={stakePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey,newAuthorizedPubkey:new PublicKey(newAuthorized),stakeAuthorizationType:{index:stakeAuthorizationType}};if(instruction.keys.length>3){o.custodianPubkey=instruction.keys[3].pubkey}return o}static decodeAuthorizeWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{newAuthorized:newAuthorized,stakeAuthorizationType:stakeAuthorizationType,authoritySeed:authoritySeed,authorityOwner:authorityOwner}=decodeData(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,instruction.data);const o={stakePubkey:instruction.keys[0].pubkey,authorityBase:instruction.keys[1].pubkey,authoritySeed:authoritySeed,authorityOwner:new PublicKey(authorityOwner),newAuthorizedPubkey:new PublicKey(newAuthorized),stakeAuthorizationType:{index:stakeAuthorizationType}};if(instruction.keys.length>3){o.custodianPubkey=instruction.keys[3].pubkey}return o}static decodeSplit(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{lamports:lamports}=decodeData(STAKE_INSTRUCTION_LAYOUTS.Split,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,splitStakePubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[2].pubkey,lamports:lamports}}static decodeMerge(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);decodeData(STAKE_INSTRUCTION_LAYOUTS.Merge,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,sourceStakePubKey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey}}static decodeWithdraw(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,5);const{lamports:lamports}=decodeData(STAKE_INSTRUCTION_LAYOUTS.Withdraw,instruction.data);const o={stakePubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey,lamports:lamports};if(instruction.keys.length>5){o.custodianPubkey=instruction.keys[5].pubkey}return o}static decodeDeactivate(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);decodeData(STAKE_INSTRUCTION_LAYOUTS.Deactivate,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey}}static checkProgramId(programId){if(!programId.equals(StakeProgram.programId)){throw new Error("invalid instruction; programId is not StakeProgram")}}static checkKeyLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}const STAKE_INSTRUCTION_LAYOUTS=Object.freeze({Initialize:{index:0,layout:struct([u32("instruction"),authorized(),lockup()])},Authorize:{index:1,layout:struct([u32("instruction"),publicKey("newAuthorized"),u32("stakeAuthorizationType")])},Delegate:{index:2,layout:struct([u32("instruction")])},Split:{index:3,layout:struct([u32("instruction"),ns64("lamports")])},Withdraw:{index:4,layout:struct([u32("instruction"),ns64("lamports")])},Deactivate:{index:5,layout:struct([u32("instruction")])},Merge:{index:7,layout:struct([u32("instruction")])},AuthorizeWithSeed:{index:8,layout:struct([u32("instruction"),publicKey("newAuthorized"),u32("stakeAuthorizationType"),rustString("authoritySeed"),publicKey("authorityOwner")])}});const StakeAuthorizationLayout=Object.freeze({Staker:{index:0},Withdrawer:{index:1}});class StakeProgram{constructor(){}static initialize(params){const{stakePubkey:stakePubkey,authorized:authorized,lockup:maybeLockup}=params;const lockup=maybeLockup||Lockup.default;const type=STAKE_INSTRUCTION_LAYOUTS.Initialize;const data=encodeData(type,{authorized:{staker:toBuffer(authorized.staker.toBuffer()),withdrawer:toBuffer(authorized.withdrawer.toBuffer())},lockup:{unixTimestamp:lockup.unixTimestamp,epoch:lockup.epoch,custodian:toBuffer(lockup.custodian.toBuffer())}});const instructionData={keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static createAccountWithSeed(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccountWithSeed({fromPubkey:params.fromPubkey,newAccountPubkey:params.stakePubkey,basePubkey:params.basePubkey,seed:params.seed,lamports:params.lamports,space:this.space,programId:this.programId}));const{stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}=params;return transaction.add(this.initialize({stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}))}static createAccount(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.stakePubkey,lamports:params.lamports,space:this.space,programId:this.programId}));const{stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}=params;return transaction.add(this.initialize({stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}))}static delegate(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,votePubkey:votePubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Delegate;const data=encodeData(type);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:votePubkey,isSigner:false,isWritable:false},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:false,isWritable:false},{pubkey:STAKE_CONFIG_ID,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static authorize(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,newAuthorizedPubkey:newAuthorizedPubkey,stakeAuthorizationType:stakeAuthorizationType,custodianPubkey:custodianPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Authorize;const data=encodeData(type,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),stakeAuthorizationType:stakeAuthorizationType.index});const keys=[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:true},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}];if(custodianPubkey){keys.push({pubkey:custodianPubkey,isSigner:false,isWritable:false})}return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static authorizeWithSeed(params){const{stakePubkey:stakePubkey,authorityBase:authorityBase,authoritySeed:authoritySeed,authorityOwner:authorityOwner,newAuthorizedPubkey:newAuthorizedPubkey,stakeAuthorizationType:stakeAuthorizationType,custodianPubkey:custodianPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;const data=encodeData(type,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),stakeAuthorizationType:stakeAuthorizationType.index,authoritySeed:authoritySeed,authorityOwner:toBuffer(authorityOwner.toBuffer())});const keys=[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:authorityBase,isSigner:true,isWritable:false},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false}];if(custodianPubkey){keys.push({pubkey:custodianPubkey,isSigner:false,isWritable:false})}return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static splitInstruction(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,splitStakePubkey:splitStakePubkey,lamports:lamports}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Split;const data=encodeData(type,{lamports:lamports});return new TransactionInstruction({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:splitStakePubkey,isSigner:false,isWritable:true},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static split(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.authorizedPubkey,newAccountPubkey:params.splitStakePubkey,lamports:0,space:this.space,programId:this.programId}));return transaction.add(this.splitInstruction(params))}static splitWithSeed(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,splitStakePubkey:splitStakePubkey,basePubkey:basePubkey,seed:seed,lamports:lamports}=params;const transaction=new Transaction;transaction.add(SystemProgram.allocate({accountPubkey:splitStakePubkey,basePubkey:basePubkey,seed:seed,space:this.space,programId:this.programId}));return transaction.add(this.splitInstruction({stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,splitStakePubkey:splitStakePubkey,lamports:lamports}))}static merge(params){const{stakePubkey:stakePubkey,sourceStakePubKey:sourceStakePubKey,authorizedPubkey:authorizedPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Merge;const data=encodeData(type);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:sourceStakePubKey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static withdraw(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,toPubkey:toPubkey,lamports:lamports,custodianPubkey:custodianPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Withdraw;const data=encodeData(type,{lamports:lamports});const keys=[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:toPubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}];if(custodianPubkey){keys.push({pubkey:custodianPubkey,isSigner:false,isWritable:false})}return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static deactivate(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Deactivate;const data=encodeData(type);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}}StakeProgram.programId=new PublicKey("Stake11111111111111111111111111111111111111");StakeProgram.space=200;const errors={IMPOSSIBLE_CASE:"Impossible case. Please create issue.",TWEAK_ADD:"The tweak was out of range or the resulted private key is invalid",TWEAK_MUL:"The tweak was out of range or equal to zero",CONTEXT_RANDOMIZE_UNKNOW:"Unknow error on context randomization",SECKEY_INVALID:"Private Key is invalid",PUBKEY_PARSE:"Public Key could not be parsed",PUBKEY_SERIALIZE:"Public Key serialization error",PUBKEY_COMBINE:"The sum of the public keys is not valid",SIG_PARSE:"Signature could not be parsed",SIGN:"The nonce generation function failed, or the private key was invalid",RECOVER:"Public key could not be recover",ECDH:"Scalar was invalid (zero or overflow)"};function assert$a(cond,msg){if(!cond)throw new Error(msg)}function isUint8Array(name,value,length){assert$a(value instanceof Uint8Array,`Expected ${name} to be an Uint8Array`);if(length!==undefined){if(Array.isArray(length)){const numbers=length.join(", ");const msg=`Expected ${name} to be an Uint8Array with length [${numbers}]`;assert$a(length.includes(value.length),msg)}else{const msg=`Expected ${name} to be an Uint8Array with length ${length}`;assert$a(value.length===length,msg)}}}function isCompressed(value){assert$a(toTypeString(value)==="Boolean","Expected compressed to be a Boolean")}function getAssertedOutput(output=(len=>new Uint8Array(len)),length){if(typeof output==="function")output=output(length);isUint8Array("output",output,length);return output}function toTypeString(value){return Object.prototype.toString.call(value).slice(8,-1)}var lib=secp256k1=>({contextRandomize(seed){assert$a(seed===null||seed instanceof Uint8Array,"Expected seed to be an Uint8Array or null");if(seed!==null)isUint8Array("seed",seed,32);switch(secp256k1.contextRandomize(seed)){case 1:throw new Error(errors.CONTEXT_RANDOMIZE_UNKNOW)}},privateKeyVerify(seckey){isUint8Array("private key",seckey,32);return secp256k1.privateKeyVerify(seckey)===0},privateKeyNegate(seckey){isUint8Array("private key",seckey,32);switch(secp256k1.privateKeyNegate(seckey)){case 0:return seckey;case 1:throw new Error(errors.IMPOSSIBLE_CASE)}},privateKeyTweakAdd(seckey,tweak){isUint8Array("private key",seckey,32);isUint8Array("tweak",tweak,32);switch(secp256k1.privateKeyTweakAdd(seckey,tweak)){case 0:return seckey;case 1:throw new Error(errors.TWEAK_ADD)}},privateKeyTweakMul(seckey,tweak){isUint8Array("private key",seckey,32);isUint8Array("tweak",tweak,32);switch(secp256k1.privateKeyTweakMul(seckey,tweak)){case 0:return seckey;case 1:throw new Error(errors.TWEAK_MUL)}},publicKeyVerify(pubkey){isUint8Array("public key",pubkey,[33,65]);return secp256k1.publicKeyVerify(pubkey)===0},publicKeyCreate(seckey,compressed=true,output){isUint8Array("private key",seckey,32);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyCreate(output,seckey)){case 0:return output;case 1:throw new Error(errors.SECKEY_INVALID);case 2:throw new Error(errors.PUBKEY_SERIALIZE)}},publicKeyConvert(pubkey,compressed=true,output){isUint8Array("public key",pubkey,[33,65]);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyConvert(output,pubkey)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.PUBKEY_SERIALIZE)}},publicKeyNegate(pubkey,compressed=true,output){isUint8Array("public key",pubkey,[33,65]);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyNegate(output,pubkey)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.IMPOSSIBLE_CASE);case 3:throw new Error(errors.PUBKEY_SERIALIZE)}},publicKeyCombine(pubkeys,compressed=true,output){assert$a(Array.isArray(pubkeys),"Expected public keys to be an Array");assert$a(pubkeys.length>0,"Expected public keys array will have more than zero items");for(const pubkey of pubkeys){isUint8Array("public key",pubkey,[33,65])}isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyCombine(output,pubkeys)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.PUBKEY_COMBINE);case 3:throw new Error(errors.PUBKEY_SERIALIZE)}},publicKeyTweakAdd(pubkey,tweak,compressed=true,output){isUint8Array("public key",pubkey,[33,65]);isUint8Array("tweak",tweak,32);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyTweakAdd(output,pubkey,tweak)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.TWEAK_ADD)}},publicKeyTweakMul(pubkey,tweak,compressed=true,output){isUint8Array("public key",pubkey,[33,65]);isUint8Array("tweak",tweak,32);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.publicKeyTweakMul(output,pubkey,tweak)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.TWEAK_MUL)}},signatureNormalize(sig){isUint8Array("signature",sig,64);switch(secp256k1.signatureNormalize(sig)){case 0:return sig;case 1:throw new Error(errors.SIG_PARSE)}},signatureExport(sig,output){isUint8Array("signature",sig,64);output=getAssertedOutput(output,72);const obj={output:output,outputlen:72};switch(secp256k1.signatureExport(obj,sig)){case 0:return output.slice(0,obj.outputlen);case 1:throw new Error(errors.SIG_PARSE);case 2:throw new Error(errors.IMPOSSIBLE_CASE)}},signatureImport(sig,output){isUint8Array("signature",sig);output=getAssertedOutput(output,64);switch(secp256k1.signatureImport(output,sig)){case 0:return output;case 1:throw new Error(errors.SIG_PARSE);case 2:throw new Error(errors.IMPOSSIBLE_CASE)}},ecdsaSign(msg32,seckey,options={},output){isUint8Array("message",msg32,32);isUint8Array("private key",seckey,32);assert$a(toTypeString(options)==="Object","Expected options to be an Object");if(options.data!==undefined)isUint8Array("options.data",options.data);if(options.noncefn!==undefined)assert$a(toTypeString(options.noncefn)==="Function","Expected options.noncefn to be a Function");output=getAssertedOutput(output,64);const obj={signature:output,recid:null};switch(secp256k1.ecdsaSign(obj,msg32,seckey,options.data,options.noncefn)){case 0:return obj;case 1:throw new Error(errors.SIGN);case 2:throw new Error(errors.IMPOSSIBLE_CASE)}},ecdsaVerify(sig,msg32,pubkey){isUint8Array("signature",sig,64);isUint8Array("message",msg32,32);isUint8Array("public key",pubkey,[33,65]);switch(secp256k1.ecdsaVerify(sig,msg32,pubkey)){case 0:return true;case 3:return false;case 1:throw new Error(errors.SIG_PARSE);case 2:throw new Error(errors.PUBKEY_PARSE)}},ecdsaRecover(sig,recid,msg32,compressed=true,output){isUint8Array("signature",sig,64);assert$a(toTypeString(recid)==="Number"&&recid>=0&&recid<=3,"Expected recovery id to be a Number within interval [0, 3]");isUint8Array("message",msg32,32);isCompressed(compressed);output=getAssertedOutput(output,compressed?33:65);switch(secp256k1.ecdsaRecover(output,sig,recid,msg32)){case 0:return output;case 1:throw new Error(errors.SIG_PARSE);case 2:throw new Error(errors.RECOVER);case 3:throw new Error(errors.IMPOSSIBLE_CASE)}},ecdh(pubkey,seckey,options={},output){isUint8Array("public key",pubkey,[33,65]);isUint8Array("private key",seckey,32);assert$a(toTypeString(options)==="Object","Expected options to be an Object");if(options.data!==undefined)isUint8Array("options.data",options.data);if(options.hashfn!==undefined){assert$a(toTypeString(options.hashfn)==="Function","Expected options.hashfn to be a Function");if(options.xbuf!==undefined)isUint8Array("options.xbuf",options.xbuf,32);if(options.ybuf!==undefined)isUint8Array("options.ybuf",options.ybuf,32);isUint8Array("output",output)}else{output=getAssertedOutput(output,32)}switch(secp256k1.ecdh(output,pubkey,seckey,options.data,options.hashfn,options.xbuf,options.ybuf)){case 0:return output;case 1:throw new Error(errors.PUBKEY_PARSE);case 2:throw new Error(errors.ECDH)}}});var elliptic$2={};var name="elliptic";var version="6.5.4";var description="EC cryptography";var main="lib/elliptic.js";var files=["lib"];var scripts={lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"};var repository={type:"git",url:"git@github.com:indutny/elliptic"};var keywords=["EC","Elliptic","curve","Cryptography"];var author="Fedor Indutny <fedor@indutny.com>";var license="MIT";var bugs={url:"https://github.com/indutny/elliptic/issues"};var homepage="https://github.com/indutny/elliptic";var devDependencies={brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"};var dependencies={"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"};var require$$0={name:name,version:version,description:description,main:main,files:files,scripts:scripts,repository:repository,keywords:keywords,author:author,license:license,bugs:bugs,homepage:homepage,devDependencies:devDependencies,dependencies:dependencies};var utils$c={};var utils$b={};(function(exports){var utils=exports;function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg!=="string"){for(var i=0;i<msg.length;i++)res[i]=msg[i]|0;return res}if(enc==="hex"){msg=msg.replace(/[^a-z0-9]+/gi,"");if(msg.length%2!==0)msg="0"+msg;for(var i=0;i<msg.length;i+=2)res.push(parseInt(msg[i]+msg[i+1],16))}else{for(var i=0;i<msg.length;i++){var c=msg.charCodeAt(i);var hi=c>>8;var lo=c&255;if(hi)res.push(hi,lo);else res.push(lo)}}return res}utils.toArray=toArray;function zero2(word){if(word.length===1)return"0"+word;else return word}utils.zero2=zero2;function toHex(msg){var res="";for(var i=0;i<msg.length;i++)res+=zero2(msg[i].toString(16));return res}utils.toHex=toHex;utils.encode=function encode(arr,enc){if(enc==="hex")return toHex(arr);else return arr}})(utils$b);(function(exports){var utils=exports;var BN=bn.exports;var minAssert=minimalisticAssert;var minUtils=utils$b;utils.assert=minAssert;utils.toArray=minUtils.toArray;utils.zero2=minUtils.zero2;utils.toHex=minUtils.toHex;utils.encode=minUtils.encode;function getNAF(num,w,bits){var naf=new Array(Math.max(num.bitLength(),bits)+1);naf.fill(0);var ws=1<<w+1;var k=num.clone();for(var i=0;i<naf.length;i++){var z;var mod=k.andln(ws-1);if(k.isOdd()){if(mod>(ws>>1)-1)z=(ws>>1)-mod;else z=mod;k.isubn(z)}else{z=0}naf[i]=z;k.iushrn(1)}return naf}utils.getNAF=getNAF;function getJSF(k1,k2){var jsf=[[],[]];k1=k1.clone();k2=k2.clone();var d1=0;var d2=0;var m8;while(k1.cmpn(-d1)>0||k2.cmpn(-d2)>0){var m14=k1.andln(3)+d1&3;var m24=k2.andln(3)+d2&3;if(m14===3)m14=-1;if(m24===3)m24=-1;var u1;if((m14&1)===0){u1=0}else{m8=k1.andln(7)+d1&7;if((m8===3||m8===5)&&m24===2)u1=-m14;else u1=m14}jsf[0].push(u1);var u2;if((m24&1)===0){u2=0}else{m8=k2.andln(7)+d2&7;if((m8===3||m8===5)&&m14===2)u2=-m24;else u2=m24}jsf[1].push(u2);if(2*d1===u1+1)d1=1-d1;if(2*d2===u2+1)d2=1-d2;k1.iushrn(1);k2.iushrn(1)}return jsf}utils.getJSF=getJSF;function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function cachedProperty(){return this[key]!==undefined?this[key]:this[key]=computer.call(this)}}utils.cachedProperty=cachedProperty;function parseBytes(bytes){return typeof bytes==="string"?utils.toArray(bytes,"hex"):bytes}utils.parseBytes=parseBytes;function intFromLE(bytes){return new BN(bytes,"hex","le")}utils.intFromLE=intFromLE})(utils$c);var brorand={exports:{}};var r;brorand.exports=function rand(len){if(!r)r=new Rand(null);return r.generate(len)};function Rand(rand){this.rand=rand}brorand.exports.Rand=Rand;Rand.prototype.generate=function generate(len){return this._rand(len)};Rand.prototype._rand=function _rand(n){if(this.rand.getBytes)return this.rand.getBytes(n);var res=new Uint8Array(n);for(var i=0;i<res.length;i++)res[i]=this.rand.getByte();return res};if(typeof self==="object"){if(self.crypto&&self.crypto.getRandomValues){Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);self.crypto.getRandomValues(arr);return arr}}else if(self.msCrypto&&self.msCrypto.getRandomValues){Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);self.msCrypto.getRandomValues(arr);return arr}}else if(typeof window==="object"){Rand.prototype._rand=function(){throw new Error("Not implemented yet")}}}else{try{var crypto$1=require("crypto");if(typeof crypto$1.randomBytes!=="function")throw new Error("Not supported");Rand.prototype._rand=function _rand(n){return crypto$1.randomBytes(n)}}catch(e){}}var curve={};var BN$8=bn.exports;var utils$a=utils$c;var getNAF=utils$a.getNAF;var getJSF=utils$a.getJSF;var assert$9=utils$a.assert;function BaseCurve(type,conf){this.type=type;this.p=new BN$8(conf.p,16);this.red=conf.prime?BN$8.red(conf.prime):BN$8.mont(this.p);this.zero=new BN$8(0).toRed(this.red);this.one=new BN$8(1).toRed(this.red);this.two=new BN$8(2).toRed(this.red);this.n=conf.n&&new BN$8(conf.n,16);this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed);this._wnafT1=new Array(4);this._wnafT2=new Array(4);this._wnafT3=new Array(4);this._wnafT4=new Array(4);this._bitLength=this.n?this.n.bitLength():0;var adjustCount=this.n&&this.p.div(this.n);if(!adjustCount||adjustCount.cmpn(100)>0){this.redN=null}else{this._maxwellTrick=true;this.redN=this.n.toRed(this.red)}}var base=BaseCurve;BaseCurve.prototype.point=function point(){throw new Error("Not implemented")};BaseCurve.prototype.validate=function validate(){throw new Error("Not implemented")};BaseCurve.prototype._fixedNafMul=function _fixedNafMul(p,k){assert$9(p.precomputed);var doubles=p._getDoubles();var naf=getNAF(k,1,this._bitLength);var I=(1<<doubles.step+1)-(doubles.step%2===0?2:1);I/=3;var repr=[];var j;var nafW;for(j=0;j<naf.length;j+=doubles.step){nafW=0;for(var l=j+doubles.step-1;l>=j;l--)nafW=(nafW<<1)+naf[l];repr.push(nafW)}var a=this.jpoint(null,null,null);var b=this.jpoint(null,null,null);for(var i=I;i>0;i--){for(j=0;j<repr.length;j++){nafW=repr[j];if(nafW===i)b=b.mixedAdd(doubles.points[j]);else if(nafW===-i)b=b.mixedAdd(doubles.points[j].neg())}a=a.add(b)}return a.toP()};BaseCurve.prototype._wnafMul=function _wnafMul(p,k){var w=4;var nafPoints=p._getNAFPoints(w);w=nafPoints.wnd;var wnd=nafPoints.points;var naf=getNAF(k,w,this._bitLength);var acc=this.jpoint(null,null,null);for(var i=naf.length-1;i>=0;i--){for(var l=0;i>=0&&naf[i]===0;i--)l++;if(i>=0)l++;acc=acc.dblp(l);if(i<0)break;var z=naf[i];assert$9(z!==0);if(p.type==="affine"){if(z>0)acc=acc.mixedAdd(wnd[z-1>>1]);else acc=acc.mixedAdd(wnd[-z-1>>1].neg())}else{if(z>0)acc=acc.add(wnd[z-1>>1]);else acc=acc.add(wnd[-z-1>>1].neg())}}return p.type==="affine"?acc.toP():acc};BaseCurve.prototype._wnafMulAdd=function _wnafMulAdd(defW,points,coeffs,len,jacobianResult){var wndWidth=this._wnafT1;var wnd=this._wnafT2;var naf=this._wnafT3;var max=0;var i;var j;var p;for(i=0;i<len;i++){p=points[i];var nafPoints=p._getNAFPoints(defW);wndWidth[i]=nafPoints.wnd;wnd[i]=nafPoints.points}for(i=len-1;i>=1;i-=2){var a=i-1;var b=i;if(wndWidth[a]!==1||wndWidth[b]!==1){naf[a]=getNAF(coeffs[a],wndWidth[a],this._bitLength);naf[b]=getNAF(coeffs[b],wndWidth[b],this._bitLength);max=Math.max(naf[a].length,max);max=Math.max(naf[b].length,max);continue}var comb=[points[a],null,null,points[b]];if(points[a].y.cmp(points[b].y)===0){comb[1]=points[a].add(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}else if(points[a].y.cmp(points[b].y.redNeg())===0){comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].add(points[b].neg())}else{comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}var index=[-3,-1,-5,-7,0,7,5,1,3];var jsf=getJSF(coeffs[a],coeffs[b]);max=Math.max(jsf[0].length,max);naf[a]=new Array(max);naf[b]=new Array(max);for(j=0;j<max;j++){var ja=jsf[0][j]|0;var jb=jsf[1][j]|0;naf[a][j]=index[(ja+1)*3+(jb+1)];naf[b][j]=0;wnd[a]=comb}}var acc=this.jpoint(null,null,null);var tmp=this._wnafT4;for(i=max;i>=0;i--){var k=0;while(i>=0){var zero=true;for(j=0;j<len;j++){tmp[j]=naf[j][i]|0;if(tmp[j]!==0)zero=false}if(!zero)break;k++;i--}if(i>=0)k++;acc=acc.dblp(k);if(i<0)break;for(j=0;j<len;j++){var z=tmp[j];if(z===0)continue;else if(z>0)p=wnd[j][z-1>>1];else if(z<0)p=wnd[j][-z-1>>1].neg();if(p.type==="affine")acc=acc.mixedAdd(p);else acc=acc.add(p)}}for(i=0;i<len;i++)wnd[i]=null;if(jacobianResult)return acc;else return acc.toP()};function BasePoint(curve,type){this.curve=curve;this.type=type;this.precomputed=null}BaseCurve.BasePoint=BasePoint;BasePoint.prototype.eq=function eq(){throw new Error("Not implemented")};BasePoint.prototype.validate=function validate(){return this.curve.validate(this)};BaseCurve.prototype.decodePoint=function decodePoint(bytes,enc){bytes=utils$a.toArray(bytes,enc);var len=this.p.byteLength();if((bytes[0]===4||bytes[0]===6||bytes[0]===7)&&bytes.length-1===2*len){if(bytes[0]===6)assert$9(bytes[bytes.length-1]%2===0);else if(bytes[0]===7)assert$9(bytes[bytes.length-1]%2===1);var res=this.point(bytes.slice(1,1+len),bytes.slice(1+len,1+2*len));return res}else if((bytes[0]===2||bytes[0]===3)&&bytes.length-1===len){return this.pointFromX(bytes.slice(1,1+len),bytes[0]===3)}throw new Error("Unknown point format")};BasePoint.prototype.encodeCompressed=function encodeCompressed(enc){return this.encode(enc,true)};BasePoint.prototype._encode=function _encode(compact){var len=this.curve.p.byteLength();var x=this.getX().toArray("be",len);if(compact)return[this.getY().isEven()?2:3].concat(x);return[4].concat(x,this.getY().toArray("be",len))};BasePoint.prototype.encode=function encode(enc,compact){return utils$a.encode(this._encode(compact),enc)};BasePoint.prototype.precompute=function precompute(power){if(this.precomputed)return this;var precomputed={doubles:null,naf:null,beta:null};precomputed.naf=this._getNAFPoints(8);precomputed.doubles=this._getDoubles(4,power);precomputed.beta=this._getBeta();this.precomputed=precomputed;return this};BasePoint.prototype._hasDoubles=function _hasDoubles(k){if(!this.precomputed)return false;var doubles=this.precomputed.doubles;if(!doubles)return false;return doubles.points.length>=Math.ceil((k.bitLength()+1)/doubles.step)};BasePoint.prototype._getDoubles=function _getDoubles(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;var doubles=[this];var acc=this;for(var i=0;i<power;i+=step){for(var j=0;j<step;j++)acc=acc.dbl();doubles.push(acc)}return{step:step,points:doubles}};BasePoint.prototype._getNAFPoints=function _getNAFPoints(wnd){if(this.precomputed&&this.precomputed.naf)return this.precomputed.naf;var res=[this];var max=(1<<wnd)-1;var dbl=max===1?null:this.dbl();for(var i=1;i<max;i++)res[i]=res[i-1].add(dbl);return{wnd:wnd,points:res}};BasePoint.prototype._getBeta=function _getBeta(){return null};BasePoint.prototype.dblp=function dblp(k){var r=this;for(var i=0;i<k;i++)r=r.dbl();return r};var inherits_browser={exports:{}};if(typeof Object.create==="function"){inherits_browser.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}}else{inherits_browser.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}var utils$9=utils$c;var BN$7=bn.exports;var inherits$2=inherits_browser.exports;var Base$2=base;var assert$8=utils$9.assert;function ShortCurve(conf){Base$2.call(this,"short",conf);this.a=new BN$7(conf.a,16).toRed(this.red);this.b=new BN$7(conf.b,16).toRed(this.red);this.tinv=this.two.redInvm();this.zeroA=this.a.fromRed().cmpn(0)===0;this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0;this.endo=this._getEndomorphism(conf);this._endoWnafT1=new Array(4);this._endoWnafT2=new Array(4)}inherits$2(ShortCurve,Base$2);var short=ShortCurve;ShortCurve.prototype._getEndomorphism=function _getEndomorphism(conf){if(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)return;var beta;var lambda;if(conf.beta){beta=new BN$7(conf.beta,16).toRed(this.red)}else{var betas=this._getEndoRoots(this.p);beta=betas[0].cmp(betas[1])<0?betas[0]:betas[1];beta=beta.toRed(this.red)}if(conf.lambda){lambda=new BN$7(conf.lambda,16)}else{var lambdas=this._getEndoRoots(this.n);if(this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta))===0){lambda=lambdas[0]}else{lambda=lambdas[1];assert$8(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta))===0)}}var basis;if(conf.basis){basis=conf.basis.map((function(vec){return{a:new BN$7(vec.a,16),b:new BN$7(vec.b,16)}}))}else{basis=this._getEndoBasis(lambda)}return{beta:beta,lambda:lambda,basis:basis}};ShortCurve.prototype._getEndoRoots=function _getEndoRoots(num){var red=num===this.p?this.red:BN$7.mont(num);var tinv=new BN$7(2).toRed(red).redInvm();var ntinv=tinv.redNeg();var s=new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv);var l1=ntinv.redAdd(s).fromRed();var l2=ntinv.redSub(s).fromRed();return[l1,l2]};ShortCurve.prototype._getEndoBasis=function _getEndoBasis(lambda){var aprxSqrt=this.n.ushrn(Math.floor(this.n.bitLength()/2));var u=lambda;var v=this.n.clone();var x1=new BN$7(1);var y1=new BN$7(0);var x2=new BN$7(0);var y2=new BN$7(1);var a0;var b0;var a1;var b1;var a2;var b2;var prevR;var i=0;var r;var x;while(u.cmpn(0)!==0){var q=v.div(u);r=v.sub(q.mul(u));x=x2.sub(q.mul(x1));var y=y2.sub(q.mul(y1));if(!a1&&r.cmp(aprxSqrt)<0){a0=prevR.neg();b0=x1;a1=r.neg();b1=x}else if(a1&&++i===2){break}prevR=r;v=u;u=r;x2=x1;x1=x;y2=y1;y1=y}a2=r.neg();b2=x;var len1=a1.sqr().add(b1.sqr());var len2=a2.sqr().add(b2.sqr());if(len2.cmp(len1)>=0){a2=a0;b2=b0}if(a1.negative){a1=a1.neg();b1=b1.neg()}if(a2.negative){a2=a2.neg();b2=b2.neg()}return[{a:a1,b:b1},{a:a2,b:b2}]};ShortCurve.prototype._endoSplit=function _endoSplit(k){var basis=this.endo.basis;var v1=basis[0];var v2=basis[1];var c1=v2.b.mul(k).divRound(this.n);var c2=v1.b.neg().mul(k).divRound(this.n);var p1=c1.mul(v1.a);var p2=c2.mul(v2.a);var q1=c1.mul(v1.b);var q2=c2.mul(v2.b);var k1=k.sub(p1).sub(p2);var k2=q1.add(q2).neg();return{k1:k1,k2:k2}};ShortCurve.prototype.pointFromX=function pointFromX(x,odd){x=new BN$7(x,16);if(!x.red)x=x.toRed(this.red);var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);var y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error("invalid point");var isOdd=y.fromRed().isOdd();if(odd&&!isOdd||!odd&&isOdd)y=y.redNeg();return this.point(x,y)};ShortCurve.prototype.validate=function validate(point){if(point.inf)return true;var x=point.x;var y=point.y;var ax=this.a.redMul(x);var rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return y.redSqr().redISub(rhs).cmpn(0)===0};ShortCurve.prototype._endoWnafMulAdd=function _endoWnafMulAdd(points,coeffs,jacobianResult){var npoints=this._endoWnafT1;var ncoeffs=this._endoWnafT2;for(var i=0;i<points.length;i++){var split=this._endoSplit(coeffs[i]);var p=points[i];var beta=p._getBeta();if(split.k1.negative){split.k1.ineg();p=p.neg(true)}if(split.k2.negative){split.k2.ineg();beta=beta.neg(true)}npoints[i*2]=p;npoints[i*2+1]=beta;ncoeffs[i*2]=split.k1;ncoeffs[i*2+1]=split.k2}var res=this._wnafMulAdd(1,npoints,ncoeffs,i*2,jacobianResult);for(var j=0;j<i*2;j++){npoints[j]=null;ncoeffs[j]=null}return res};function Point$2(curve,x,y,isRed){Base$2.BasePoint.call(this,curve,"affine");if(x===null&&y===null){this.x=null;this.y=null;this.inf=true}else{this.x=new BN$7(x,16);this.y=new BN$7(y,16);if(isRed){this.x.forceRed(this.curve.red);this.y.forceRed(this.curve.red)}if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);this.inf=false}}inherits$2(Point$2,Base$2.BasePoint);ShortCurve.prototype.point=function point(x,y,isRed){return new Point$2(this,x,y,isRed)};ShortCurve.prototype.pointFromJSON=function pointFromJSON(obj,red){return Point$2.fromJSON(this,obj,red)};Point$2.prototype._getBeta=function _getBeta(){if(!this.curve.endo)return;var pre=this.precomputed;if(pre&&pre.beta)return pre.beta;var beta=this.curve.point(this.x.redMul(this.curve.endo.beta),this.y);if(pre){var curve=this.curve;var endoMul=function(p){return curve.point(p.x.redMul(curve.endo.beta),p.y)};pre.beta=beta;beta.precomputed={beta:null,naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(endoMul)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(endoMul)}}}return beta};Point$2.prototype.toJSON=function toJSON(){if(!this.precomputed)return[this.x,this.y];return[this.x,this.y,this.precomputed&&{doubles:this.precomputed.doubles&&{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf&&{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}]};Point$2.fromJSON=function fromJSON(curve,obj,red){if(typeof obj==="string")obj=JSON.parse(obj);var res=curve.point(obj[0],obj[1],red);if(!obj[2])return res;function obj2point(obj){return curve.point(obj[0],obj[1],red)}var pre=obj[2];res.precomputed={beta:null,doubles:pre.doubles&&{step:pre.doubles.step,points:[res].concat(pre.doubles.points.map(obj2point))},naf:pre.naf&&{wnd:pre.naf.wnd,points:[res].concat(pre.naf.points.map(obj2point))}};return res};Point$2.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+">"};Point$2.prototype.isInfinity=function isInfinity(){return this.inf};Point$2.prototype.add=function add(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(this.x.cmp(p.x)===0)return this.curve.point(null,null);var c=this.y.redSub(p.y);if(c.cmpn(0)!==0)c=c.redMul(this.x.redSub(p.x).redInvm());var nx=c.redSqr().redISub(this.x).redISub(p.x);var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point$2.prototype.dbl=function dbl(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(ys1.cmpn(0)===0)return this.curve.point(null,null);var a=this.curve.a;var x2=this.x.redSqr();var dyinv=ys1.redInvm();var c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);var nx=c.redSqr().redISub(this.x.redAdd(this.x));var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point$2.prototype.getX=function getX(){return this.x.fromRed()};Point$2.prototype.getY=function getY(){return this.y.fromRed()};Point$2.prototype.mul=function mul(k){k=new BN$7(k,16);if(this.isInfinity())return this;else if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else if(this.curve.endo)return this.curve._endoWnafMulAdd([this],[k]);else return this.curve._wnafMul(this,k)};Point$2.prototype.mulAdd=function mulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs);else return this.curve._wnafMulAdd(1,points,coeffs,2)};Point$2.prototype.jmulAdd=function jmulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs,true);else return this.curve._wnafMulAdd(1,points,coeffs,2,true)};Point$2.prototype.eq=function eq(p){return this===p||this.inf===p.inf&&(this.inf||this.x.cmp(p.x)===0&&this.y.cmp(p.y)===0)};Point$2.prototype.neg=function neg(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed;var negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res};Point$2.prototype.toJ=function toJ(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res};function JPoint(curve,x,y,z){Base$2.BasePoint.call(this,curve,"jacobian");if(x===null&&y===null&&z===null){this.x=this.curve.one;this.y=this.curve.one;this.z=new BN$7(0)}else{this.x=new BN$7(x,16);this.y=new BN$7(y,16);this.z=new BN$7(z,16)}if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);this.zOne=this.z===this.curve.one}inherits$2(JPoint,Base$2.BasePoint);ShortCurve.prototype.jpoint=function jpoint(x,y,z){return new JPoint(this,x,y,z)};JPoint.prototype.toP=function toP(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm();var zinv2=zinv.redSqr();var ax=this.x.redMul(zinv2);var ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)};JPoint.prototype.neg=function neg(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)};JPoint.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr();var z2=this.z.redSqr();var u1=this.x.redMul(pz2);var u2=p.x.redMul(z2);var s1=this.y.redMul(pz2.redMul(p.z));var s2=p.y.redMul(z2.redMul(this.z));var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.mixedAdd=function mixedAdd(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr();var u1=this.x;var u2=p.x.redMul(z2);var s1=this.y;var s2=p.y.redMul(z2).redMul(this.z);var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.dblp=function dblp(pow){if(pow===0)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();var i;if(this.curve.zeroA||this.curve.threeA){var r=this;for(i=0;i<pow;i++)r=r.dbl();return r}var a=this.curve.a;var tinv=this.curve.tinv;var jx=this.x;var jy=this.y;var jz=this.z;var jz4=jz.redSqr().redSqr();var jyd=jy.redAdd(jy);for(i=0;i<pow;i++){var jx2=jx.redSqr();var jyd2=jyd.redSqr();var jyd4=jyd2.redSqr();var c=jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));var t1=jx.redMul(jyd2);var nx=c.redSqr().redISub(t1.redAdd(t1));var t2=t1.redISub(nx);var dny=c.redMul(t2);dny=dny.redIAdd(dny).redISub(jyd4);var nz=jyd.redMul(jz);if(i+1<pow)jz4=jz4.redMul(jyd4);jx=nx;jz=nz;jyd=dny}return this.curve.jpoint(jx,jyd.redMul(tinv),jz)};JPoint.prototype.dbl=function dbl(){if(this.isInfinity())return this;if(this.curve.zeroA)return this._zeroDbl();else if(this.curve.threeA)return this._threeDbl();else return this._dbl()};JPoint.prototype._zeroDbl=function _zeroDbl(){var nx;var ny;var nz;if(this.zOne){var xx=this.x.redSqr();var yy=this.y.redSqr();var yyyy=yy.redSqr();var s=this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);s=s.redIAdd(s);var m=xx.redAdd(xx).redIAdd(xx);var t=m.redSqr().redISub(s).redISub(s);var yyyy8=yyyy.redIAdd(yyyy);yyyy8=yyyy8.redIAdd(yyyy8);yyyy8=yyyy8.redIAdd(yyyy8);nx=t;ny=m.redMul(s.redISub(t)).redISub(yyyy8);nz=this.y.redAdd(this.y)}else{var a=this.x.redSqr();var b=this.y.redSqr();var c=b.redSqr();var d=this.x.redAdd(b).redSqr().redISub(a).redISub(c);d=d.redIAdd(d);var e=a.redAdd(a).redIAdd(a);var f=e.redSqr();var c8=c.redIAdd(c);c8=c8.redIAdd(c8);c8=c8.redIAdd(c8);nx=f.redISub(d).redISub(d);ny=e.redMul(d.redISub(nx)).redISub(c8);nz=this.y.redMul(this.z);nz=nz.redIAdd(nz)}return this.curve.jpoint(nx,ny,nz)};JPoint.prototype._threeDbl=function _threeDbl(){var nx;var ny;var nz;if(this.zOne){var xx=this.x.redSqr();var yy=this.y.redSqr();var yyyy=yy.redSqr();var s=this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);s=s.redIAdd(s);var m=xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);var t=m.redSqr().redISub(s).redISub(s);nx=t;var yyyy8=yyyy.redIAdd(yyyy);yyyy8=yyyy8.redIAdd(yyyy8);yyyy8=yyyy8.redIAdd(yyyy8);ny=m.redMul(s.redISub(t)).redISub(yyyy8);nz=this.y.redAdd(this.y)}else{var delta=this.z.redSqr();var gamma=this.y.redSqr();var beta=this.x.redMul(gamma);var alpha=this.x.redSub(delta).redMul(this.x.redAdd(delta));alpha=alpha.redAdd(alpha).redIAdd(alpha);var beta4=beta.redIAdd(beta);beta4=beta4.redIAdd(beta4);var beta8=beta4.redAdd(beta4);nx=alpha.redSqr().redISub(beta8);nz=this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);var ggamma8=gamma.redSqr();ggamma8=ggamma8.redIAdd(ggamma8);ggamma8=ggamma8.redIAdd(ggamma8);ggamma8=ggamma8.redIAdd(ggamma8);ny=alpha.redMul(beta4.redISub(nx)).redISub(ggamma8)}return this.curve.jpoint(nx,ny,nz)};JPoint.prototype._dbl=function _dbl(){var a=this.curve.a;var jx=this.x;var jy=this.y;var jz=this.z;var jz4=jz.redSqr().redSqr();var jx2=jx.redSqr();var jy2=jy.redSqr();var c=jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));var jxd4=jx.redAdd(jx);jxd4=jxd4.redIAdd(jxd4);var t1=jxd4.redMul(jy2);var nx=c.redSqr().redISub(t1.redAdd(t1));var t2=t1.redISub(nx);var jyd8=jy2.redSqr();jyd8=jyd8.redIAdd(jyd8);jyd8=jyd8.redIAdd(jyd8);jyd8=jyd8.redIAdd(jyd8);var ny=c.redMul(t2).redISub(jyd8);var nz=jy.redAdd(jy).redMul(jz);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.trpl=function trpl(){if(!this.curve.zeroA)return this.dbl().add(this);var xx=this.x.redSqr();var yy=this.y.redSqr();var zz=this.z.redSqr();var yyyy=yy.redSqr();var m=xx.redAdd(xx).redIAdd(xx);var mm=m.redSqr();var e=this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);e=e.redIAdd(e);e=e.redAdd(e).redIAdd(e);e=e.redISub(mm);var ee=e.redSqr();var t=yyyy.redIAdd(yyyy);t=t.redIAdd(t);t=t.redIAdd(t);t=t.redIAdd(t);var u=m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);var yyu4=yy.redMul(u);yyu4=yyu4.redIAdd(yyu4);yyu4=yyu4.redIAdd(yyu4);var nx=this.x.redMul(ee).redISub(yyu4);nx=nx.redIAdd(nx);nx=nx.redIAdd(nx);var ny=this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));ny=ny.redIAdd(ny);ny=ny.redIAdd(ny);ny=ny.redIAdd(ny);var nz=this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.mul=function mul(k,kbase){k=new BN$7(k,kbase);return this.curve._wnafMul(this,k)};JPoint.prototype.eq=function eq(p){if(p.type==="affine")return this.eq(p.toJ());if(this===p)return true;var z2=this.z.redSqr();var pz2=p.z.redSqr();if(this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0)!==0)return false;var z3=z2.redMul(this.z);var pz3=pz2.redMul(p.z);return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0)===0};JPoint.prototype.eqXToP=function eqXToP(x){var zs=this.z.redSqr();var rx=x.toRed(this.curve.red).redMul(zs);if(this.x.cmp(rx)===0)return true;var xc=x.clone();var t=this.curve.redN.redMul(zs);for(;;){xc.iadd(this.curve.n);if(xc.cmp(this.curve.p)>=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}};JPoint.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC JPoint Infinity>";return"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"};JPoint.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0};var BN$6=bn.exports;var inherits$1=inherits_browser.exports;var Base$1=base;var utils$8=utils$c;function MontCurve(conf){Base$1.call(this,"mont",conf);this.a=new BN$6(conf.a,16).toRed(this.red);this.b=new BN$6(conf.b,16).toRed(this.red);this.i4=new BN$6(4).toRed(this.red).redInvm();this.two=new BN$6(2).toRed(this.red);this.a24=this.i4.redMul(this.a.redAdd(this.two))}inherits$1(MontCurve,Base$1);var mont=MontCurve;MontCurve.prototype.validate=function validate(point){var x=point.normalize().x;var x2=x.redSqr();var rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);var y=rhs.redSqrt();return y.redSqr().cmp(rhs)===0};function Point$1(curve,x,z){Base$1.BasePoint.call(this,curve,"projective");if(x===null&&z===null){this.x=this.curve.one;this.z=this.curve.zero}else{this.x=new BN$6(x,16);this.z=new BN$6(z,16);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red)}}inherits$1(Point$1,Base$1.BasePoint);MontCurve.prototype.decodePoint=function decodePoint(bytes,enc){return this.point(utils$8.toArray(bytes,enc),1)};MontCurve.prototype.point=function point(x,z){return new Point$1(this,x,z)};MontCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point$1.fromJSON(this,obj)};Point$1.prototype.precompute=function precompute(){};Point$1.prototype._encode=function _encode(){return this.getX().toArray("be",this.curve.p.byteLength())};Point$1.fromJSON=function fromJSON(curve,obj){return new Point$1(curve,obj[0],obj[1]||curve.one)};Point$1.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"};Point$1.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0};Point$1.prototype.dbl=function dbl(){var a=this.x.redAdd(this.z);var aa=a.redSqr();var b=this.x.redSub(this.z);var bb=b.redSqr();var c=aa.redSub(bb);var nx=aa.redMul(bb);var nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)};Point$1.prototype.add=function add(){throw new Error("Not supported on Montgomery curve")};Point$1.prototype.diffAdd=function diffAdd(p,diff){var a=this.x.redAdd(this.z);var b=this.x.redSub(this.z);var c=p.x.redAdd(p.z);var d=p.x.redSub(p.z);var da=d.redMul(a);var cb=c.redMul(b);var nx=diff.z.redMul(da.redAdd(cb).redSqr());var nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)};Point$1.prototype.mul=function mul(k){var t=k.clone();var a=this;var b=this.curve.point(null,null);var c=this;for(var bits=[];t.cmpn(0)!==0;t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--){if(bits[i]===0){a=a.diffAdd(b,c);b=b.dbl()}else{b=a.diffAdd(b,c);a=a.dbl()}}return b};Point$1.prototype.mulAdd=function mulAdd(){throw new Error("Not supported on Montgomery curve")};Point$1.prototype.jumlAdd=function jumlAdd(){throw new Error("Not supported on Montgomery curve")};Point$1.prototype.eq=function eq(other){return this.getX().cmp(other.getX())===0};Point$1.prototype.normalize=function normalize(){this.x=this.x.redMul(this.z.redInvm());this.z=this.curve.one;return this};Point$1.prototype.getX=function getX(){this.normalize();return this.x.fromRed()};var utils$7=utils$c;var BN$5=bn.exports;var inherits=inherits_browser.exports;var Base=base;var assert$7=utils$7.assert;function EdwardsCurve(conf){this.twisted=(conf.a|0)!==1;this.mOneA=this.twisted&&(conf.a|0)===-1;this.extended=this.mOneA;Base.call(this,"edwards",conf);this.a=new BN$5(conf.a,16).umod(this.red.m);this.a=this.a.toRed(this.red);this.c=new BN$5(conf.c,16).toRed(this.red);this.c2=this.c.redSqr();this.d=new BN$5(conf.d,16).toRed(this.red);this.dd=this.d.redAdd(this.d);assert$7(!this.twisted||this.c.fromRed().cmpn(1)===0);this.oneC=(conf.c|0)===1}inherits(EdwardsCurve,Base);var edwards=EdwardsCurve;EdwardsCurve.prototype._mulA=function _mulA(num){if(this.mOneA)return num.redNeg();else return this.a.redMul(num)};EdwardsCurve.prototype._mulC=function _mulC(num){if(this.oneC)return num;else return this.c.redMul(num)};EdwardsCurve.prototype.jpoint=function jpoint(x,y,z,t){return this.point(x,y,z,t)};EdwardsCurve.prototype.pointFromX=function pointFromX(x,odd){x=new BN$5(x,16);if(!x.red)x=x.toRed(this.red);var x2=x.redSqr();var rhs=this.c2.redSub(this.a.redMul(x2));var lhs=this.one.redSub(this.c2.redMul(this.d).redMul(x2));var y2=rhs.redMul(lhs.redInvm());var y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error("invalid point");var isOdd=y.fromRed().isOdd();if(odd&&!isOdd||!odd&&isOdd)y=y.redNeg();return this.point(x,y)};EdwardsCurve.prototype.pointFromY=function pointFromY(y,odd){y=new BN$5(y,16);if(!y.red)y=y.toRed(this.red);var y2=y.redSqr();var lhs=y2.redSub(this.c2);var rhs=y2.redMul(this.d).redMul(this.c2).redSub(this.a);var x2=lhs.redMul(rhs.redInvm());if(x2.cmp(this.zero)===0){if(odd)throw new Error("invalid point");else return this.point(this.zero,y)}var x=x2.redSqrt();if(x.redSqr().redSub(x2).cmp(this.zero)!==0)throw new Error("invalid point");if(x.fromRed().isOdd()!==odd)x=x.redNeg();return this.point(x,y)};EdwardsCurve.prototype.validate=function validate(point){if(point.isInfinity())return true;point.normalize();var x2=point.x.redSqr();var y2=point.y.redSqr();var lhs=x2.redMul(this.a).redAdd(y2);var rhs=this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));return lhs.cmp(rhs)===0};function Point(curve,x,y,z,t){Base.BasePoint.call(this,curve,"projective");if(x===null&&y===null&&z===null){this.x=this.curve.zero;this.y=this.curve.one;this.z=this.curve.one;this.t=this.curve.zero;this.zOne=true}else{this.x=new BN$5(x,16);this.y=new BN$5(y,16);this.z=z?new BN$5(z,16):this.curve.one;this.t=t&&new BN$5(t,16);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);if(this.t&&!this.t.red)this.t=this.t.toRed(this.curve.red);this.zOne=this.z===this.curve.one;if(this.curve.extended&&!this.t){this.t=this.x.redMul(this.y);if(!this.zOne)this.t=this.t.redMul(this.z.redInvm())}}}inherits(Point,Base.BasePoint);EdwardsCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point.fromJSON(this,obj)};EdwardsCurve.prototype.point=function point(x,y,z,t){return new Point(this,x,y,z,t)};Point.fromJSON=function fromJSON(curve,obj){return new Point(curve,obj[0],obj[1],obj[2])};Point.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"};Point.prototype.isInfinity=function isInfinity(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)};Point.prototype._extDbl=function _extDbl(){var a=this.x.redSqr();var b=this.y.redSqr();var c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a);var e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);var g=d.redAdd(b);var f=g.redSub(c);var h=d.redSub(b);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projDbl=function _projDbl(){var b=this.x.redAdd(this.y).redSqr();var c=this.x.redSqr();var d=this.y.redSqr();var nx;var ny;var nz;var e;var h;var j;if(this.curve.twisted){e=this.curve._mulA(c);var f=e.redAdd(d);if(this.zOne){nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));ny=f.redMul(e.redSub(d));nz=f.redSqr().redSub(f).redSub(f)}else{h=this.z.redSqr();j=f.redSub(h).redISub(h);nx=b.redSub(c).redISub(d).redMul(j);ny=f.redMul(e.redSub(d));nz=f.redMul(j)}}else{e=c.redAdd(d);h=this.curve._mulC(this.z).redSqr();j=e.redSub(h).redSub(h);nx=this.curve._mulC(b.redISub(e)).redMul(j);ny=this.curve._mulC(e).redMul(c.redISub(d));nz=e.redMul(j)}return this.curve.point(nx,ny,nz)};Point.prototype.dbl=function dbl(){if(this.isInfinity())return this;if(this.curve.extended)return this._extDbl();else return this._projDbl()};Point.prototype._extAdd=function _extAdd(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x));var b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));var c=this.t.redMul(this.curve.dd).redMul(p.t);var d=this.z.redMul(p.z.redAdd(p.z));var e=b.redSub(a);var f=d.redSub(c);var g=d.redAdd(c);var h=b.redAdd(a);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projAdd=function _projAdd(p){var a=this.z.redMul(p.z);var b=a.redSqr();var c=this.x.redMul(p.x);var d=this.y.redMul(p.y);var e=this.curve.d.redMul(c).redMul(d);var f=b.redSub(e);var g=b.redAdd(e);var tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);var nx=a.redMul(f).redMul(tmp);var ny;var nz;if(this.curve.twisted){ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));nz=f.redMul(g)}else{ny=a.redMul(g).redMul(d.redSub(c));nz=this.curve._mulC(f).redMul(g)}return this.curve.point(nx,ny,nz)};Point.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;if(this.curve.extended)return this._extAdd(p);else return this._projAdd(p)};Point.prototype.mul=function mul(k){if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else return this.curve._wnafMul(this,k)};Point.prototype.mulAdd=function mulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,false)};Point.prototype.jmulAdd=function jmulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,true)};Point.prototype.normalize=function normalize(){if(this.zOne)return this;var zi=this.z.redInvm();this.x=this.x.redMul(zi);this.y=this.y.redMul(zi);if(this.t)this.t=this.t.redMul(zi);this.z=this.curve.one;this.zOne=true;return this};Point.prototype.neg=function neg(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())};Point.prototype.getX=function getX(){this.normalize();return this.x.fromRed()};Point.prototype.getY=function getY(){this.normalize();return this.y.fromRed()};Point.prototype.eq=function eq(other){return this===other||this.getX().cmp(other.getX())===0&&this.getY().cmp(other.getY())===0};Point.prototype.eqXToP=function eqXToP(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(rx)===0)return true;var xc=x.clone();var t=this.curve.redN.redMul(this.z);for(;;){xc.iadd(this.curve.n);if(xc.cmp(this.curve.p)>=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}};Point.prototype.toP=Point.prototype.normalize;Point.prototype.mixedAdd=Point.prototype.add;(function(exports){var curve=exports;curve.base=base;curve.short=short;curve.mont=mont;curve.edwards=edwards})(curve);var curves$2={};(function(exports){var curves=exports;var hash=hash$3;var curve$1=curve;var utils=utils$c;var assert=utils.assert;function PresetCurve(options){if(options.type==="short")this.curve=new curve$1.short(options);else if(options.type==="edwards")this.curve=new curve$1.edwards(options);else this.curve=new curve$1.mont(options);this.g=this.curve.g;this.n=this.curve.n;this.hash=options.hash;assert(this.g.validate(),"Invalid curve");assert(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}curves.PresetCurve=PresetCurve;function defineCurve(name,options){Object.defineProperty(curves,name,{configurable:true,enumerable:true,get:function(){var curve=new PresetCurve(options);Object.defineProperty(curves,name,{configurable:true,enumerable:true,value:curve});return curve}})}defineCurve("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:hash.sha256,gRed:false,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]});defineCurve("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:hash.sha256,gRed:false,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]});defineCurve("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:hash.sha256,gRed:false,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]});defineCurve("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f "+"5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 "+"f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:hash.sha384,gRed:false,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 "+"5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 "+"0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]});defineCurve("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b "+"99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd "+"3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 "+"f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:hash.sha512,gRed:false,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 "+"053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 "+"a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 "+"579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 "+"3fad0761 353c7086 a272c240 88be9476 9fd16650"]});defineCurve("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["9"]});defineCurve("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var pre;try{pre=require("./precomputed/secp256k1")}catch(e){pre=undefined}defineCurve("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:hash.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:false,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",pre]})})(curves$2);var hash$1=hash$3;var utils$6=utils$b;var assert$6=minimalisticAssert;function HmacDRBG$1(options){if(!(this instanceof HmacDRBG$1))return new HmacDRBG$1(options);this.hash=options.hash;this.predResist=!!options.predResist;this.outLen=this.hash.outSize;this.minEntropy=options.minEntropy||this.hash.hmacStrength;this._reseed=null;this.reseedInterval=null;this.K=null;this.V=null;var entropy=utils$6.toArray(options.entropy,options.entropyEnc||"hex");var nonce=utils$6.toArray(options.nonce,options.nonceEnc||"hex");var pers=utils$6.toArray(options.pers,options.persEnc||"hex");assert$6(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._init(entropy,nonce,pers)}var hmacDrbg=HmacDRBG$1;HmacDRBG$1.prototype._init=function init(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8);this.V=new Array(this.outLen/8);for(var i=0;i<this.V.length;i++){this.K[i]=0;this.V[i]=1}this._update(seed);this._reseed=1;this.reseedInterval=281474976710656};HmacDRBG$1.prototype._hmac=function hmac(){return new hash$1.hmac(this.hash,this.K)};HmacDRBG$1.prototype._update=function update(seed){var kmac=this._hmac().update(this.V).update([0]);if(seed)kmac=kmac.update(seed);this.K=kmac.digest();this.V=this._hmac().update(this.V).digest();if(!seed)return;this.K=this._hmac().update(this.V).update([1]).update(seed).digest();this.V=this._hmac().update(this.V).digest()};HmacDRBG$1.prototype.reseed=function reseed(entropy,entropyEnc,add,addEnc){if(typeof entropyEnc!=="string"){addEnc=add;add=entropyEnc;entropyEnc=null}entropy=utils$6.toArray(entropy,entropyEnc);add=utils$6.toArray(add,addEnc);assert$6(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._update(entropy.concat(add||[]));this._reseed=1};HmacDRBG$1.prototype.generate=function generate(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");if(typeof enc!=="string"){addEnc=add;add=enc;enc=null}if(add){add=utils$6.toArray(add,addEnc||"hex");this._update(add)}var temp=[];while(temp.length<len){this.V=this._hmac().update(this.V).digest();temp=temp.concat(this.V)}var res=temp.slice(0,len);this._update(add);this._reseed++;return utils$6.encode(res,enc)};var BN$4=bn.exports;var utils$5=utils$c;var assert$5=utils$5.assert;function KeyPair$3(ec,options){this.ec=ec;this.priv=null;this.pub=null;if(options.priv)this._importPrivate(options.priv,options.privEnc);if(options.pub)this._importPublic(options.pub,options.pubEnc)}var key$1=KeyPair$3;KeyPair$3.fromPublic=function fromPublic(ec,pub,enc){if(pub instanceof KeyPair$3)return pub;return new KeyPair$3(ec,{pub:pub,pubEnc:enc})};KeyPair$3.fromPrivate=function fromPrivate(ec,priv,enc){if(priv instanceof KeyPair$3)return priv;return new KeyPair$3(ec,{priv:priv,privEnc:enc})};KeyPair$3.prototype.validate=function validate(){var pub=this.getPublic();if(pub.isInfinity())return{result:false,reason:"Invalid public key"};if(!pub.validate())return{result:false,reason:"Public key is not a point"};if(!pub.mul(this.ec.curve.n).isInfinity())return{result:false,reason:"Public key * N != O"};return{result:true,reason:null}};KeyPair$3.prototype.getPublic=function getPublic(compact,enc){if(typeof compact==="string"){enc=compact;compact=null}if(!this.pub)this.pub=this.ec.g.mul(this.priv);if(!enc)return this.pub;return this.pub.encode(enc,compact)};KeyPair$3.prototype.getPrivate=function getPrivate(enc){if(enc==="hex")return this.priv.toString(16,2);else return this.priv};KeyPair$3.prototype._importPrivate=function _importPrivate(key,enc){this.priv=new BN$4(key,enc||16);this.priv=this.priv.umod(this.ec.curve.n)};KeyPair$3.prototype._importPublic=function _importPublic(key,enc){if(key.x||key.y){if(this.ec.curve.type==="mont"){assert$5(key.x,"Need x coordinate")}else if(this.ec.curve.type==="short"||this.ec.curve.type==="edwards"){assert$5(key.x&&key.y,"Need both x and y coordinate")}this.pub=this.ec.curve.point(key.x,key.y);return}this.pub=this.ec.curve.decodePoint(key,enc)};KeyPair$3.prototype.derive=function derive(pub){if(!pub.validate()){assert$5(pub.validate(),"public point not validated")}return pub.mul(this.priv).getX()};KeyPair$3.prototype.sign=function sign(msg,enc,options){return this.ec.sign(msg,this,enc,options)};KeyPair$3.prototype.verify=function verify(msg,signature){return this.ec.verify(msg,signature,this)};KeyPair$3.prototype.inspect=function inspect(){return"<Key priv: "+(this.priv&&this.priv.toString(16,2))+" pub: "+(this.pub&&this.pub.inspect())+" >"};var BN$3=bn.exports;var utils$4=utils$c;var assert$4=utils$4.assert;function Signature$3(options,enc){if(options instanceof Signature$3)return options;if(this._importDER(options,enc))return;assert$4(options.r&&options.s,"Signature without r or s");this.r=new BN$3(options.r,16);this.s=new BN$3(options.s,16);if(options.recoveryParam===undefined)this.recoveryParam=null;else this.recoveryParam=options.recoveryParam}var signature$1=Signature$3;function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(initial&128)){return initial}var octetLen=initial&15;if(octetLen===0||octetLen>4){return false}var val=0;for(var i=0,off=p.place;i<octetLen;i++,off++){val<<=8;val|=buf[off];val>>>=0}if(val<=127){return false}p.place=off;return val}function rmPadding(buf){var i=0;var len=buf.length-1;while(!buf[i]&&!(buf[i+1]&128)&&i<len){i++}if(i===0){return buf}return buf.slice(i)}Signature$3.prototype._importDER=function _importDER(data,enc){data=utils$4.toArray(data,enc);var p=new Position;if(data[p.place++]!==48){return false}var len=getLength(data,p);if(len===false){return false}if(len+p.place!==data.length){return false}if(data[p.place++]!==2){return false}var rlen=getLength(data,p);if(rlen===false){return false}var r=data.slice(p.place,rlen+p.place);p.place+=rlen;if(data[p.place++]!==2){return false}var slen=getLength(data,p);if(slen===false){return false}if(data.length!==slen+p.place){return false}var s=data.slice(p.place,slen+p.place);if(r[0]===0){if(r[1]&128){r=r.slice(1)}else{return false}}if(s[0]===0){if(s[1]&128){s=s.slice(1)}else{return false}}this.r=new BN$3(r);this.s=new BN$3(s);this.recoveryParam=null;return true};function constructLength(arr,len){if(len<128){arr.push(len);return}var octets=1+(Math.log(len)/Math.LN2>>>3);arr.push(octets|128);while(--octets){arr.push(len>>>(octets<<3)&255)}arr.push(len)}Signature$3.prototype.toDER=function toDER(enc){var r=this.r.toArray();var s=this.s.toArray();if(r[0]&128)r=[0].concat(r);if(s[0]&128)s=[0].concat(s);r=rmPadding(r);s=rmPadding(s);while(!s[0]&&!(s[1]&128)){s=s.slice(1)}var arr=[2];constructLength(arr,r.length);arr=arr.concat(r);arr.push(2);constructLength(arr,s.length);var backHalf=arr.concat(s);var res=[48];constructLength(res,backHalf.length);res=res.concat(backHalf);return utils$4.encode(res,enc)};var BN$2=bn.exports;var HmacDRBG=hmacDrbg;var utils$3=utils$c;var curves$1=curves$2;var rand=brorand.exports;var assert$3=utils$3.assert;var KeyPair$2=key$1;var Signature$2=signature$1;function EC$1(options){if(!(this instanceof EC$1))return new EC$1(options);if(typeof options==="string"){assert$3(Object.prototype.hasOwnProperty.call(curves$1,options),"Unknown curve "+options);options=curves$1[options]}if(options instanceof curves$1.PresetCurve)options={curve:options};this.curve=options.curve.curve;this.n=this.curve.n;this.nh=this.n.ushrn(1);this.g=this.curve.g;this.g=options.curve.g;this.g.precompute(options.curve.n.bitLength()+1);this.hash=options.hash||options.curve.hash}var ec$1=EC$1;EC$1.prototype.keyPair=function keyPair(options){return new KeyPair$2(this,options)};EC$1.prototype.keyFromPrivate=function keyFromPrivate(priv,enc){return KeyPair$2.fromPrivate(this,priv,enc)};EC$1.prototype.keyFromPublic=function keyFromPublic(pub,enc){return KeyPair$2.fromPublic(this,pub,enc)};EC$1.prototype.genKeyPair=function genKeyPair(options){if(!options)options={};var drbg=new HmacDRBG({hash:this.hash,pers:options.pers,persEnc:options.persEnc||"utf8",entropy:options.entropy||rand(this.hash.hmacStrength),entropyEnc:options.entropy&&options.entropyEnc||"utf8",nonce:this.n.toArray()});var bytes=this.n.byteLength();var ns2=this.n.sub(new BN$2(2));for(;;){var priv=new BN$2(drbg.generate(bytes));if(priv.cmp(ns2)>0)continue;priv.iaddn(1);return this.keyFromPrivate(priv)}};EC$1.prototype._truncateToN=function _truncateToN(msg,truncOnly){var delta=msg.byteLength()*8-this.n.bitLength();if(delta>0)msg=msg.ushrn(delta);if(!truncOnly&&msg.cmp(this.n)>=0)return msg.sub(this.n);else return msg};EC$1.prototype.sign=function sign(msg,key,enc,options){if(typeof enc==="object"){options=enc;enc=null}if(!options)options={};key=this.keyFromPrivate(key,enc);msg=this._truncateToN(new BN$2(msg,16));var bytes=this.n.byteLength();var bkey=key.getPrivate().toArray("be",bytes);var nonce=msg.toArray("be",bytes);var drbg=new HmacDRBG({hash:this.hash,entropy:bkey,nonce:nonce,pers:options.pers,persEnc:options.persEnc||"utf8"});var ns1=this.n.sub(new BN$2(1));for(var iter=0;;iter++){var k=options.k?options.k(iter):new BN$2(drbg.generate(this.n.byteLength()));k=this._truncateToN(k,true);if(k.cmpn(1)<=0||k.cmp(ns1)>=0)continue;var kp=this.g.mul(k);if(kp.isInfinity())continue;var kpX=kp.getX();var r=kpX.umod(this.n);if(r.cmpn(0)===0)continue;var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));s=s.umod(this.n);if(s.cmpn(0)===0)continue;var recoveryParam=(kp.getY().isOdd()?1:0)|(kpX.cmp(r)!==0?2:0);if(options.canonical&&s.cmp(this.nh)>0){s=this.n.sub(s);recoveryParam^=1}return new Signature$2({r:r,s:s,recoveryParam:recoveryParam})}};EC$1.prototype.verify=function verify(msg,signature,key,enc){msg=this._truncateToN(new BN$2(msg,16));key=this.keyFromPublic(key,enc);signature=new Signature$2(signature,"hex");var r=signature.r;var s=signature.s;if(r.cmpn(1)<0||r.cmp(this.n)>=0)return false;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return false;var sinv=s.invm(this.n);var u1=sinv.mul(msg).umod(this.n);var u2=sinv.mul(r).umod(this.n);var p;if(!this.curve._maxwellTrick){p=this.g.mulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.getX().umod(this.n).cmp(r)===0}p=this.g.jmulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.eqXToP(r)};EC$1.prototype.recoverPubKey=function(msg,signature,j,enc){assert$3((3&j)===j,"The recovery param is more than two bits");signature=new Signature$2(signature,enc);var n=this.n;var e=new BN$2(msg);var r=signature.r;var s=signature.s;var isYOdd=j&1;var isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error("Unable to find sencond key candinate");if(isSecondKey)r=this.curve.pointFromX(r.add(this.curve.n),isYOdd);else r=this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n);var s1=n.sub(e).mul(rInv).umod(n);var s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)};EC$1.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){signature=new Signature$2(signature,enc);if(signature.recoveryParam!==null)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch(e){continue}if(Qprime.eq(Q))return i}throw new Error("Unable to find valid recovery factor")};var utils$2=utils$c;var assert$2=utils$2.assert;var parseBytes$2=utils$2.parseBytes;var cachedProperty$1=utils$2.cachedProperty;function KeyPair$1(eddsa,params){this.eddsa=eddsa;this._secret=parseBytes$2(params.secret);if(eddsa.isPoint(params.pub))this._pub=params.pub;else this._pubBytes=parseBytes$2(params.pub)}KeyPair$1.fromPublic=function fromPublic(eddsa,pub){if(pub instanceof KeyPair$1)return pub;return new KeyPair$1(eddsa,{pub:pub})};KeyPair$1.fromSecret=function fromSecret(eddsa,secret){if(secret instanceof KeyPair$1)return secret;return new KeyPair$1(eddsa,{secret:secret})};KeyPair$1.prototype.secret=function secret(){return this._secret};cachedProperty$1(KeyPair$1,"pubBytes",(function pubBytes(){return this.eddsa.encodePoint(this.pub())}));cachedProperty$1(KeyPair$1,"pub",(function pub(){if(this._pubBytes)return this.eddsa.decodePoint(this._pubBytes);return this.eddsa.g.mul(this.priv())}));cachedProperty$1(KeyPair$1,"privBytes",(function privBytes(){var eddsa=this.eddsa;var hash=this.hash();var lastIx=eddsa.encodingLength-1;var a=hash.slice(0,eddsa.encodingLength);a[0]&=248;a[lastIx]&=127;a[lastIx]|=64;return a}));cachedProperty$1(KeyPair$1,"priv",(function priv(){return this.eddsa.decodeInt(this.privBytes())}));cachedProperty$1(KeyPair$1,"hash",(function hash(){return this.eddsa.hash().update(this.secret()).digest()}));cachedProperty$1(KeyPair$1,"messagePrefix",(function messagePrefix(){return this.hash().slice(this.eddsa.encodingLength)}));KeyPair$1.prototype.sign=function sign(message){assert$2(this._secret,"KeyPair can only verify");return this.eddsa.sign(message,this)};KeyPair$1.prototype.verify=function verify(message,sig){return this.eddsa.verify(message,sig,this)};KeyPair$1.prototype.getSecret=function getSecret(enc){assert$2(this._secret,"KeyPair is public only");return utils$2.encode(this.secret(),enc)};KeyPair$1.prototype.getPublic=function getPublic(enc){return utils$2.encode(this.pubBytes(),enc)};var key=KeyPair$1;var BN$1=bn.exports;var utils$1=utils$c;var assert$1=utils$1.assert;var cachedProperty=utils$1.cachedProperty;var parseBytes$1=utils$1.parseBytes;function Signature$1(eddsa,sig){this.eddsa=eddsa;if(typeof sig!=="object")sig=parseBytes$1(sig);if(Array.isArray(sig)){sig={R:sig.slice(0,eddsa.encodingLength),S:sig.slice(eddsa.encodingLength)}}assert$1(sig.R&&sig.S,"Signature without R or S");if(eddsa.isPoint(sig.R))this._R=sig.R;if(sig.S instanceof BN$1)this._S=sig.S;this._Rencoded=Array.isArray(sig.R)?sig.R:sig.Rencoded;this._Sencoded=Array.isArray(sig.S)?sig.S:sig.Sencoded}cachedProperty(Signature$1,"S",(function S(){return this.eddsa.decodeInt(this.Sencoded())}));cachedProperty(Signature$1,"R",(function R(){return this.eddsa.decodePoint(this.Rencoded())}));cachedProperty(Signature$1,"Rencoded",(function Rencoded(){return this.eddsa.encodePoint(this.R())}));cachedProperty(Signature$1,"Sencoded",(function Sencoded(){return this.eddsa.encodeInt(this.S())}));Signature$1.prototype.toBytes=function toBytes(){return this.Rencoded().concat(this.Sencoded())};Signature$1.prototype.toHex=function toHex(){return utils$1.encode(this.toBytes(),"hex").toUpperCase()};var signature=Signature$1;var hash=hash$3;var curves=curves$2;var utils=utils$c;var assert=utils.assert;var parseBytes=utils.parseBytes;var KeyPair=key;var Signature=signature;function EDDSA(curve){assert(curve==="ed25519","only tested with ed25519 so far");if(!(this instanceof EDDSA))return new EDDSA(curve);curve=curves[curve].curve;this.curve=curve;this.g=curve.g;this.g.precompute(curve.n.bitLength()+1);this.pointClass=curve.point().constructor;this.encodingLength=Math.ceil(curve.n.bitLength()/8);this.hash=hash.sha512}var eddsa=EDDSA;EDDSA.prototype.sign=function sign(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret);var r=this.hashInt(key.messagePrefix(),message);var R=this.g.mul(r);var Rencoded=this.encodePoint(R);var s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv());var S=r.add(s_).umod(this.curve.n);return this.makeSignature({R:R,S:S,Rencoded:Rencoded})};EDDSA.prototype.verify=function verify(message,sig,pub){message=parseBytes(message);sig=this.makeSignature(sig);var key=this.keyFromPublic(pub);var h=this.hashInt(sig.Rencoded(),key.pubBytes(),message);var SG=this.g.mul(sig.S());var RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)};EDDSA.prototype.hashInt=function hashInt(){var hash=this.hash();for(var i=0;i<arguments.length;i++)hash.update(arguments[i]);return utils.intFromLE(hash.digest()).umod(this.curve.n)};EDDSA.prototype.keyFromPublic=function keyFromPublic(pub){return KeyPair.fromPublic(this,pub)};EDDSA.prototype.keyFromSecret=function keyFromSecret(secret){return KeyPair.fromSecret(this,secret)};EDDSA.prototype.makeSignature=function makeSignature(sig){if(sig instanceof Signature)return sig;return new Signature(this,sig)};EDDSA.prototype.encodePoint=function encodePoint(point){var enc=point.getY().toArray("le",this.encodingLength);enc[this.encodingLength-1]|=point.getX().isOdd()?128:0;return enc};EDDSA.prototype.decodePoint=function decodePoint(bytes){bytes=utils.parseBytes(bytes);var lastIx=bytes.length-1;var normed=bytes.slice(0,lastIx).concat(bytes[lastIx]&~128);var xIsOdd=(bytes[lastIx]&128)!==0;var y=utils.intFromLE(normed);return this.curve.pointFromY(y,xIsOdd)};EDDSA.prototype.encodeInt=function encodeInt(num){return num.toArray("le",this.encodingLength)};EDDSA.prototype.decodeInt=function decodeInt(bytes){return utils.intFromLE(bytes)};EDDSA.prototype.isPoint=function isPoint(val){return val instanceof this.pointClass};(function(exports){var elliptic=exports;elliptic.version=require$$0.version;elliptic.utils=utils$c;elliptic.rand=brorand.exports;elliptic.curve=curve;elliptic.curves=curves$2;elliptic.ec=ec$1;elliptic.eddsa=eddsa})(elliptic$2);const EC=elliptic$2.ec;const ec=new EC("secp256k1");const ecparams=ec.curve;const BN=ecparams.n.constructor;function loadCompressedPublicKey(first,xbuf){let x=new BN(xbuf);if(x.cmp(ecparams.p)>=0)return null;x=x.toRed(ecparams.red);let y=x.redSqr().redIMul(x).redIAdd(ecparams.b).redSqrt();if(first===3!==y.isOdd())y=y.redNeg();return ec.keyPair({pub:{x:x,y:y}})}function loadUncompressedPublicKey(first,xbuf,ybuf){let x=new BN(xbuf);let y=new BN(ybuf);if(x.cmp(ecparams.p)>=0||y.cmp(ecparams.p)>=0)return null;x=x.toRed(ecparams.red);y=y.toRed(ecparams.red);if((first===6||first===7)&&y.isOdd()!==(first===7))return null;const x3=x.redSqr().redIMul(x);if(!y.redSqr().redISub(x3.redIAdd(ecparams.b)).isZero())return null;return ec.keyPair({pub:{x:x,y:y}})}function loadPublicKey(pubkey){const first=pubkey[0];switch(first){case 2:case 3:if(pubkey.length!==33)return null;return loadCompressedPublicKey(first,pubkey.subarray(1,33));case 4:case 6:case 7:if(pubkey.length!==65)return null;return loadUncompressedPublicKey(first,pubkey.subarray(1,33),pubkey.subarray(33,65));default:return null}}function savePublicKey(output,point){const pubkey=point.encode(null,output.length===33);for(let i=0;i<output.length;++i)output[i]=pubkey[i]}var elliptic$1={contextRandomize(){return 0},privateKeyVerify(seckey){const bn=new BN(seckey);return bn.cmp(ecparams.n)<0&&!bn.isZero()?0:1},privateKeyNegate(seckey){const bn=new BN(seckey);const negate=ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Uint8Array,"be",32);seckey.set(negate);return 0},privateKeyTweakAdd(seckey,tweak){const bn=new BN(tweak);if(bn.cmp(ecparams.n)>=0)return 1;bn.iadd(new BN(seckey));if(bn.cmp(ecparams.n)>=0)bn.isub(ecparams.n);if(bn.isZero())return 1;const tweaked=bn.toArrayLike(Uint8Array,"be",32);seckey.set(tweaked);return 0},privateKeyTweakMul(seckey,tweak){let bn=new BN(tweak);if(bn.cmp(ecparams.n)>=0||bn.isZero())return 1;bn.imul(new BN(seckey));if(bn.cmp(ecparams.n)>=0)bn=bn.umod(ecparams.n);const tweaked=bn.toArrayLike(Uint8Array,"be",32);seckey.set(tweaked);return 0},publicKeyVerify(pubkey){const pair=loadPublicKey(pubkey);return pair===null?1:0},publicKeyCreate(output,seckey){const bn=new BN(seckey);if(bn.cmp(ecparams.n)>=0||bn.isZero())return 1;const point=ec.keyFromPrivate(seckey).getPublic();savePublicKey(output,point);return 0},publicKeyConvert(output,pubkey){const pair=loadPublicKey(pubkey);if(pair===null)return 1;const point=pair.getPublic();savePublicKey(output,point);return 0},publicKeyNegate(output,pubkey){const pair=loadPublicKey(pubkey);if(pair===null)return 1;const point=pair.getPublic();point.y=point.y.redNeg();savePublicKey(output,point);return 0},publicKeyCombine(output,pubkeys){const pairs=new Array(pubkeys.length);for(let i=0;i<pubkeys.length;++i){pairs[i]=loadPublicKey(pubkeys[i]);if(pairs[i]===null)return 1}let point=pairs[0].getPublic();for(let i=1;i<pairs.length;++i)point=point.add(pairs[i].pub);if(point.isInfinity())return 2;savePublicKey(output,point);return 0},publicKeyTweakAdd(output,pubkey,tweak){const pair=loadPublicKey(pubkey);if(pair===null)return 1;tweak=new BN(tweak);if(tweak.cmp(ecparams.n)>=0)return 2;const point=pair.getPublic().add(ecparams.g.mul(tweak));if(point.isInfinity())return 2;savePublicKey(output,point);return 0},publicKeyTweakMul(output,pubkey,tweak){const pair=loadPublicKey(pubkey);if(pair===null)return 1;tweak=new BN(tweak);if(tweak.cmp(ecparams.n)>=0||tweak.isZero())return 2;const point=pair.getPublic().mul(tweak);savePublicKey(output,point);return 0},signatureNormalize(sig){const r=new BN(sig.subarray(0,32));const s=new BN(sig.subarray(32,64));if(r.cmp(ecparams.n)>=0||s.cmp(ecparams.n)>=0)return 1;if(s.cmp(ec.nh)===1){sig.set(ecparams.n.sub(s).toArrayLike(Uint8Array,"be",32),32)}return 0},signatureExport(obj,sig){const sigR=sig.subarray(0,32);const sigS=sig.subarray(32,64);if(new BN(sigR).cmp(ecparams.n)>=0)return 1;if(new BN(sigS).cmp(ecparams.n)>=0)return 1;const{output:output}=obj;let r=output.subarray(4,4+33);r[0]=0;r.set(sigR,1);let lenR=33;let posR=0;for(;lenR>1&&r[posR]===0&&!(r[posR+1]&128);--lenR,++posR);r=r.subarray(posR);if(r[0]&128)return 1;if(lenR>1&&r[0]===0&&!(r[1]&128))return 1;let s=output.subarray(6+33,6+33+33);s[0]=0;s.set(sigS,1);let lenS=33;let posS=0;for(;lenS>1&&s[posS]===0&&!(s[posS+1]&128);--lenS,++posS);s=s.subarray(posS);if(s[0]&128)return 1;if(lenS>1&&s[0]===0&&!(s[1]&128))return 1;obj.outputlen=6+lenR+lenS;output[0]=48;output[1]=obj.outputlen-2;output[2]=2;output[3]=r.length;output.set(r,4);output[4+lenR]=2;output[5+lenR]=s.length;output.set(s,6+lenR);return 0},signatureImport(output,sig){if(sig.length<8)return 1;if(sig.length>72)return 1;if(sig[0]!==48)return 1;if(sig[1]!==sig.length-2)return 1;if(sig[2]!==2)return 1;const lenR=sig[3];if(lenR===0)return 1;if(5+lenR>=sig.length)return 1;if(sig[4+lenR]!==2)return 1;const lenS=sig[5+lenR];if(lenS===0)return 1;if(6+lenR+lenS!==sig.length)return 1;if(sig[4]&128)return 1;if(lenR>1&&sig[4]===0&&!(sig[5]&128))return 1;if(sig[lenR+6]&128)return 1;if(lenS>1&&sig[lenR+6]===0&&!(sig[lenR+7]&128))return 1;let sigR=sig.subarray(4,4+lenR);if(sigR.length===33&&sigR[0]===0)sigR=sigR.subarray(1);if(sigR.length>32)return 1;let sigS=sig.subarray(6+lenR);if(sigS.length===33&&sigS[0]===0)sigS=sigS.slice(1);if(sigS.length>32)throw new Error("S length is too long");let r=new BN(sigR);if(r.cmp(ecparams.n)>=0)r=new BN(0);let s=new BN(sig.subarray(6+lenR));if(s.cmp(ecparams.n)>=0)s=new BN(0);output.set(r.toArrayLike(Uint8Array,"be",32),0);output.set(s.toArrayLike(Uint8Array,"be",32),32);return 0},ecdsaSign(obj,message,seckey,data,noncefn){if(noncefn){const _noncefn=noncefn;noncefn=counter=>{const nonce=_noncefn(message,seckey,null,data,counter);const isValid=nonce instanceof Uint8Array&&nonce.length===32;if(!isValid)throw new Error("This is the way");return new BN(nonce)}}const d=new BN(seckey);if(d.cmp(ecparams.n)>=0||d.isZero())return 1;let sig;try{sig=ec.sign(message,seckey,{canonical:true,k:noncefn,pers:data})}catch(err){return 1}obj.signature.set(sig.r.toArrayLike(Uint8Array,"be",32),0);obj.signature.set(sig.s.toArrayLike(Uint8Array,"be",32),32);obj.recid=sig.recoveryParam;return 0},ecdsaVerify(sig,msg32,pubkey){const sigObj={r:sig.subarray(0,32),s:sig.subarray(32,64)};const sigr=new BN(sigObj.r);const sigs=new BN(sigObj.s);if(sigr.cmp(ecparams.n)>=0||sigs.cmp(ecparams.n)>=0)return 1;if(sigs.cmp(ec.nh)===1||sigr.isZero()||sigs.isZero())return 3;const pair=loadPublicKey(pubkey);if(pair===null)return 2;const point=pair.getPublic();const isValid=ec.verify(msg32,sigObj,point);return isValid?0:3},ecdsaRecover(output,sig,recid,msg32){const sigObj={r:sig.slice(0,32),s:sig.slice(32,64)};const sigr=new BN(sigObj.r);const sigs=new BN(sigObj.s);if(sigr.cmp(ecparams.n)>=0||sigs.cmp(ecparams.n)>=0)return 1;if(sigr.isZero()||sigs.isZero())return 2;let point;try{point=ec.recoverPubKey(msg32,sigObj,recid)}catch(err){return 2}savePublicKey(output,point);return 0},ecdh(output,pubkey,seckey,data,hashfn,xbuf,ybuf){const pair=loadPublicKey(pubkey);if(pair===null)return 1;const scalar=new BN(seckey);if(scalar.cmp(ecparams.n)>=0||scalar.isZero())return 2;const point=pair.getPublic().mul(scalar);if(hashfn===undefined){const data=point.encode(null,true);const sha256=ec.hash().update(data).digest();for(let i=0;i<32;++i)output[i]=sha256[i]}else{if(!xbuf)xbuf=new Uint8Array(32);const x=point.getX().toArray("be",32);for(let i=0;i<32;++i)xbuf[i]=x[i];if(!ybuf)ybuf=new Uint8Array(32);const y=point.getY().toArray("be",32);for(let i=0;i<32;++i)ybuf[i]=y[i];const hash=hashfn(xbuf,ybuf,data);const isValid=hash instanceof Uint8Array&&hash.length===output.length;if(!isValid)return 2;output.set(hash)}return 0}};var elliptic=lib(elliptic$1);var secp256k1=elliptic;var sha3$1={exports:{}};
31
31
  /**
32
32
  * [js-sha3]{@link https://github.com/emn178/js-sha3}
33
33
  *