@solana/web3.js 1.41.10 → 1.42.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.
@@ -14,5 +14,5 @@ var solanaWeb3=function(exports){"use strict";var commonjsGlobal=typeof globalTh
14
14
  * @author Chen, Yi-Cyuan [emn178@gmail.com]
15
15
  * @copyright Chen, Yi-Cyuan 2015-2018
16
16
  * @license MIT
17
- */(function(module){(function(){var INPUT_ERROR="input is invalid type";var FINALIZE_ERROR="finalize already called";var WINDOW=typeof window==="object";var root=WINDOW?window:{};if(root.JS_SHA3_NO_WINDOW){WINDOW=false}var WEB_WORKER=!WINDOW&&typeof self==="object";var NODE_JS=!root.JS_SHA3_NO_NODE_JS&&typeof process==="object"&&process.versions&&process.versions.node;if(NODE_JS){root=commonjsGlobal}else if(WEB_WORKER){root=self}var COMMON_JS=!root.JS_SHA3_NO_COMMON_JS&&"object"==="object"&&module.exports;var ARRAY_BUFFER=!root.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer!=="undefined";var HEX_CHARS="0123456789abcdef".split("");var SHAKE_PADDING=[31,7936,2031616,520093696];var CSHAKE_PADDING=[4,1024,262144,67108864];var KECCAK_PADDING=[1,256,65536,16777216];var PADDING=[6,1536,393216,100663296];var SHIFT=[0,8,16,24];var RC=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];var BITS=[224,256,384,512];var SHAKE_BITS=[128,256];var OUTPUT_TYPES=["hex","buffer","arrayBuffer","array","digest"];var CSHAKE_BYTEPAD={128:168,256:136};if(root.JS_SHA3_NO_NODE_JS||!Array.isArray){Array.isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"}}if(ARRAY_BUFFER&&(root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)){ArrayBuffer.isView=function(obj){return typeof obj==="object"&&obj.buffer&&obj.buffer.constructor===ArrayBuffer}}var createOutputMethod=function(bits,padding,outputType){return function(message){return new Keccak(bits,padding,bits).update(message)[outputType]()}};var createShakeOutputMethod=function(bits,padding,outputType){return function(message,outputBits){return new Keccak(bits,padding,outputBits).update(message)[outputType]()}};var createCshakeOutputMethod=function(bits,padding,outputType){return function(message,outputBits,n,s){return methods["cshake"+bits].update(message,outputBits,n,s)[outputType]()}};var createKmacOutputMethod=function(bits,padding,outputType){return function(key,message,outputBits,s){return methods["kmac"+bits].update(key,message,outputBits,s)[outputType]()}};var createOutputMethods=function(method,createMethod,bits,padding){for(var i=0;i<OUTPUT_TYPES.length;++i){var type=OUTPUT_TYPES[i];method[type]=createMethod(bits,padding,type)}return method};var createMethod=function(bits,padding){var method=createOutputMethod(bits,padding,"hex");method.create=function(){return new Keccak(bits,padding,bits)};method.update=function(message){return method.create().update(message)};return createOutputMethods(method,createOutputMethod,bits,padding)};var createShakeMethod=function(bits,padding){var method=createShakeOutputMethod(bits,padding,"hex");method.create=function(outputBits){return new Keccak(bits,padding,outputBits)};method.update=function(message,outputBits){return method.create(outputBits).update(message)};return createOutputMethods(method,createShakeOutputMethod,bits,padding)};var createCshakeMethod=function(bits,padding){var w=CSHAKE_BYTEPAD[bits];var method=createCshakeOutputMethod(bits,padding,"hex");method.create=function(outputBits,n,s){if(!n&&!s){return methods["shake"+bits].create(outputBits)}else{return new Keccak(bits,padding,outputBits).bytepad([n,s],w)}};method.update=function(message,outputBits,n,s){return method.create(outputBits,n,s).update(message)};return createOutputMethods(method,createCshakeOutputMethod,bits,padding)};var createKmacMethod=function(bits,padding){var w=CSHAKE_BYTEPAD[bits];var method=createKmacOutputMethod(bits,padding,"hex");method.create=function(key,outputBits,s){return new Kmac(bits,padding,outputBits).bytepad(["KMAC",s],w).bytepad([key],w)};method.update=function(key,message,outputBits,s){return method.create(key,outputBits,s).update(message)};return createOutputMethods(method,createKmacOutputMethod,bits,padding)};var algorithms=[{name:"keccak",padding:KECCAK_PADDING,bits:BITS,createMethod:createMethod},{name:"sha3",padding:PADDING,bits:BITS,createMethod:createMethod},{name:"shake",padding:SHAKE_PADDING,bits:SHAKE_BITS,createMethod:createShakeMethod},{name:"cshake",padding:CSHAKE_PADDING,bits:SHAKE_BITS,createMethod:createCshakeMethod},{name:"kmac",padding:CSHAKE_PADDING,bits:SHAKE_BITS,createMethod:createKmacMethod}];var methods={},methodNames=[];for(var i=0;i<algorithms.length;++i){var algorithm=algorithms[i];var bits=algorithm.bits;for(var j=0;j<bits.length;++j){var methodName=algorithm.name+"_"+bits[j];methodNames.push(methodName);methods[methodName]=algorithm.createMethod(bits[j],algorithm.padding);if(algorithm.name!=="sha3"){var newMethodName=algorithm.name+bits[j];methodNames.push(newMethodName);methods[newMethodName]=methods[methodName]}}}function Keccak(bits,padding,outputBits){this.blocks=[];this.s=[];this.padding=padding;this.outputBits=outputBits;this.reset=true;this.finalized=false;this.block=0;this.start=0;this.blockCount=1600-(bits<<1)>>5;this.byteCount=this.blockCount<<2;this.outputBlocks=outputBits>>5;this.extraBytes=(outputBits&31)>>3;for(var i=0;i<50;++i){this.s[i]=0}}Keccak.prototype.update=function(message){if(this.finalized){throw new Error(FINALIZE_ERROR)}var notString,type=typeof message;if(type!=="string"){if(type==="object"){if(message===null){throw new Error(INPUT_ERROR)}else if(ARRAY_BUFFER&&message.constructor===ArrayBuffer){message=new Uint8Array(message)}else if(!Array.isArray(message)){if(!ARRAY_BUFFER||!ArrayBuffer.isView(message)){throw new Error(INPUT_ERROR)}}}else{throw new Error(INPUT_ERROR)}notString=true}var blocks=this.blocks,byteCount=this.byteCount,length=message.length,blockCount=this.blockCount,index=0,s=this.s,i,code;while(index<length){if(this.reset){this.reset=false;blocks[0]=this.block;for(i=1;i<blockCount+1;++i){blocks[i]=0}}if(notString){for(i=this.start;index<length&&i<byteCount;++index){blocks[i>>2]|=message[index]<<SHIFT[i++&3]}}else{for(i=this.start;index<length&&i<byteCount;++index){code=message.charCodeAt(index);if(code<128){blocks[i>>2]|=code<<SHIFT[i++&3]}else if(code<2048){blocks[i>>2]|=(192|code>>6)<<SHIFT[i++&3];blocks[i>>2]|=(128|code&63)<<SHIFT[i++&3]}else if(code<55296||code>=57344){blocks[i>>2]|=(224|code>>12)<<SHIFT[i++&3];blocks[i>>2]|=(128|code>>6&63)<<SHIFT[i++&3];blocks[i>>2]|=(128|code&63)<<SHIFT[i++&3]}else{code=65536+((code&1023)<<10|message.charCodeAt(++index)&1023);blocks[i>>2]|=(240|code>>18)<<SHIFT[i++&3];blocks[i>>2]|=(128|code>>12&63)<<SHIFT[i++&3];blocks[i>>2]|=(128|code>>6&63)<<SHIFT[i++&3];blocks[i>>2]|=(128|code&63)<<SHIFT[i++&3]}}}this.lastByteIndex=i;if(i>=byteCount){this.start=i-byteCount;this.block=blocks[blockCount];for(i=0;i<blockCount;++i){s[i]^=blocks[i]}f(s);this.reset=true}else{this.start=i}}return this};Keccak.prototype.encode=function(x,right){var o=x&255,n=1;var bytes=[o];x=x>>8;o=x&255;while(o>0){bytes.unshift(o);x=x>>8;o=x&255;++n}if(right){bytes.push(n)}else{bytes.unshift(n)}this.update(bytes);return bytes.length};Keccak.prototype.encodeString=function(str){var notString,type=typeof str;if(type!=="string"){if(type==="object"){if(str===null){throw new Error(INPUT_ERROR)}else if(ARRAY_BUFFER&&str.constructor===ArrayBuffer){str=new Uint8Array(str)}else if(!Array.isArray(str)){if(!ARRAY_BUFFER||!ArrayBuffer.isView(str)){throw new Error(INPUT_ERROR)}}}else{throw new Error(INPUT_ERROR)}notString=true}var bytes=0,length=str.length;if(notString){bytes=length}else{for(var i=0;i<str.length;++i){var code=str.charCodeAt(i);if(code<128){bytes+=1}else if(code<2048){bytes+=2}else if(code<55296||code>=57344){bytes+=3}else{code=65536+((code&1023)<<10|str.charCodeAt(++i)&1023);bytes+=4}}}bytes+=this.encode(bytes*8);this.update(str);return bytes};Keccak.prototype.bytepad=function(strs,w){var bytes=this.encode(w);for(var i=0;i<strs.length;++i){bytes+=this.encodeString(strs[i])}var paddingBytes=w-bytes%w;var zeros=[];zeros.length=paddingBytes;this.update(zeros);return this};Keccak.prototype.finalize=function(){if(this.finalized){return}this.finalized=true;var blocks=this.blocks,i=this.lastByteIndex,blockCount=this.blockCount,s=this.s;blocks[i>>2]|=this.padding[i&3];if(this.lastByteIndex===this.byteCount){blocks[0]=blocks[blockCount];for(i=1;i<blockCount+1;++i){blocks[i]=0}}blocks[blockCount-1]|=2147483648;for(i=0;i<blockCount;++i){s[i]^=blocks[i]}f(s)};Keccak.prototype.toString=Keccak.prototype.hex=function(){this.finalize();var blockCount=this.blockCount,s=this.s,outputBlocks=this.outputBlocks,extraBytes=this.extraBytes,i=0,j=0;var hex="",block;while(j<outputBlocks){for(i=0;i<blockCount&&j<outputBlocks;++i,++j){block=s[i];hex+=HEX_CHARS[block>>4&15]+HEX_CHARS[block&15]+HEX_CHARS[block>>12&15]+HEX_CHARS[block>>8&15]+HEX_CHARS[block>>20&15]+HEX_CHARS[block>>16&15]+HEX_CHARS[block>>28&15]+HEX_CHARS[block>>24&15]}if(j%blockCount===0){f(s);i=0}}if(extraBytes){block=s[i];hex+=HEX_CHARS[block>>4&15]+HEX_CHARS[block&15];if(extraBytes>1){hex+=HEX_CHARS[block>>12&15]+HEX_CHARS[block>>8&15]}if(extraBytes>2){hex+=HEX_CHARS[block>>20&15]+HEX_CHARS[block>>16&15]}}return hex};Keccak.prototype.arrayBuffer=function(){this.finalize();var blockCount=this.blockCount,s=this.s,outputBlocks=this.outputBlocks,extraBytes=this.extraBytes,i=0,j=0;var bytes=this.outputBits>>3;var buffer;if(extraBytes){buffer=new ArrayBuffer(outputBlocks+1<<2)}else{buffer=new ArrayBuffer(bytes)}var array=new Uint32Array(buffer);while(j<outputBlocks){for(i=0;i<blockCount&&j<outputBlocks;++i,++j){array[j]=s[i]}if(j%blockCount===0){f(s)}}if(extraBytes){array[i]=s[i];buffer=buffer.slice(0,bytes)}return buffer};Keccak.prototype.buffer=Keccak.prototype.arrayBuffer;Keccak.prototype.digest=Keccak.prototype.array=function(){this.finalize();var blockCount=this.blockCount,s=this.s,outputBlocks=this.outputBlocks,extraBytes=this.extraBytes,i=0,j=0;var array=[],offset,block;while(j<outputBlocks){for(i=0;i<blockCount&&j<outputBlocks;++i,++j){offset=j<<2;block=s[i];array[offset]=block&255;array[offset+1]=block>>8&255;array[offset+2]=block>>16&255;array[offset+3]=block>>24&255}if(j%blockCount===0){f(s)}}if(extraBytes){offset=j<<2;block=s[i];array[offset]=block&255;if(extraBytes>1){array[offset+1]=block>>8&255}if(extraBytes>2){array[offset+2]=block>>16&255}}return array};function Kmac(bits,padding,outputBits){Keccak.call(this,bits,padding,outputBits)}Kmac.prototype=new Keccak;Kmac.prototype.finalize=function(){this.encode(this.outputBits,true);return Keccak.prototype.finalize.call(this)};var f=function(s){var h,l,n,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25,b26,b27,b28,b29,b30,b31,b32,b33,b34,b35,b36,b37,b38,b39,b40,b41,b42,b43,b44,b45,b46,b47,b48,b49;for(n=0;n<48;n+=2){c0=s[0]^s[10]^s[20]^s[30]^s[40];c1=s[1]^s[11]^s[21]^s[31]^s[41];c2=s[2]^s[12]^s[22]^s[32]^s[42];c3=s[3]^s[13]^s[23]^s[33]^s[43];c4=s[4]^s[14]^s[24]^s[34]^s[44];c5=s[5]^s[15]^s[25]^s[35]^s[45];c6=s[6]^s[16]^s[26]^s[36]^s[46];c7=s[7]^s[17]^s[27]^s[37]^s[47];c8=s[8]^s[18]^s[28]^s[38]^s[48];c9=s[9]^s[19]^s[29]^s[39]^s[49];h=c8^(c2<<1|c3>>>31);l=c9^(c3<<1|c2>>>31);s[0]^=h;s[1]^=l;s[10]^=h;s[11]^=l;s[20]^=h;s[21]^=l;s[30]^=h;s[31]^=l;s[40]^=h;s[41]^=l;h=c0^(c4<<1|c5>>>31);l=c1^(c5<<1|c4>>>31);s[2]^=h;s[3]^=l;s[12]^=h;s[13]^=l;s[22]^=h;s[23]^=l;s[32]^=h;s[33]^=l;s[42]^=h;s[43]^=l;h=c2^(c6<<1|c7>>>31);l=c3^(c7<<1|c6>>>31);s[4]^=h;s[5]^=l;s[14]^=h;s[15]^=l;s[24]^=h;s[25]^=l;s[34]^=h;s[35]^=l;s[44]^=h;s[45]^=l;h=c4^(c8<<1|c9>>>31);l=c5^(c9<<1|c8>>>31);s[6]^=h;s[7]^=l;s[16]^=h;s[17]^=l;s[26]^=h;s[27]^=l;s[36]^=h;s[37]^=l;s[46]^=h;s[47]^=l;h=c6^(c0<<1|c1>>>31);l=c7^(c1<<1|c0>>>31);s[8]^=h;s[9]^=l;s[18]^=h;s[19]^=l;s[28]^=h;s[29]^=l;s[38]^=h;s[39]^=l;s[48]^=h;s[49]^=l;b0=s[0];b1=s[1];b32=s[11]<<4|s[10]>>>28;b33=s[10]<<4|s[11]>>>28;b14=s[20]<<3|s[21]>>>29;b15=s[21]<<3|s[20]>>>29;b46=s[31]<<9|s[30]>>>23;b47=s[30]<<9|s[31]>>>23;b28=s[40]<<18|s[41]>>>14;b29=s[41]<<18|s[40]>>>14;b20=s[2]<<1|s[3]>>>31;b21=s[3]<<1|s[2]>>>31;b2=s[13]<<12|s[12]>>>20;b3=s[12]<<12|s[13]>>>20;b34=s[22]<<10|s[23]>>>22;b35=s[23]<<10|s[22]>>>22;b16=s[33]<<13|s[32]>>>19;b17=s[32]<<13|s[33]>>>19;b48=s[42]<<2|s[43]>>>30;b49=s[43]<<2|s[42]>>>30;b40=s[5]<<30|s[4]>>>2;b41=s[4]<<30|s[5]>>>2;b22=s[14]<<6|s[15]>>>26;b23=s[15]<<6|s[14]>>>26;b4=s[25]<<11|s[24]>>>21;b5=s[24]<<11|s[25]>>>21;b36=s[34]<<15|s[35]>>>17;b37=s[35]<<15|s[34]>>>17;b18=s[45]<<29|s[44]>>>3;b19=s[44]<<29|s[45]>>>3;b10=s[6]<<28|s[7]>>>4;b11=s[7]<<28|s[6]>>>4;b42=s[17]<<23|s[16]>>>9;b43=s[16]<<23|s[17]>>>9;b24=s[26]<<25|s[27]>>>7;b25=s[27]<<25|s[26]>>>7;b6=s[36]<<21|s[37]>>>11;b7=s[37]<<21|s[36]>>>11;b38=s[47]<<24|s[46]>>>8;b39=s[46]<<24|s[47]>>>8;b30=s[8]<<27|s[9]>>>5;b31=s[9]<<27|s[8]>>>5;b12=s[18]<<20|s[19]>>>12;b13=s[19]<<20|s[18]>>>12;b44=s[29]<<7|s[28]>>>25;b45=s[28]<<7|s[29]>>>25;b26=s[38]<<8|s[39]>>>24;b27=s[39]<<8|s[38]>>>24;b8=s[48]<<14|s[49]>>>18;b9=s[49]<<14|s[48]>>>18;s[0]=b0^~b2&b4;s[1]=b1^~b3&b5;s[10]=b10^~b12&b14;s[11]=b11^~b13&b15;s[20]=b20^~b22&b24;s[21]=b21^~b23&b25;s[30]=b30^~b32&b34;s[31]=b31^~b33&b35;s[40]=b40^~b42&b44;s[41]=b41^~b43&b45;s[2]=b2^~b4&b6;s[3]=b3^~b5&b7;s[12]=b12^~b14&b16;s[13]=b13^~b15&b17;s[22]=b22^~b24&b26;s[23]=b23^~b25&b27;s[32]=b32^~b34&b36;s[33]=b33^~b35&b37;s[42]=b42^~b44&b46;s[43]=b43^~b45&b47;s[4]=b4^~b6&b8;s[5]=b5^~b7&b9;s[14]=b14^~b16&b18;s[15]=b15^~b17&b19;s[24]=b24^~b26&b28;s[25]=b25^~b27&b29;s[34]=b34^~b36&b38;s[35]=b35^~b37&b39;s[44]=b44^~b46&b48;s[45]=b45^~b47&b49;s[6]=b6^~b8&b0;s[7]=b7^~b9&b1;s[16]=b16^~b18&b10;s[17]=b17^~b19&b11;s[26]=b26^~b28&b20;s[27]=b27^~b29&b21;s[36]=b36^~b38&b30;s[37]=b37^~b39&b31;s[46]=b46^~b48&b40;s[47]=b47^~b49&b41;s[8]=b8^~b0&b2;s[9]=b9^~b1&b3;s[18]=b18^~b10&b12;s[19]=b19^~b11&b13;s[28]=b28^~b20&b22;s[29]=b29^~b21&b23;s[38]=b38^~b30&b32;s[39]=b39^~b31&b33;s[48]=b48^~b40&b42;s[49]=b49^~b41&b43;s[0]^=RC[n];s[1]^=RC[n+1]}};if(COMMON_JS){module.exports=methods}else{for(i=0;i<methodNames.length;++i){root[methodNames[i]]=methods[methodNames[i]]}}})()})(sha3$1);var sha3=sha3$1.exports;function encodeData(type,fields){const allocLength=type.layout.span>=0?type.layout.span:getAlloc(type,fields);const data=buffer.Buffer.alloc(allocLength);const layoutFields=Object.assign({instruction:type.index},fields);type.layout.encode(layoutFields,data);return data}function decodeData(type,buffer){let data;try{data=type.layout.decode(buffer)}catch(err){throw new Error("invalid instruction; "+err)}if(data.instruction!==type.index){throw new Error(`invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`)}return data}const FeeCalculatorLayout=nu64("lamportsPerSignature");const NonceAccountLayout=struct([u32("version"),u32("state"),publicKey("authorizedPubkey"),publicKey("nonce"),struct([FeeCalculatorLayout],"feeCalculator")]);const NONCE_ACCOUNT_LENGTH=NonceAccountLayout.span;class NonceAccount{constructor(args){this.authorizedPubkey=void 0;this.nonce=void 0;this.feeCalculator=void 0;this.authorizedPubkey=args.authorizedPubkey;this.nonce=args.nonce;this.feeCalculator=args.feeCalculator}static fromAccountData(buffer){const nonceAccount=NonceAccountLayout.decode(toBuffer(buffer),0);return new NonceAccount({authorizedPubkey:new PublicKey(nonceAccount.authorizedPubkey),nonce:new PublicKey(nonceAccount.nonce).toString(),feeCalculator:nonceAccount.feeCalculator})}}class SystemInstruction{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(SYSTEM_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a SystemInstruction")}return type}static decodeCreateAccount(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{lamports:lamports,space:space,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.Create,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,newAccountPubkey:instruction.keys[1].pubkey,lamports:lamports,space:space,programId:new PublicKey(programId)}}static decodeTransfer(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{lamports:lamports}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.Transfer,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,lamports:lamports}}static decodeTransferWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{lamports:lamports,seed:seed,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,basePubkey:instruction.keys[1].pubkey,toPubkey:instruction.keys[2].pubkey,lamports:lamports,seed:seed,programId:new PublicKey(programId)}}static decodeAllocate(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{space:space}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.Allocate,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,space:space}}static decodeAllocateWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{base:base,seed:seed,space:space,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,basePubkey:new PublicKey(base),seed:seed,space:space,programId:new PublicKey(programId)}}static decodeAssign(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.Assign,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,programId:new PublicKey(programId)}}static decodeAssignWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{base:base,seed:seed,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,basePubkey:new PublicKey(base),seed:seed,programId:new PublicKey(programId)}}static decodeCreateWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{base:base,seed:seed,lamports:lamports,space:space,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,newAccountPubkey:instruction.keys[1].pubkey,basePubkey:new PublicKey(base),seed:seed,lamports:lamports,space:space,programId:new PublicKey(programId)}}static decodeNonceInitialize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{authorized:authorized}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:new PublicKey(authorized)}}static decodeNonceAdvance(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);decodeData(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey}}static decodeNonceWithdraw(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,5);const{lamports:lamports}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey,lamports:lamports}}static decodeNonceAuthorize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{authorized:authorized}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[1].pubkey,newAuthorizedPubkey:new PublicKey(authorized)}}static checkProgramId(programId){if(!programId.equals(SystemProgram.programId)){throw new Error("invalid instruction; programId is not SystemProgram")}}static checkKeyLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}const SYSTEM_INSTRUCTION_LAYOUTS=Object.freeze({Create:{index:0,layout:struct([u32("instruction"),ns64("lamports"),ns64("space"),publicKey("programId")])},Assign:{index:1,layout:struct([u32("instruction"),publicKey("programId")])},Transfer:{index:2,layout:struct([u32("instruction"),u64("lamports")])},CreateWithSeed:{index:3,layout:struct([u32("instruction"),publicKey("base"),rustString("seed"),ns64("lamports"),ns64("space"),publicKey("programId")])},AdvanceNonceAccount:{index:4,layout:struct([u32("instruction")])},WithdrawNonceAccount:{index:5,layout:struct([u32("instruction"),ns64("lamports")])},InitializeNonceAccount:{index:6,layout:struct([u32("instruction"),publicKey("authorized")])},AuthorizeNonceAccount:{index:7,layout:struct([u32("instruction"),publicKey("authorized")])},Allocate:{index:8,layout:struct([u32("instruction"),ns64("space")])},AllocateWithSeed:{index:9,layout:struct([u32("instruction"),publicKey("base"),rustString("seed"),ns64("space"),publicKey("programId")])},AssignWithSeed:{index:10,layout:struct([u32("instruction"),publicKey("base"),rustString("seed"),publicKey("programId")])},TransferWithSeed:{index:11,layout:struct([u32("instruction"),u64("lamports"),rustString("seed"),publicKey("programId")])}});class SystemProgram{constructor(){}static createAccount(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.Create;const data=encodeData(type,{lamports:params.lamports,space:params.space,programId:toBuffer(params.programId.toBuffer())});return new TransactionInstruction({keys:[{pubkey:params.fromPubkey,isSigner:true,isWritable:true},{pubkey:params.newAccountPubkey,isSigner:true,isWritable:true}],programId:this.programId,data:data})}static transfer(params){let data;let keys;if("basePubkey"in params){const type=SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;data=encodeData(type,{lamports:BigInt(params.lamports),seed:params.seed,programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.fromPubkey,isSigner:false,isWritable:true},{pubkey:params.basePubkey,isSigner:true,isWritable:false},{pubkey:params.toPubkey,isSigner:false,isWritable:true}]}else{const type=SYSTEM_INSTRUCTION_LAYOUTS.Transfer;data=encodeData(type,{lamports:BigInt(params.lamports)});keys=[{pubkey:params.fromPubkey,isSigner:true,isWritable:true},{pubkey:params.toPubkey,isSigner:false,isWritable:true}]}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}static assign(params){let data;let keys;if("basePubkey"in params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;data=encodeData(type,{base:toBuffer(params.basePubkey.toBuffer()),seed:params.seed,programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.accountPubkey,isSigner:false,isWritable:true},{pubkey:params.basePubkey,isSigner:true,isWritable:false}]}else{const type=SYSTEM_INSTRUCTION_LAYOUTS.Assign;data=encodeData(type,{programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.accountPubkey,isSigner:true,isWritable:true}]}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}static createAccountWithSeed(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;const data=encodeData(type,{base:toBuffer(params.basePubkey.toBuffer()),seed:params.seed,lamports:params.lamports,space:params.space,programId:toBuffer(params.programId.toBuffer())});let keys=[{pubkey:params.fromPubkey,isSigner:true,isWritable:true},{pubkey:params.newAccountPubkey,isSigner:false,isWritable:true}];if(params.basePubkey!=params.fromPubkey){keys.push({pubkey:params.basePubkey,isSigner:true,isWritable:false})}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}static createNonceAccount(params){const transaction=new Transaction;if("basePubkey"in params&&"seed"in params){transaction.add(SystemProgram.createAccountWithSeed({fromPubkey:params.fromPubkey,newAccountPubkey:params.noncePubkey,basePubkey:params.basePubkey,seed:params.seed,lamports:params.lamports,space:NONCE_ACCOUNT_LENGTH,programId:this.programId}))}else{transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.noncePubkey,lamports:params.lamports,space:NONCE_ACCOUNT_LENGTH,programId:this.programId}))}const initParams={noncePubkey:params.noncePubkey,authorizedPubkey:params.authorizedPubkey};transaction.add(this.nonceInitialize(initParams));return transaction}static nonceInitialize(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;const data=encodeData(type,{authorized:toBuffer(params.authorizedPubkey.toBuffer())});const instructionData={keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RECENT_BLOCKHASHES_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static nonceAdvance(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount;const data=encodeData(type);const instructionData={keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RECENT_BLOCKHASHES_PUBKEY,isSigner:false,isWritable:false},{pubkey:params.authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static nonceWithdraw(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount;const data=encodeData(type,{lamports:params.lamports});return new TransactionInstruction({keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:params.toPubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RECENT_BLOCKHASHES_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false},{pubkey:params.authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static nonceAuthorize(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;const data=encodeData(type,{authorized:toBuffer(params.newAuthorizedPubkey.toBuffer())});return new TransactionInstruction({keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:params.authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static allocate(params){let data;let keys;if("basePubkey"in params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;data=encodeData(type,{base:toBuffer(params.basePubkey.toBuffer()),seed:params.seed,space:params.space,programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.accountPubkey,isSigner:false,isWritable:true},{pubkey:params.basePubkey,isSigner:true,isWritable:false}]}else{const type=SYSTEM_INSTRUCTION_LAYOUTS.Allocate;data=encodeData(type,{space:params.space});keys=[{pubkey:params.accountPubkey,isSigner:true,isWritable:true}]}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}}SystemProgram.programId=new PublicKey("11111111111111111111111111111111");const CHUNK_SIZE=PACKET_DATA_SIZE-300;class Loader{constructor(){}static getMinNumSignatures(dataLength){return 2*(Math.ceil(dataLength/Loader.chunkSize)+1+1)}static async load(connection,payer,program,programId,data){{const balanceNeeded=await connection.getMinimumBalanceForRentExemption(data.length);const programInfo=await connection.getAccountInfo(program.publicKey,"confirmed");let transaction=null;if(programInfo!==null){if(programInfo.executable){console.error("Program load failed, account is already executable");return false}if(programInfo.data.length!==data.length){transaction=transaction||new Transaction;transaction.add(SystemProgram.allocate({accountPubkey:program.publicKey,space:data.length}))}if(!programInfo.owner.equals(programId)){transaction=transaction||new Transaction;transaction.add(SystemProgram.assign({accountPubkey:program.publicKey,programId:programId}))}if(programInfo.lamports<balanceNeeded){transaction=transaction||new Transaction;transaction.add(SystemProgram.transfer({fromPubkey:payer.publicKey,toPubkey:program.publicKey,lamports:balanceNeeded-programInfo.lamports}))}}else{transaction=(new Transaction).add(SystemProgram.createAccount({fromPubkey:payer.publicKey,newAccountPubkey:program.publicKey,lamports:balanceNeeded>0?balanceNeeded:1,space:data.length,programId:programId}))}if(transaction!==null){await sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"})}}const dataLayout=struct([u32("instruction"),u32("offset"),u32("bytesLength"),u32("bytesLengthPadding"),seq(u8("byte"),offset(u32(),-8),"bytes")]);const chunkSize=Loader.chunkSize;let offset$1=0;let array=data;let transactions=[];while(array.length>0){const bytes=array.slice(0,chunkSize);const data=buffer.Buffer.alloc(chunkSize+16);dataLayout.encode({instruction:0,offset:offset$1,bytes:bytes,bytesLength:0,bytesLengthPadding:0},data);const transaction=(new Transaction).add({keys:[{pubkey:program.publicKey,isSigner:true,isWritable:true}],programId:programId,data:data});transactions.push(sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"}));if(connection._rpcEndpoint.includes("solana.com")){const REQUESTS_PER_SECOND=4;await sleep(1e3/REQUESTS_PER_SECOND)}offset$1+=chunkSize;array=array.slice(chunkSize)}await Promise.all(transactions);{const dataLayout=struct([u32("instruction")]);const data=buffer.Buffer.alloc(dataLayout.span);dataLayout.encode({instruction:1},data);const transaction=(new Transaction).add({keys:[{pubkey:program.publicKey,isSigner:true,isWritable:true},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false}],programId:programId,data:data});await sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"})}return true}}Loader.chunkSize=CHUNK_SIZE;const BPF_LOADER_PROGRAM_ID=new PublicKey("BPFLoader2111111111111111111111111111111111");class BpfLoader{static getMinNumSignatures(dataLength){return Loader.getMinNumSignatures(dataLength)}static load(connection,payer,program,elf,loaderProgramId){return Loader.load(connection,payer,program,loaderProgramId,elf)}}class ComputeBudgetInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=u8("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a ComputeBudgetInstruction")}return type}static decodeRequestUnits(instruction){this.checkProgramId(instruction.programId);const{units:units,additionalFee:additionalFee}=decodeData(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits,instruction.data);return{units:units,additionalFee:additionalFee}}static decodeRequestHeapFrame(instruction){this.checkProgramId(instruction.programId);const{bytes:bytes}=decodeData(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame,instruction.data);return{bytes:bytes}}static checkProgramId(programId){if(!programId.equals(ComputeBudgetProgram.programId)){throw new Error("invalid instruction; programId is not ComputeBudgetProgram")}}}const COMPUTE_BUDGET_INSTRUCTION_LAYOUTS=Object.freeze({RequestUnits:{index:0,layout:struct([u8("instruction"),u32("units"),u32("additionalFee")])},RequestHeapFrame:{index:1,layout:struct([u8("instruction"),u32("bytes")])}});class ComputeBudgetProgram{constructor(){}static requestUnits(params){const type=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;const data=encodeData(type,params);return new TransactionInstruction({keys:[],programId:this.programId,data:data})}static requestHeapFrame(params){const type=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;const data=encodeData(type,params);return new TransactionInstruction({keys:[],programId:this.programId,data:data})}}ComputeBudgetProgram.programId=new PublicKey("ComputeBudget111111111111111111111111111111");var browserPonyfill={exports:{}};(function(module,exports){var global=typeof self!=="undefined"?self:commonjsGlobal;var __self__=function(){function F(){this.fetch=false;this.DOMException=global.DOMException}F.prototype=global;return new F}();(function(self){(function(exports){var support={searchParams:"URLSearchParams"in self,iterable:"Symbol"in self&&"iterator"in Symbol,blob:"FileReader"in self&&"Blob"in self&&function(){try{new Blob;return true}catch(e){return false}}(),formData:"FormData"in self,arrayBuffer:"ArrayBuffer"in self};function isDataView(obj){return obj&&DataView.prototype.isPrototypeOf(obj)}if(support.arrayBuffer){var viewClasses=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"];var isArrayBufferView=ArrayBuffer.isView||function(obj){return obj&&viewClasses.indexOf(Object.prototype.toString.call(obj))>-1}}function normalizeName(name){if(typeof name!=="string"){name=String(name)}if(/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)){throw new TypeError("Invalid character in header field name")}return name.toLowerCase()}function normalizeValue(value){if(typeof value!=="string"){value=String(value)}return value}function iteratorFor(items){var iterator={next:function(){var value=items.shift();return{done:value===undefined,value:value}}};if(support.iterable){iterator[Symbol.iterator]=function(){return iterator}}return iterator}function Headers(headers){this.map={};if(headers instanceof Headers){headers.forEach((function(value,name){this.append(name,value)}),this)}else if(Array.isArray(headers)){headers.forEach((function(header){this.append(header[0],header[1])}),this)}else if(headers){Object.getOwnPropertyNames(headers).forEach((function(name){this.append(name,headers[name])}),this)}}Headers.prototype.append=function(name,value){name=normalizeName(name);value=normalizeValue(value);var oldValue=this.map[name];this.map[name]=oldValue?oldValue+", "+value:value};Headers.prototype["delete"]=function(name){delete this.map[normalizeName(name)]};Headers.prototype.get=function(name){name=normalizeName(name);return this.has(name)?this.map[name]:null};Headers.prototype.has=function(name){return this.map.hasOwnProperty(normalizeName(name))};Headers.prototype.set=function(name,value){this.map[normalizeName(name)]=normalizeValue(value)};Headers.prototype.forEach=function(callback,thisArg){for(var name in this.map){if(this.map.hasOwnProperty(name)){callback.call(thisArg,this.map[name],name,this)}}};Headers.prototype.keys=function(){var items=[];this.forEach((function(value,name){items.push(name)}));return iteratorFor(items)};Headers.prototype.values=function(){var items=[];this.forEach((function(value){items.push(value)}));return iteratorFor(items)};Headers.prototype.entries=function(){var items=[];this.forEach((function(value,name){items.push([name,value])}));return iteratorFor(items)};if(support.iterable){Headers.prototype[Symbol.iterator]=Headers.prototype.entries}function consumed(body){if(body.bodyUsed){return Promise.reject(new TypeError("Already read"))}body.bodyUsed=true}function fileReaderReady(reader){return new Promise((function(resolve,reject){reader.onload=function(){resolve(reader.result)};reader.onerror=function(){reject(reader.error)}}))}function readBlobAsArrayBuffer(blob){var reader=new FileReader;var promise=fileReaderReady(reader);reader.readAsArrayBuffer(blob);return promise}function readBlobAsText(blob){var reader=new FileReader;var promise=fileReaderReady(reader);reader.readAsText(blob);return promise}function readArrayBufferAsText(buf){var view=new Uint8Array(buf);var chars=new Array(view.length);for(var i=0;i<view.length;i++){chars[i]=String.fromCharCode(view[i])}return chars.join("")}function bufferClone(buf){if(buf.slice){return buf.slice(0)}else{var view=new Uint8Array(buf.byteLength);view.set(new Uint8Array(buf));return view.buffer}}function Body(){this.bodyUsed=false;this._initBody=function(body){this._bodyInit=body;if(!body){this._bodyText=""}else if(typeof body==="string"){this._bodyText=body}else if(support.blob&&Blob.prototype.isPrototypeOf(body)){this._bodyBlob=body}else if(support.formData&&FormData.prototype.isPrototypeOf(body)){this._bodyFormData=body}else if(support.searchParams&&URLSearchParams.prototype.isPrototypeOf(body)){this._bodyText=body.toString()}else if(support.arrayBuffer&&support.blob&&isDataView(body)){this._bodyArrayBuffer=bufferClone(body.buffer);this._bodyInit=new Blob([this._bodyArrayBuffer])}else if(support.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(body)||isArrayBufferView(body))){this._bodyArrayBuffer=bufferClone(body)}else{this._bodyText=body=Object.prototype.toString.call(body)}if(!this.headers.get("content-type")){if(typeof body==="string"){this.headers.set("content-type","text/plain;charset=UTF-8")}else if(this._bodyBlob&&this._bodyBlob.type){this.headers.set("content-type",this._bodyBlob.type)}else if(support.searchParams&&URLSearchParams.prototype.isPrototypeOf(body)){this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8")}}};if(support.blob){this.blob=function(){var rejected=consumed(this);if(rejected){return rejected}if(this._bodyBlob){return Promise.resolve(this._bodyBlob)}else if(this._bodyArrayBuffer){return Promise.resolve(new Blob([this._bodyArrayBuffer]))}else if(this._bodyFormData){throw new Error("could not read FormData body as blob")}else{return Promise.resolve(new Blob([this._bodyText]))}};this.arrayBuffer=function(){if(this._bodyArrayBuffer){return consumed(this)||Promise.resolve(this._bodyArrayBuffer)}else{return this.blob().then(readBlobAsArrayBuffer)}}}this.text=function(){var rejected=consumed(this);if(rejected){return rejected}if(this._bodyBlob){return readBlobAsText(this._bodyBlob)}else if(this._bodyArrayBuffer){return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))}else if(this._bodyFormData){throw new Error("could not read FormData body as text")}else{return Promise.resolve(this._bodyText)}};if(support.formData){this.formData=function(){return this.text().then(decode)}}this.json=function(){return this.text().then(JSON.parse)};return this}var methods=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function normalizeMethod(method){var upcased=method.toUpperCase();return methods.indexOf(upcased)>-1?upcased:method}function Request(input,options){options=options||{};var body=options.body;if(input instanceof Request){if(input.bodyUsed){throw new TypeError("Already read")}this.url=input.url;this.credentials=input.credentials;if(!options.headers){this.headers=new Headers(input.headers)}this.method=input.method;this.mode=input.mode;this.signal=input.signal;if(!body&&input._bodyInit!=null){body=input._bodyInit;input.bodyUsed=true}}else{this.url=String(input)}this.credentials=options.credentials||this.credentials||"same-origin";if(options.headers||!this.headers){this.headers=new Headers(options.headers)}this.method=normalizeMethod(options.method||this.method||"GET");this.mode=options.mode||this.mode||null;this.signal=options.signal||this.signal;this.referrer=null;if((this.method==="GET"||this.method==="HEAD")&&body){throw new TypeError("Body not allowed for GET or HEAD requests")}this._initBody(body)}Request.prototype.clone=function(){return new Request(this,{body:this._bodyInit})};function decode(body){var form=new FormData;body.trim().split("&").forEach((function(bytes){if(bytes){var split=bytes.split("=");var name=split.shift().replace(/\+/g," ");var value=split.join("=").replace(/\+/g," ");form.append(decodeURIComponent(name),decodeURIComponent(value))}}));return form}function parseHeaders(rawHeaders){var headers=new Headers;var preProcessedHeaders=rawHeaders.replace(/\r?\n[\t ]+/g," ");preProcessedHeaders.split(/\r?\n/).forEach((function(line){var parts=line.split(":");var key=parts.shift().trim();if(key){var value=parts.join(":").trim();headers.append(key,value)}}));return headers}Body.call(Request.prototype);function Response(bodyInit,options){if(!options){options={}}this.type="default";this.status=options.status===undefined?200:options.status;this.ok=this.status>=200&&this.status<300;this.statusText="statusText"in options?options.statusText:"OK";this.headers=new Headers(options.headers);this.url=options.url||"";this._initBody(bodyInit)}Body.call(Response.prototype);Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url})};Response.error=function(){var response=new Response(null,{status:0,statusText:""});response.type="error";return response};var redirectStatuses=[301,302,303,307,308];Response.redirect=function(url,status){if(redirectStatuses.indexOf(status)===-1){throw new RangeError("Invalid status code")}return new Response(null,{status:status,headers:{location:url}})};exports.DOMException=self.DOMException;try{new exports.DOMException}catch(err){exports.DOMException=function(message,name){this.message=message;this.name=name;var error=Error(message);this.stack=error.stack};exports.DOMException.prototype=Object.create(Error.prototype);exports.DOMException.prototype.constructor=exports.DOMException}function fetch(input,init){return new Promise((function(resolve,reject){var request=new Request(input,init);if(request.signal&&request.signal.aborted){return reject(new exports.DOMException("Aborted","AbortError"))}var xhr=new XMLHttpRequest;function abortXhr(){xhr.abort()}xhr.onload=function(){var options={status:xhr.status,statusText:xhr.statusText,headers:parseHeaders(xhr.getAllResponseHeaders()||"")};options.url="responseURL"in xhr?xhr.responseURL:options.headers.get("X-Request-URL");var body="response"in xhr?xhr.response:xhr.responseText;resolve(new Response(body,options))};xhr.onerror=function(){reject(new TypeError("Network request failed"))};xhr.ontimeout=function(){reject(new TypeError("Network request failed"))};xhr.onabort=function(){reject(new exports.DOMException("Aborted","AbortError"))};xhr.open(request.method,request.url,true);if(request.credentials==="include"){xhr.withCredentials=true}else if(request.credentials==="omit"){xhr.withCredentials=false}if("responseType"in xhr&&support.blob){xhr.responseType="blob"}request.headers.forEach((function(value,name){xhr.setRequestHeader(name,value)}));if(request.signal){request.signal.addEventListener("abort",abortXhr);xhr.onreadystatechange=function(){if(xhr.readyState===4){request.signal.removeEventListener("abort",abortXhr)}}}xhr.send(typeof request._bodyInit==="undefined"?null:request._bodyInit)}))}fetch.polyfill=true;if(!self.fetch){self.fetch=fetch;self.Headers=Headers;self.Request=Request;self.Response=Response}exports.Headers=Headers;exports.Request=Request;exports.Response=Response;exports.fetch=fetch;Object.defineProperty(exports,"__esModule",{value:true});return exports})({})})(__self__);__self__.fetch.ponyfill=true;delete __self__.fetch.polyfill;var ctx=__self__;exports=ctx.fetch;exports.default=ctx.fetch;exports.fetch=ctx.fetch;exports.Headers=ctx.Headers;exports.Request=ctx.Request;exports.Response=ctx.Response;module.exports=exports})(browserPonyfill,browserPonyfill.exports);var crossFetch=getDefaultExportFromCjs(browserPonyfill.exports);var objToString=Object.prototype.toString;var objKeys=Object.keys||function(obj){var keys=[];for(var name in obj){keys.push(name)}return keys};function stringify(val,isArrayProp){var i,max,str,keys,key,propVal,toStr;if(val===true){return"true"}if(val===false){return"false"}switch(typeof val){case"object":if(val===null){return null}else if(val.toJSON&&typeof val.toJSON==="function"){return stringify(val.toJSON(),isArrayProp)}else{toStr=objToString.call(val);if(toStr==="[object Array]"){str="[";max=val.length-1;for(i=0;i<max;i++){str+=stringify(val[i],true)+","}if(max>-1){str+=stringify(val[i],true)}return str+"]"}else if(toStr==="[object Object]"){keys=objKeys(val).sort();max=keys.length;str="";i=0;while(i<max){key=keys[i];propVal=stringify(val[key],false);if(propVal!==undefined){if(str){str+=","}str+=JSON.stringify(key)+":"+propVal}i++}return"{"+str+"}"}else{return JSON.stringify(val)}}case"function":case"undefined":return isArrayProp?null:undefined;case"string":return JSON.stringify(val);default:return isFinite(val)?val:null}}var fastStableStringify=function(val){var returnVal=stringify(val,false);if(returnVal!==undefined){return""+returnVal}};var fastStableStringify$1=fastStableStringify;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;class TransactionExpiredBlockheightExceededError extends Error{constructor(signature){super(`Signature ${signature} has expired: block height exceeded.`);this.signature=void 0;this.signature=signature}}Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class TransactionExpiredTimeoutError extends Error{constructor(signature,timeoutSeconds){super(`Transaction was not confirmed in ${timeoutSeconds.toFixed(2)} seconds. It is `+"unknown if it succeeded or failed. Check signature "+`${signature} using the Solana Explorer or CLI tools.`);this.signature=void 0;this.signature=signature}}Object.defineProperty(TransactionExpiredTimeoutError.prototype,"name",{value:"TransactionExpiredTimeoutError"});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())}));const BlockProductionResponseStruct=jsonRpcResultAndContext(type({byIdentity:record(string(),array(number())),range:type({firstSlot:number(),lastSlot:number()})}));function createRpcClient(url,useHttps,httpHeaders,customFetch,fetchMiddleware,disableRetryOnRateLimit){const fetch=customFetch?customFetch:crossFetch;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._rpcWebSocketGeneration=0;this._disableBlockhashCaching=false;this._pollingBlockhash=false;this._blockhashInfo={recentBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]};this._nextClientSubscriptionId=0;this._subscriptionDisposeFunctionsByClientSubscriptionId={};this._subscriptionCallbacksByServerSubscriptionId={};this._subscriptionsByHash={};this._subscriptionsAutoDisposedByRpc=new Set;let url=new URL(endpoint);const useHttps=url.protocol==="https:";let wsEndpoint;let httpHeaders;let fetch;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;fetch=commitmentOrConfig.fetch;fetchMiddleware=commitmentOrConfig.fetchMiddleware;disableRetryOnRateLimit=commitmentOrConfig.disableRetryOnRateLimit}this._rpcEndpoint=endpoint;this._rpcWsEndpoint=wsEndpoint||makeWebsocketUrl(endpoint);this._rpcClient=createRpcClient(url.toString(),useHttps,httpHeaders,fetch,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}get rpcEndpoint(){return this._rpcEndpoint}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(strategy,commitment){let rawSignature;if(typeof strategy=="string"){rawSignature=strategy}else{const config=strategy;rawSignature=config.signature}let decodedSignature;try{decodedSignature=bs58$1.decode(rawSignature)}catch(err){throw new Error("signature must be base58 encoded: "+rawSignature)}assert$c(decodedSignature.length===64,"signature has invalid length");const subscriptionCommitment=commitment||this.commitment;let timeoutId;let subscriptionId;let done=false;const confirmationPromise=new Promise(((resolve,reject)=>{try{subscriptionId=this.onSignature(rawSignature,((result,context)=>{subscriptionId=undefined;const response={context:context,value:result};done=true;resolve({__type:exports.TransactionStatus.PROCESSED,response:response})}),subscriptionCommitment)}catch(err){reject(err)}}));const checkBlockHeight=async()=>{try{const blockHeight=await this.getBlockHeight(commitment);return blockHeight}catch(_e){return-1}};const expiryPromise=new Promise((resolve=>{if(typeof strategy==="string"){let timeoutMs=this._confirmTransactionInitialTimeout||60*1e3;switch(subscriptionCommitment){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":{timeoutMs=this._confirmTransactionInitialTimeout||30*1e3;break}}timeoutId=setTimeout((()=>resolve({__type:exports.TransactionStatus.TIMED_OUT,timeoutMs:timeoutMs})),timeoutMs)}else{let config=strategy;(async()=>{let currentBlockHeight=await checkBlockHeight();if(done)return;while(currentBlockHeight<=config.lastValidBlockHeight){await sleep(1e3);if(done)return;currentBlockHeight=await checkBlockHeight();if(done)return}resolve({__type:exports.TransactionStatus.BLOCKHEIGHT_EXCEEDED})})()}}));let result;try{const outcome=await Promise.race([confirmationPromise,expiryPromise]);switch(outcome.__type){case exports.TransactionStatus.BLOCKHEIGHT_EXCEEDED:throw new TransactionExpiredBlockheightExceededError(rawSignature);case exports.TransactionStatus.PROCESSED:result=outcome.response;break;case exports.TransactionStatus.TIMED_OUT:throw new TransactionExpiredTimeoutError(rawSignature,outcome.timeoutMs/1e3)}}finally{clearTimeout(timeoutId);if(subscriptionId){this.removeSignatureListener(subscriptionId)}}return result}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 getBlockHeight(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getBlockHeight",args);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new Error("failed to get block height information: "+res.error.message)}return res.result}async getBlockProduction(configOrCommitment){let extra;let commitment;if(typeof configOrCommitment==="string"){commitment=configOrCommitment}else if(configOrCommitment){const{commitment:c,...rest}=configOrCommitment;commitment=c;extra=rest}const args=this._buildArgs([],commitment,"base64",extra);const unsafeRes=await this._rpcRequest("getBlockProduction",args);const res=create(unsafeRes,BlockProductionResponseStruct);if("error"in res){throw new Error("failed to get block production information: "+res.error.message)}return res.result}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 getTransactions(signatures,commitment){const batch=signatures.map((signature=>{const args=this._buildArgsAtLeastConfirmed([signature],commitment);return{methodName:"getTransaction",args:args}}));const unsafeRes=await this._rpcBatchRequest(batch);const res=unsafeRes.map((unsafeRes=>{const res=create(unsafeRes,GetTransactionRpcResult);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){let originalTx=transactionOrMessage;transaction=new Transaction({recentBlockhash:originalTx.recentBlockhash,nonceInfo:originalTx.nonceInfo,feePayer:originalTx.feePayer,signatures:[...originalTx.signatures]});transaction.instructions=transactionOrMessage.instructions}else{transaction=Transaction.populate(transactionOrMessage);transaction._message=transaction._json=undefined}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}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){this._rpcWebSocketConnected=false;console.error("ws error:",err.message)}_wsOnClose(code){this._rpcWebSocketConnected=false;this._rpcWebSocketGeneration++;if(this._rpcWebSocketHeartbeat){clearInterval(this._rpcWebSocketHeartbeat);this._rpcWebSocketHeartbeat=null}if(code===1e3){this._updateSubscriptions();return}this._subscriptionCallbacksByServerSubscriptionId={};Object.entries(this._subscriptionsByHash).forEach((([hash,subscription])=>{this._subscriptionsByHash[hash]={...subscription,state:"pending"}}))}async _updateSubscriptions(){if(Object.keys(this._subscriptionsByHash).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}const activeWebSocketGeneration=this._rpcWebSocketGeneration;const isCurrentConnectionStillActive=()=>activeWebSocketGeneration===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map((async hash=>{const subscription=this._subscriptionsByHash[hash];if(subscription===undefined){return}switch(subscription.state){case"pending":case"unsubscribed":if(subscription.callbacks.size===0){delete this._subscriptionsByHash[hash];if(subscription.state==="unsubscribed"){delete this._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId]}await this._updateSubscriptions();return}await(async()=>{const{args:args,method:method}=subscription;try{this._subscriptionsByHash[hash]={...subscription,state:"subscribing"};const serverSubscriptionId=await this._rpcWebSocket.call(method,args);this._subscriptionsByHash[hash]={...subscription,serverSubscriptionId:serverSubscriptionId,state:"subscribed"};this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId]=subscription.callbacks;await this._updateSubscriptions()}catch(e){if(e instanceof Error){console.error(`${method} error for argument`,args,e.message)}if(!isCurrentConnectionStillActive()){return}this._subscriptionsByHash[hash]={...subscription,state:"pending"};await this._updateSubscriptions()}})();break;case"subscribed":if(subscription.callbacks.size===0){await(async()=>{const{serverSubscriptionId:serverSubscriptionId,unsubscribeMethod:unsubscribeMethod}=subscription;if(this._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)){this._subscriptionsAutoDisposedByRpc.delete(serverSubscriptionId)}else{this._subscriptionsByHash[hash]={...subscription,state:"unsubscribing"};try{await this._rpcWebSocket.call(unsubscribeMethod,[serverSubscriptionId])}catch(e){if(e instanceof Error){console.error(`${unsubscribeMethod} error:`,e.message)}if(!isCurrentConnectionStillActive()){return}this._subscriptionsByHash[hash]={...subscription,state:"subscribed"};await this._updateSubscriptions();return}}this._subscriptionsByHash[hash]={...subscription,state:"unsubscribed"};await this._updateSubscriptions()})()}break}})))}_handleServerNotification(serverSubscriptionId,callbackArgs){const callbacks=this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId];if(callbacks===undefined){return}callbacks.forEach((cb=>{try{cb(...callbackArgs)}catch(e){console.error(e)}}))}_wsOnAccountNotification(notification){const{result:result,subscription:subscription}=create(notification,AccountNotificationResult);this._handleServerNotification(subscription,[result.value,result.context])}_makeSubscription(subscriptionConfig,args){const clientSubscriptionId=this._nextClientSubscriptionId++;const hash=fastStableStringify$1([subscriptionConfig.method,args],true);const existingSubscription=this._subscriptionsByHash[hash];if(existingSubscription===undefined){this._subscriptionsByHash[hash]={...subscriptionConfig,args:args,callbacks:new Set([subscriptionConfig.callback]),state:"pending"}}else{existingSubscription.callbacks.add(subscriptionConfig.callback)}this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];const subscription=this._subscriptionsByHash[hash];assert$c(subscription!==undefined,`Could not find a \`Subscription\` when tearing down client subscription #${clientSubscriptionId}`);subscription.callbacks.delete(subscriptionConfig.callback);await this._updateSubscriptions()};this._updateSubscriptions();return clientSubscriptionId}onAccountChange(publicKey,callback,commitment){const args=this._buildArgs([publicKey.toBase58()],commitment||this._commitment||"finalized","base64");return this._makeSubscription({callback:callback,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},args)}async removeAccountChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"account change")}_wsOnProgramAccountNotification(notification){const{result:result,subscription:subscription}=create(notification,ProgramAccountNotificationResult);this._handleServerNotification(subscription,[{accountId:result.value.pubkey,accountInfo:result.value.account},result.context])}onProgramAccountChange(programId,callback,commitment,filters){const args=this._buildArgs([programId.toBase58()],commitment||this._commitment||"finalized","base64",filters?{filters:filters}:undefined);return this._makeSubscription({callback:callback,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},args)}async removeProgramAccountChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"program account change")}onLogs(filter,callback,commitment){const args=this._buildArgs([typeof filter==="object"?{mentions:[filter.toString()]}:filter],commitment||this._commitment||"finalized");return this._makeSubscription({callback:callback,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},args)}async removeOnLogsListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"logs")}_wsOnLogsNotification(notification){const{result:result,subscription:subscription}=create(notification,LogsNotificationResult);this._handleServerNotification(subscription,[result.value,result.context])}_wsOnSlotNotification(notification){const{result:result,subscription:subscription}=create(notification,SlotNotificationResult);this._handleServerNotification(subscription,[result])}onSlotChange(callback){return this._makeSubscription({callback:callback,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"slot change")}_wsOnSlotUpdatesNotification(notification){const{result:result,subscription:subscription}=create(notification,SlotUpdateNotificationResult);this._handleServerNotification(subscription,[result])}onSlotUpdate(callback){return this._makeSubscription({callback:callback,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"slot update")}async _unsubscribeClientSubscription(clientSubscriptionId,subscriptionName){const dispose=this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];if(dispose){await dispose()}else{console.warn("Ignored unsubscribe request because an active subscription with id "+`\`${clientSubscriptionId}\` for '${subscriptionName}' events `+"could not be found.")}}_buildArgs(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment||encoding||extra){let options={};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{result:result,subscription:subscription}=create(notification,SignatureNotificationResult);if(result.value!=="receivedSignature"){this._subscriptionsAutoDisposedByRpc.add(subscription)}this._handleServerNotification(subscription,result.value==="receivedSignature"?[{type:"received"},result.context]:[{type:"status",result:result.value},result.context])}onSignature(signature,callback,commitment){const args=this._buildArgs([signature],commitment||this._commitment||"finalized");const clientSubscriptionId=this._makeSubscription({callback:(notification,context)=>{if(notification.type==="status"){callback(notification.result,context);try{this.removeSignatureListener(clientSubscriptionId)}catch(_err){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},args);return clientSubscriptionId}onSignatureWithOptions(signature,callback,options){const{commitment:commitment,...extra}={...options,commitment:options&&options.commitment||this._commitment||"finalized"};const args=this._buildArgs([signature],commitment,undefined,extra);const clientSubscriptionId=this._makeSubscription({callback:(notification,context)=>{callback(notification,context);try{this.removeSignatureListener(clientSubscriptionId)}catch(_err){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},args);return clientSubscriptionId}async removeSignatureListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"signature result")}_wsOnRootNotification(notification){const{result:result,subscription:subscription}=create(notification,RootNotificationResult);this._handleServerNotification(subscription,[result])}onRootChange(callback){return this._makeSubscription({callback:callback,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"root change")}}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);const index=instructionIndex==null?65535:instructionIndex;ED25519_INSTRUCTION_LAYOUT.encode({numSignatures:numSignatures,padding:0,signatureOffset:signatureOffset,signatureInstructionIndex:index,publicKeyOffset:publicKeyOffset,publicKeyInstructionIndex:index,messageDataOffset:messageDataOffset,messageDataSize:message.length,messageInstructionIndex:index},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{publicKeyCreate:publicKeyCreate,ecdsaSign:ecdsaSign}=secp256k1;const PRIVATE_KEY_BYTES=32;const ETHEREUM_ADDRESS_BYTES=20;const PUBLIC_KEY_BYTES=64;const SIGNATURE_OFFSETS_SERIALIZED_SIZE=11;const SECP256K1_INSTRUCTION_LAYOUT=struct([u8("numSignatures"),u16("signatureOffset"),u8("signatureInstructionIndex"),u16("ethAddressOffset"),u8("ethAddressInstructionIndex"),u16("messageDataOffset"),u16("messageDataSize"),u8("messageInstructionIndex"),blob(20,"ethAddress"),blob(64,"signature"),u8("recoveryId")]);class Secp256k1Program{constructor(){}static publicKeyToEthAddress(publicKey){assert$c(publicKey.length===PUBLIC_KEY_BYTES,`Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`);try{return buffer.Buffer.from(sha3.keccak_256.update(toBuffer(publicKey)).digest()).slice(-ETHEREUM_ADDRESS_BYTES)}catch(error){throw new Error(`Error constructing Ethereum address: ${error}`)}}static createInstructionWithPublicKey(params){const{publicKey:publicKey,message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex}=params;return Secp256k1Program.createInstructionWithEthAddress({ethAddress:Secp256k1Program.publicKeyToEthAddress(publicKey),message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex})}static createInstructionWithEthAddress(params){const{ethAddress:rawAddress,message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex=0}=params;let ethAddress;if(typeof rawAddress==="string"){if(rawAddress.startsWith("0x")){ethAddress=buffer.Buffer.from(rawAddress.substr(2),"hex")}else{ethAddress=buffer.Buffer.from(rawAddress,"hex")}}else{ethAddress=rawAddress}assert$c(ethAddress.length===ETHEREUM_ADDRESS_BYTES,`Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`);const dataStart=1+SIGNATURE_OFFSETS_SERIALIZED_SIZE;const ethAddressOffset=dataStart;const signatureOffset=dataStart+ethAddress.length;const messageDataOffset=signatureOffset+signature.length+1;const numSignatures=1;const instructionData=buffer.Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span+message.length);SECP256K1_INSTRUCTION_LAYOUT.encode({numSignatures:numSignatures,signatureOffset:signatureOffset,signatureInstructionIndex:instructionIndex,ethAddressOffset:ethAddressOffset,ethAddressInstructionIndex:instructionIndex,messageDataOffset:messageDataOffset,messageDataSize:message.length,messageInstructionIndex:instructionIndex,signature:toBuffer(signature),ethAddress:toBuffer(ethAddress),recoveryId:recoveryId},instructionData);instructionData.fill(toBuffer(message),SECP256K1_INSTRUCTION_LAYOUT.span);return new TransactionInstruction({keys:[],programId:Secp256k1Program.programId,data:instructionData})}static createInstructionWithPrivateKey(params){const{privateKey:pkey,message:message,instructionIndex:instructionIndex}=params;assert$c(pkey.length===PRIVATE_KEY_BYTES,`Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`);try{const privateKey=toBuffer(pkey);const publicKey=publicKeyCreate(privateKey,false).slice(1);const messageHash=buffer.Buffer.from(sha3.keccak_256.update(toBuffer(message)).digest());const{signature:signature,recid:recoveryId}=ecdsaSign(messageHash,privateKey);return this.createInstructionWithPublicKey({publicKey:publicKey,message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex})}catch(error){throw new Error(`Error creating instruction; ${error}`)}}}Secp256k1Program.programId=new PublicKey("KeccakSecp256k11111111111111111111111111111");const VALIDATOR_INFO_KEY=new PublicKey("Va1idator1nfo111111111111111111111111111111");const InfoString=type({name:string(),website:optional(string()),details:optional(string()),keybaseUsername:optional(string())});class ValidatorInfo{constructor(key,info){this.key=void 0;this.info=void 0;this.key=key;this.info=info}static fromConfigData(buffer$1){const PUBKEY_LENGTH=32;let byteArray=[...buffer$1];const configKeyCount=decodeLength(byteArray);if(configKeyCount!==2)return null;const configKeys=[];for(let i=0;i<2;i++){const publicKey=new PublicKey(byteArray.slice(0,PUBKEY_LENGTH));byteArray=byteArray.slice(PUBKEY_LENGTH);const isSigner=byteArray.slice(0,1)[0]===1;byteArray=byteArray.slice(1);configKeys.push({publicKey:publicKey,isSigner:isSigner})}if(configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)){if(configKeys[1].isSigner){const rawInfo=rustString().decode(buffer.Buffer.from(byteArray));const info=JSON.parse(rawInfo);assert$b(info,InfoString);return new ValidatorInfo(configKeys[1].publicKey,info)}}return null}}const VOTE_PROGRAM_ID=new PublicKey("Vote111111111111111111111111111111111111111");const VoteAccountLayout=struct([publicKey("nodePubkey"),publicKey("authorizedWithdrawer"),u8("commission"),nu64(),seq(struct([nu64("slot"),u32("confirmationCount")]),offset(u32(),-8),"votes"),u8("rootSlotValid"),nu64("rootSlot"),nu64(),seq(struct([nu64("epoch"),publicKey("authorizedVoter")]),offset(u32(),-8),"authorizedVoters"),struct([seq(struct([publicKey("authorizedPubkey"),nu64("epochOfLastAuthorizedSwitch"),nu64("targetEpoch")]),32,"buf"),nu64("idx"),u8("isEmpty")],"priorVoters"),nu64(),seq(struct([nu64("epoch"),nu64("credits"),nu64("prevCredits")]),offset(u32(),-8),"epochCredits"),struct([nu64("slot"),nu64("timestamp")],"lastTimestamp")]);class VoteAccount{constructor(args){this.nodePubkey=void 0;this.authorizedWithdrawer=void 0;this.commission=void 0;this.rootSlot=void 0;this.votes=void 0;this.authorizedVoters=void 0;this.priorVoters=void 0;this.epochCredits=void 0;this.lastTimestamp=void 0;this.nodePubkey=args.nodePubkey;this.authorizedWithdrawer=args.authorizedWithdrawer;this.commission=args.commission;this.rootSlot=args.rootSlot;this.votes=args.votes;this.authorizedVoters=args.authorizedVoters;this.priorVoters=args.priorVoters;this.epochCredits=args.epochCredits;this.lastTimestamp=args.lastTimestamp}static fromAccountData(buffer){const versionOffset=4;const va=VoteAccountLayout.decode(toBuffer(buffer),versionOffset);let rootSlot=va.rootSlot;if(!va.rootSlotValid){rootSlot=null}return new VoteAccount({nodePubkey:new PublicKey(va.nodePubkey),authorizedWithdrawer:new PublicKey(va.authorizedWithdrawer),commission:va.commission,votes:va.votes,rootSlot:rootSlot,authorizedVoters:va.authorizedVoters.map(parseAuthorizedVoter),priorVoters:getPriorVoters(va.priorVoters),epochCredits:va.epochCredits,lastTimestamp:va.lastTimestamp})}}function parseAuthorizedVoter({authorizedVoter:authorizedVoter,epoch:epoch}){return{epoch:epoch,authorizedVoter:new PublicKey(authorizedVoter)}}function parsePriorVoters({authorizedPubkey:authorizedPubkey,epochOfLastAuthorizedSwitch:epochOfLastAuthorizedSwitch,targetEpoch:targetEpoch}){return{authorizedPubkey:new PublicKey(authorizedPubkey),epochOfLastAuthorizedSwitch:epochOfLastAuthorizedSwitch,targetEpoch:targetEpoch}}function getPriorVoters({buf:buf,idx:idx,isEmpty:isEmpty}){if(isEmpty){return[]}return[...buf.slice(idx+1).map(parsePriorVoters),...buf.slice(0,idx).map(parsePriorVoters)]}class VoteInit{constructor(nodePubkey,authorizedVoter,authorizedWithdrawer,commission){this.nodePubkey=void 0;this.authorizedVoter=void 0;this.authorizedWithdrawer=void 0;this.commission=void 0;this.nodePubkey=nodePubkey;this.authorizedVoter=authorizedVoter;this.authorizedWithdrawer=authorizedWithdrawer;this.commission=commission}}class VoteInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=u32("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(VOTE_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a VoteInstruction")}return type}static decodeInitializeAccount(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,4);const{voteInit:voteInit}=decodeData(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount,instruction.data);return{votePubkey:instruction.keys[0].pubkey,nodePubkey:instruction.keys[3].pubkey,voteInit:new VoteInit(new PublicKey(voteInit.nodePubkey),new PublicKey(voteInit.authorizedVoter),new PublicKey(voteInit.authorizedWithdrawer),voteInit.commission)}}static decodeAuthorize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{newAuthorized:newAuthorized,voteAuthorizationType:voteAuthorizationType}=decodeData(VOTE_INSTRUCTION_LAYOUTS.Authorize,instruction.data);return{votePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey,newAuthorizedPubkey:new PublicKey(newAuthorized),voteAuthorizationType:{index:voteAuthorizationType}}}static decodeWithdraw(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{lamports:lamports}=decodeData(VOTE_INSTRUCTION_LAYOUTS.Withdraw,instruction.data);return{votePubkey:instruction.keys[0].pubkey,authorizedWithdrawerPubkey:instruction.keys[2].pubkey,lamports:lamports,toPubkey:instruction.keys[1].pubkey}}static checkProgramId(programId){if(!programId.equals(VoteProgram.programId)){throw new Error("invalid instruction; programId is not VoteProgram")}}static checkKeyLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}const VOTE_INSTRUCTION_LAYOUTS=Object.freeze({InitializeAccount:{index:0,layout:struct([u32("instruction"),voteInit()])},Authorize:{index:1,layout:struct([u32("instruction"),publicKey("newAuthorized"),u32("voteAuthorizationType")])},Withdraw:{index:3,layout:struct([u32("instruction"),ns64("lamports")])}});const VoteAuthorizationLayout=Object.freeze({Voter:{index:0},Withdrawer:{index:1}});class VoteProgram{constructor(){}static initializeAccount(params){const{votePubkey:votePubkey,nodePubkey:nodePubkey,voteInit:voteInit}=params;const type=VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;const data=encodeData(type,{voteInit:{nodePubkey:toBuffer(voteInit.nodePubkey.toBuffer()),authorizedVoter:toBuffer(voteInit.authorizedVoter.toBuffer()),authorizedWithdrawer:toBuffer(voteInit.authorizedWithdrawer.toBuffer()),commission:voteInit.commission}});const instructionData={keys:[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:nodePubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static createAccount(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.votePubkey,lamports:params.lamports,space:this.space,programId:this.programId}));return transaction.add(this.initializeAccount({votePubkey:params.votePubkey,nodePubkey:params.voteInit.nodePubkey,voteInit:params.voteInit}))}static authorize(params){const{votePubkey:votePubkey,authorizedPubkey:authorizedPubkey,newAuthorizedPubkey:newAuthorizedPubkey,voteAuthorizationType:voteAuthorizationType}=params;const type=VOTE_INSTRUCTION_LAYOUTS.Authorize;const data=encodeData(type,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),voteAuthorizationType:voteAuthorizationType.index});const keys=[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}];return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static withdraw(params){const{votePubkey:votePubkey,authorizedWithdrawerPubkey:authorizedWithdrawerPubkey,lamports:lamports,toPubkey:toPubkey}=params;const type=VOTE_INSTRUCTION_LAYOUTS.Withdraw;const data=encodeData(type,{lamports:lamports});const keys=[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:toPubkey,isSigner:false,isWritable:true},{pubkey:authorizedWithdrawerPubkey,isSigner:true,isWritable:false}];return(new Transaction).add({keys:keys,programId:this.programId,data:data})}}VoteProgram.programId=new PublicKey("Vote111111111111111111111111111111111111111");VoteProgram.space=3731;async function sendAndConfirmRawTransaction(connection,rawTransaction,options){const sendOptions=options&&{skipPreflight:options.skipPreflight,preflightCommitment:options.preflightCommitment||options.commitment};const signature=await connection.sendRawTransaction(rawTransaction,sendOptions);const status=(await connection.confirmTransaction(signature,options&&options.commitment)).value;if(status.err){throw new Error(`Raw transaction ${signature} failed (${JSON.stringify(status)})`)}return signature}const endpoint={http:{devnet:"http://api.devnet.solana.com",testnet:"http://api.testnet.solana.com","mainnet-beta":"http://api.mainnet-beta.solana.com/"},https:{devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com","mainnet-beta":"https://api.mainnet-beta.solana.com/"}};function clusterApiUrl(cluster,tls){const key=tls===false?"http":"https";if(!cluster){return endpoint[key]["devnet"]}const url=endpoint[key][cluster];if(!url){throw new Error(`Unknown ${key} cluster: ${cluster}`)}return url}const LAMPORTS_PER_SOL=1e9;exports.Account=Account;exports.Authorized=Authorized;exports.BLOCKHASH_CACHE_TIMEOUT_MS=BLOCKHASH_CACHE_TIMEOUT_MS;exports.BPF_LOADER_DEPRECATED_PROGRAM_ID=BPF_LOADER_DEPRECATED_PROGRAM_ID;exports.BPF_LOADER_PROGRAM_ID=BPF_LOADER_PROGRAM_ID;exports.BpfLoader=BpfLoader;exports.COMPUTE_BUDGET_INSTRUCTION_LAYOUTS=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS;exports.ComputeBudgetInstruction=ComputeBudgetInstruction;exports.ComputeBudgetProgram=ComputeBudgetProgram;exports.Connection=Connection;exports.Ed25519Program=Ed25519Program;exports.Enum=Enum;exports.EpochSchedule=EpochSchedule;exports.FeeCalculatorLayout=FeeCalculatorLayout;exports.Keypair=Keypair;exports.LAMPORTS_PER_SOL=LAMPORTS_PER_SOL;exports.Loader=Loader;exports.Lockup=Lockup;exports.MAX_SEED_LENGTH=MAX_SEED_LENGTH;exports.Message=Message;exports.NONCE_ACCOUNT_LENGTH=NONCE_ACCOUNT_LENGTH;exports.NonceAccount=NonceAccount;exports.PACKET_DATA_SIZE=PACKET_DATA_SIZE;exports.PublicKey=PublicKey;exports.SIGNATURE_LENGTH_IN_BYTES=SIGNATURE_LENGTH_IN_BYTES;exports.SOLANA_SCHEMA=SOLANA_SCHEMA;exports.STAKE_CONFIG_ID=STAKE_CONFIG_ID;exports.STAKE_INSTRUCTION_LAYOUTS=STAKE_INSTRUCTION_LAYOUTS;exports.SYSTEM_INSTRUCTION_LAYOUTS=SYSTEM_INSTRUCTION_LAYOUTS;exports.SYSVAR_CLOCK_PUBKEY=SYSVAR_CLOCK_PUBKEY;exports.SYSVAR_EPOCH_SCHEDULE_PUBKEY=SYSVAR_EPOCH_SCHEDULE_PUBKEY;exports.SYSVAR_INSTRUCTIONS_PUBKEY=SYSVAR_INSTRUCTIONS_PUBKEY;exports.SYSVAR_RECENT_BLOCKHASHES_PUBKEY=SYSVAR_RECENT_BLOCKHASHES_PUBKEY;exports.SYSVAR_RENT_PUBKEY=SYSVAR_RENT_PUBKEY;exports.SYSVAR_REWARDS_PUBKEY=SYSVAR_REWARDS_PUBKEY;exports.SYSVAR_SLOT_HASHES_PUBKEY=SYSVAR_SLOT_HASHES_PUBKEY;exports.SYSVAR_SLOT_HISTORY_PUBKEY=SYSVAR_SLOT_HISTORY_PUBKEY;exports.SYSVAR_STAKE_HISTORY_PUBKEY=SYSVAR_STAKE_HISTORY_PUBKEY;exports.Secp256k1Program=Secp256k1Program;exports.SendTransactionError=SendTransactionError;exports.StakeAuthorizationLayout=StakeAuthorizationLayout;exports.StakeInstruction=StakeInstruction;exports.StakeProgram=StakeProgram;exports.Struct=Struct$1;exports.SystemInstruction=SystemInstruction;exports.SystemProgram=SystemProgram;exports.Transaction=Transaction;exports.TransactionInstruction=TransactionInstruction;exports.VALIDATOR_INFO_KEY=VALIDATOR_INFO_KEY;exports.VOTE_PROGRAM_ID=VOTE_PROGRAM_ID;exports.ValidatorInfo=ValidatorInfo;exports.VoteAccount=VoteAccount;exports.VoteAuthorizationLayout=VoteAuthorizationLayout;exports.VoteInit=VoteInit;exports.VoteInstruction=VoteInstruction;exports.VoteProgram=VoteProgram;exports.clusterApiUrl=clusterApiUrl;exports.sendAndConfirmRawTransaction=sendAndConfirmRawTransaction;exports.sendAndConfirmTransaction=sendAndConfirmTransaction;Object.defineProperty(exports,"__esModule",{value:true});return exports}({});
17
+ */(function(module){(function(){var INPUT_ERROR="input is invalid type";var FINALIZE_ERROR="finalize already called";var WINDOW=typeof window==="object";var root=WINDOW?window:{};if(root.JS_SHA3_NO_WINDOW){WINDOW=false}var WEB_WORKER=!WINDOW&&typeof self==="object";var NODE_JS=!root.JS_SHA3_NO_NODE_JS&&typeof process==="object"&&process.versions&&process.versions.node;if(NODE_JS){root=commonjsGlobal}else if(WEB_WORKER){root=self}var COMMON_JS=!root.JS_SHA3_NO_COMMON_JS&&"object"==="object"&&module.exports;var ARRAY_BUFFER=!root.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer!=="undefined";var HEX_CHARS="0123456789abcdef".split("");var SHAKE_PADDING=[31,7936,2031616,520093696];var CSHAKE_PADDING=[4,1024,262144,67108864];var KECCAK_PADDING=[1,256,65536,16777216];var PADDING=[6,1536,393216,100663296];var SHIFT=[0,8,16,24];var RC=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];var BITS=[224,256,384,512];var SHAKE_BITS=[128,256];var OUTPUT_TYPES=["hex","buffer","arrayBuffer","array","digest"];var CSHAKE_BYTEPAD={128:168,256:136};if(root.JS_SHA3_NO_NODE_JS||!Array.isArray){Array.isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"}}if(ARRAY_BUFFER&&(root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)){ArrayBuffer.isView=function(obj){return typeof obj==="object"&&obj.buffer&&obj.buffer.constructor===ArrayBuffer}}var createOutputMethod=function(bits,padding,outputType){return function(message){return new Keccak(bits,padding,bits).update(message)[outputType]()}};var createShakeOutputMethod=function(bits,padding,outputType){return function(message,outputBits){return new Keccak(bits,padding,outputBits).update(message)[outputType]()}};var createCshakeOutputMethod=function(bits,padding,outputType){return function(message,outputBits,n,s){return methods["cshake"+bits].update(message,outputBits,n,s)[outputType]()}};var createKmacOutputMethod=function(bits,padding,outputType){return function(key,message,outputBits,s){return methods["kmac"+bits].update(key,message,outputBits,s)[outputType]()}};var createOutputMethods=function(method,createMethod,bits,padding){for(var i=0;i<OUTPUT_TYPES.length;++i){var type=OUTPUT_TYPES[i];method[type]=createMethod(bits,padding,type)}return method};var createMethod=function(bits,padding){var method=createOutputMethod(bits,padding,"hex");method.create=function(){return new Keccak(bits,padding,bits)};method.update=function(message){return method.create().update(message)};return createOutputMethods(method,createOutputMethod,bits,padding)};var createShakeMethod=function(bits,padding){var method=createShakeOutputMethod(bits,padding,"hex");method.create=function(outputBits){return new Keccak(bits,padding,outputBits)};method.update=function(message,outputBits){return method.create(outputBits).update(message)};return createOutputMethods(method,createShakeOutputMethod,bits,padding)};var createCshakeMethod=function(bits,padding){var w=CSHAKE_BYTEPAD[bits];var method=createCshakeOutputMethod(bits,padding,"hex");method.create=function(outputBits,n,s){if(!n&&!s){return methods["shake"+bits].create(outputBits)}else{return new Keccak(bits,padding,outputBits).bytepad([n,s],w)}};method.update=function(message,outputBits,n,s){return method.create(outputBits,n,s).update(message)};return createOutputMethods(method,createCshakeOutputMethod,bits,padding)};var createKmacMethod=function(bits,padding){var w=CSHAKE_BYTEPAD[bits];var method=createKmacOutputMethod(bits,padding,"hex");method.create=function(key,outputBits,s){return new Kmac(bits,padding,outputBits).bytepad(["KMAC",s],w).bytepad([key],w)};method.update=function(key,message,outputBits,s){return method.create(key,outputBits,s).update(message)};return createOutputMethods(method,createKmacOutputMethod,bits,padding)};var algorithms=[{name:"keccak",padding:KECCAK_PADDING,bits:BITS,createMethod:createMethod},{name:"sha3",padding:PADDING,bits:BITS,createMethod:createMethod},{name:"shake",padding:SHAKE_PADDING,bits:SHAKE_BITS,createMethod:createShakeMethod},{name:"cshake",padding:CSHAKE_PADDING,bits:SHAKE_BITS,createMethod:createCshakeMethod},{name:"kmac",padding:CSHAKE_PADDING,bits:SHAKE_BITS,createMethod:createKmacMethod}];var methods={},methodNames=[];for(var i=0;i<algorithms.length;++i){var algorithm=algorithms[i];var bits=algorithm.bits;for(var j=0;j<bits.length;++j){var methodName=algorithm.name+"_"+bits[j];methodNames.push(methodName);methods[methodName]=algorithm.createMethod(bits[j],algorithm.padding);if(algorithm.name!=="sha3"){var newMethodName=algorithm.name+bits[j];methodNames.push(newMethodName);methods[newMethodName]=methods[methodName]}}}function Keccak(bits,padding,outputBits){this.blocks=[];this.s=[];this.padding=padding;this.outputBits=outputBits;this.reset=true;this.finalized=false;this.block=0;this.start=0;this.blockCount=1600-(bits<<1)>>5;this.byteCount=this.blockCount<<2;this.outputBlocks=outputBits>>5;this.extraBytes=(outputBits&31)>>3;for(var i=0;i<50;++i){this.s[i]=0}}Keccak.prototype.update=function(message){if(this.finalized){throw new Error(FINALIZE_ERROR)}var notString,type=typeof message;if(type!=="string"){if(type==="object"){if(message===null){throw new Error(INPUT_ERROR)}else if(ARRAY_BUFFER&&message.constructor===ArrayBuffer){message=new Uint8Array(message)}else if(!Array.isArray(message)){if(!ARRAY_BUFFER||!ArrayBuffer.isView(message)){throw new Error(INPUT_ERROR)}}}else{throw new Error(INPUT_ERROR)}notString=true}var blocks=this.blocks,byteCount=this.byteCount,length=message.length,blockCount=this.blockCount,index=0,s=this.s,i,code;while(index<length){if(this.reset){this.reset=false;blocks[0]=this.block;for(i=1;i<blockCount+1;++i){blocks[i]=0}}if(notString){for(i=this.start;index<length&&i<byteCount;++index){blocks[i>>2]|=message[index]<<SHIFT[i++&3]}}else{for(i=this.start;index<length&&i<byteCount;++index){code=message.charCodeAt(index);if(code<128){blocks[i>>2]|=code<<SHIFT[i++&3]}else if(code<2048){blocks[i>>2]|=(192|code>>6)<<SHIFT[i++&3];blocks[i>>2]|=(128|code&63)<<SHIFT[i++&3]}else if(code<55296||code>=57344){blocks[i>>2]|=(224|code>>12)<<SHIFT[i++&3];blocks[i>>2]|=(128|code>>6&63)<<SHIFT[i++&3];blocks[i>>2]|=(128|code&63)<<SHIFT[i++&3]}else{code=65536+((code&1023)<<10|message.charCodeAt(++index)&1023);blocks[i>>2]|=(240|code>>18)<<SHIFT[i++&3];blocks[i>>2]|=(128|code>>12&63)<<SHIFT[i++&3];blocks[i>>2]|=(128|code>>6&63)<<SHIFT[i++&3];blocks[i>>2]|=(128|code&63)<<SHIFT[i++&3]}}}this.lastByteIndex=i;if(i>=byteCount){this.start=i-byteCount;this.block=blocks[blockCount];for(i=0;i<blockCount;++i){s[i]^=blocks[i]}f(s);this.reset=true}else{this.start=i}}return this};Keccak.prototype.encode=function(x,right){var o=x&255,n=1;var bytes=[o];x=x>>8;o=x&255;while(o>0){bytes.unshift(o);x=x>>8;o=x&255;++n}if(right){bytes.push(n)}else{bytes.unshift(n)}this.update(bytes);return bytes.length};Keccak.prototype.encodeString=function(str){var notString,type=typeof str;if(type!=="string"){if(type==="object"){if(str===null){throw new Error(INPUT_ERROR)}else if(ARRAY_BUFFER&&str.constructor===ArrayBuffer){str=new Uint8Array(str)}else if(!Array.isArray(str)){if(!ARRAY_BUFFER||!ArrayBuffer.isView(str)){throw new Error(INPUT_ERROR)}}}else{throw new Error(INPUT_ERROR)}notString=true}var bytes=0,length=str.length;if(notString){bytes=length}else{for(var i=0;i<str.length;++i){var code=str.charCodeAt(i);if(code<128){bytes+=1}else if(code<2048){bytes+=2}else if(code<55296||code>=57344){bytes+=3}else{code=65536+((code&1023)<<10|str.charCodeAt(++i)&1023);bytes+=4}}}bytes+=this.encode(bytes*8);this.update(str);return bytes};Keccak.prototype.bytepad=function(strs,w){var bytes=this.encode(w);for(var i=0;i<strs.length;++i){bytes+=this.encodeString(strs[i])}var paddingBytes=w-bytes%w;var zeros=[];zeros.length=paddingBytes;this.update(zeros);return this};Keccak.prototype.finalize=function(){if(this.finalized){return}this.finalized=true;var blocks=this.blocks,i=this.lastByteIndex,blockCount=this.blockCount,s=this.s;blocks[i>>2]|=this.padding[i&3];if(this.lastByteIndex===this.byteCount){blocks[0]=blocks[blockCount];for(i=1;i<blockCount+1;++i){blocks[i]=0}}blocks[blockCount-1]|=2147483648;for(i=0;i<blockCount;++i){s[i]^=blocks[i]}f(s)};Keccak.prototype.toString=Keccak.prototype.hex=function(){this.finalize();var blockCount=this.blockCount,s=this.s,outputBlocks=this.outputBlocks,extraBytes=this.extraBytes,i=0,j=0;var hex="",block;while(j<outputBlocks){for(i=0;i<blockCount&&j<outputBlocks;++i,++j){block=s[i];hex+=HEX_CHARS[block>>4&15]+HEX_CHARS[block&15]+HEX_CHARS[block>>12&15]+HEX_CHARS[block>>8&15]+HEX_CHARS[block>>20&15]+HEX_CHARS[block>>16&15]+HEX_CHARS[block>>28&15]+HEX_CHARS[block>>24&15]}if(j%blockCount===0){f(s);i=0}}if(extraBytes){block=s[i];hex+=HEX_CHARS[block>>4&15]+HEX_CHARS[block&15];if(extraBytes>1){hex+=HEX_CHARS[block>>12&15]+HEX_CHARS[block>>8&15]}if(extraBytes>2){hex+=HEX_CHARS[block>>20&15]+HEX_CHARS[block>>16&15]}}return hex};Keccak.prototype.arrayBuffer=function(){this.finalize();var blockCount=this.blockCount,s=this.s,outputBlocks=this.outputBlocks,extraBytes=this.extraBytes,i=0,j=0;var bytes=this.outputBits>>3;var buffer;if(extraBytes){buffer=new ArrayBuffer(outputBlocks+1<<2)}else{buffer=new ArrayBuffer(bytes)}var array=new Uint32Array(buffer);while(j<outputBlocks){for(i=0;i<blockCount&&j<outputBlocks;++i,++j){array[j]=s[i]}if(j%blockCount===0){f(s)}}if(extraBytes){array[i]=s[i];buffer=buffer.slice(0,bytes)}return buffer};Keccak.prototype.buffer=Keccak.prototype.arrayBuffer;Keccak.prototype.digest=Keccak.prototype.array=function(){this.finalize();var blockCount=this.blockCount,s=this.s,outputBlocks=this.outputBlocks,extraBytes=this.extraBytes,i=0,j=0;var array=[],offset,block;while(j<outputBlocks){for(i=0;i<blockCount&&j<outputBlocks;++i,++j){offset=j<<2;block=s[i];array[offset]=block&255;array[offset+1]=block>>8&255;array[offset+2]=block>>16&255;array[offset+3]=block>>24&255}if(j%blockCount===0){f(s)}}if(extraBytes){offset=j<<2;block=s[i];array[offset]=block&255;if(extraBytes>1){array[offset+1]=block>>8&255}if(extraBytes>2){array[offset+2]=block>>16&255}}return array};function Kmac(bits,padding,outputBits){Keccak.call(this,bits,padding,outputBits)}Kmac.prototype=new Keccak;Kmac.prototype.finalize=function(){this.encode(this.outputBits,true);return Keccak.prototype.finalize.call(this)};var f=function(s){var h,l,n,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25,b26,b27,b28,b29,b30,b31,b32,b33,b34,b35,b36,b37,b38,b39,b40,b41,b42,b43,b44,b45,b46,b47,b48,b49;for(n=0;n<48;n+=2){c0=s[0]^s[10]^s[20]^s[30]^s[40];c1=s[1]^s[11]^s[21]^s[31]^s[41];c2=s[2]^s[12]^s[22]^s[32]^s[42];c3=s[3]^s[13]^s[23]^s[33]^s[43];c4=s[4]^s[14]^s[24]^s[34]^s[44];c5=s[5]^s[15]^s[25]^s[35]^s[45];c6=s[6]^s[16]^s[26]^s[36]^s[46];c7=s[7]^s[17]^s[27]^s[37]^s[47];c8=s[8]^s[18]^s[28]^s[38]^s[48];c9=s[9]^s[19]^s[29]^s[39]^s[49];h=c8^(c2<<1|c3>>>31);l=c9^(c3<<1|c2>>>31);s[0]^=h;s[1]^=l;s[10]^=h;s[11]^=l;s[20]^=h;s[21]^=l;s[30]^=h;s[31]^=l;s[40]^=h;s[41]^=l;h=c0^(c4<<1|c5>>>31);l=c1^(c5<<1|c4>>>31);s[2]^=h;s[3]^=l;s[12]^=h;s[13]^=l;s[22]^=h;s[23]^=l;s[32]^=h;s[33]^=l;s[42]^=h;s[43]^=l;h=c2^(c6<<1|c7>>>31);l=c3^(c7<<1|c6>>>31);s[4]^=h;s[5]^=l;s[14]^=h;s[15]^=l;s[24]^=h;s[25]^=l;s[34]^=h;s[35]^=l;s[44]^=h;s[45]^=l;h=c4^(c8<<1|c9>>>31);l=c5^(c9<<1|c8>>>31);s[6]^=h;s[7]^=l;s[16]^=h;s[17]^=l;s[26]^=h;s[27]^=l;s[36]^=h;s[37]^=l;s[46]^=h;s[47]^=l;h=c6^(c0<<1|c1>>>31);l=c7^(c1<<1|c0>>>31);s[8]^=h;s[9]^=l;s[18]^=h;s[19]^=l;s[28]^=h;s[29]^=l;s[38]^=h;s[39]^=l;s[48]^=h;s[49]^=l;b0=s[0];b1=s[1];b32=s[11]<<4|s[10]>>>28;b33=s[10]<<4|s[11]>>>28;b14=s[20]<<3|s[21]>>>29;b15=s[21]<<3|s[20]>>>29;b46=s[31]<<9|s[30]>>>23;b47=s[30]<<9|s[31]>>>23;b28=s[40]<<18|s[41]>>>14;b29=s[41]<<18|s[40]>>>14;b20=s[2]<<1|s[3]>>>31;b21=s[3]<<1|s[2]>>>31;b2=s[13]<<12|s[12]>>>20;b3=s[12]<<12|s[13]>>>20;b34=s[22]<<10|s[23]>>>22;b35=s[23]<<10|s[22]>>>22;b16=s[33]<<13|s[32]>>>19;b17=s[32]<<13|s[33]>>>19;b48=s[42]<<2|s[43]>>>30;b49=s[43]<<2|s[42]>>>30;b40=s[5]<<30|s[4]>>>2;b41=s[4]<<30|s[5]>>>2;b22=s[14]<<6|s[15]>>>26;b23=s[15]<<6|s[14]>>>26;b4=s[25]<<11|s[24]>>>21;b5=s[24]<<11|s[25]>>>21;b36=s[34]<<15|s[35]>>>17;b37=s[35]<<15|s[34]>>>17;b18=s[45]<<29|s[44]>>>3;b19=s[44]<<29|s[45]>>>3;b10=s[6]<<28|s[7]>>>4;b11=s[7]<<28|s[6]>>>4;b42=s[17]<<23|s[16]>>>9;b43=s[16]<<23|s[17]>>>9;b24=s[26]<<25|s[27]>>>7;b25=s[27]<<25|s[26]>>>7;b6=s[36]<<21|s[37]>>>11;b7=s[37]<<21|s[36]>>>11;b38=s[47]<<24|s[46]>>>8;b39=s[46]<<24|s[47]>>>8;b30=s[8]<<27|s[9]>>>5;b31=s[9]<<27|s[8]>>>5;b12=s[18]<<20|s[19]>>>12;b13=s[19]<<20|s[18]>>>12;b44=s[29]<<7|s[28]>>>25;b45=s[28]<<7|s[29]>>>25;b26=s[38]<<8|s[39]>>>24;b27=s[39]<<8|s[38]>>>24;b8=s[48]<<14|s[49]>>>18;b9=s[49]<<14|s[48]>>>18;s[0]=b0^~b2&b4;s[1]=b1^~b3&b5;s[10]=b10^~b12&b14;s[11]=b11^~b13&b15;s[20]=b20^~b22&b24;s[21]=b21^~b23&b25;s[30]=b30^~b32&b34;s[31]=b31^~b33&b35;s[40]=b40^~b42&b44;s[41]=b41^~b43&b45;s[2]=b2^~b4&b6;s[3]=b3^~b5&b7;s[12]=b12^~b14&b16;s[13]=b13^~b15&b17;s[22]=b22^~b24&b26;s[23]=b23^~b25&b27;s[32]=b32^~b34&b36;s[33]=b33^~b35&b37;s[42]=b42^~b44&b46;s[43]=b43^~b45&b47;s[4]=b4^~b6&b8;s[5]=b5^~b7&b9;s[14]=b14^~b16&b18;s[15]=b15^~b17&b19;s[24]=b24^~b26&b28;s[25]=b25^~b27&b29;s[34]=b34^~b36&b38;s[35]=b35^~b37&b39;s[44]=b44^~b46&b48;s[45]=b45^~b47&b49;s[6]=b6^~b8&b0;s[7]=b7^~b9&b1;s[16]=b16^~b18&b10;s[17]=b17^~b19&b11;s[26]=b26^~b28&b20;s[27]=b27^~b29&b21;s[36]=b36^~b38&b30;s[37]=b37^~b39&b31;s[46]=b46^~b48&b40;s[47]=b47^~b49&b41;s[8]=b8^~b0&b2;s[9]=b9^~b1&b3;s[18]=b18^~b10&b12;s[19]=b19^~b11&b13;s[28]=b28^~b20&b22;s[29]=b29^~b21&b23;s[38]=b38^~b30&b32;s[39]=b39^~b31&b33;s[48]=b48^~b40&b42;s[49]=b49^~b41&b43;s[0]^=RC[n];s[1]^=RC[n+1]}};if(COMMON_JS){module.exports=methods}else{for(i=0;i<methodNames.length;++i){root[methodNames[i]]=methods[methodNames[i]]}}})()})(sha3$1);var sha3=sha3$1.exports;function encodeData(type,fields){const allocLength=type.layout.span>=0?type.layout.span:getAlloc(type,fields);const data=buffer.Buffer.alloc(allocLength);const layoutFields=Object.assign({instruction:type.index},fields);type.layout.encode(layoutFields,data);return data}function decodeData(type,buffer){let data;try{data=type.layout.decode(buffer)}catch(err){throw new Error("invalid instruction; "+err)}if(data.instruction!==type.index){throw new Error(`invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`)}return data}const FeeCalculatorLayout=nu64("lamportsPerSignature");const NonceAccountLayout=struct([u32("version"),u32("state"),publicKey("authorizedPubkey"),publicKey("nonce"),struct([FeeCalculatorLayout],"feeCalculator")]);const NONCE_ACCOUNT_LENGTH=NonceAccountLayout.span;class NonceAccount{constructor(args){this.authorizedPubkey=void 0;this.nonce=void 0;this.feeCalculator=void 0;this.authorizedPubkey=args.authorizedPubkey;this.nonce=args.nonce;this.feeCalculator=args.feeCalculator}static fromAccountData(buffer){const nonceAccount=NonceAccountLayout.decode(toBuffer(buffer),0);return new NonceAccount({authorizedPubkey:new PublicKey(nonceAccount.authorizedPubkey),nonce:new PublicKey(nonceAccount.nonce).toString(),feeCalculator:nonceAccount.feeCalculator})}}class SystemInstruction{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(SYSTEM_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a SystemInstruction")}return type}static decodeCreateAccount(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{lamports:lamports,space:space,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.Create,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,newAccountPubkey:instruction.keys[1].pubkey,lamports:lamports,space:space,programId:new PublicKey(programId)}}static decodeTransfer(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{lamports:lamports}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.Transfer,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,lamports:lamports}}static decodeTransferWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{lamports:lamports,seed:seed,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,basePubkey:instruction.keys[1].pubkey,toPubkey:instruction.keys[2].pubkey,lamports:lamports,seed:seed,programId:new PublicKey(programId)}}static decodeAllocate(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{space:space}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.Allocate,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,space:space}}static decodeAllocateWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{base:base,seed:seed,space:space,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,basePubkey:new PublicKey(base),seed:seed,space:space,programId:new PublicKey(programId)}}static decodeAssign(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.Assign,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,programId:new PublicKey(programId)}}static decodeAssignWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{base:base,seed:seed,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,basePubkey:new PublicKey(base),seed:seed,programId:new PublicKey(programId)}}static decodeCreateWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{base:base,seed:seed,lamports:lamports,space:space,programId:programId}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,newAccountPubkey:instruction.keys[1].pubkey,basePubkey:new PublicKey(base),seed:seed,lamports:lamports,space:space,programId:new PublicKey(programId)}}static decodeNonceInitialize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{authorized:authorized}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:new PublicKey(authorized)}}static decodeNonceAdvance(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);decodeData(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey}}static decodeNonceWithdraw(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,5);const{lamports:lamports}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey,lamports:lamports}}static decodeNonceAuthorize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{authorized:authorized}=decodeData(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[1].pubkey,newAuthorizedPubkey:new PublicKey(authorized)}}static checkProgramId(programId){if(!programId.equals(SystemProgram.programId)){throw new Error("invalid instruction; programId is not SystemProgram")}}static checkKeyLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}const SYSTEM_INSTRUCTION_LAYOUTS=Object.freeze({Create:{index:0,layout:struct([u32("instruction"),ns64("lamports"),ns64("space"),publicKey("programId")])},Assign:{index:1,layout:struct([u32("instruction"),publicKey("programId")])},Transfer:{index:2,layout:struct([u32("instruction"),u64("lamports")])},CreateWithSeed:{index:3,layout:struct([u32("instruction"),publicKey("base"),rustString("seed"),ns64("lamports"),ns64("space"),publicKey("programId")])},AdvanceNonceAccount:{index:4,layout:struct([u32("instruction")])},WithdrawNonceAccount:{index:5,layout:struct([u32("instruction"),ns64("lamports")])},InitializeNonceAccount:{index:6,layout:struct([u32("instruction"),publicKey("authorized")])},AuthorizeNonceAccount:{index:7,layout:struct([u32("instruction"),publicKey("authorized")])},Allocate:{index:8,layout:struct([u32("instruction"),ns64("space")])},AllocateWithSeed:{index:9,layout:struct([u32("instruction"),publicKey("base"),rustString("seed"),ns64("space"),publicKey("programId")])},AssignWithSeed:{index:10,layout:struct([u32("instruction"),publicKey("base"),rustString("seed"),publicKey("programId")])},TransferWithSeed:{index:11,layout:struct([u32("instruction"),u64("lamports"),rustString("seed"),publicKey("programId")])}});class SystemProgram{constructor(){}static createAccount(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.Create;const data=encodeData(type,{lamports:params.lamports,space:params.space,programId:toBuffer(params.programId.toBuffer())});return new TransactionInstruction({keys:[{pubkey:params.fromPubkey,isSigner:true,isWritable:true},{pubkey:params.newAccountPubkey,isSigner:true,isWritable:true}],programId:this.programId,data:data})}static transfer(params){let data;let keys;if("basePubkey"in params){const type=SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;data=encodeData(type,{lamports:BigInt(params.lamports),seed:params.seed,programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.fromPubkey,isSigner:false,isWritable:true},{pubkey:params.basePubkey,isSigner:true,isWritable:false},{pubkey:params.toPubkey,isSigner:false,isWritable:true}]}else{const type=SYSTEM_INSTRUCTION_LAYOUTS.Transfer;data=encodeData(type,{lamports:BigInt(params.lamports)});keys=[{pubkey:params.fromPubkey,isSigner:true,isWritable:true},{pubkey:params.toPubkey,isSigner:false,isWritable:true}]}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}static assign(params){let data;let keys;if("basePubkey"in params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;data=encodeData(type,{base:toBuffer(params.basePubkey.toBuffer()),seed:params.seed,programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.accountPubkey,isSigner:false,isWritable:true},{pubkey:params.basePubkey,isSigner:true,isWritable:false}]}else{const type=SYSTEM_INSTRUCTION_LAYOUTS.Assign;data=encodeData(type,{programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.accountPubkey,isSigner:true,isWritable:true}]}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}static createAccountWithSeed(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;const data=encodeData(type,{base:toBuffer(params.basePubkey.toBuffer()),seed:params.seed,lamports:params.lamports,space:params.space,programId:toBuffer(params.programId.toBuffer())});let keys=[{pubkey:params.fromPubkey,isSigner:true,isWritable:true},{pubkey:params.newAccountPubkey,isSigner:false,isWritable:true}];if(params.basePubkey!=params.fromPubkey){keys.push({pubkey:params.basePubkey,isSigner:true,isWritable:false})}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}static createNonceAccount(params){const transaction=new Transaction;if("basePubkey"in params&&"seed"in params){transaction.add(SystemProgram.createAccountWithSeed({fromPubkey:params.fromPubkey,newAccountPubkey:params.noncePubkey,basePubkey:params.basePubkey,seed:params.seed,lamports:params.lamports,space:NONCE_ACCOUNT_LENGTH,programId:this.programId}))}else{transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.noncePubkey,lamports:params.lamports,space:NONCE_ACCOUNT_LENGTH,programId:this.programId}))}const initParams={noncePubkey:params.noncePubkey,authorizedPubkey:params.authorizedPubkey};transaction.add(this.nonceInitialize(initParams));return transaction}static nonceInitialize(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;const data=encodeData(type,{authorized:toBuffer(params.authorizedPubkey.toBuffer())});const instructionData={keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RECENT_BLOCKHASHES_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static nonceAdvance(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount;const data=encodeData(type);const instructionData={keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RECENT_BLOCKHASHES_PUBKEY,isSigner:false,isWritable:false},{pubkey:params.authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static nonceWithdraw(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount;const data=encodeData(type,{lamports:params.lamports});return new TransactionInstruction({keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:params.toPubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RECENT_BLOCKHASHES_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false},{pubkey:params.authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static nonceAuthorize(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;const data=encodeData(type,{authorized:toBuffer(params.newAuthorizedPubkey.toBuffer())});return new TransactionInstruction({keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:params.authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static allocate(params){let data;let keys;if("basePubkey"in params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;data=encodeData(type,{base:toBuffer(params.basePubkey.toBuffer()),seed:params.seed,space:params.space,programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.accountPubkey,isSigner:false,isWritable:true},{pubkey:params.basePubkey,isSigner:true,isWritable:false}]}else{const type=SYSTEM_INSTRUCTION_LAYOUTS.Allocate;data=encodeData(type,{space:params.space});keys=[{pubkey:params.accountPubkey,isSigner:true,isWritable:true}]}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}}SystemProgram.programId=new PublicKey("11111111111111111111111111111111");const CHUNK_SIZE=PACKET_DATA_SIZE-300;class Loader{constructor(){}static getMinNumSignatures(dataLength){return 2*(Math.ceil(dataLength/Loader.chunkSize)+1+1)}static async load(connection,payer,program,programId,data){{const balanceNeeded=await connection.getMinimumBalanceForRentExemption(data.length);const programInfo=await connection.getAccountInfo(program.publicKey,"confirmed");let transaction=null;if(programInfo!==null){if(programInfo.executable){console.error("Program load failed, account is already executable");return false}if(programInfo.data.length!==data.length){transaction=transaction||new Transaction;transaction.add(SystemProgram.allocate({accountPubkey:program.publicKey,space:data.length}))}if(!programInfo.owner.equals(programId)){transaction=transaction||new Transaction;transaction.add(SystemProgram.assign({accountPubkey:program.publicKey,programId:programId}))}if(programInfo.lamports<balanceNeeded){transaction=transaction||new Transaction;transaction.add(SystemProgram.transfer({fromPubkey:payer.publicKey,toPubkey:program.publicKey,lamports:balanceNeeded-programInfo.lamports}))}}else{transaction=(new Transaction).add(SystemProgram.createAccount({fromPubkey:payer.publicKey,newAccountPubkey:program.publicKey,lamports:balanceNeeded>0?balanceNeeded:1,space:data.length,programId:programId}))}if(transaction!==null){await sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"})}}const dataLayout=struct([u32("instruction"),u32("offset"),u32("bytesLength"),u32("bytesLengthPadding"),seq(u8("byte"),offset(u32(),-8),"bytes")]);const chunkSize=Loader.chunkSize;let offset$1=0;let array=data;let transactions=[];while(array.length>0){const bytes=array.slice(0,chunkSize);const data=buffer.Buffer.alloc(chunkSize+16);dataLayout.encode({instruction:0,offset:offset$1,bytes:bytes,bytesLength:0,bytesLengthPadding:0},data);const transaction=(new Transaction).add({keys:[{pubkey:program.publicKey,isSigner:true,isWritable:true}],programId:programId,data:data});transactions.push(sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"}));if(connection._rpcEndpoint.includes("solana.com")){const REQUESTS_PER_SECOND=4;await sleep(1e3/REQUESTS_PER_SECOND)}offset$1+=chunkSize;array=array.slice(chunkSize)}await Promise.all(transactions);{const dataLayout=struct([u32("instruction")]);const data=buffer.Buffer.alloc(dataLayout.span);dataLayout.encode({instruction:1},data);const transaction=(new Transaction).add({keys:[{pubkey:program.publicKey,isSigner:true,isWritable:true},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false}],programId:programId,data:data});await sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"})}return true}}Loader.chunkSize=CHUNK_SIZE;const BPF_LOADER_PROGRAM_ID=new PublicKey("BPFLoader2111111111111111111111111111111111");class BpfLoader{static getMinNumSignatures(dataLength){return Loader.getMinNumSignatures(dataLength)}static load(connection,payer,program,elf,loaderProgramId){return Loader.load(connection,payer,program,loaderProgramId,elf)}}class ComputeBudgetInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=u8("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a ComputeBudgetInstruction")}return type}static decodeRequestUnits(instruction){this.checkProgramId(instruction.programId);const{units:units,additionalFee:additionalFee}=decodeData(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits,instruction.data);return{units:units,additionalFee:additionalFee}}static decodeRequestHeapFrame(instruction){this.checkProgramId(instruction.programId);const{bytes:bytes}=decodeData(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame,instruction.data);return{bytes:bytes}}static checkProgramId(programId){if(!programId.equals(ComputeBudgetProgram.programId)){throw new Error("invalid instruction; programId is not ComputeBudgetProgram")}}}const COMPUTE_BUDGET_INSTRUCTION_LAYOUTS=Object.freeze({RequestUnits:{index:0,layout:struct([u8("instruction"),u32("units"),u32("additionalFee")])},RequestHeapFrame:{index:1,layout:struct([u8("instruction"),u32("bytes")])}});class ComputeBudgetProgram{constructor(){}static requestUnits(params){const type=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;const data=encodeData(type,params);return new TransactionInstruction({keys:[],programId:this.programId,data:data})}static requestHeapFrame(params){const type=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;const data=encodeData(type,params);return new TransactionInstruction({keys:[],programId:this.programId,data:data})}}ComputeBudgetProgram.programId=new PublicKey("ComputeBudget111111111111111111111111111111");var browserPonyfill={exports:{}};(function(module,exports){var global=typeof self!=="undefined"?self:commonjsGlobal;var __self__=function(){function F(){this.fetch=false;this.DOMException=global.DOMException}F.prototype=global;return new F}();(function(self){(function(exports){var support={searchParams:"URLSearchParams"in self,iterable:"Symbol"in self&&"iterator"in Symbol,blob:"FileReader"in self&&"Blob"in self&&function(){try{new Blob;return true}catch(e){return false}}(),formData:"FormData"in self,arrayBuffer:"ArrayBuffer"in self};function isDataView(obj){return obj&&DataView.prototype.isPrototypeOf(obj)}if(support.arrayBuffer){var viewClasses=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"];var isArrayBufferView=ArrayBuffer.isView||function(obj){return obj&&viewClasses.indexOf(Object.prototype.toString.call(obj))>-1}}function normalizeName(name){if(typeof name!=="string"){name=String(name)}if(/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)){throw new TypeError("Invalid character in header field name")}return name.toLowerCase()}function normalizeValue(value){if(typeof value!=="string"){value=String(value)}return value}function iteratorFor(items){var iterator={next:function(){var value=items.shift();return{done:value===undefined,value:value}}};if(support.iterable){iterator[Symbol.iterator]=function(){return iterator}}return iterator}function Headers(headers){this.map={};if(headers instanceof Headers){headers.forEach((function(value,name){this.append(name,value)}),this)}else if(Array.isArray(headers)){headers.forEach((function(header){this.append(header[0],header[1])}),this)}else if(headers){Object.getOwnPropertyNames(headers).forEach((function(name){this.append(name,headers[name])}),this)}}Headers.prototype.append=function(name,value){name=normalizeName(name);value=normalizeValue(value);var oldValue=this.map[name];this.map[name]=oldValue?oldValue+", "+value:value};Headers.prototype["delete"]=function(name){delete this.map[normalizeName(name)]};Headers.prototype.get=function(name){name=normalizeName(name);return this.has(name)?this.map[name]:null};Headers.prototype.has=function(name){return this.map.hasOwnProperty(normalizeName(name))};Headers.prototype.set=function(name,value){this.map[normalizeName(name)]=normalizeValue(value)};Headers.prototype.forEach=function(callback,thisArg){for(var name in this.map){if(this.map.hasOwnProperty(name)){callback.call(thisArg,this.map[name],name,this)}}};Headers.prototype.keys=function(){var items=[];this.forEach((function(value,name){items.push(name)}));return iteratorFor(items)};Headers.prototype.values=function(){var items=[];this.forEach((function(value){items.push(value)}));return iteratorFor(items)};Headers.prototype.entries=function(){var items=[];this.forEach((function(value,name){items.push([name,value])}));return iteratorFor(items)};if(support.iterable){Headers.prototype[Symbol.iterator]=Headers.prototype.entries}function consumed(body){if(body.bodyUsed){return Promise.reject(new TypeError("Already read"))}body.bodyUsed=true}function fileReaderReady(reader){return new Promise((function(resolve,reject){reader.onload=function(){resolve(reader.result)};reader.onerror=function(){reject(reader.error)}}))}function readBlobAsArrayBuffer(blob){var reader=new FileReader;var promise=fileReaderReady(reader);reader.readAsArrayBuffer(blob);return promise}function readBlobAsText(blob){var reader=new FileReader;var promise=fileReaderReady(reader);reader.readAsText(blob);return promise}function readArrayBufferAsText(buf){var view=new Uint8Array(buf);var chars=new Array(view.length);for(var i=0;i<view.length;i++){chars[i]=String.fromCharCode(view[i])}return chars.join("")}function bufferClone(buf){if(buf.slice){return buf.slice(0)}else{var view=new Uint8Array(buf.byteLength);view.set(new Uint8Array(buf));return view.buffer}}function Body(){this.bodyUsed=false;this._initBody=function(body){this._bodyInit=body;if(!body){this._bodyText=""}else if(typeof body==="string"){this._bodyText=body}else if(support.blob&&Blob.prototype.isPrototypeOf(body)){this._bodyBlob=body}else if(support.formData&&FormData.prototype.isPrototypeOf(body)){this._bodyFormData=body}else if(support.searchParams&&URLSearchParams.prototype.isPrototypeOf(body)){this._bodyText=body.toString()}else if(support.arrayBuffer&&support.blob&&isDataView(body)){this._bodyArrayBuffer=bufferClone(body.buffer);this._bodyInit=new Blob([this._bodyArrayBuffer])}else if(support.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(body)||isArrayBufferView(body))){this._bodyArrayBuffer=bufferClone(body)}else{this._bodyText=body=Object.prototype.toString.call(body)}if(!this.headers.get("content-type")){if(typeof body==="string"){this.headers.set("content-type","text/plain;charset=UTF-8")}else if(this._bodyBlob&&this._bodyBlob.type){this.headers.set("content-type",this._bodyBlob.type)}else if(support.searchParams&&URLSearchParams.prototype.isPrototypeOf(body)){this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8")}}};if(support.blob){this.blob=function(){var rejected=consumed(this);if(rejected){return rejected}if(this._bodyBlob){return Promise.resolve(this._bodyBlob)}else if(this._bodyArrayBuffer){return Promise.resolve(new Blob([this._bodyArrayBuffer]))}else if(this._bodyFormData){throw new Error("could not read FormData body as blob")}else{return Promise.resolve(new Blob([this._bodyText]))}};this.arrayBuffer=function(){if(this._bodyArrayBuffer){return consumed(this)||Promise.resolve(this._bodyArrayBuffer)}else{return this.blob().then(readBlobAsArrayBuffer)}}}this.text=function(){var rejected=consumed(this);if(rejected){return rejected}if(this._bodyBlob){return readBlobAsText(this._bodyBlob)}else if(this._bodyArrayBuffer){return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))}else if(this._bodyFormData){throw new Error("could not read FormData body as text")}else{return Promise.resolve(this._bodyText)}};if(support.formData){this.formData=function(){return this.text().then(decode)}}this.json=function(){return this.text().then(JSON.parse)};return this}var methods=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function normalizeMethod(method){var upcased=method.toUpperCase();return methods.indexOf(upcased)>-1?upcased:method}function Request(input,options){options=options||{};var body=options.body;if(input instanceof Request){if(input.bodyUsed){throw new TypeError("Already read")}this.url=input.url;this.credentials=input.credentials;if(!options.headers){this.headers=new Headers(input.headers)}this.method=input.method;this.mode=input.mode;this.signal=input.signal;if(!body&&input._bodyInit!=null){body=input._bodyInit;input.bodyUsed=true}}else{this.url=String(input)}this.credentials=options.credentials||this.credentials||"same-origin";if(options.headers||!this.headers){this.headers=new Headers(options.headers)}this.method=normalizeMethod(options.method||this.method||"GET");this.mode=options.mode||this.mode||null;this.signal=options.signal||this.signal;this.referrer=null;if((this.method==="GET"||this.method==="HEAD")&&body){throw new TypeError("Body not allowed for GET or HEAD requests")}this._initBody(body)}Request.prototype.clone=function(){return new Request(this,{body:this._bodyInit})};function decode(body){var form=new FormData;body.trim().split("&").forEach((function(bytes){if(bytes){var split=bytes.split("=");var name=split.shift().replace(/\+/g," ");var value=split.join("=").replace(/\+/g," ");form.append(decodeURIComponent(name),decodeURIComponent(value))}}));return form}function parseHeaders(rawHeaders){var headers=new Headers;var preProcessedHeaders=rawHeaders.replace(/\r?\n[\t ]+/g," ");preProcessedHeaders.split(/\r?\n/).forEach((function(line){var parts=line.split(":");var key=parts.shift().trim();if(key){var value=parts.join(":").trim();headers.append(key,value)}}));return headers}Body.call(Request.prototype);function Response(bodyInit,options){if(!options){options={}}this.type="default";this.status=options.status===undefined?200:options.status;this.ok=this.status>=200&&this.status<300;this.statusText="statusText"in options?options.statusText:"OK";this.headers=new Headers(options.headers);this.url=options.url||"";this._initBody(bodyInit)}Body.call(Response.prototype);Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url})};Response.error=function(){var response=new Response(null,{status:0,statusText:""});response.type="error";return response};var redirectStatuses=[301,302,303,307,308];Response.redirect=function(url,status){if(redirectStatuses.indexOf(status)===-1){throw new RangeError("Invalid status code")}return new Response(null,{status:status,headers:{location:url}})};exports.DOMException=self.DOMException;try{new exports.DOMException}catch(err){exports.DOMException=function(message,name){this.message=message;this.name=name;var error=Error(message);this.stack=error.stack};exports.DOMException.prototype=Object.create(Error.prototype);exports.DOMException.prototype.constructor=exports.DOMException}function fetch(input,init){return new Promise((function(resolve,reject){var request=new Request(input,init);if(request.signal&&request.signal.aborted){return reject(new exports.DOMException("Aborted","AbortError"))}var xhr=new XMLHttpRequest;function abortXhr(){xhr.abort()}xhr.onload=function(){var options={status:xhr.status,statusText:xhr.statusText,headers:parseHeaders(xhr.getAllResponseHeaders()||"")};options.url="responseURL"in xhr?xhr.responseURL:options.headers.get("X-Request-URL");var body="response"in xhr?xhr.response:xhr.responseText;resolve(new Response(body,options))};xhr.onerror=function(){reject(new TypeError("Network request failed"))};xhr.ontimeout=function(){reject(new TypeError("Network request failed"))};xhr.onabort=function(){reject(new exports.DOMException("Aborted","AbortError"))};xhr.open(request.method,request.url,true);if(request.credentials==="include"){xhr.withCredentials=true}else if(request.credentials==="omit"){xhr.withCredentials=false}if("responseType"in xhr&&support.blob){xhr.responseType="blob"}request.headers.forEach((function(value,name){xhr.setRequestHeader(name,value)}));if(request.signal){request.signal.addEventListener("abort",abortXhr);xhr.onreadystatechange=function(){if(xhr.readyState===4){request.signal.removeEventListener("abort",abortXhr)}}}xhr.send(typeof request._bodyInit==="undefined"?null:request._bodyInit)}))}fetch.polyfill=true;if(!self.fetch){self.fetch=fetch;self.Headers=Headers;self.Request=Request;self.Response=Response}exports.Headers=Headers;exports.Request=Request;exports.Response=Response;exports.fetch=fetch;Object.defineProperty(exports,"__esModule",{value:true});return exports})({})})(__self__);__self__.fetch.ponyfill=true;delete __self__.fetch.polyfill;var ctx=__self__;exports=ctx.fetch;exports.default=ctx.fetch;exports.fetch=ctx.fetch;exports.Headers=ctx.Headers;exports.Request=ctx.Request;exports.Response=ctx.Response;module.exports=exports})(browserPonyfill,browserPonyfill.exports);var crossFetch=getDefaultExportFromCjs(browserPonyfill.exports);var objToString=Object.prototype.toString;var objKeys=Object.keys||function(obj){var keys=[];for(var name in obj){keys.push(name)}return keys};function stringify(val,isArrayProp){var i,max,str,keys,key,propVal,toStr;if(val===true){return"true"}if(val===false){return"false"}switch(typeof val){case"object":if(val===null){return null}else if(val.toJSON&&typeof val.toJSON==="function"){return stringify(val.toJSON(),isArrayProp)}else{toStr=objToString.call(val);if(toStr==="[object Array]"){str="[";max=val.length-1;for(i=0;i<max;i++){str+=stringify(val[i],true)+","}if(max>-1){str+=stringify(val[i],true)}return str+"]"}else if(toStr==="[object Object]"){keys=objKeys(val).sort();max=keys.length;str="";i=0;while(i<max){key=keys[i];propVal=stringify(val[key],false);if(propVal!==undefined){if(str){str+=","}str+=JSON.stringify(key)+":"+propVal}i++}return"{"+str+"}"}else{return JSON.stringify(val)}}case"function":case"undefined":return isArrayProp?null:undefined;case"string":return JSON.stringify(val);default:return isFinite(val)?val:null}}var fastStableStringify=function(val){var returnVal=stringify(val,false);if(returnVal!==undefined){return""+returnVal}};var fastStableStringify$1=fastStableStringify;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;class TransactionExpiredBlockheightExceededError extends Error{constructor(signature){super(`Signature ${signature} has expired: block height exceeded.`);this.signature=void 0;this.signature=signature}}Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class TransactionExpiredTimeoutError extends Error{constructor(signature,timeoutSeconds){super(`Transaction was not confirmed in ${timeoutSeconds.toFixed(2)} seconds. It is `+"unknown if it succeeded or failed. Check signature "+`${signature} using the Solana Explorer or CLI tools.`);this.signature=void 0;this.signature=signature}}Object.defineProperty(TransactionExpiredTimeoutError.prototype,"name",{value:"TransactionExpiredTimeoutError"});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())}));const BlockProductionResponseStruct=jsonRpcResultAndContext(type({byIdentity:record(string(),array(number())),range:type({firstSlot:number(),lastSlot:number()})}));function createRpcClient(url,useHttps,httpHeaders,customFetch,fetchMiddleware,disableRetryOnRateLimit){const fetch=customFetch?customFetch:crossFetch;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._rpcWebSocketGeneration=0;this._disableBlockhashCaching=false;this._pollingBlockhash=false;this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]};this._nextClientSubscriptionId=0;this._subscriptionDisposeFunctionsByClientSubscriptionId={};this._subscriptionCallbacksByServerSubscriptionId={};this._subscriptionsByHash={};this._subscriptionsAutoDisposedByRpc=new Set;let url=new URL(endpoint);const useHttps=url.protocol==="https:";let wsEndpoint;let httpHeaders;let fetch;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;fetch=commitmentOrConfig.fetch;fetchMiddleware=commitmentOrConfig.fetchMiddleware;disableRetryOnRateLimit=commitmentOrConfig.disableRetryOnRateLimit}this._rpcEndpoint=endpoint;this._rpcWsEndpoint=wsEndpoint||makeWebsocketUrl(endpoint);this._rpcClient=createRpcClient(url.toString(),useHttps,httpHeaders,fetch,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}get rpcEndpoint(){return this._rpcEndpoint}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(strategy,commitment){let rawSignature;if(typeof strategy=="string"){rawSignature=strategy}else{const config=strategy;rawSignature=config.signature}let decodedSignature;try{decodedSignature=bs58$1.decode(rawSignature)}catch(err){throw new Error("signature must be base58 encoded: "+rawSignature)}assert$c(decodedSignature.length===64,"signature has invalid length");const subscriptionCommitment=commitment||this.commitment;let timeoutId;let subscriptionId;let done=false;const confirmationPromise=new Promise(((resolve,reject)=>{try{subscriptionId=this.onSignature(rawSignature,((result,context)=>{subscriptionId=undefined;const response={context:context,value:result};done=true;resolve({__type:exports.TransactionStatus.PROCESSED,response:response})}),subscriptionCommitment)}catch(err){reject(err)}}));const checkBlockHeight=async()=>{try{const blockHeight=await this.getBlockHeight(commitment);return blockHeight}catch(_e){return-1}};const expiryPromise=new Promise((resolve=>{if(typeof strategy==="string"){let timeoutMs=this._confirmTransactionInitialTimeout||60*1e3;switch(subscriptionCommitment){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":{timeoutMs=this._confirmTransactionInitialTimeout||30*1e3;break}}timeoutId=setTimeout((()=>resolve({__type:exports.TransactionStatus.TIMED_OUT,timeoutMs:timeoutMs})),timeoutMs)}else{let config=strategy;(async()=>{let currentBlockHeight=await checkBlockHeight();if(done)return;while(currentBlockHeight<=config.lastValidBlockHeight){await sleep(1e3);if(done)return;currentBlockHeight=await checkBlockHeight();if(done)return}resolve({__type:exports.TransactionStatus.BLOCKHEIGHT_EXCEEDED})})()}}));let result;try{const outcome=await Promise.race([confirmationPromise,expiryPromise]);switch(outcome.__type){case exports.TransactionStatus.BLOCKHEIGHT_EXCEEDED:throw new TransactionExpiredBlockheightExceededError(rawSignature);case exports.TransactionStatus.PROCESSED:result=outcome.response;break;case exports.TransactionStatus.TIMED_OUT:throw new TransactionExpiredTimeoutError(rawSignature,outcome.timeoutMs/1e3)}}finally{clearTimeout(timeoutId);if(subscriptionId){this.removeSignatureListener(subscriptionId)}}return result}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 getBlockHeight(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getBlockHeight",args);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new Error("failed to get block height information: "+res.error.message)}return res.result}async getBlockProduction(configOrCommitment){let extra;let commitment;if(typeof configOrCommitment==="string"){commitment=configOrCommitment}else if(configOrCommitment){const{commitment:c,...rest}=configOrCommitment;commitment=c;extra=rest}const args=this._buildArgs([],commitment,"base64",extra);const unsafeRes=await this._rpcRequest("getBlockProduction",args);const res=create(unsafeRes,BlockProductionResponseStruct);if("error"in res){throw new Error("failed to get block production information: "+res.error.message)}return res.result}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 getTransactions(signatures,commitment){const batch=signatures.map((signature=>{const args=this._buildArgsAtLeastConfirmed([signature],commitment);return{methodName:"getTransaction",args:args}}));const unsafeRes=await this._rpcBatchRequest(batch);const res=unsafeRes.map((unsafeRes=>{const res=create(unsafeRes,GetTransactionRpcResult);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 _blockhashWithExpiryBlockHeight(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.latestBlockhash!==null&&!expired){return this._blockhashInfo.latestBlockhash}}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=true;try{const startTime=Date.now();const cachedLatestBlockhash=this._blockhashInfo.latestBlockhash;const cachedBlockhash=cachedLatestBlockhash?cachedLatestBlockhash.blockhash:null;for(let i=0;i<50;i++){const latestBlockhash=await this.getLatestBlockhash("finalized");if(cachedBlockhash!==latestBlockhash.blockhash){this._blockhashInfo={latestBlockhash:latestBlockhash,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]};return latestBlockhash}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){let originalTx=transactionOrMessage;transaction=new Transaction;transaction.feePayer=originalTx.feePayer;transaction.instructions=transactionOrMessage.instructions;transaction.nonceInfo=originalTx.nonceInfo;transaction.signatures=originalTx.signatures}else{transaction=Transaction.populate(transactionOrMessage);transaction._message=transaction._json=undefined}if(transaction.nonceInfo&&signers){transaction.sign(...signers)}else{let disableCache=this._disableBlockhashCaching;for(;;){const latestBlockhash=await this._blockhashWithExpiryBlockHeight(disableCache);transaction.lastValidBlockHeight=latestBlockhash.lastValidBlockHeight;transaction.recentBlockhash=latestBlockhash.blockhash;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(;;){const latestBlockhash=await this._blockhashWithExpiryBlockHeight(disableCache);transaction.lastValidBlockHeight=latestBlockhash.lastValidBlockHeight;transaction.recentBlockhash=latestBlockhash.blockhash;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}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){this._rpcWebSocketConnected=false;console.error("ws error:",err.message)}_wsOnClose(code){this._rpcWebSocketConnected=false;this._rpcWebSocketGeneration++;if(this._rpcWebSocketHeartbeat){clearInterval(this._rpcWebSocketHeartbeat);this._rpcWebSocketHeartbeat=null}if(code===1e3){this._updateSubscriptions();return}this._subscriptionCallbacksByServerSubscriptionId={};Object.entries(this._subscriptionsByHash).forEach((([hash,subscription])=>{this._subscriptionsByHash[hash]={...subscription,state:"pending"}}))}async _updateSubscriptions(){if(Object.keys(this._subscriptionsByHash).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}const activeWebSocketGeneration=this._rpcWebSocketGeneration;const isCurrentConnectionStillActive=()=>activeWebSocketGeneration===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map((async hash=>{const subscription=this._subscriptionsByHash[hash];if(subscription===undefined){return}switch(subscription.state){case"pending":case"unsubscribed":if(subscription.callbacks.size===0){delete this._subscriptionsByHash[hash];if(subscription.state==="unsubscribed"){delete this._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId]}await this._updateSubscriptions();return}await(async()=>{const{args:args,method:method}=subscription;try{this._subscriptionsByHash[hash]={...subscription,state:"subscribing"};const serverSubscriptionId=await this._rpcWebSocket.call(method,args);this._subscriptionsByHash[hash]={...subscription,serverSubscriptionId:serverSubscriptionId,state:"subscribed"};this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId]=subscription.callbacks;await this._updateSubscriptions()}catch(e){if(e instanceof Error){console.error(`${method} error for argument`,args,e.message)}if(!isCurrentConnectionStillActive()){return}this._subscriptionsByHash[hash]={...subscription,state:"pending"};await this._updateSubscriptions()}})();break;case"subscribed":if(subscription.callbacks.size===0){await(async()=>{const{serverSubscriptionId:serverSubscriptionId,unsubscribeMethod:unsubscribeMethod}=subscription;if(this._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)){this._subscriptionsAutoDisposedByRpc.delete(serverSubscriptionId)}else{this._subscriptionsByHash[hash]={...subscription,state:"unsubscribing"};try{await this._rpcWebSocket.call(unsubscribeMethod,[serverSubscriptionId])}catch(e){if(e instanceof Error){console.error(`${unsubscribeMethod} error:`,e.message)}if(!isCurrentConnectionStillActive()){return}this._subscriptionsByHash[hash]={...subscription,state:"subscribed"};await this._updateSubscriptions();return}}this._subscriptionsByHash[hash]={...subscription,state:"unsubscribed"};await this._updateSubscriptions()})()}break}})))}_handleServerNotification(serverSubscriptionId,callbackArgs){const callbacks=this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId];if(callbacks===undefined){return}callbacks.forEach((cb=>{try{cb(...callbackArgs)}catch(e){console.error(e)}}))}_wsOnAccountNotification(notification){const{result:result,subscription:subscription}=create(notification,AccountNotificationResult);this._handleServerNotification(subscription,[result.value,result.context])}_makeSubscription(subscriptionConfig,args){const clientSubscriptionId=this._nextClientSubscriptionId++;const hash=fastStableStringify$1([subscriptionConfig.method,args],true);const existingSubscription=this._subscriptionsByHash[hash];if(existingSubscription===undefined){this._subscriptionsByHash[hash]={...subscriptionConfig,args:args,callbacks:new Set([subscriptionConfig.callback]),state:"pending"}}else{existingSubscription.callbacks.add(subscriptionConfig.callback)}this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];const subscription=this._subscriptionsByHash[hash];assert$c(subscription!==undefined,`Could not find a \`Subscription\` when tearing down client subscription #${clientSubscriptionId}`);subscription.callbacks.delete(subscriptionConfig.callback);await this._updateSubscriptions()};this._updateSubscriptions();return clientSubscriptionId}onAccountChange(publicKey,callback,commitment){const args=this._buildArgs([publicKey.toBase58()],commitment||this._commitment||"finalized","base64");return this._makeSubscription({callback:callback,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},args)}async removeAccountChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"account change")}_wsOnProgramAccountNotification(notification){const{result:result,subscription:subscription}=create(notification,ProgramAccountNotificationResult);this._handleServerNotification(subscription,[{accountId:result.value.pubkey,accountInfo:result.value.account},result.context])}onProgramAccountChange(programId,callback,commitment,filters){const args=this._buildArgs([programId.toBase58()],commitment||this._commitment||"finalized","base64",filters?{filters:filters}:undefined);return this._makeSubscription({callback:callback,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},args)}async removeProgramAccountChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"program account change")}onLogs(filter,callback,commitment){const args=this._buildArgs([typeof filter==="object"?{mentions:[filter.toString()]}:filter],commitment||this._commitment||"finalized");return this._makeSubscription({callback:callback,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},args)}async removeOnLogsListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"logs")}_wsOnLogsNotification(notification){const{result:result,subscription:subscription}=create(notification,LogsNotificationResult);this._handleServerNotification(subscription,[result.value,result.context])}_wsOnSlotNotification(notification){const{result:result,subscription:subscription}=create(notification,SlotNotificationResult);this._handleServerNotification(subscription,[result])}onSlotChange(callback){return this._makeSubscription({callback:callback,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"slot change")}_wsOnSlotUpdatesNotification(notification){const{result:result,subscription:subscription}=create(notification,SlotUpdateNotificationResult);this._handleServerNotification(subscription,[result])}onSlotUpdate(callback){return this._makeSubscription({callback:callback,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"slot update")}async _unsubscribeClientSubscription(clientSubscriptionId,subscriptionName){const dispose=this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];if(dispose){await dispose()}else{console.warn("Ignored unsubscribe request because an active subscription with id "+`\`${clientSubscriptionId}\` for '${subscriptionName}' events `+"could not be found.")}}_buildArgs(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment||encoding||extra){let options={};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{result:result,subscription:subscription}=create(notification,SignatureNotificationResult);if(result.value!=="receivedSignature"){this._subscriptionsAutoDisposedByRpc.add(subscription)}this._handleServerNotification(subscription,result.value==="receivedSignature"?[{type:"received"},result.context]:[{type:"status",result:result.value},result.context])}onSignature(signature,callback,commitment){const args=this._buildArgs([signature],commitment||this._commitment||"finalized");const clientSubscriptionId=this._makeSubscription({callback:(notification,context)=>{if(notification.type==="status"){callback(notification.result,context);try{this.removeSignatureListener(clientSubscriptionId)}catch(_err){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},args);return clientSubscriptionId}onSignatureWithOptions(signature,callback,options){const{commitment:commitment,...extra}={...options,commitment:options&&options.commitment||this._commitment||"finalized"};const args=this._buildArgs([signature],commitment,undefined,extra);const clientSubscriptionId=this._makeSubscription({callback:(notification,context)=>{callback(notification,context);try{this.removeSignatureListener(clientSubscriptionId)}catch(_err){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},args);return clientSubscriptionId}async removeSignatureListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"signature result")}_wsOnRootNotification(notification){const{result:result,subscription:subscription}=create(notification,RootNotificationResult);this._handleServerNotification(subscription,[result])}onRootChange(callback){return this._makeSubscription({callback:callback,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"root change")}}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);const index=instructionIndex==null?65535:instructionIndex;ED25519_INSTRUCTION_LAYOUT.encode({numSignatures:numSignatures,padding:0,signatureOffset:signatureOffset,signatureInstructionIndex:index,publicKeyOffset:publicKeyOffset,publicKeyInstructionIndex:index,messageDataOffset:messageDataOffset,messageDataSize:message.length,messageInstructionIndex:index},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{publicKeyCreate:publicKeyCreate,ecdsaSign:ecdsaSign}=secp256k1;const PRIVATE_KEY_BYTES=32;const ETHEREUM_ADDRESS_BYTES=20;const PUBLIC_KEY_BYTES=64;const SIGNATURE_OFFSETS_SERIALIZED_SIZE=11;const SECP256K1_INSTRUCTION_LAYOUT=struct([u8("numSignatures"),u16("signatureOffset"),u8("signatureInstructionIndex"),u16("ethAddressOffset"),u8("ethAddressInstructionIndex"),u16("messageDataOffset"),u16("messageDataSize"),u8("messageInstructionIndex"),blob(20,"ethAddress"),blob(64,"signature"),u8("recoveryId")]);class Secp256k1Program{constructor(){}static publicKeyToEthAddress(publicKey){assert$c(publicKey.length===PUBLIC_KEY_BYTES,`Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`);try{return buffer.Buffer.from(sha3.keccak_256.update(toBuffer(publicKey)).digest()).slice(-ETHEREUM_ADDRESS_BYTES)}catch(error){throw new Error(`Error constructing Ethereum address: ${error}`)}}static createInstructionWithPublicKey(params){const{publicKey:publicKey,message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex}=params;return Secp256k1Program.createInstructionWithEthAddress({ethAddress:Secp256k1Program.publicKeyToEthAddress(publicKey),message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex})}static createInstructionWithEthAddress(params){const{ethAddress:rawAddress,message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex=0}=params;let ethAddress;if(typeof rawAddress==="string"){if(rawAddress.startsWith("0x")){ethAddress=buffer.Buffer.from(rawAddress.substr(2),"hex")}else{ethAddress=buffer.Buffer.from(rawAddress,"hex")}}else{ethAddress=rawAddress}assert$c(ethAddress.length===ETHEREUM_ADDRESS_BYTES,`Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`);const dataStart=1+SIGNATURE_OFFSETS_SERIALIZED_SIZE;const ethAddressOffset=dataStart;const signatureOffset=dataStart+ethAddress.length;const messageDataOffset=signatureOffset+signature.length+1;const numSignatures=1;const instructionData=buffer.Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span+message.length);SECP256K1_INSTRUCTION_LAYOUT.encode({numSignatures:numSignatures,signatureOffset:signatureOffset,signatureInstructionIndex:instructionIndex,ethAddressOffset:ethAddressOffset,ethAddressInstructionIndex:instructionIndex,messageDataOffset:messageDataOffset,messageDataSize:message.length,messageInstructionIndex:instructionIndex,signature:toBuffer(signature),ethAddress:toBuffer(ethAddress),recoveryId:recoveryId},instructionData);instructionData.fill(toBuffer(message),SECP256K1_INSTRUCTION_LAYOUT.span);return new TransactionInstruction({keys:[],programId:Secp256k1Program.programId,data:instructionData})}static createInstructionWithPrivateKey(params){const{privateKey:pkey,message:message,instructionIndex:instructionIndex}=params;assert$c(pkey.length===PRIVATE_KEY_BYTES,`Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`);try{const privateKey=toBuffer(pkey);const publicKey=publicKeyCreate(privateKey,false).slice(1);const messageHash=buffer.Buffer.from(sha3.keccak_256.update(toBuffer(message)).digest());const{signature:signature,recid:recoveryId}=ecdsaSign(messageHash,privateKey);return this.createInstructionWithPublicKey({publicKey:publicKey,message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex})}catch(error){throw new Error(`Error creating instruction; ${error}`)}}}Secp256k1Program.programId=new PublicKey("KeccakSecp256k11111111111111111111111111111");const VALIDATOR_INFO_KEY=new PublicKey("Va1idator1nfo111111111111111111111111111111");const InfoString=type({name:string(),website:optional(string()),details:optional(string()),keybaseUsername:optional(string())});class ValidatorInfo{constructor(key,info){this.key=void 0;this.info=void 0;this.key=key;this.info=info}static fromConfigData(buffer$1){const PUBKEY_LENGTH=32;let byteArray=[...buffer$1];const configKeyCount=decodeLength(byteArray);if(configKeyCount!==2)return null;const configKeys=[];for(let i=0;i<2;i++){const publicKey=new PublicKey(byteArray.slice(0,PUBKEY_LENGTH));byteArray=byteArray.slice(PUBKEY_LENGTH);const isSigner=byteArray.slice(0,1)[0]===1;byteArray=byteArray.slice(1);configKeys.push({publicKey:publicKey,isSigner:isSigner})}if(configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)){if(configKeys[1].isSigner){const rawInfo=rustString().decode(buffer.Buffer.from(byteArray));const info=JSON.parse(rawInfo);assert$b(info,InfoString);return new ValidatorInfo(configKeys[1].publicKey,info)}}return null}}const VOTE_PROGRAM_ID=new PublicKey("Vote111111111111111111111111111111111111111");const VoteAccountLayout=struct([publicKey("nodePubkey"),publicKey("authorizedWithdrawer"),u8("commission"),nu64(),seq(struct([nu64("slot"),u32("confirmationCount")]),offset(u32(),-8),"votes"),u8("rootSlotValid"),nu64("rootSlot"),nu64(),seq(struct([nu64("epoch"),publicKey("authorizedVoter")]),offset(u32(),-8),"authorizedVoters"),struct([seq(struct([publicKey("authorizedPubkey"),nu64("epochOfLastAuthorizedSwitch"),nu64("targetEpoch")]),32,"buf"),nu64("idx"),u8("isEmpty")],"priorVoters"),nu64(),seq(struct([nu64("epoch"),nu64("credits"),nu64("prevCredits")]),offset(u32(),-8),"epochCredits"),struct([nu64("slot"),nu64("timestamp")],"lastTimestamp")]);class VoteAccount{constructor(args){this.nodePubkey=void 0;this.authorizedWithdrawer=void 0;this.commission=void 0;this.rootSlot=void 0;this.votes=void 0;this.authorizedVoters=void 0;this.priorVoters=void 0;this.epochCredits=void 0;this.lastTimestamp=void 0;this.nodePubkey=args.nodePubkey;this.authorizedWithdrawer=args.authorizedWithdrawer;this.commission=args.commission;this.rootSlot=args.rootSlot;this.votes=args.votes;this.authorizedVoters=args.authorizedVoters;this.priorVoters=args.priorVoters;this.epochCredits=args.epochCredits;this.lastTimestamp=args.lastTimestamp}static fromAccountData(buffer){const versionOffset=4;const va=VoteAccountLayout.decode(toBuffer(buffer),versionOffset);let rootSlot=va.rootSlot;if(!va.rootSlotValid){rootSlot=null}return new VoteAccount({nodePubkey:new PublicKey(va.nodePubkey),authorizedWithdrawer:new PublicKey(va.authorizedWithdrawer),commission:va.commission,votes:va.votes,rootSlot:rootSlot,authorizedVoters:va.authorizedVoters.map(parseAuthorizedVoter),priorVoters:getPriorVoters(va.priorVoters),epochCredits:va.epochCredits,lastTimestamp:va.lastTimestamp})}}function parseAuthorizedVoter({authorizedVoter:authorizedVoter,epoch:epoch}){return{epoch:epoch,authorizedVoter:new PublicKey(authorizedVoter)}}function parsePriorVoters({authorizedPubkey:authorizedPubkey,epochOfLastAuthorizedSwitch:epochOfLastAuthorizedSwitch,targetEpoch:targetEpoch}){return{authorizedPubkey:new PublicKey(authorizedPubkey),epochOfLastAuthorizedSwitch:epochOfLastAuthorizedSwitch,targetEpoch:targetEpoch}}function getPriorVoters({buf:buf,idx:idx,isEmpty:isEmpty}){if(isEmpty){return[]}return[...buf.slice(idx+1).map(parsePriorVoters),...buf.slice(0,idx).map(parsePriorVoters)]}class VoteInit{constructor(nodePubkey,authorizedVoter,authorizedWithdrawer,commission){this.nodePubkey=void 0;this.authorizedVoter=void 0;this.authorizedWithdrawer=void 0;this.commission=void 0;this.nodePubkey=nodePubkey;this.authorizedVoter=authorizedVoter;this.authorizedWithdrawer=authorizedWithdrawer;this.commission=commission}}class VoteInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=u32("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(VOTE_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a VoteInstruction")}return type}static decodeInitializeAccount(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,4);const{voteInit:voteInit}=decodeData(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount,instruction.data);return{votePubkey:instruction.keys[0].pubkey,nodePubkey:instruction.keys[3].pubkey,voteInit:new VoteInit(new PublicKey(voteInit.nodePubkey),new PublicKey(voteInit.authorizedVoter),new PublicKey(voteInit.authorizedWithdrawer),voteInit.commission)}}static decodeAuthorize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{newAuthorized:newAuthorized,voteAuthorizationType:voteAuthorizationType}=decodeData(VOTE_INSTRUCTION_LAYOUTS.Authorize,instruction.data);return{votePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey,newAuthorizedPubkey:new PublicKey(newAuthorized),voteAuthorizationType:{index:voteAuthorizationType}}}static decodeWithdraw(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{lamports:lamports}=decodeData(VOTE_INSTRUCTION_LAYOUTS.Withdraw,instruction.data);return{votePubkey:instruction.keys[0].pubkey,authorizedWithdrawerPubkey:instruction.keys[2].pubkey,lamports:lamports,toPubkey:instruction.keys[1].pubkey}}static checkProgramId(programId){if(!programId.equals(VoteProgram.programId)){throw new Error("invalid instruction; programId is not VoteProgram")}}static checkKeyLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}const VOTE_INSTRUCTION_LAYOUTS=Object.freeze({InitializeAccount:{index:0,layout:struct([u32("instruction"),voteInit()])},Authorize:{index:1,layout:struct([u32("instruction"),publicKey("newAuthorized"),u32("voteAuthorizationType")])},Withdraw:{index:3,layout:struct([u32("instruction"),ns64("lamports")])}});const VoteAuthorizationLayout=Object.freeze({Voter:{index:0},Withdrawer:{index:1}});class VoteProgram{constructor(){}static initializeAccount(params){const{votePubkey:votePubkey,nodePubkey:nodePubkey,voteInit:voteInit}=params;const type=VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;const data=encodeData(type,{voteInit:{nodePubkey:toBuffer(voteInit.nodePubkey.toBuffer()),authorizedVoter:toBuffer(voteInit.authorizedVoter.toBuffer()),authorizedWithdrawer:toBuffer(voteInit.authorizedWithdrawer.toBuffer()),commission:voteInit.commission}});const instructionData={keys:[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:nodePubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static createAccount(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.votePubkey,lamports:params.lamports,space:this.space,programId:this.programId}));return transaction.add(this.initializeAccount({votePubkey:params.votePubkey,nodePubkey:params.voteInit.nodePubkey,voteInit:params.voteInit}))}static authorize(params){const{votePubkey:votePubkey,authorizedPubkey:authorizedPubkey,newAuthorizedPubkey:newAuthorizedPubkey,voteAuthorizationType:voteAuthorizationType}=params;const type=VOTE_INSTRUCTION_LAYOUTS.Authorize;const data=encodeData(type,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),voteAuthorizationType:voteAuthorizationType.index});const keys=[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}];return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static withdraw(params){const{votePubkey:votePubkey,authorizedWithdrawerPubkey:authorizedWithdrawerPubkey,lamports:lamports,toPubkey:toPubkey}=params;const type=VOTE_INSTRUCTION_LAYOUTS.Withdraw;const data=encodeData(type,{lamports:lamports});const keys=[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:toPubkey,isSigner:false,isWritable:true},{pubkey:authorizedWithdrawerPubkey,isSigner:true,isWritable:false}];return(new Transaction).add({keys:keys,programId:this.programId,data:data})}}VoteProgram.programId=new PublicKey("Vote111111111111111111111111111111111111111");VoteProgram.space=3731;async function sendAndConfirmRawTransaction(connection,rawTransaction,confirmationStrategyOrConfirmOptions,maybeConfirmOptions){let confirmationStrategy;let options;if(confirmationStrategyOrConfirmOptions&&Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions,"lastValidBlockHeight")){confirmationStrategy=confirmationStrategyOrConfirmOptions;options=maybeConfirmOptions}else{options=confirmationStrategyOrConfirmOptions}const sendOptions=options&&{skipPreflight:options.skipPreflight,preflightCommitment:options.preflightCommitment||options.commitment};const signature=await connection.sendRawTransaction(rawTransaction,sendOptions);const commitment=options&&options.commitment;const confirmationPromise=confirmationStrategy?connection.confirmTransaction(confirmationStrategy,commitment):connection.confirmTransaction(signature,commitment);const status=(await confirmationPromise).value;if(status.err){throw new Error(`Raw transaction ${signature} failed (${JSON.stringify(status)})`)}return signature}const endpoint={http:{devnet:"http://api.devnet.solana.com",testnet:"http://api.testnet.solana.com","mainnet-beta":"http://api.mainnet-beta.solana.com/"},https:{devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com","mainnet-beta":"https://api.mainnet-beta.solana.com/"}};function clusterApiUrl(cluster,tls){const key=tls===false?"http":"https";if(!cluster){return endpoint[key]["devnet"]}const url=endpoint[key][cluster];if(!url){throw new Error(`Unknown ${key} cluster: ${cluster}`)}return url}const LAMPORTS_PER_SOL=1e9;exports.Account=Account;exports.Authorized=Authorized;exports.BLOCKHASH_CACHE_TIMEOUT_MS=BLOCKHASH_CACHE_TIMEOUT_MS;exports.BPF_LOADER_DEPRECATED_PROGRAM_ID=BPF_LOADER_DEPRECATED_PROGRAM_ID;exports.BPF_LOADER_PROGRAM_ID=BPF_LOADER_PROGRAM_ID;exports.BpfLoader=BpfLoader;exports.COMPUTE_BUDGET_INSTRUCTION_LAYOUTS=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS;exports.ComputeBudgetInstruction=ComputeBudgetInstruction;exports.ComputeBudgetProgram=ComputeBudgetProgram;exports.Connection=Connection;exports.Ed25519Program=Ed25519Program;exports.Enum=Enum;exports.EpochSchedule=EpochSchedule;exports.FeeCalculatorLayout=FeeCalculatorLayout;exports.Keypair=Keypair;exports.LAMPORTS_PER_SOL=LAMPORTS_PER_SOL;exports.Loader=Loader;exports.Lockup=Lockup;exports.MAX_SEED_LENGTH=MAX_SEED_LENGTH;exports.Message=Message;exports.NONCE_ACCOUNT_LENGTH=NONCE_ACCOUNT_LENGTH;exports.NonceAccount=NonceAccount;exports.PACKET_DATA_SIZE=PACKET_DATA_SIZE;exports.PublicKey=PublicKey;exports.SIGNATURE_LENGTH_IN_BYTES=SIGNATURE_LENGTH_IN_BYTES;exports.SOLANA_SCHEMA=SOLANA_SCHEMA;exports.STAKE_CONFIG_ID=STAKE_CONFIG_ID;exports.STAKE_INSTRUCTION_LAYOUTS=STAKE_INSTRUCTION_LAYOUTS;exports.SYSTEM_INSTRUCTION_LAYOUTS=SYSTEM_INSTRUCTION_LAYOUTS;exports.SYSVAR_CLOCK_PUBKEY=SYSVAR_CLOCK_PUBKEY;exports.SYSVAR_EPOCH_SCHEDULE_PUBKEY=SYSVAR_EPOCH_SCHEDULE_PUBKEY;exports.SYSVAR_INSTRUCTIONS_PUBKEY=SYSVAR_INSTRUCTIONS_PUBKEY;exports.SYSVAR_RECENT_BLOCKHASHES_PUBKEY=SYSVAR_RECENT_BLOCKHASHES_PUBKEY;exports.SYSVAR_RENT_PUBKEY=SYSVAR_RENT_PUBKEY;exports.SYSVAR_REWARDS_PUBKEY=SYSVAR_REWARDS_PUBKEY;exports.SYSVAR_SLOT_HASHES_PUBKEY=SYSVAR_SLOT_HASHES_PUBKEY;exports.SYSVAR_SLOT_HISTORY_PUBKEY=SYSVAR_SLOT_HISTORY_PUBKEY;exports.SYSVAR_STAKE_HISTORY_PUBKEY=SYSVAR_STAKE_HISTORY_PUBKEY;exports.Secp256k1Program=Secp256k1Program;exports.SendTransactionError=SendTransactionError;exports.StakeAuthorizationLayout=StakeAuthorizationLayout;exports.StakeInstruction=StakeInstruction;exports.StakeProgram=StakeProgram;exports.Struct=Struct$1;exports.SystemInstruction=SystemInstruction;exports.SystemProgram=SystemProgram;exports.Transaction=Transaction;exports.TransactionInstruction=TransactionInstruction;exports.VALIDATOR_INFO_KEY=VALIDATOR_INFO_KEY;exports.VOTE_PROGRAM_ID=VOTE_PROGRAM_ID;exports.ValidatorInfo=ValidatorInfo;exports.VoteAccount=VoteAccount;exports.VoteAuthorizationLayout=VoteAuthorizationLayout;exports.VoteInit=VoteInit;exports.VoteInstruction=VoteInstruction;exports.VoteProgram=VoteProgram;exports.clusterApiUrl=clusterApiUrl;exports.sendAndConfirmRawTransaction=sendAndConfirmRawTransaction;exports.sendAndConfirmTransaction=sendAndConfirmTransaction;Object.defineProperty(exports,"__esModule",{value:true});return exports}({});
18
18
  //# sourceMappingURL=index.iife.min.js.map