{"version":3,"sources":["jsdelivr-header.js","/npm/@solana/web3.js@1.87.6/src/utils/ed25519.ts","/npm/@solana/web3.js@1.87.6/src/utils/to-buffer.ts","/npm/@solana/web3.js@1.87.6/src/utils/borsh-schema.ts","/npm/@solana/web3.js@1.87.6/src/publickey.ts","/npm/@solana/web3.js@1.87.6/src/account.ts","/npm/@solana/web3.js@1.87.6/src/bpf-loader-deprecated.ts","/npm/@solana/web3.js@1.87.6/src/transaction/constants.ts","/npm/@solana/web3.js@1.87.6/src/transaction/expiry-custom-errors.ts","/npm/@solana/web3.js@1.87.6/src/message/account-keys.ts","/npm/@solana/web3.js@1.87.6/src/layout.ts","/npm/@solana/web3.js@1.87.6/src/utils/shortvec-encoding.ts","/npm/@solana/web3.js@1.87.6/src/utils/assert.ts","/npm/@solana/web3.js@1.87.6/src/message/compiled-keys.ts","/npm/@solana/web3.js@1.87.6/src/message/legacy.ts","/npm/@solana/web3.js@1.87.6/src/message/v0.ts","/npm/@solana/web3.js@1.87.6/src/message/versioned.ts","/npm/@solana/web3.js@1.87.6/src/transaction/legacy.ts","/npm/@solana/web3.js@1.87.6/src/transaction/message.ts","/npm/@solana/web3.js@1.87.6/src/transaction/versioned.ts","/npm/@solana/web3.js@1.87.6/src/timing.ts","/npm/@solana/web3.js@1.87.6/src/sysvar.ts","/npm/@solana/web3.js@1.87.6/src/utils/send-and-confirm-transaction.ts","/npm/@solana/web3.js@1.87.6/src/utils/sleep.ts","/npm/@solana/web3.js@1.87.6/src/instruction.ts","/npm/@solana/web3.js@1.87.6/src/fee-calculator.ts","/npm/@solana/web3.js@1.87.6/src/nonce-account.ts","/npm/@solana/web3.js@1.87.6/src/utils/bigint.ts","/npm/@solana/web3.js@1.87.6/src/programs/system.ts","/npm/@solana/web3.js@1.87.6/src/loader.ts","/npm/@solana/web3.js@1.87.6/src/bpf-loader.ts","/npm/node_modules/.pnpm/fast-stable-stringify@1.0.0/node_modules/fast-stable-stringify/index.js","/npm/@solana/web3.js@1.87.6/src/epoch-schedule.ts","/npm/@solana/web3.js@1.87.6/src/errors.ts","/npm/@solana/web3.js@1.87.6/src/__forks__/browser/fetch-impl.ts","/npm/@solana/web3.js@1.87.6/src/rpc-websocket.ts","/npm/@solana/web3.js@1.87.6/src/programs/address-lookup-table/state.ts","/npm/@solana/web3.js@1.87.6/src/account-data.ts","/npm/@solana/web3.js@1.87.6/src/utils/makeWebsocketUrl.ts","/npm/@solana/web3.js@1.87.6/src/connection.ts","/npm/@solana/web3.js@1.87.6/src/keypair.ts","/npm/@solana/web3.js@1.87.6/src/programs/address-lookup-table/index.ts","/npm/@solana/web3.js@1.87.6/src/programs/compute-budget.ts","/npm/@solana/web3.js@1.87.6/src/programs/ed25519.ts","/npm/@solana/web3.js@1.87.6/src/utils/secp256k1.ts","/npm/@solana/web3.js@1.87.6/src/programs/secp256k1.ts","/npm/@solana/web3.js@1.87.6/src/programs/stake.ts","/npm/@solana/web3.js@1.87.6/src/programs/vote.ts","/npm/@solana/web3.js@1.87.6/src/validator-info.ts","/npm/@solana/web3.js@1.87.6/src/vote-account.ts","/npm/@solana/web3.js@1.87.6/src/utils/cluster.ts","/npm/@solana/web3.js@1.87.6/src/utils/send-and-confirm-raw-transaction.ts","/npm/@solana/web3.js@1.87.6/src/index.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,2tsBCWO,MAAM,GAAqB,EAAQ,MAAM,iBACnC,GAAkB,KAC7B,MAAM,EAAgB,EAAQ,MAAM,mBAC9B,EAAY,GAAa,GACzB,EAAY,IAAI,WAAW,IAGjC,OAFA,EAAU,IAAI,GACd,EAAU,IAAI,EAAW,IAClB,CACL,YACA,YACD,EAEU,GAAe,EAAQ,aAC7B,SAAS,GAAU,GACxB,IAEE,OADA,EAAQ,cAAc,QAAQ,IACvB,CACT,CAAE,MACA,OAAO,CACT,CACF,CACO,MAAM,GAAO,CAClB,EACA,IACG,EAAQ,KAAK,EAAS,EAAU,MAAM,EAAG,KACjC,GAAS,EAAQ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B,EACxB,EAAW,mBAAmB,EAAsB,GACpD,EAAW,mBAAmB,EAAW,GACvC,SAAgB,GAAqB,MAE3C,GAAI,EAAO,IACT,MAAM,IAAI,MACP,mBAAkB,aAAqB,KAAK,UAAU,OAI3D,OAAO,CACT,CC9EO,MAAM,GAAmB,W","file":"/npm/@solana/web3.js@1.87.6/lib/index.browser.esm.js/+esm","sourceRoot":"","sourcesContent":["/**\n * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0.\n * Original file: /npm/@solana/web3.js@1.87.6/lib/index.browser.esm.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","import {ed25519} from '@noble/curves/ed25519';\n\n/**\n * A 64 byte secret key, the first 32 bytes of which is the\n * private scalar and the last 32 bytes is the public key.\n * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/\n */\ntype Ed25519SecretKey = Uint8Array;\n\n/**\n * Ed25519 Keypair\n */\nexport interface Ed25519Keypair {\n  publicKey: Uint8Array;\n  secretKey: Ed25519SecretKey;\n}\n\nexport const generatePrivateKey = ed25519.utils.randomPrivateKey;\nexport const generateKeypair = (): Ed25519Keypair => {\n  const privateScalar = ed25519.utils.randomPrivateKey();\n  const publicKey = getPublicKey(privateScalar);\n  const secretKey = new Uint8Array(64);\n  secretKey.set(privateScalar);\n  secretKey.set(publicKey, 32);\n  return {\n    publicKey,\n    secretKey,\n  };\n};\nexport const getPublicKey = ed25519.getPublicKey;\nexport function isOnCurve(publicKey: Uint8Array): boolean {\n  try {\n    ed25519.ExtendedPoint.fromHex(publicKey);\n    return true;\n  } catch {\n    return false;\n  }\n}\nexport const sign = (\n  message: Parameters<typeof ed25519.sign>[0],\n  secretKey: Ed25519SecretKey,\n) => ed25519.sign(message, secretKey.slice(0, 32));\nexport const verify = ed25519.verify;\n","import {Buffer} from 'buffer';\n\nexport const toBuffer = (arr: Buffer | Uint8Array | Array<number>): Buffer => {\n  if (Buffer.isBuffer(arr)) {\n    return arr;\n  } else if (arr instanceof Uint8Array) {\n    return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);\n  } else {\n    return Buffer.from(arr);\n  }\n};\n","import {Buffer} from 'buffer';\nimport {serialize, deserialize, deserializeUnchecked} from 'borsh';\n\n// Class wrapping a plain object\nexport class Struct {\n  constructor(properties: any) {\n    Object.assign(this, properties);\n  }\n\n  encode(): Buffer {\n    return Buffer.from(serialize(SOLANA_SCHEMA, this));\n  }\n\n  static decode(data: Buffer): any {\n    return deserialize(SOLANA_SCHEMA, this, data);\n  }\n\n  static decodeUnchecked(data: Buffer): any {\n    return deserializeUnchecked(SOLANA_SCHEMA, this, data);\n  }\n}\n\n// Class representing a Rust-compatible enum, since enums are only strings or\n// numbers in pure JS\nexport class Enum extends Struct {\n  enum: string = '';\n  constructor(properties: any) {\n    super(properties);\n    if (Object.keys(properties).length !== 1) {\n      throw new Error('Enum can only take single value');\n    }\n    Object.keys(properties).map(key => {\n      this.enum = key;\n    });\n  }\n}\n\nexport const SOLANA_SCHEMA: Map<Function, any> = new Map();\n","import BN from 'bn.js';\nimport bs58 from 'bs58';\nimport {Buffer} from 'buffer';\nimport {sha256} from '@noble/hashes/sha256';\n\nimport {isOnCurve} from './utils/ed25519';\nimport {Struct, SOLANA_SCHEMA} from './utils/borsh-schema';\nimport {toBuffer} from './utils/to-buffer';\n\n/**\n * Maximum length of derived pubkey seed\n */\nexport const MAX_SEED_LENGTH = 32;\n\n/**\n * Size of public key in bytes\n */\nexport const PUBLIC_KEY_LENGTH = 32;\n\n/**\n * Value to be converted into public key\n */\nexport type PublicKeyInitData =\n  | number\n  | string\n  | Uint8Array\n  | Array<number>\n  | PublicKeyData;\n\n/**\n * JSON object representation of PublicKey class\n */\nexport type PublicKeyData = {\n  /** @internal */\n  _bn: BN;\n};\n\nfunction isPublicKeyData(value: PublicKeyInitData): value is PublicKeyData {\n  return (value as PublicKeyData)._bn !== undefined;\n}\n\n// local counter used by PublicKey.unique()\nlet uniquePublicKeyCounter = 1;\n\n/**\n * A public key\n */\nexport class PublicKey extends Struct {\n  /** @internal */\n  _bn: BN;\n\n  /**\n   * Create a new PublicKey object\n   * @param value ed25519 public key as buffer or base-58 encoded string\n   */\n  constructor(value: PublicKeyInitData) {\n    super({});\n    if (isPublicKeyData(value)) {\n      this._bn = value._bn;\n    } else {\n      if (typeof value === 'string') {\n        // assume base 58 encoding by default\n        const decoded = bs58.decode(value);\n        if (decoded.length != PUBLIC_KEY_LENGTH) {\n          throw new Error(`Invalid public key input`);\n        }\n        this._bn = new BN(decoded);\n      } else {\n        this._bn = new BN(value);\n      }\n\n      if (this._bn.byteLength() > PUBLIC_KEY_LENGTH) {\n        throw new Error(`Invalid public key input`);\n      }\n    }\n  }\n\n  /**\n   * Returns a unique PublicKey for tests and benchmarks using a counter\n   */\n  static unique(): PublicKey {\n    const key = new PublicKey(uniquePublicKeyCounter);\n    uniquePublicKeyCounter += 1;\n    return new PublicKey(key.toBuffer());\n  }\n\n  /**\n   * Default public key value. The base58-encoded string representation is all ones (as seen below)\n   * The underlying BN number is 32 bytes that are all zeros\n   */\n  static default: PublicKey = new PublicKey('11111111111111111111111111111111');\n\n  /**\n   * Checks if two publicKeys are equal\n   */\n  equals(publicKey: PublicKey): boolean {\n    return this._bn.eq(publicKey._bn);\n  }\n\n  /**\n   * Return the base-58 representation of the public key\n   */\n  toBase58(): string {\n    return bs58.encode(this.toBytes());\n  }\n\n  toJSON(): string {\n    return this.toBase58();\n  }\n\n  /**\n   * Return the byte array representation of the public key in big endian\n   */\n  toBytes(): Uint8Array {\n    const buf = this.toBuffer();\n    return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n  }\n\n  /**\n   * Return the Buffer representation of the public key in big endian\n   */\n  toBuffer(): Buffer {\n    const b = this._bn.toArrayLike(Buffer);\n    if (b.length === PUBLIC_KEY_LENGTH) {\n      return b;\n    }\n\n    const zeroPad = Buffer.alloc(32);\n    b.copy(zeroPad, 32 - b.length);\n    return zeroPad;\n  }\n\n  get [Symbol.toStringTag](): string {\n    return `PublicKey(${this.toString()})`;\n  }\n\n  /**\n   * Return the base-58 representation of the public key\n   */\n  toString(): string {\n    return this.toBase58();\n  }\n\n  /**\n   * Derive a public key from another key, a seed, and a program ID.\n   * The program ID will also serve as the owner of the public key, giving\n   * it permission to write data to the account.\n   */\n  /* eslint-disable require-await */\n  static async createWithSeed(\n    fromPublicKey: PublicKey,\n    seed: string,\n    programId: PublicKey,\n  ): Promise<PublicKey> {\n    const buffer = Buffer.concat([\n      fromPublicKey.toBuffer(),\n      Buffer.from(seed),\n      programId.toBuffer(),\n    ]);\n    const publicKeyBytes = sha256(buffer);\n    return new PublicKey(publicKeyBytes);\n  }\n\n  /**\n   * Derive a program address from seeds and a program ID.\n   */\n  /* eslint-disable require-await */\n  static createProgramAddressSync(\n    seeds: Array<Buffer | Uint8Array>,\n    programId: PublicKey,\n  ): PublicKey {\n    let buffer = Buffer.alloc(0);\n    seeds.forEach(function (seed) {\n      if (seed.length > MAX_SEED_LENGTH) {\n        throw new TypeError(`Max seed length exceeded`);\n      }\n      buffer = Buffer.concat([buffer, toBuffer(seed)]);\n    });\n    buffer = Buffer.concat([\n      buffer,\n      programId.toBuffer(),\n      Buffer.from('ProgramDerivedAddress'),\n    ]);\n    const publicKeyBytes = sha256(buffer);\n    if (isOnCurve(publicKeyBytes)) {\n      throw new Error(`Invalid seeds, address must fall off the curve`);\n    }\n    return new PublicKey(publicKeyBytes);\n  }\n\n  /**\n   * Async version of createProgramAddressSync\n   * For backwards compatibility\n   *\n   * @deprecated Use {@link createProgramAddressSync} instead\n   */\n  /* eslint-disable require-await */\n  static async createProgramAddress(\n    seeds: Array<Buffer | Uint8Array>,\n    programId: PublicKey,\n  ): Promise<PublicKey> {\n    return this.createProgramAddressSync(seeds, programId);\n  }\n\n  /**\n   * Find a valid program address\n   *\n   * Valid program addresses must fall off the ed25519 curve.  This function\n   * iterates a nonce until it finds one that when combined with the seeds\n   * results in a valid program address.\n   */\n  static findProgramAddressSync(\n    seeds: Array<Buffer | Uint8Array>,\n    programId: PublicKey,\n  ): [PublicKey, number] {\n    let nonce = 255;\n    let address;\n    while (nonce != 0) {\n      try {\n        const seedsWithNonce = seeds.concat(Buffer.from([nonce]));\n        address = this.createProgramAddressSync(seedsWithNonce, programId);\n      } catch (err) {\n        if (err instanceof TypeError) {\n          throw err;\n        }\n        nonce--;\n        continue;\n      }\n      return [address, nonce];\n    }\n    throw new Error(`Unable to find a viable program address nonce`);\n  }\n\n  /**\n   * Async version of findProgramAddressSync\n   * For backwards compatibility\n   *\n   * @deprecated Use {@link findProgramAddressSync} instead\n   */\n  static async findProgramAddress(\n    seeds: Array<Buffer | Uint8Array>,\n    programId: PublicKey,\n  ): Promise<[PublicKey, number]> {\n    return this.findProgramAddressSync(seeds, programId);\n  }\n\n  /**\n   * Check that a pubkey is on the ed25519 curve.\n   */\n  static isOnCurve(pubkeyData: PublicKeyInitData): boolean {\n    const pubkey = new PublicKey(pubkeyData);\n    return isOnCurve(pubkey.toBytes());\n  }\n}\n\nSOLANA_SCHEMA.set(PublicKey, {\n  kind: 'struct',\n  fields: [['_bn', 'u256']],\n});\n","import {Buffer} from 'buffer';\n\nimport {generatePrivateKey, getPublicKey} from './utils/ed25519';\nimport {toBuffer} from './utils/to-buffer';\nimport {PublicKey} from './publickey';\n\n/**\n * An account key pair (public and secret keys).\n *\n * @deprecated since v1.10.0, please use {@link Keypair} instead.\n */\nexport class Account {\n  /** @internal */\n  private _publicKey: Buffer;\n  /** @internal */\n  private _secretKey: Buffer;\n\n  /**\n   * Create a new Account object\n   *\n   * If the secretKey parameter is not provided a new key pair is randomly\n   * created for the account\n   *\n   * @param secretKey Secret key for the account\n   */\n  constructor(secretKey?: Uint8Array | Array<number>) {\n    if (secretKey) {\n      const secretKeyBuffer = toBuffer(secretKey);\n      if (secretKey.length !== 64) {\n        throw new Error('bad secret key size');\n      }\n      this._publicKey = secretKeyBuffer.slice(32, 64);\n      this._secretKey = secretKeyBuffer.slice(0, 32);\n    } else {\n      this._secretKey = toBuffer(generatePrivateKey());\n      this._publicKey = toBuffer(getPublicKey(this._secretKey));\n    }\n  }\n\n  /**\n   * The public key for this account\n   */\n  get publicKey(): PublicKey {\n    return new PublicKey(this._publicKey);\n  }\n\n  /**\n   * The **unencrypted** secret key for this account. The first 32 bytes\n   * is the private scalar and the last 32 bytes is the public key.\n   * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/\n   */\n  get secretKey(): Buffer {\n    return Buffer.concat([this._secretKey, this._publicKey], 64);\n  }\n}\n","import {PublicKey} from './publickey';\n\nexport const BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey(\n  'BPFLoader1111111111111111111111111111111111',\n);\n","/**\n * Maximum over-the-wire size of a Transaction\n *\n * 1280 is IPv6 minimum MTU\n * 40 bytes is the size of the IPv6 header\n * 8 bytes is the size of the fragment header\n */\nexport const PACKET_DATA_SIZE = 1280 - 40 - 8;\n\nexport const VERSION_PREFIX_MASK = 0x7f;\n\nexport const SIGNATURE_LENGTH_IN_BYTES = 64;\n","export class TransactionExpiredBlockheightExceededError extends Error {\n  signature: string;\n\n  constructor(signature: string) {\n    super(`Signature ${signature} has expired: block height exceeded.`);\n    this.signature = signature;\n  }\n}\n\nObject.defineProperty(\n  TransactionExpiredBlockheightExceededError.prototype,\n  'name',\n  {\n    value: 'TransactionExpiredBlockheightExceededError',\n  },\n);\n\nexport class TransactionExpiredTimeoutError extends Error {\n  signature: string;\n\n  constructor(signature: string, timeoutSeconds: number) {\n    super(\n      `Transaction was not confirmed in ${timeoutSeconds.toFixed(\n        2,\n      )} seconds. It is ` +\n        'unknown if it succeeded or failed. Check signature ' +\n        `${signature} using the Solana Explorer or CLI tools.`,\n    );\n    this.signature = signature;\n  }\n}\n\nObject.defineProperty(TransactionExpiredTimeoutError.prototype, 'name', {\n  value: 'TransactionExpiredTimeoutError',\n});\n\nexport class TransactionExpiredNonceInvalidError extends Error {\n  signature: string;\n\n  constructor(signature: string) {\n    super(`Signature ${signature} has expired: the nonce is no longer valid.`);\n    this.signature = signature;\n  }\n}\n\nObject.defineProperty(TransactionExpiredNonceInvalidError.prototype, 'name', {\n  value: 'TransactionExpiredNonceInvalidError',\n});\n","import {LoadedAddresses} from '../connection';\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport {MessageCompiledInstruction} from './index';\n\nexport type AccountKeysFromLookups = LoadedAddresses;\n\nexport class MessageAccountKeys {\n  staticAccountKeys: Array<PublicKey>;\n  accountKeysFromLookups?: AccountKeysFromLookups;\n\n  constructor(\n    staticAccountKeys: Array<PublicKey>,\n    accountKeysFromLookups?: AccountKeysFromLookups,\n  ) {\n    this.staticAccountKeys = staticAccountKeys;\n    this.accountKeysFromLookups = accountKeysFromLookups;\n  }\n\n  keySegments(): Array<Array<PublicKey>> {\n    const keySegments = [this.staticAccountKeys];\n    if (this.accountKeysFromLookups) {\n      keySegments.push(this.accountKeysFromLookups.writable);\n      keySegments.push(this.accountKeysFromLookups.readonly);\n    }\n    return keySegments;\n  }\n\n  get(index: number): PublicKey | undefined {\n    for (const keySegment of this.keySegments()) {\n      if (index < keySegment.length) {\n        return keySegment[index];\n      } else {\n        index -= keySegment.length;\n      }\n    }\n    return;\n  }\n\n  get length(): number {\n    return this.keySegments().flat().length;\n  }\n\n  compileInstructions(\n    instructions: Array<TransactionInstruction>,\n  ): Array<MessageCompiledInstruction> {\n    // Bail early if any account indexes would overflow a u8\n    const U8_MAX = 255;\n    if (this.length > U8_MAX + 1) {\n      throw new Error('Account index overflow encountered during compilation');\n    }\n\n    const keyIndexMap = new Map();\n    this.keySegments()\n      .flat()\n      .forEach((key, index) => {\n        keyIndexMap.set(key.toBase58(), index);\n      });\n\n    const findKeyIndex = (key: PublicKey) => {\n      const keyIndex = keyIndexMap.get(key.toBase58());\n      if (keyIndex === undefined)\n        throw new Error(\n          'Encountered an unknown instruction account key during compilation',\n        );\n      return keyIndex;\n    };\n\n    return instructions.map((instruction): MessageCompiledInstruction => {\n      return {\n        programIdIndex: findKeyIndex(instruction.programId),\n        accountKeyIndexes: instruction.keys.map(meta =>\n          findKeyIndex(meta.pubkey),\n        ),\n        data: instruction.data,\n      };\n    });\n  }\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {VoteAuthorizeWithSeedArgs} from './programs/vote';\n\n/**\n * Layout for a public key\n */\nexport const publicKey = (property: string = 'publicKey') => {\n  return BufferLayout.blob(32, property);\n};\n\n/**\n * Layout for a signature\n */\nexport const signature = (property: string = 'signature') => {\n  return BufferLayout.blob(64, property);\n};\n\n/**\n * Layout for a 64bit unsigned value\n */\nexport const uint64 = (property: string = 'uint64') => {\n  return BufferLayout.blob(8, property);\n};\n\ninterface IRustStringShim\n  extends Omit<\n    BufferLayout.Structure<\n      Readonly<{\n        length: number;\n        lengthPadding: number;\n        chars: Uint8Array;\n      }>\n    >,\n    'decode' | 'encode' | 'replicate'\n  > {\n  alloc: (str: string) => number;\n  decode: (b: Uint8Array, offset?: number) => string;\n  encode: (str: string, b: Uint8Array, offset?: number) => number;\n  replicate: (property: string) => this;\n}\n\n/**\n * Layout for a Rust String type\n */\nexport const rustString = (\n  property: string = 'string',\n): BufferLayout.Layout<string> => {\n  const rsl = BufferLayout.struct<\n    Readonly<{\n      length?: number;\n      lengthPadding?: number;\n      chars: Uint8Array;\n    }>\n  >(\n    [\n      BufferLayout.u32('length'),\n      BufferLayout.u32('lengthPadding'),\n      BufferLayout.blob(BufferLayout.offset(BufferLayout.u32(), -8), 'chars'),\n    ],\n    property,\n  );\n  const _decode = rsl.decode.bind(rsl);\n  const _encode = rsl.encode.bind(rsl);\n\n  const rslShim = rsl as unknown as IRustStringShim;\n\n  rslShim.decode = (b: Uint8Array, offset?: number) => {\n    const data = _decode(b, offset);\n    return data['chars'].toString();\n  };\n\n  rslShim.encode = (str: string, b: Uint8Array, offset?: number) => {\n    const data = {\n      chars: Buffer.from(str, 'utf8'),\n    };\n    return _encode(data, b, offset);\n  };\n\n  rslShim.alloc = (str: string) => {\n    return (\n      BufferLayout.u32().span +\n      BufferLayout.u32().span +\n      Buffer.from(str, 'utf8').length\n    );\n  };\n\n  return rslShim;\n};\n\n/**\n * Layout for an Authorized object\n */\nexport const authorized = (property: string = 'authorized') => {\n  return BufferLayout.struct<\n    Readonly<{\n      staker: Uint8Array;\n      withdrawer: Uint8Array;\n    }>\n  >([publicKey('staker'), publicKey('withdrawer')], property);\n};\n\n/**\n * Layout for a Lockup object\n */\nexport const lockup = (property: string = 'lockup') => {\n  return BufferLayout.struct<\n    Readonly<{\n      custodian: Uint8Array;\n      epoch: number;\n      unixTimestamp: number;\n    }>\n  >(\n    [\n      BufferLayout.ns64('unixTimestamp'),\n      BufferLayout.ns64('epoch'),\n      publicKey('custodian'),\n    ],\n    property,\n  );\n};\n\n/**\n *  Layout for a VoteInit object\n */\nexport const voteInit = (property: string = 'voteInit') => {\n  return BufferLayout.struct<\n    Readonly<{\n      authorizedVoter: Uint8Array;\n      authorizedWithdrawer: Uint8Array;\n      commission: number;\n      nodePubkey: Uint8Array;\n    }>\n  >(\n    [\n      publicKey('nodePubkey'),\n      publicKey('authorizedVoter'),\n      publicKey('authorizedWithdrawer'),\n      BufferLayout.u8('commission'),\n    ],\n    property,\n  );\n};\n\n/**\n *  Layout for a VoteAuthorizeWithSeedArgs object\n */\nexport const voteAuthorizeWithSeedArgs = (\n  property: string = 'voteAuthorizeWithSeedArgs',\n) => {\n  return BufferLayout.struct<VoteAuthorizeWithSeedArgs>(\n    [\n      BufferLayout.u32('voteAuthorizationType'),\n      publicKey('currentAuthorityDerivedKeyOwnerPubkey'),\n      rustString('currentAuthorityDerivedKeySeed'),\n      publicKey('newAuthorized'),\n    ],\n    property,\n  );\n};\n\nexport function getAlloc(type: any, fields: any): number {\n  const getItemAlloc = (item: any): number => {\n    if (item.span >= 0) {\n      return item.span;\n    } else if (typeof item.alloc === 'function') {\n      return item.alloc(fields[item.property]);\n    } else if ('count' in item && 'elementLayout' in item) {\n      const field = fields[item.property];\n      if (Array.isArray(field)) {\n        return field.length * getItemAlloc(item.elementLayout);\n      }\n    } else if ('fields' in item) {\n      // This is a `Structure` whose size needs to be recursively measured.\n      return getAlloc({layout: item}, fields[item.property]);\n    }\n    // Couldn't determine allocated size of layout\n    return 0;\n  };\n\n  let alloc = 0;\n  type.layout.fields.forEach((item: any) => {\n    alloc += getItemAlloc(item);\n  });\n\n  return alloc;\n}\n","export function decodeLength(bytes: Array<number>): number {\n  let len = 0;\n  let size = 0;\n  for (;;) {\n    let elem = bytes.shift() as number;\n    len |= (elem & 0x7f) << (size * 7);\n    size += 1;\n    if ((elem & 0x80) === 0) {\n      break;\n    }\n  }\n  return len;\n}\n\nexport function encodeLength(bytes: Array<number>, len: number) {\n  let rem_len = len;\n  for (;;) {\n    let elem = rem_len & 0x7f;\n    rem_len >>= 7;\n    if (rem_len == 0) {\n      bytes.push(elem);\n      break;\n    } else {\n      elem |= 0x80;\n      bytes.push(elem);\n    }\n  }\n}\n","export default function (\n  condition: unknown,\n  message?: string,\n): asserts condition {\n  if (!condition) {\n    throw new Error(message || 'Assertion failed');\n  }\n}\n","import {MessageHeader, MessageAddressTableLookup} from './index';\nimport {AccountKeysFromLookups} from './account-keys';\nimport {AddressLookupTableAccount} from '../programs';\nimport {TransactionInstruction} from '../transaction';\nimport assert from '../utils/assert';\nimport {PublicKey} from '../publickey';\n\nexport type CompiledKeyMeta = {\n  isSigner: boolean;\n  isWritable: boolean;\n  isInvoked: boolean;\n};\n\ntype KeyMetaMap = Map<string, CompiledKeyMeta>;\n\nexport class CompiledKeys {\n  payer: PublicKey;\n  keyMetaMap: KeyMetaMap;\n\n  constructor(payer: PublicKey, keyMetaMap: KeyMetaMap) {\n    this.payer = payer;\n    this.keyMetaMap = keyMetaMap;\n  }\n\n  static compile(\n    instructions: Array<TransactionInstruction>,\n    payer: PublicKey,\n  ): CompiledKeys {\n    const keyMetaMap: KeyMetaMap = new Map();\n    const getOrInsertDefault = (pubkey: PublicKey): CompiledKeyMeta => {\n      const address = pubkey.toBase58();\n      let keyMeta = keyMetaMap.get(address);\n      if (keyMeta === undefined) {\n        keyMeta = {\n          isSigner: false,\n          isWritable: false,\n          isInvoked: false,\n        };\n        keyMetaMap.set(address, keyMeta);\n      }\n      return keyMeta;\n    };\n\n    const payerKeyMeta = getOrInsertDefault(payer);\n    payerKeyMeta.isSigner = true;\n    payerKeyMeta.isWritable = true;\n\n    for (const ix of instructions) {\n      getOrInsertDefault(ix.programId).isInvoked = true;\n      for (const accountMeta of ix.keys) {\n        const keyMeta = getOrInsertDefault(accountMeta.pubkey);\n        keyMeta.isSigner ||= accountMeta.isSigner;\n        keyMeta.isWritable ||= accountMeta.isWritable;\n      }\n    }\n\n    return new CompiledKeys(payer, keyMetaMap);\n  }\n\n  getMessageComponents(): [MessageHeader, Array<PublicKey>] {\n    const mapEntries = [...this.keyMetaMap.entries()];\n    assert(mapEntries.length <= 256, 'Max static account keys length exceeded');\n\n    const writableSigners = mapEntries.filter(\n      ([, meta]) => meta.isSigner && meta.isWritable,\n    );\n    const readonlySigners = mapEntries.filter(\n      ([, meta]) => meta.isSigner && !meta.isWritable,\n    );\n    const writableNonSigners = mapEntries.filter(\n      ([, meta]) => !meta.isSigner && meta.isWritable,\n    );\n    const readonlyNonSigners = mapEntries.filter(\n      ([, meta]) => !meta.isSigner && !meta.isWritable,\n    );\n\n    const header: MessageHeader = {\n      numRequiredSignatures: writableSigners.length + readonlySigners.length,\n      numReadonlySignedAccounts: readonlySigners.length,\n      numReadonlyUnsignedAccounts: readonlyNonSigners.length,\n    };\n\n    // sanity checks\n    {\n      assert(\n        writableSigners.length > 0,\n        'Expected at least one writable signer key',\n      );\n      const [payerAddress] = writableSigners[0];\n      assert(\n        payerAddress === this.payer.toBase58(),\n        'Expected first writable signer key to be the fee payer',\n      );\n    }\n\n    const staticAccountKeys = [\n      ...writableSigners.map(([address]) => new PublicKey(address)),\n      ...readonlySigners.map(([address]) => new PublicKey(address)),\n      ...writableNonSigners.map(([address]) => new PublicKey(address)),\n      ...readonlyNonSigners.map(([address]) => new PublicKey(address)),\n    ];\n\n    return [header, staticAccountKeys];\n  }\n\n  extractTableLookup(\n    lookupTable: AddressLookupTableAccount,\n  ): [MessageAddressTableLookup, AccountKeysFromLookups] | undefined {\n    const [writableIndexes, drainedWritableKeys] =\n      this.drainKeysFoundInLookupTable(\n        lookupTable.state.addresses,\n        keyMeta =>\n          !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable,\n      );\n    const [readonlyIndexes, drainedReadonlyKeys] =\n      this.drainKeysFoundInLookupTable(\n        lookupTable.state.addresses,\n        keyMeta =>\n          !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable,\n      );\n\n    // Don't extract lookup if no keys were found\n    if (writableIndexes.length === 0 && readonlyIndexes.length === 0) {\n      return;\n    }\n\n    return [\n      {\n        accountKey: lookupTable.key,\n        writableIndexes,\n        readonlyIndexes,\n      },\n      {\n        writable: drainedWritableKeys,\n        readonly: drainedReadonlyKeys,\n      },\n    ];\n  }\n\n  /** @internal */\n  private drainKeysFoundInLookupTable(\n    lookupTableEntries: Array<PublicKey>,\n    keyMetaFilter: (keyMeta: CompiledKeyMeta) => boolean,\n  ): [Array<number>, Array<PublicKey>] {\n    const lookupTableIndexes = new Array();\n    const drainedKeys = new Array();\n\n    for (const [address, keyMeta] of this.keyMetaMap.entries()) {\n      if (keyMetaFilter(keyMeta)) {\n        const key = new PublicKey(address);\n        const lookupTableIndex = lookupTableEntries.findIndex(entry =>\n          entry.equals(key),\n        );\n        if (lookupTableIndex >= 0) {\n          assert(lookupTableIndex < 256, 'Max lookup table index exceeded');\n          lookupTableIndexes.push(lookupTableIndex);\n          drainedKeys.push(key);\n          this.keyMetaMap.delete(address);\n        }\n      }\n    }\n\n    return [lookupTableIndexes, drainedKeys];\n  }\n}\n","import bs58 from 'bs58';\nimport {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {PublicKey, PUBLIC_KEY_LENGTH} from '../publickey';\nimport type {Blockhash} from '../blockhash';\nimport * as Layout from '../layout';\nimport {PACKET_DATA_SIZE, VERSION_PREFIX_MASK} from '../transaction/constants';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport {toBuffer} from '../utils/to-buffer';\nimport {\n  MessageHeader,\n  MessageAddressTableLookup,\n  MessageCompiledInstruction,\n} from './index';\nimport {TransactionInstruction} from '../transaction';\nimport {CompiledKeys} from './compiled-keys';\nimport {MessageAccountKeys} from './account-keys';\n\n/**\n * An instruction to execute by a program\n *\n * @property {number} programIdIndex\n * @property {number[]} accounts\n * @property {string} data\n */\nexport type CompiledInstruction = {\n  /** Index into the transaction keys array indicating the program account that executes this instruction */\n  programIdIndex: number;\n  /** Ordered indices into the transaction keys array indicating which accounts to pass to the program */\n  accounts: number[];\n  /** The program input data encoded as base 58 */\n  data: string;\n};\n\n/**\n * Message constructor arguments\n */\nexport type MessageArgs = {\n  /** The message header, identifying signed and read-only `accountKeys` */\n  header: MessageHeader;\n  /** All the account keys used by this transaction */\n  accountKeys: string[] | PublicKey[];\n  /** The hash of a recent ledger block */\n  recentBlockhash: Blockhash;\n  /** Instructions that will be executed in sequence and committed in one atomic transaction if all succeed. */\n  instructions: CompiledInstruction[];\n};\n\nexport type CompileLegacyArgs = {\n  payerKey: PublicKey;\n  instructions: Array<TransactionInstruction>;\n  recentBlockhash: Blockhash;\n};\n\n/**\n * List of instructions to be processed atomically\n */\nexport class Message {\n  header: MessageHeader;\n  accountKeys: PublicKey[];\n  recentBlockhash: Blockhash;\n  instructions: CompiledInstruction[];\n\n  private indexToProgramIds: Map<number, PublicKey> = new Map<\n    number,\n    PublicKey\n  >();\n\n  constructor(args: MessageArgs) {\n    this.header = args.header;\n    this.accountKeys = args.accountKeys.map(account => new PublicKey(account));\n    this.recentBlockhash = args.recentBlockhash;\n    this.instructions = args.instructions;\n    this.instructions.forEach(ix =>\n      this.indexToProgramIds.set(\n        ix.programIdIndex,\n        this.accountKeys[ix.programIdIndex],\n      ),\n    );\n  }\n\n  get version(): 'legacy' {\n    return 'legacy';\n  }\n\n  get staticAccountKeys(): Array<PublicKey> {\n    return this.accountKeys;\n  }\n\n  get compiledInstructions(): Array<MessageCompiledInstruction> {\n    return this.instructions.map(\n      (ix): MessageCompiledInstruction => ({\n        programIdIndex: ix.programIdIndex,\n        accountKeyIndexes: ix.accounts,\n        data: bs58.decode(ix.data),\n      }),\n    );\n  }\n\n  get addressTableLookups(): Array<MessageAddressTableLookup> {\n    return [];\n  }\n\n  getAccountKeys(): MessageAccountKeys {\n    return new MessageAccountKeys(this.staticAccountKeys);\n  }\n\n  static compile(args: CompileLegacyArgs): Message {\n    const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);\n    const [header, staticAccountKeys] = compiledKeys.getMessageComponents();\n    const accountKeys = new MessageAccountKeys(staticAccountKeys);\n    const instructions = accountKeys.compileInstructions(args.instructions).map(\n      (ix: MessageCompiledInstruction): CompiledInstruction => ({\n        programIdIndex: ix.programIdIndex,\n        accounts: ix.accountKeyIndexes,\n        data: bs58.encode(ix.data),\n      }),\n    );\n    return new Message({\n      header,\n      accountKeys: staticAccountKeys,\n      recentBlockhash: args.recentBlockhash,\n      instructions,\n    });\n  }\n\n  isAccountSigner(index: number): boolean {\n    return index < this.header.numRequiredSignatures;\n  }\n\n  isAccountWritable(index: number): boolean {\n    const numSignedAccounts = this.header.numRequiredSignatures;\n    if (index >= this.header.numRequiredSignatures) {\n      const unsignedAccountIndex = index - numSignedAccounts;\n      const numUnsignedAccounts = this.accountKeys.length - numSignedAccounts;\n      const numWritableUnsignedAccounts =\n        numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts;\n      return unsignedAccountIndex < numWritableUnsignedAccounts;\n    } else {\n      const numWritableSignedAccounts =\n        numSignedAccounts - this.header.numReadonlySignedAccounts;\n      return index < numWritableSignedAccounts;\n    }\n  }\n\n  isProgramId(index: number): boolean {\n    return this.indexToProgramIds.has(index);\n  }\n\n  programIds(): PublicKey[] {\n    return [...this.indexToProgramIds.values()];\n  }\n\n  nonProgramIds(): PublicKey[] {\n    return this.accountKeys.filter((_, index) => !this.isProgramId(index));\n  }\n\n  serialize(): Buffer {\n    const numKeys = this.accountKeys.length;\n\n    let keyCount: number[] = [];\n    shortvec.encodeLength(keyCount, numKeys);\n\n    const instructions = this.instructions.map(instruction => {\n      const {accounts, programIdIndex} = instruction;\n      const data = Array.from(bs58.decode(instruction.data));\n\n      let keyIndicesCount: number[] = [];\n      shortvec.encodeLength(keyIndicesCount, accounts.length);\n\n      let dataCount: number[] = [];\n      shortvec.encodeLength(dataCount, data.length);\n\n      return {\n        programIdIndex,\n        keyIndicesCount: Buffer.from(keyIndicesCount),\n        keyIndices: accounts,\n        dataLength: Buffer.from(dataCount),\n        data,\n      };\n    });\n\n    let instructionCount: number[] = [];\n    shortvec.encodeLength(instructionCount, instructions.length);\n    let instructionBuffer = Buffer.alloc(PACKET_DATA_SIZE);\n    Buffer.from(instructionCount).copy(instructionBuffer);\n    let instructionBufferLength = instructionCount.length;\n\n    instructions.forEach(instruction => {\n      const instructionLayout = BufferLayout.struct<\n        Readonly<{\n          data: number[];\n          dataLength: Uint8Array;\n          keyIndices: number[];\n          keyIndicesCount: Uint8Array;\n          programIdIndex: number;\n        }>\n      >([\n        BufferLayout.u8('programIdIndex'),\n\n        BufferLayout.blob(\n          instruction.keyIndicesCount.length,\n          'keyIndicesCount',\n        ),\n        BufferLayout.seq(\n          BufferLayout.u8('keyIndex'),\n          instruction.keyIndices.length,\n          'keyIndices',\n        ),\n        BufferLayout.blob(instruction.dataLength.length, 'dataLength'),\n        BufferLayout.seq(\n          BufferLayout.u8('userdatum'),\n          instruction.data.length,\n          'data',\n        ),\n      ]);\n      const length = instructionLayout.encode(\n        instruction,\n        instructionBuffer,\n        instructionBufferLength,\n      );\n      instructionBufferLength += length;\n    });\n    instructionBuffer = instructionBuffer.slice(0, instructionBufferLength);\n\n    const signDataLayout = BufferLayout.struct<\n      Readonly<{\n        keyCount: Uint8Array;\n        keys: Uint8Array[];\n        numReadonlySignedAccounts: Uint8Array;\n        numReadonlyUnsignedAccounts: Uint8Array;\n        numRequiredSignatures: Uint8Array;\n        recentBlockhash: Uint8Array;\n      }>\n    >([\n      BufferLayout.blob(1, 'numRequiredSignatures'),\n      BufferLayout.blob(1, 'numReadonlySignedAccounts'),\n      BufferLayout.blob(1, 'numReadonlyUnsignedAccounts'),\n      BufferLayout.blob(keyCount.length, 'keyCount'),\n      BufferLayout.seq(Layout.publicKey('key'), numKeys, 'keys'),\n      Layout.publicKey('recentBlockhash'),\n    ]);\n\n    const transaction = {\n      numRequiredSignatures: Buffer.from([this.header.numRequiredSignatures]),\n      numReadonlySignedAccounts: Buffer.from([\n        this.header.numReadonlySignedAccounts,\n      ]),\n      numReadonlyUnsignedAccounts: Buffer.from([\n        this.header.numReadonlyUnsignedAccounts,\n      ]),\n      keyCount: Buffer.from(keyCount),\n      keys: this.accountKeys.map(key => toBuffer(key.toBytes())),\n      recentBlockhash: bs58.decode(this.recentBlockhash),\n    };\n\n    let signData = Buffer.alloc(2048);\n    const length = signDataLayout.encode(transaction, signData);\n    instructionBuffer.copy(signData, length);\n    return signData.slice(0, length + instructionBuffer.length);\n  }\n\n  /**\n   * Decode a compiled message into a Message object.\n   */\n  static from(buffer: Buffer | Uint8Array | Array<number>): Message {\n    // Slice up wire data\n    let byteArray = [...buffer];\n\n    const numRequiredSignatures = byteArray.shift()!;\n    if (\n      numRequiredSignatures !==\n      (numRequiredSignatures & VERSION_PREFIX_MASK)\n    ) {\n      throw new Error(\n        'Versioned messages must be deserialized with VersionedMessage.deserialize()',\n      );\n    }\n\n    const numReadonlySignedAccounts = byteArray.shift()!;\n    const numReadonlyUnsignedAccounts = byteArray.shift()!;\n\n    const accountCount = shortvec.decodeLength(byteArray);\n    let accountKeys = [];\n    for (let i = 0; i < accountCount; i++) {\n      const account = byteArray.slice(0, PUBLIC_KEY_LENGTH);\n      byteArray = byteArray.slice(PUBLIC_KEY_LENGTH);\n      accountKeys.push(new PublicKey(Buffer.from(account)));\n    }\n\n    const recentBlockhash = byteArray.slice(0, PUBLIC_KEY_LENGTH);\n    byteArray = byteArray.slice(PUBLIC_KEY_LENGTH);\n\n    const instructionCount = shortvec.decodeLength(byteArray);\n    let instructions: CompiledInstruction[] = [];\n    for (let i = 0; i < instructionCount; i++) {\n      const programIdIndex = byteArray.shift()!;\n      const accountCount = shortvec.decodeLength(byteArray);\n      const accounts = byteArray.slice(0, accountCount);\n      byteArray = byteArray.slice(accountCount);\n      const dataLength = shortvec.decodeLength(byteArray);\n      const dataSlice = byteArray.slice(0, dataLength);\n      const data = bs58.encode(Buffer.from(dataSlice));\n      byteArray = byteArray.slice(dataLength);\n      instructions.push({\n        programIdIndex,\n        accounts,\n        data,\n      });\n    }\n\n    const messageArgs = {\n      header: {\n        numRequiredSignatures,\n        numReadonlySignedAccounts,\n        numReadonlyUnsignedAccounts,\n      },\n      recentBlockhash: bs58.encode(Buffer.from(recentBlockhash)),\n      accountKeys,\n      instructions,\n    };\n\n    return new Message(messageArgs);\n  }\n}\n","import bs58 from 'bs58';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport * as Layout from '../layout';\nimport {Blockhash} from '../blockhash';\nimport {\n  MessageHeader,\n  MessageAddressTableLookup,\n  MessageCompiledInstruction,\n} from './index';\nimport {PublicKey, PUBLIC_KEY_LENGTH} from '../publickey';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport assert from '../utils/assert';\nimport {PACKET_DATA_SIZE, VERSION_PREFIX_MASK} from '../transaction/constants';\nimport {TransactionInstruction} from '../transaction';\nimport {AddressLookupTableAccount} from '../programs';\nimport {CompiledKeys} from './compiled-keys';\nimport {AccountKeysFromLookups, MessageAccountKeys} from './account-keys';\n\n/**\n * Message constructor arguments\n */\nexport type MessageV0Args = {\n  /** The message header, identifying signed and read-only `accountKeys` */\n  header: MessageHeader;\n  /** The static account keys used by this transaction */\n  staticAccountKeys: PublicKey[];\n  /** The hash of a recent ledger block */\n  recentBlockhash: Blockhash;\n  /** Instructions that will be executed in sequence and committed in one atomic transaction if all succeed. */\n  compiledInstructions: MessageCompiledInstruction[];\n  /** Instructions that will be executed in sequence and committed in one atomic transaction if all succeed. */\n  addressTableLookups: MessageAddressTableLookup[];\n};\n\nexport type CompileV0Args = {\n  payerKey: PublicKey;\n  instructions: Array<TransactionInstruction>;\n  recentBlockhash: Blockhash;\n  addressLookupTableAccounts?: Array<AddressLookupTableAccount>;\n};\n\nexport type GetAccountKeysArgs =\n  | {\n      accountKeysFromLookups?: AccountKeysFromLookups | null;\n    }\n  | {\n      addressLookupTableAccounts?: AddressLookupTableAccount[] | null;\n    };\n\nexport class MessageV0 {\n  header: MessageHeader;\n  staticAccountKeys: Array<PublicKey>;\n  recentBlockhash: Blockhash;\n  compiledInstructions: Array<MessageCompiledInstruction>;\n  addressTableLookups: Array<MessageAddressTableLookup>;\n\n  constructor(args: MessageV0Args) {\n    this.header = args.header;\n    this.staticAccountKeys = args.staticAccountKeys;\n    this.recentBlockhash = args.recentBlockhash;\n    this.compiledInstructions = args.compiledInstructions;\n    this.addressTableLookups = args.addressTableLookups;\n  }\n\n  get version(): 0 {\n    return 0;\n  }\n\n  get numAccountKeysFromLookups(): number {\n    let count = 0;\n    for (const lookup of this.addressTableLookups) {\n      count += lookup.readonlyIndexes.length + lookup.writableIndexes.length;\n    }\n    return count;\n  }\n\n  getAccountKeys(args?: GetAccountKeysArgs): MessageAccountKeys {\n    let accountKeysFromLookups: AccountKeysFromLookups | undefined;\n    if (\n      args &&\n      'accountKeysFromLookups' in args &&\n      args.accountKeysFromLookups\n    ) {\n      if (\n        this.numAccountKeysFromLookups !=\n        args.accountKeysFromLookups.writable.length +\n          args.accountKeysFromLookups.readonly.length\n      ) {\n        throw new Error(\n          'Failed to get account keys because of a mismatch in the number of account keys from lookups',\n        );\n      }\n      accountKeysFromLookups = args.accountKeysFromLookups;\n    } else if (\n      args &&\n      'addressLookupTableAccounts' in args &&\n      args.addressLookupTableAccounts\n    ) {\n      accountKeysFromLookups = this.resolveAddressTableLookups(\n        args.addressLookupTableAccounts,\n      );\n    } else if (this.addressTableLookups.length > 0) {\n      throw new Error(\n        'Failed to get account keys because address table lookups were not resolved',\n      );\n    }\n    return new MessageAccountKeys(\n      this.staticAccountKeys,\n      accountKeysFromLookups,\n    );\n  }\n\n  isAccountSigner(index: number): boolean {\n    return index < this.header.numRequiredSignatures;\n  }\n\n  isAccountWritable(index: number): boolean {\n    const numSignedAccounts = this.header.numRequiredSignatures;\n    const numStaticAccountKeys = this.staticAccountKeys.length;\n    if (index >= numStaticAccountKeys) {\n      const lookupAccountKeysIndex = index - numStaticAccountKeys;\n      const numWritableLookupAccountKeys = this.addressTableLookups.reduce(\n        (count, lookup) => count + lookup.writableIndexes.length,\n        0,\n      );\n      return lookupAccountKeysIndex < numWritableLookupAccountKeys;\n    } else if (index >= this.header.numRequiredSignatures) {\n      const unsignedAccountIndex = index - numSignedAccounts;\n      const numUnsignedAccounts = numStaticAccountKeys - numSignedAccounts;\n      const numWritableUnsignedAccounts =\n        numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts;\n      return unsignedAccountIndex < numWritableUnsignedAccounts;\n    } else {\n      const numWritableSignedAccounts =\n        numSignedAccounts - this.header.numReadonlySignedAccounts;\n      return index < numWritableSignedAccounts;\n    }\n  }\n\n  resolveAddressTableLookups(\n    addressLookupTableAccounts: AddressLookupTableAccount[],\n  ): AccountKeysFromLookups {\n    const accountKeysFromLookups: AccountKeysFromLookups = {\n      writable: [],\n      readonly: [],\n    };\n\n    for (const tableLookup of this.addressTableLookups) {\n      const tableAccount = addressLookupTableAccounts.find(account =>\n        account.key.equals(tableLookup.accountKey),\n      );\n      if (!tableAccount) {\n        throw new Error(\n          `Failed to find address lookup table account for table key ${tableLookup.accountKey.toBase58()}`,\n        );\n      }\n\n      for (const index of tableLookup.writableIndexes) {\n        if (index < tableAccount.state.addresses.length) {\n          accountKeysFromLookups.writable.push(\n            tableAccount.state.addresses[index],\n          );\n        } else {\n          throw new Error(\n            `Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`,\n          );\n        }\n      }\n\n      for (const index of tableLookup.readonlyIndexes) {\n        if (index < tableAccount.state.addresses.length) {\n          accountKeysFromLookups.readonly.push(\n            tableAccount.state.addresses[index],\n          );\n        } else {\n          throw new Error(\n            `Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`,\n          );\n        }\n      }\n    }\n\n    return accountKeysFromLookups;\n  }\n\n  static compile(args: CompileV0Args): MessageV0 {\n    const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);\n\n    const addressTableLookups = new Array<MessageAddressTableLookup>();\n    const accountKeysFromLookups: AccountKeysFromLookups = {\n      writable: new Array(),\n      readonly: new Array(),\n    };\n    const lookupTableAccounts = args.addressLookupTableAccounts || [];\n    for (const lookupTable of lookupTableAccounts) {\n      const extractResult = compiledKeys.extractTableLookup(lookupTable);\n      if (extractResult !== undefined) {\n        const [addressTableLookup, {writable, readonly}] = extractResult;\n        addressTableLookups.push(addressTableLookup);\n        accountKeysFromLookups.writable.push(...writable);\n        accountKeysFromLookups.readonly.push(...readonly);\n      }\n    }\n\n    const [header, staticAccountKeys] = compiledKeys.getMessageComponents();\n    const accountKeys = new MessageAccountKeys(\n      staticAccountKeys,\n      accountKeysFromLookups,\n    );\n    const compiledInstructions = accountKeys.compileInstructions(\n      args.instructions,\n    );\n    return new MessageV0({\n      header,\n      staticAccountKeys,\n      recentBlockhash: args.recentBlockhash,\n      compiledInstructions,\n      addressTableLookups,\n    });\n  }\n\n  serialize(): Uint8Array {\n    const encodedStaticAccountKeysLength = Array<number>();\n    shortvec.encodeLength(\n      encodedStaticAccountKeysLength,\n      this.staticAccountKeys.length,\n    );\n\n    const serializedInstructions = this.serializeInstructions();\n    const encodedInstructionsLength = Array<number>();\n    shortvec.encodeLength(\n      encodedInstructionsLength,\n      this.compiledInstructions.length,\n    );\n\n    const serializedAddressTableLookups = this.serializeAddressTableLookups();\n    const encodedAddressTableLookupsLength = Array<number>();\n    shortvec.encodeLength(\n      encodedAddressTableLookupsLength,\n      this.addressTableLookups.length,\n    );\n\n    const messageLayout = BufferLayout.struct<{\n      prefix: number;\n      header: MessageHeader;\n      staticAccountKeysLength: Uint8Array;\n      staticAccountKeys: Array<Uint8Array>;\n      recentBlockhash: Uint8Array;\n      instructionsLength: Uint8Array;\n      serializedInstructions: Uint8Array;\n      addressTableLookupsLength: Uint8Array;\n      serializedAddressTableLookups: Uint8Array;\n    }>([\n      BufferLayout.u8('prefix'),\n      BufferLayout.struct<MessageHeader>(\n        [\n          BufferLayout.u8('numRequiredSignatures'),\n          BufferLayout.u8('numReadonlySignedAccounts'),\n          BufferLayout.u8('numReadonlyUnsignedAccounts'),\n        ],\n        'header',\n      ),\n      BufferLayout.blob(\n        encodedStaticAccountKeysLength.length,\n        'staticAccountKeysLength',\n      ),\n      BufferLayout.seq(\n        Layout.publicKey(),\n        this.staticAccountKeys.length,\n        'staticAccountKeys',\n      ),\n      Layout.publicKey('recentBlockhash'),\n      BufferLayout.blob(encodedInstructionsLength.length, 'instructionsLength'),\n      BufferLayout.blob(\n        serializedInstructions.length,\n        'serializedInstructions',\n      ),\n      BufferLayout.blob(\n        encodedAddressTableLookupsLength.length,\n        'addressTableLookupsLength',\n      ),\n      BufferLayout.blob(\n        serializedAddressTableLookups.length,\n        'serializedAddressTableLookups',\n      ),\n    ]);\n\n    const serializedMessage = new Uint8Array(PACKET_DATA_SIZE);\n    const MESSAGE_VERSION_0_PREFIX = 1 << 7;\n    const serializedMessageLength = messageLayout.encode(\n      {\n        prefix: MESSAGE_VERSION_0_PREFIX,\n        header: this.header,\n        staticAccountKeysLength: new Uint8Array(encodedStaticAccountKeysLength),\n        staticAccountKeys: this.staticAccountKeys.map(key => key.toBytes()),\n        recentBlockhash: bs58.decode(this.recentBlockhash),\n        instructionsLength: new Uint8Array(encodedInstructionsLength),\n        serializedInstructions,\n        addressTableLookupsLength: new Uint8Array(\n          encodedAddressTableLookupsLength,\n        ),\n        serializedAddressTableLookups,\n      },\n      serializedMessage,\n    );\n    return serializedMessage.slice(0, serializedMessageLength);\n  }\n\n  private serializeInstructions(): Uint8Array {\n    let serializedLength = 0;\n    const serializedInstructions = new Uint8Array(PACKET_DATA_SIZE);\n    for (const instruction of this.compiledInstructions) {\n      const encodedAccountKeyIndexesLength = Array<number>();\n      shortvec.encodeLength(\n        encodedAccountKeyIndexesLength,\n        instruction.accountKeyIndexes.length,\n      );\n\n      const encodedDataLength = Array<number>();\n      shortvec.encodeLength(encodedDataLength, instruction.data.length);\n\n      const instructionLayout = BufferLayout.struct<{\n        programIdIndex: number;\n        encodedAccountKeyIndexesLength: Uint8Array;\n        accountKeyIndexes: number[];\n        encodedDataLength: Uint8Array;\n        data: Uint8Array;\n      }>([\n        BufferLayout.u8('programIdIndex'),\n        BufferLayout.blob(\n          encodedAccountKeyIndexesLength.length,\n          'encodedAccountKeyIndexesLength',\n        ),\n        BufferLayout.seq(\n          BufferLayout.u8(),\n          instruction.accountKeyIndexes.length,\n          'accountKeyIndexes',\n        ),\n        BufferLayout.blob(encodedDataLength.length, 'encodedDataLength'),\n        BufferLayout.blob(instruction.data.length, 'data'),\n      ]);\n\n      serializedLength += instructionLayout.encode(\n        {\n          programIdIndex: instruction.programIdIndex,\n          encodedAccountKeyIndexesLength: new Uint8Array(\n            encodedAccountKeyIndexesLength,\n          ),\n          accountKeyIndexes: instruction.accountKeyIndexes,\n          encodedDataLength: new Uint8Array(encodedDataLength),\n          data: instruction.data,\n        },\n        serializedInstructions,\n        serializedLength,\n      );\n    }\n\n    return serializedInstructions.slice(0, serializedLength);\n  }\n\n  private serializeAddressTableLookups(): Uint8Array {\n    let serializedLength = 0;\n    const serializedAddressTableLookups = new Uint8Array(PACKET_DATA_SIZE);\n    for (const lookup of this.addressTableLookups) {\n      const encodedWritableIndexesLength = Array<number>();\n      shortvec.encodeLength(\n        encodedWritableIndexesLength,\n        lookup.writableIndexes.length,\n      );\n\n      const encodedReadonlyIndexesLength = Array<number>();\n      shortvec.encodeLength(\n        encodedReadonlyIndexesLength,\n        lookup.readonlyIndexes.length,\n      );\n\n      const addressTableLookupLayout = BufferLayout.struct<{\n        accountKey: Uint8Array;\n        encodedWritableIndexesLength: Uint8Array;\n        writableIndexes: number[];\n        encodedReadonlyIndexesLength: Uint8Array;\n        readonlyIndexes: number[];\n      }>([\n        Layout.publicKey('accountKey'),\n        BufferLayout.blob(\n          encodedWritableIndexesLength.length,\n          'encodedWritableIndexesLength',\n        ),\n        BufferLayout.seq(\n          BufferLayout.u8(),\n          lookup.writableIndexes.length,\n          'writableIndexes',\n        ),\n        BufferLayout.blob(\n          encodedReadonlyIndexesLength.length,\n          'encodedReadonlyIndexesLength',\n        ),\n        BufferLayout.seq(\n          BufferLayout.u8(),\n          lookup.readonlyIndexes.length,\n          'readonlyIndexes',\n        ),\n      ]);\n\n      serializedLength += addressTableLookupLayout.encode(\n        {\n          accountKey: lookup.accountKey.toBytes(),\n          encodedWritableIndexesLength: new Uint8Array(\n            encodedWritableIndexesLength,\n          ),\n          writableIndexes: lookup.writableIndexes,\n          encodedReadonlyIndexesLength: new Uint8Array(\n            encodedReadonlyIndexesLength,\n          ),\n          readonlyIndexes: lookup.readonlyIndexes,\n        },\n        serializedAddressTableLookups,\n        serializedLength,\n      );\n    }\n\n    return serializedAddressTableLookups.slice(0, serializedLength);\n  }\n\n  static deserialize(serializedMessage: Uint8Array): MessageV0 {\n    let byteArray = [...serializedMessage];\n\n    const prefix = byteArray.shift() as number;\n    const maskedPrefix = prefix & VERSION_PREFIX_MASK;\n    assert(\n      prefix !== maskedPrefix,\n      `Expected versioned message but received legacy message`,\n    );\n\n    const version = maskedPrefix;\n    assert(\n      version === 0,\n      `Expected versioned message with version 0 but found version ${version}`,\n    );\n\n    const header: MessageHeader = {\n      numRequiredSignatures: byteArray.shift() as number,\n      numReadonlySignedAccounts: byteArray.shift() as number,\n      numReadonlyUnsignedAccounts: byteArray.shift() as number,\n    };\n\n    const staticAccountKeys = [];\n    const staticAccountKeysLength = shortvec.decodeLength(byteArray);\n    for (let i = 0; i < staticAccountKeysLength; i++) {\n      staticAccountKeys.push(\n        new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH)),\n      );\n    }\n\n    const recentBlockhash = bs58.encode(byteArray.splice(0, PUBLIC_KEY_LENGTH));\n\n    const instructionCount = shortvec.decodeLength(byteArray);\n    const compiledInstructions: MessageCompiledInstruction[] = [];\n    for (let i = 0; i < instructionCount; i++) {\n      const programIdIndex = byteArray.shift() as number;\n      const accountKeyIndexesLength = shortvec.decodeLength(byteArray);\n      const accountKeyIndexes = byteArray.splice(0, accountKeyIndexesLength);\n      const dataLength = shortvec.decodeLength(byteArray);\n      const data = new Uint8Array(byteArray.splice(0, dataLength));\n      compiledInstructions.push({\n        programIdIndex,\n        accountKeyIndexes,\n        data,\n      });\n    }\n\n    const addressTableLookupsCount = shortvec.decodeLength(byteArray);\n    const addressTableLookups: MessageAddressTableLookup[] = [];\n    for (let i = 0; i < addressTableLookupsCount; i++) {\n      const accountKey = new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH));\n      const writableIndexesLength = shortvec.decodeLength(byteArray);\n      const writableIndexes = byteArray.splice(0, writableIndexesLength);\n      const readonlyIndexesLength = shortvec.decodeLength(byteArray);\n      const readonlyIndexes = byteArray.splice(0, readonlyIndexesLength);\n      addressTableLookups.push({\n        accountKey,\n        writableIndexes,\n        readonlyIndexes,\n      });\n    }\n\n    return new MessageV0({\n      header,\n      staticAccountKeys,\n      recentBlockhash,\n      compiledInstructions,\n      addressTableLookups,\n    });\n  }\n}\n","import {VERSION_PREFIX_MASK} from '../transaction/constants';\nimport {Message} from './legacy';\nimport {MessageV0} from './v0';\n\nexport type VersionedMessage = Message | MessageV0;\n// eslint-disable-next-line no-redeclare\nexport const VersionedMessage = {\n  deserializeMessageVersion(serializedMessage: Uint8Array): 'legacy' | number {\n    const prefix = serializedMessage[0];\n    const maskedPrefix = prefix & VERSION_PREFIX_MASK;\n\n    // if the highest bit of the prefix is not set, the message is not versioned\n    if (maskedPrefix === prefix) {\n      return 'legacy';\n    }\n\n    // the lower 7 bits of the prefix indicate the message version\n    return maskedPrefix;\n  },\n\n  deserialize: (serializedMessage: Uint8Array): VersionedMessage => {\n    const version =\n      VersionedMessage.deserializeMessageVersion(serializedMessage);\n    if (version === 'legacy') {\n      return Message.from(serializedMessage);\n    }\n\n    if (version === 0) {\n      return MessageV0.deserialize(serializedMessage);\n    } else {\n      throw new Error(\n        `Transaction message version ${version} deserialization is not supported`,\n      );\n    }\n  },\n};\n","import bs58 from 'bs58';\nimport {Buffer} from 'buffer';\n\nimport {PACKET_DATA_SIZE, SIGNATURE_LENGTH_IN_BYTES} from './constants';\nimport {Connection} from '../connection';\nimport {Message} from '../message';\nimport {PublicKey} from '../publickey';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport {toBuffer} from '../utils/to-buffer';\nimport invariant from '../utils/assert';\nimport type {Signer} from '../keypair';\nimport type {Blockhash} from '../blockhash';\nimport type {CompiledInstruction} from '../message';\nimport {sign, verify} from '../utils/ed25519';\n\n/**\n * Transaction signature as base-58 encoded string\n */\nexport type TransactionSignature = string;\n\nexport const enum TransactionStatus {\n  BLOCKHEIGHT_EXCEEDED,\n  PROCESSED,\n  TIMED_OUT,\n  NONCE_INVALID,\n}\n\n/**\n * Default (empty) signature\n */\nconst DEFAULT_SIGNATURE = Buffer.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0);\n\n/**\n * Account metadata used to define instructions\n */\nexport type AccountMeta = {\n  /** An account's public key */\n  pubkey: PublicKey;\n  /** True if an instruction requires a transaction signature matching `pubkey` */\n  isSigner: boolean;\n  /** True if the `pubkey` can be loaded as a read-write account. */\n  isWritable: boolean;\n};\n\n/**\n * List of TransactionInstruction object fields that may be initialized at construction\n */\nexport type TransactionInstructionCtorFields = {\n  keys: Array<AccountMeta>;\n  programId: PublicKey;\n  data?: Buffer;\n};\n\n/**\n * Configuration object for Transaction.serialize()\n */\nexport type SerializeConfig = {\n  /** Require all transaction signatures be present (default: true) */\n  requireAllSignatures?: boolean;\n  /** Verify provided signatures (default: true) */\n  verifySignatures?: boolean;\n};\n\n/**\n * @internal\n */\nexport interface TransactionInstructionJSON {\n  keys: {\n    pubkey: string;\n    isSigner: boolean;\n    isWritable: boolean;\n  }[];\n  programId: string;\n  data: number[];\n}\n\n/**\n * Transaction Instruction class\n */\nexport class TransactionInstruction {\n  /**\n   * Public keys to include in this transaction\n   * Boolean represents whether this pubkey needs to sign the transaction\n   */\n  keys: Array<AccountMeta>;\n\n  /**\n   * Program Id to execute\n   */\n  programId: PublicKey;\n\n  /**\n   * Program input\n   */\n  data: Buffer = Buffer.alloc(0);\n\n  constructor(opts: TransactionInstructionCtorFields) {\n    this.programId = opts.programId;\n    this.keys = opts.keys;\n    if (opts.data) {\n      this.data = opts.data;\n    }\n  }\n\n  /**\n   * @internal\n   */\n  toJSON(): TransactionInstructionJSON {\n    return {\n      keys: this.keys.map(({pubkey, isSigner, isWritable}) => ({\n        pubkey: pubkey.toJSON(),\n        isSigner,\n        isWritable,\n      })),\n      programId: this.programId.toJSON(),\n      data: [...this.data],\n    };\n  }\n}\n\n/**\n * Pair of signature and corresponding public key\n */\nexport type SignaturePubkeyPair = {\n  signature: Buffer | null;\n  publicKey: PublicKey;\n};\n\n/**\n * List of Transaction object fields that may be initialized at construction\n */\nexport type TransactionCtorFields_DEPRECATED = {\n  /** Optional nonce information used for offline nonce'd transactions */\n  nonceInfo?: NonceInformation | null;\n  /** The transaction fee payer */\n  feePayer?: PublicKey | null;\n  /** One or more signatures */\n  signatures?: Array<SignaturePubkeyPair>;\n  /** A recent blockhash */\n  recentBlockhash?: Blockhash;\n};\n\n// For backward compatibility; an unfortunate consequence of being\n// forced to over-export types by the documentation generator.\n// See https://github.com/solana-labs/solana/pull/25820\nexport type TransactionCtorFields = TransactionCtorFields_DEPRECATED;\n\n/**\n * Blockhash-based transactions have a lifetime that are defined by\n * the blockhash they include. Any transaction whose blockhash is\n * too old will be rejected.\n */\nexport type TransactionBlockhashCtor = {\n  /** The transaction fee payer */\n  feePayer?: PublicKey | null;\n  /** One or more signatures */\n  signatures?: Array<SignaturePubkeyPair>;\n  /** A recent blockhash */\n  blockhash: Blockhash;\n  /** the last block chain can advance to before tx is declared expired */\n  lastValidBlockHeight: number;\n};\n\n/**\n * Use these options to construct a durable nonce transaction.\n */\nexport type TransactionNonceCtor = {\n  /** The transaction fee payer */\n  feePayer?: PublicKey | null;\n  minContextSlot: number;\n  nonceInfo: NonceInformation;\n  /** One or more signatures */\n  signatures?: Array<SignaturePubkeyPair>;\n};\n\n/**\n * Nonce information to be used to build an offline Transaction.\n */\nexport type NonceInformation = {\n  /** The current blockhash stored in the nonce */\n  nonce: Blockhash;\n  /** AdvanceNonceAccount Instruction */\n  nonceInstruction: TransactionInstruction;\n};\n\n/**\n * @internal\n */\nexport interface TransactionJSON {\n  recentBlockhash: string | null;\n  feePayer: string | null;\n  nonceInfo: {\n    nonce: string;\n    nonceInstruction: TransactionInstructionJSON;\n  } | null;\n  instructions: TransactionInstructionJSON[];\n  signers: string[];\n}\n\n/**\n * Transaction class\n */\nexport class Transaction {\n  /**\n   * Signatures for the transaction.  Typically created by invoking the\n   * `sign()` method\n   */\n  signatures: Array<SignaturePubkeyPair> = [];\n\n  /**\n   * The first (payer) Transaction signature\n   *\n   * @returns {Buffer | null} Buffer of payer's signature\n   */\n  get signature(): Buffer | null {\n    if (this.signatures.length > 0) {\n      return this.signatures[0].signature;\n    }\n    return null;\n  }\n\n  /**\n   * The transaction fee payer\n   */\n  feePayer?: PublicKey;\n\n  /**\n   * The instructions to atomically execute\n   */\n  instructions: Array<TransactionInstruction> = [];\n\n  /**\n   * A recent transaction id. Must be populated by the caller\n   */\n  recentBlockhash?: Blockhash;\n\n  /**\n   * the last block chain can advance to before tx is declared expired\n   * */\n  lastValidBlockHeight?: number;\n\n  /**\n   * Optional Nonce information. If populated, transaction will use a durable\n   * Nonce hash instead of a recentBlockhash. Must be populated by the caller\n   */\n  nonceInfo?: NonceInformation;\n\n  /**\n   * If this is a nonce transaction this represents the minimum slot from which\n   * to evaluate if the nonce has advanced when attempting to confirm the\n   * transaction. This protects against a case where the transaction confirmation\n   * logic loads the nonce account from an old slot and assumes the mismatch in\n   * nonce value implies that the nonce has been advanced.\n   */\n  minNonceContextSlot?: number;\n\n  /**\n   * @internal\n   */\n  _message?: Message;\n\n  /**\n   * @internal\n   */\n  _json?: TransactionJSON;\n\n  // Construct a transaction with a blockhash and lastValidBlockHeight\n  constructor(opts?: TransactionBlockhashCtor);\n\n  // Construct a transaction using a durable nonce\n  constructor(opts?: TransactionNonceCtor);\n\n  /**\n   * @deprecated `TransactionCtorFields` has been deprecated and will be removed in a future version.\n   * Please supply a `TransactionBlockhashCtor` instead.\n   */\n  constructor(opts?: TransactionCtorFields_DEPRECATED);\n\n  /**\n   * Construct an empty Transaction\n   */\n  constructor(\n    opts?:\n      | TransactionBlockhashCtor\n      | TransactionNonceCtor\n      | TransactionCtorFields_DEPRECATED,\n  ) {\n    if (!opts) {\n      return;\n    }\n    if (opts.feePayer) {\n      this.feePayer = opts.feePayer;\n    }\n    if (opts.signatures) {\n      this.signatures = opts.signatures;\n    }\n    if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) {\n      const {minContextSlot, nonceInfo} = opts as TransactionNonceCtor;\n      this.minNonceContextSlot = minContextSlot;\n      this.nonceInfo = nonceInfo;\n    } else if (\n      Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')\n    ) {\n      const {blockhash, lastValidBlockHeight} =\n        opts as TransactionBlockhashCtor;\n      this.recentBlockhash = blockhash;\n      this.lastValidBlockHeight = lastValidBlockHeight;\n    } else {\n      const {recentBlockhash, nonceInfo} =\n        opts as TransactionCtorFields_DEPRECATED;\n      if (nonceInfo) {\n        this.nonceInfo = nonceInfo;\n      }\n      this.recentBlockhash = recentBlockhash;\n    }\n  }\n\n  /**\n   * @internal\n   */\n  toJSON(): TransactionJSON {\n    return {\n      recentBlockhash: this.recentBlockhash || null,\n      feePayer: this.feePayer ? this.feePayer.toJSON() : null,\n      nonceInfo: this.nonceInfo\n        ? {\n            nonce: this.nonceInfo.nonce,\n            nonceInstruction: this.nonceInfo.nonceInstruction.toJSON(),\n          }\n        : null,\n      instructions: this.instructions.map(instruction => instruction.toJSON()),\n      signers: this.signatures.map(({publicKey}) => {\n        return publicKey.toJSON();\n      }),\n    };\n  }\n\n  /**\n   * Add one or more instructions to this Transaction\n   *\n   * @param {Array< Transaction | TransactionInstruction | TransactionInstructionCtorFields >} items - Instructions to add to the Transaction\n   */\n  add(\n    ...items: Array<\n      Transaction | TransactionInstruction | TransactionInstructionCtorFields\n    >\n  ): Transaction {\n    if (items.length === 0) {\n      throw new Error('No instructions');\n    }\n\n    items.forEach((item: any) => {\n      if ('instructions' in item) {\n        this.instructions = this.instructions.concat(item.instructions);\n      } else if ('data' in item && 'programId' in item && 'keys' in item) {\n        this.instructions.push(item);\n      } else {\n        this.instructions.push(new TransactionInstruction(item));\n      }\n    });\n    return this;\n  }\n\n  /**\n   * Compile transaction data\n   */\n  compileMessage(): Message {\n    if (\n      this._message &&\n      JSON.stringify(this.toJSON()) === JSON.stringify(this._json)\n    ) {\n      return this._message;\n    }\n\n    let recentBlockhash;\n    let instructions: TransactionInstruction[];\n    if (this.nonceInfo) {\n      recentBlockhash = this.nonceInfo.nonce;\n      if (this.instructions[0] != this.nonceInfo.nonceInstruction) {\n        instructions = [this.nonceInfo.nonceInstruction, ...this.instructions];\n      } else {\n        instructions = this.instructions;\n      }\n    } else {\n      recentBlockhash = this.recentBlockhash;\n      instructions = this.instructions;\n    }\n    if (!recentBlockhash) {\n      throw new Error('Transaction recentBlockhash required');\n    }\n\n    if (instructions.length < 1) {\n      console.warn('No instructions provided');\n    }\n\n    let feePayer: PublicKey;\n    if (this.feePayer) {\n      feePayer = this.feePayer;\n    } else if (this.signatures.length > 0 && this.signatures[0].publicKey) {\n      // Use implicit fee payer\n      feePayer = this.signatures[0].publicKey;\n    } else {\n      throw new Error('Transaction fee payer required');\n    }\n\n    for (let i = 0; i < instructions.length; i++) {\n      if (instructions[i].programId === undefined) {\n        throw new Error(\n          `Transaction instruction index ${i} has undefined program id`,\n        );\n      }\n    }\n\n    const programIds: string[] = [];\n    const accountMetas: AccountMeta[] = [];\n    instructions.forEach(instruction => {\n      instruction.keys.forEach(accountMeta => {\n        accountMetas.push({...accountMeta});\n      });\n\n      const programId = instruction.programId.toString();\n      if (!programIds.includes(programId)) {\n        programIds.push(programId);\n      }\n    });\n\n    // Append programID account metas\n    programIds.forEach(programId => {\n      accountMetas.push({\n        pubkey: new PublicKey(programId),\n        isSigner: false,\n        isWritable: false,\n      });\n    });\n\n    // Cull duplicate account metas\n    const uniqueMetas: AccountMeta[] = [];\n    accountMetas.forEach(accountMeta => {\n      const pubkeyString = accountMeta.pubkey.toString();\n      const uniqueIndex = uniqueMetas.findIndex(x => {\n        return x.pubkey.toString() === pubkeyString;\n      });\n      if (uniqueIndex > -1) {\n        uniqueMetas[uniqueIndex].isWritable =\n          uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable;\n        uniqueMetas[uniqueIndex].isSigner =\n          uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner;\n      } else {\n        uniqueMetas.push(accountMeta);\n      }\n    });\n\n    // Sort. Prioritizing first by signer, then by writable\n    uniqueMetas.sort(function (x, y) {\n      if (x.isSigner !== y.isSigner) {\n        // Signers always come before non-signers\n        return x.isSigner ? -1 : 1;\n      }\n      if (x.isWritable !== y.isWritable) {\n        // Writable accounts always come before read-only accounts\n        return x.isWritable ? -1 : 1;\n      }\n      // Otherwise, sort by pubkey, stringwise.\n      const options = {\n        localeMatcher: 'best fit',\n        usage: 'sort',\n        sensitivity: 'variant',\n        ignorePunctuation: false,\n        numeric: false,\n        caseFirst: 'lower',\n      } as Intl.CollatorOptions;\n      return x.pubkey\n        .toBase58()\n        .localeCompare(y.pubkey.toBase58(), 'en', options);\n    });\n\n    // Move fee payer to the front\n    const feePayerIndex = uniqueMetas.findIndex(x => {\n      return x.pubkey.equals(feePayer);\n    });\n    if (feePayerIndex > -1) {\n      const [payerMeta] = uniqueMetas.splice(feePayerIndex, 1);\n      payerMeta.isSigner = true;\n      payerMeta.isWritable = true;\n      uniqueMetas.unshift(payerMeta);\n    } else {\n      uniqueMetas.unshift({\n        pubkey: feePayer,\n        isSigner: true,\n        isWritable: true,\n      });\n    }\n\n    // Disallow unknown signers\n    for (const signature of this.signatures) {\n      const uniqueIndex = uniqueMetas.findIndex(x => {\n        return x.pubkey.equals(signature.publicKey);\n      });\n      if (uniqueIndex > -1) {\n        if (!uniqueMetas[uniqueIndex].isSigner) {\n          uniqueMetas[uniqueIndex].isSigner = true;\n          console.warn(\n            'Transaction references a signature that is unnecessary, ' +\n              'only the fee payer and instruction signer accounts should sign a transaction. ' +\n              'This behavior is deprecated and will throw an error in the next major version release.',\n          );\n        }\n      } else {\n        throw new Error(`unknown signer: ${signature.publicKey.toString()}`);\n      }\n    }\n\n    let numRequiredSignatures = 0;\n    let numReadonlySignedAccounts = 0;\n    let numReadonlyUnsignedAccounts = 0;\n\n    // Split out signing from non-signing keys and count header values\n    const signedKeys: string[] = [];\n    const unsignedKeys: string[] = [];\n    uniqueMetas.forEach(({pubkey, isSigner, isWritable}) => {\n      if (isSigner) {\n        signedKeys.push(pubkey.toString());\n        numRequiredSignatures += 1;\n        if (!isWritable) {\n          numReadonlySignedAccounts += 1;\n        }\n      } else {\n        unsignedKeys.push(pubkey.toString());\n        if (!isWritable) {\n          numReadonlyUnsignedAccounts += 1;\n        }\n      }\n    });\n\n    const accountKeys = signedKeys.concat(unsignedKeys);\n    const compiledInstructions: CompiledInstruction[] = instructions.map(\n      instruction => {\n        const {data, programId} = instruction;\n        return {\n          programIdIndex: accountKeys.indexOf(programId.toString()),\n          accounts: instruction.keys.map(meta =>\n            accountKeys.indexOf(meta.pubkey.toString()),\n          ),\n          data: bs58.encode(data),\n        };\n      },\n    );\n\n    compiledInstructions.forEach(instruction => {\n      invariant(instruction.programIdIndex >= 0);\n      instruction.accounts.forEach(keyIndex => invariant(keyIndex >= 0));\n    });\n\n    return new Message({\n      header: {\n        numRequiredSignatures,\n        numReadonlySignedAccounts,\n        numReadonlyUnsignedAccounts,\n      },\n      accountKeys,\n      recentBlockhash,\n      instructions: compiledInstructions,\n    });\n  }\n\n  /**\n   * @internal\n   */\n  _compile(): Message {\n    const message = this.compileMessage();\n    const signedKeys = message.accountKeys.slice(\n      0,\n      message.header.numRequiredSignatures,\n    );\n\n    if (this.signatures.length === signedKeys.length) {\n      const valid = this.signatures.every((pair, index) => {\n        return signedKeys[index].equals(pair.publicKey);\n      });\n\n      if (valid) return message;\n    }\n\n    this.signatures = signedKeys.map(publicKey => ({\n      signature: null,\n      publicKey,\n    }));\n\n    return message;\n  }\n\n  /**\n   * Get a buffer of the Transaction data that need to be covered by signatures\n   */\n  serializeMessage(): Buffer {\n    return this._compile().serialize();\n  }\n\n  /**\n   * Get the estimated fee associated with a transaction\n   *\n   * @param {Connection} connection Connection to RPC Endpoint.\n   *\n   * @returns {Promise<number | null>} The estimated fee for the transaction\n   */\n  async getEstimatedFee(connection: Connection): Promise<number | null> {\n    return (await connection.getFeeForMessage(this.compileMessage())).value;\n  }\n\n  /**\n   * Specify the public keys which will be used to sign the Transaction.\n   * The first signer will be used as the transaction fee payer account.\n   *\n   * Signatures can be added with either `partialSign` or `addSignature`\n   *\n   * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be\n   * specified and it can be set in the Transaction constructor or with the\n   * `feePayer` property.\n   */\n  setSigners(...signers: Array<PublicKey>) {\n    if (signers.length === 0) {\n      throw new Error('No signers');\n    }\n\n    const seen = new Set();\n    this.signatures = signers\n      .filter(publicKey => {\n        const key = publicKey.toString();\n        if (seen.has(key)) {\n          return false;\n        } else {\n          seen.add(key);\n          return true;\n        }\n      })\n      .map(publicKey => ({signature: null, publicKey}));\n  }\n\n  /**\n   * Sign the Transaction with the specified signers. Multiple signatures may\n   * be applied to a Transaction. The first signature is considered \"primary\"\n   * and is used identify and confirm transactions.\n   *\n   * If the Transaction `feePayer` is not set, the first signer will be used\n   * as the transaction fee payer account.\n   *\n   * Transaction fields should not be modified after the first call to `sign`,\n   * as doing so may invalidate the signature and cause the Transaction to be\n   * rejected.\n   *\n   * The Transaction must be assigned a valid `recentBlockhash` before invoking this method\n   *\n   * @param {Array<Signer>} signers Array of signers that will sign the transaction\n   */\n  sign(...signers: Array<Signer>) {\n    if (signers.length === 0) {\n      throw new Error('No signers');\n    }\n\n    // Dedupe signers\n    const seen = new Set();\n    const uniqueSigners = [];\n    for (const signer of signers) {\n      const key = signer.publicKey.toString();\n      if (seen.has(key)) {\n        continue;\n      } else {\n        seen.add(key);\n        uniqueSigners.push(signer);\n      }\n    }\n\n    this.signatures = uniqueSigners.map(signer => ({\n      signature: null,\n      publicKey: signer.publicKey,\n    }));\n\n    const message = this._compile();\n    this._partialSign(message, ...uniqueSigners);\n  }\n\n  /**\n   * Partially sign a transaction with the specified accounts. All accounts must\n   * correspond to either the fee payer or a signer account in the transaction\n   * instructions.\n   *\n   * All the caveats from the `sign` method apply to `partialSign`\n   *\n   * @param {Array<Signer>} signers Array of signers that will sign the transaction\n   */\n  partialSign(...signers: Array<Signer>) {\n    if (signers.length === 0) {\n      throw new Error('No signers');\n    }\n\n    // Dedupe signers\n    const seen = new Set();\n    const uniqueSigners = [];\n    for (const signer of signers) {\n      const key = signer.publicKey.toString();\n      if (seen.has(key)) {\n        continue;\n      } else {\n        seen.add(key);\n        uniqueSigners.push(signer);\n      }\n    }\n\n    const message = this._compile();\n    this._partialSign(message, ...uniqueSigners);\n  }\n\n  /**\n   * @internal\n   */\n  _partialSign(message: Message, ...signers: Array<Signer>) {\n    const signData = message.serialize();\n    signers.forEach(signer => {\n      const signature = sign(signData, signer.secretKey);\n      this._addSignature(signer.publicKey, toBuffer(signature));\n    });\n  }\n\n  /**\n   * Add an externally created signature to a transaction. The public key\n   * must correspond to either the fee payer or a signer account in the transaction\n   * instructions.\n   *\n   * @param {PublicKey} pubkey Public key that will be added to the transaction.\n   * @param {Buffer} signature An externally created signature to add to the transaction.\n   */\n  addSignature(pubkey: PublicKey, signature: Buffer) {\n    this._compile(); // Ensure signatures array is populated\n    this._addSignature(pubkey, signature);\n  }\n\n  /**\n   * @internal\n   */\n  _addSignature(pubkey: PublicKey, signature: Buffer) {\n    invariant(signature.length === 64);\n\n    const index = this.signatures.findIndex(sigpair =>\n      pubkey.equals(sigpair.publicKey),\n    );\n    if (index < 0) {\n      throw new Error(`unknown signer: ${pubkey.toString()}`);\n    }\n\n    this.signatures[index].signature = Buffer.from(signature);\n  }\n\n  /**\n   * Verify signatures of a Transaction\n   * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one.\n   * If no boolean is provided, we expect a fully signed Transaction by default.\n   *\n   * @param {boolean} [requireAllSignatures=true] Require a fully signed Transaction\n   */\n  verifySignatures(requireAllSignatures?: boolean): boolean {\n    return this._verifySignatures(\n      this.serializeMessage(),\n      requireAllSignatures === undefined ? true : requireAllSignatures,\n    );\n  }\n\n  /**\n   * @internal\n   */\n  _verifySignatures(\n    signData: Uint8Array,\n    requireAllSignatures: boolean,\n  ): boolean {\n    for (const {signature, publicKey} of this.signatures) {\n      if (signature === null) {\n        if (requireAllSignatures) {\n          return false;\n        }\n      } else {\n        if (!verify(signature, signData, publicKey.toBytes())) {\n          return false;\n        }\n      }\n    }\n    return true;\n  }\n\n  /**\n   * Serialize the Transaction in the wire format.\n   *\n   * @param {Buffer} [config] Config of transaction.\n   *\n   * @returns {Buffer} Signature of transaction in wire format.\n   */\n  serialize(config?: SerializeConfig): Buffer {\n    const {requireAllSignatures, verifySignatures} = Object.assign(\n      {requireAllSignatures: true, verifySignatures: true},\n      config,\n    );\n\n    const signData = this.serializeMessage();\n    if (\n      verifySignatures &&\n      !this._verifySignatures(signData, requireAllSignatures)\n    ) {\n      throw new Error('Signature verification failed');\n    }\n\n    return this._serialize(signData);\n  }\n\n  /**\n   * @internal\n   */\n  _serialize(signData: Buffer): Buffer {\n    const {signatures} = this;\n    const signatureCount: number[] = [];\n    shortvec.encodeLength(signatureCount, signatures.length);\n    const transactionLength =\n      signatureCount.length + signatures.length * 64 + signData.length;\n    const wireTransaction = Buffer.alloc(transactionLength);\n    invariant(signatures.length < 256);\n    Buffer.from(signatureCount).copy(wireTransaction, 0);\n    signatures.forEach(({signature}, index) => {\n      if (signature !== null) {\n        invariant(signature.length === 64, `signature has invalid length`);\n        Buffer.from(signature).copy(\n          wireTransaction,\n          signatureCount.length + index * 64,\n        );\n      }\n    });\n    signData.copy(\n      wireTransaction,\n      signatureCount.length + signatures.length * 64,\n    );\n    invariant(\n      wireTransaction.length <= PACKET_DATA_SIZE,\n      `Transaction too large: ${wireTransaction.length} > ${PACKET_DATA_SIZE}`,\n    );\n    return wireTransaction;\n  }\n\n  /**\n   * Deprecated method\n   * @internal\n   */\n  get keys(): Array<PublicKey> {\n    invariant(this.instructions.length === 1);\n    return this.instructions[0].keys.map(keyObj => keyObj.pubkey);\n  }\n\n  /**\n   * Deprecated method\n   * @internal\n   */\n  get programId(): PublicKey {\n    invariant(this.instructions.length === 1);\n    return this.instructions[0].programId;\n  }\n\n  /**\n   * Deprecated method\n   * @internal\n   */\n  get data(): Buffer {\n    invariant(this.instructions.length === 1);\n    return this.instructions[0].data;\n  }\n\n  /**\n   * Parse a wire transaction into a Transaction object.\n   *\n   * @param {Buffer | Uint8Array | Array<number>} buffer Signature of wire Transaction\n   *\n   * @returns {Transaction} Transaction associated with the signature\n   */\n  static from(buffer: Buffer | Uint8Array | Array<number>): Transaction {\n    // Slice up wire data\n    let byteArray = [...buffer];\n\n    const signatureCount = shortvec.decodeLength(byteArray);\n    let signatures = [];\n    for (let i = 0; i < signatureCount; i++) {\n      const signature = byteArray.slice(0, SIGNATURE_LENGTH_IN_BYTES);\n      byteArray = byteArray.slice(SIGNATURE_LENGTH_IN_BYTES);\n      signatures.push(bs58.encode(Buffer.from(signature)));\n    }\n\n    return Transaction.populate(Message.from(byteArray), signatures);\n  }\n\n  /**\n   * Populate Transaction object from message and signatures\n   *\n   * @param {Message} message Message of transaction\n   * @param {Array<string>} signatures List of signatures to assign to the transaction\n   *\n   * @returns {Transaction} The populated Transaction\n   */\n  static populate(\n    message: Message,\n    signatures: Array<string> = [],\n  ): Transaction {\n    const transaction = new Transaction();\n    transaction.recentBlockhash = message.recentBlockhash;\n    if (message.header.numRequiredSignatures > 0) {\n      transaction.feePayer = message.accountKeys[0];\n    }\n    signatures.forEach((signature, index) => {\n      const sigPubkeyPair = {\n        signature:\n          signature == bs58.encode(DEFAULT_SIGNATURE)\n            ? null\n            : bs58.decode(signature),\n        publicKey: message.accountKeys[index],\n      };\n      transaction.signatures.push(sigPubkeyPair);\n    });\n\n    message.instructions.forEach(instruction => {\n      const keys = instruction.accounts.map(account => {\n        const pubkey = message.accountKeys[account];\n        return {\n          pubkey,\n          isSigner:\n            transaction.signatures.some(\n              keyObj => keyObj.publicKey.toString() === pubkey.toString(),\n            ) || message.isAccountSigner(account),\n          isWritable: message.isAccountWritable(account),\n        };\n      });\n\n      transaction.instructions.push(\n        new TransactionInstruction({\n          keys,\n          programId: message.accountKeys[instruction.programIdIndex],\n          data: bs58.decode(instruction.data),\n        }),\n      );\n    });\n\n    transaction._message = message;\n    transaction._json = transaction.toJSON();\n\n    return transaction;\n  }\n}\n","import {AccountKeysFromLookups} from '../message/account-keys';\nimport assert from '../utils/assert';\nimport {toBuffer} from '../utils/to-buffer';\nimport {Blockhash} from '../blockhash';\nimport {Message, MessageV0, VersionedMessage} from '../message';\nimport {PublicKey} from '../publickey';\nimport {AddressLookupTableAccount} from '../programs';\nimport {AccountMeta, TransactionInstruction} from './legacy';\n\nexport type TransactionMessageArgs = {\n  payerKey: PublicKey;\n  instructions: Array<TransactionInstruction>;\n  recentBlockhash: Blockhash;\n};\n\nexport type DecompileArgs =\n  | {\n      accountKeysFromLookups: AccountKeysFromLookups;\n    }\n  | {\n      addressLookupTableAccounts: AddressLookupTableAccount[];\n    };\n\nexport class TransactionMessage {\n  payerKey: PublicKey;\n  instructions: Array<TransactionInstruction>;\n  recentBlockhash: Blockhash;\n\n  constructor(args: TransactionMessageArgs) {\n    this.payerKey = args.payerKey;\n    this.instructions = args.instructions;\n    this.recentBlockhash = args.recentBlockhash;\n  }\n\n  static decompile(\n    message: VersionedMessage,\n    args?: DecompileArgs,\n  ): TransactionMessage {\n    const {header, compiledInstructions, recentBlockhash} = message;\n\n    const {\n      numRequiredSignatures,\n      numReadonlySignedAccounts,\n      numReadonlyUnsignedAccounts,\n    } = header;\n\n    const numWritableSignedAccounts =\n      numRequiredSignatures - numReadonlySignedAccounts;\n    assert(numWritableSignedAccounts > 0, 'Message header is invalid');\n\n    const numWritableUnsignedAccounts =\n      message.staticAccountKeys.length -\n      numRequiredSignatures -\n      numReadonlyUnsignedAccounts;\n    assert(numWritableUnsignedAccounts >= 0, 'Message header is invalid');\n\n    const accountKeys = message.getAccountKeys(args);\n    const payerKey = accountKeys.get(0);\n    if (payerKey === undefined) {\n      throw new Error(\n        'Failed to decompile message because no account keys were found',\n      );\n    }\n\n    const instructions: TransactionInstruction[] = [];\n    for (const compiledIx of compiledInstructions) {\n      const keys: AccountMeta[] = [];\n\n      for (const keyIndex of compiledIx.accountKeyIndexes) {\n        const pubkey = accountKeys.get(keyIndex);\n        if (pubkey === undefined) {\n          throw new Error(\n            `Failed to find key for account key index ${keyIndex}`,\n          );\n        }\n\n        const isSigner = keyIndex < numRequiredSignatures;\n\n        let isWritable;\n        if (isSigner) {\n          isWritable = keyIndex < numWritableSignedAccounts;\n        } else if (keyIndex < accountKeys.staticAccountKeys.length) {\n          isWritable =\n            keyIndex - numRequiredSignatures < numWritableUnsignedAccounts;\n        } else {\n          isWritable =\n            keyIndex - accountKeys.staticAccountKeys.length <\n            // accountKeysFromLookups cannot be undefined because we already found a pubkey for this index above\n            accountKeys.accountKeysFromLookups!.writable.length;\n        }\n\n        keys.push({\n          pubkey,\n          isSigner: keyIndex < header.numRequiredSignatures,\n          isWritable,\n        });\n      }\n\n      const programId = accountKeys.get(compiledIx.programIdIndex);\n      if (programId === undefined) {\n        throw new Error(\n          `Failed to find program id for program id index ${compiledIx.programIdIndex}`,\n        );\n      }\n\n      instructions.push(\n        new TransactionInstruction({\n          programId,\n          data: toBuffer(compiledIx.data),\n          keys,\n        }),\n      );\n    }\n\n    return new TransactionMessage({\n      payerKey,\n      instructions,\n      recentBlockhash,\n    });\n  }\n\n  compileToLegacyMessage(): Message {\n    return Message.compile({\n      payerKey: this.payerKey,\n      recentBlockhash: this.recentBlockhash,\n      instructions: this.instructions,\n    });\n  }\n\n  compileToV0Message(\n    addressLookupTableAccounts?: AddressLookupTableAccount[],\n  ): MessageV0 {\n    return MessageV0.compile({\n      payerKey: this.payerKey,\n      recentBlockhash: this.recentBlockhash,\n      instructions: this.instructions,\n      addressLookupTableAccounts,\n    });\n  }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {Signer} from '../keypair';\nimport assert from '../utils/assert';\nimport {VersionedMessage} from '../message/versioned';\nimport {SIGNATURE_LENGTH_IN_BYTES} from './constants';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport * as Layout from '../layout';\nimport {sign} from '../utils/ed25519';\nimport {PublicKey} from '../publickey';\n\nexport type TransactionVersion = 'legacy' | 0;\n\n/**\n * Versioned transaction class\n */\nexport class VersionedTransaction {\n  signatures: Array<Uint8Array>;\n  message: VersionedMessage;\n\n  get version(): TransactionVersion {\n    return this.message.version;\n  }\n\n  constructor(message: VersionedMessage, signatures?: Array<Uint8Array>) {\n    if (signatures !== undefined) {\n      assert(\n        signatures.length === message.header.numRequiredSignatures,\n        'Expected signatures length to be equal to the number of required signatures',\n      );\n      this.signatures = signatures;\n    } else {\n      const defaultSignatures = [];\n      for (let i = 0; i < message.header.numRequiredSignatures; i++) {\n        defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES));\n      }\n      this.signatures = defaultSignatures;\n    }\n    this.message = message;\n  }\n\n  serialize(): Uint8Array {\n    const serializedMessage = this.message.serialize();\n\n    const encodedSignaturesLength = Array<number>();\n    shortvec.encodeLength(encodedSignaturesLength, this.signatures.length);\n\n    const transactionLayout = BufferLayout.struct<{\n      encodedSignaturesLength: Uint8Array;\n      signatures: Array<Uint8Array>;\n      serializedMessage: Uint8Array;\n    }>([\n      BufferLayout.blob(\n        encodedSignaturesLength.length,\n        'encodedSignaturesLength',\n      ),\n      BufferLayout.seq(\n        Layout.signature(),\n        this.signatures.length,\n        'signatures',\n      ),\n      BufferLayout.blob(serializedMessage.length, 'serializedMessage'),\n    ]);\n\n    const serializedTransaction = new Uint8Array(2048);\n    const serializedTransactionLength = transactionLayout.encode(\n      {\n        encodedSignaturesLength: new Uint8Array(encodedSignaturesLength),\n        signatures: this.signatures,\n        serializedMessage,\n      },\n      serializedTransaction,\n    );\n\n    return serializedTransaction.slice(0, serializedTransactionLength);\n  }\n\n  static deserialize(serializedTransaction: Uint8Array): VersionedTransaction {\n    let byteArray = [...serializedTransaction];\n\n    const signatures = [];\n    const signaturesLength = shortvec.decodeLength(byteArray);\n    for (let i = 0; i < signaturesLength; i++) {\n      signatures.push(\n        new Uint8Array(byteArray.splice(0, SIGNATURE_LENGTH_IN_BYTES)),\n      );\n    }\n\n    const message = VersionedMessage.deserialize(new Uint8Array(byteArray));\n    return new VersionedTransaction(message, signatures);\n  }\n\n  sign(signers: Array<Signer>) {\n    const messageData = this.message.serialize();\n    const signerPubkeys = this.message.staticAccountKeys.slice(\n      0,\n      this.message.header.numRequiredSignatures,\n    );\n    for (const signer of signers) {\n      const signerIndex = signerPubkeys.findIndex(pubkey =>\n        pubkey.equals(signer.publicKey),\n      );\n      assert(\n        signerIndex >= 0,\n        `Cannot sign with non signer key ${signer.publicKey.toBase58()}`,\n      );\n      this.signatures[signerIndex] = sign(messageData, signer.secretKey);\n    }\n  }\n\n  addSignature(publicKey: PublicKey, signature: Uint8Array) {\n    assert(signature.byteLength === 64, 'Signature must be 64 bytes long');\n    const signerPubkeys = this.message.staticAccountKeys.slice(\n      0,\n      this.message.header.numRequiredSignatures,\n    );\n    const signerIndex = signerPubkeys.findIndex(pubkey =>\n      pubkey.equals(publicKey),\n    );\n    assert(\n      signerIndex >= 0,\n      `Can not add signature; \\`${publicKey.toBase58()}\\` is not required to sign this transaction`,\n    );\n    this.signatures[signerIndex] = signature;\n  }\n}\n","// TODO: These constants should be removed in favor of reading them out of a\n// Syscall account\n\n/**\n * @internal\n */\nexport const NUM_TICKS_PER_SECOND = 160;\n\n/**\n * @internal\n */\nexport const DEFAULT_TICKS_PER_SLOT = 64;\n\n/**\n * @internal\n */\nexport const NUM_SLOTS_PER_SECOND =\n  NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT;\n\n/**\n * @internal\n */\nexport const MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND;\n","import {PublicKey} from './publickey';\n\nexport const SYSVAR_CLOCK_PUBKEY = new PublicKey(\n  'SysvarC1ock11111111111111111111111111111111',\n);\n\nexport const SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey(\n  'SysvarEpochSchedu1e111111111111111111111111',\n);\n\nexport const SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey(\n  'Sysvar1nstructions1111111111111111111111111',\n);\n\nexport const SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey(\n  'SysvarRecentB1ockHashes11111111111111111111',\n);\n\nexport const SYSVAR_RENT_PUBKEY = new PublicKey(\n  'SysvarRent111111111111111111111111111111111',\n);\n\nexport const SYSVAR_REWARDS_PUBKEY = new PublicKey(\n  'SysvarRewards111111111111111111111111111111',\n);\n\nexport const SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey(\n  'SysvarS1otHashes111111111111111111111111111',\n);\n\nexport const SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey(\n  'SysvarS1otHistory11111111111111111111111111',\n);\n\nexport const SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey(\n  'SysvarStakeHistory1111111111111111111111111',\n);\n","import {Connection, SignatureResult} from '../connection';\nimport {Transaction} from '../transaction';\nimport type {ConfirmOptions} from '../connection';\nimport type {Signer} from '../keypair';\nimport type {TransactionSignature} from '../transaction';\n\n/**\n * Sign, send and confirm a transaction.\n *\n * If `commitment` option is not specified, defaults to 'max' commitment.\n *\n * @param {Connection} connection\n * @param {Transaction} transaction\n * @param {Array<Signer>} signers\n * @param {ConfirmOptions} [options]\n * @returns {Promise<TransactionSignature>}\n */\nexport async function sendAndConfirmTransaction(\n  connection: Connection,\n  transaction: Transaction,\n  signers: Array<Signer>,\n  options?: ConfirmOptions &\n    Readonly<{\n      // A signal that, when aborted, cancels any outstanding transaction confirmation operations\n      abortSignal?: AbortSignal;\n    }>,\n): Promise<TransactionSignature> {\n  const sendOptions = options && {\n    skipPreflight: options.skipPreflight,\n    preflightCommitment: options.preflightCommitment || options.commitment,\n    maxRetries: options.maxRetries,\n    minContextSlot: options.minContextSlot,\n  };\n\n  const signature = await connection.sendTransaction(\n    transaction,\n    signers,\n    sendOptions,\n  );\n\n  let status: SignatureResult;\n  if (\n    transaction.recentBlockhash != null &&\n    transaction.lastValidBlockHeight != null\n  ) {\n    status = (\n      await connection.confirmTransaction(\n        {\n          abortSignal: options?.abortSignal,\n          signature: signature,\n          blockhash: transaction.recentBlockhash,\n          lastValidBlockHeight: transaction.lastValidBlockHeight,\n        },\n        options && options.commitment,\n      )\n    ).value;\n  } else if (\n    transaction.minNonceContextSlot != null &&\n    transaction.nonceInfo != null\n  ) {\n    const {nonceInstruction} = transaction.nonceInfo;\n    const nonceAccountPubkey = nonceInstruction.keys[0].pubkey;\n    status = (\n      await connection.confirmTransaction(\n        {\n          abortSignal: options?.abortSignal,\n          minContextSlot: transaction.minNonceContextSlot,\n          nonceAccountPubkey,\n          nonceValue: transaction.nonceInfo.nonce,\n          signature,\n        },\n        options && options.commitment,\n      )\n    ).value;\n  } else {\n    if (options?.abortSignal != null) {\n      console.warn(\n        'sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was ' +\n          'supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` ' +\n          'or a combination of `nonceInfo` and `minNonceContextSlot` are abortable.',\n      );\n    }\n    status = (\n      await connection.confirmTransaction(\n        signature,\n        options && options.commitment,\n      )\n    ).value;\n  }\n\n  if (status.err) {\n    throw new Error(\n      `Transaction ${signature} failed (${JSON.stringify(status)})`,\n    );\n  }\n\n  return signature;\n}\n","// zzz\nexport function sleep(ms: number): Promise<void> {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport * as Layout from './layout';\n\nexport interface IInstructionInputData {\n  readonly instruction: number;\n}\n\n/**\n * @internal\n */\nexport type InstructionType<TInputData extends IInstructionInputData> = {\n  /** The Instruction index (from solana upstream program) */\n  index: number;\n  /** The BufferLayout to use to build data */\n  layout: BufferLayout.Layout<TInputData>;\n};\n\n/**\n * Populate a buffer of instruction data using an InstructionType\n * @internal\n */\nexport function encodeData<TInputData extends IInstructionInputData>(\n  type: InstructionType<TInputData>,\n  fields?: any,\n): Buffer {\n  const allocLength =\n    type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields);\n  const data = Buffer.alloc(allocLength);\n  const layoutFields = Object.assign({instruction: type.index}, fields);\n  type.layout.encode(layoutFields, data);\n  return data;\n}\n\n/**\n * Decode instruction data buffer using an InstructionType\n * @internal\n */\nexport function decodeData<TInputData extends IInstructionInputData>(\n  type: InstructionType<TInputData>,\n  buffer: Buffer,\n): TInputData {\n  let data: TInputData;\n  try {\n    data = type.layout.decode(buffer);\n  } catch (err) {\n    throw new Error('invalid instruction; ' + err);\n  }\n\n  if (data.instruction !== type.index) {\n    throw new Error(\n      `invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`,\n    );\n  }\n\n  return data;\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\n/**\n * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11\n *\n * @internal\n */\nexport const FeeCalculatorLayout = BufferLayout.nu64('lamportsPerSignature');\n\n/**\n * Calculator for transaction fees.\n *\n * @deprecated Deprecated since Solana v1.8.0.\n */\nexport interface FeeCalculator {\n  /** Cost in lamports to validate a signature. */\n  lamportsPerSignature: number;\n}\n","import * as BufferLayout from '@solana/buffer-layout';\nimport {Buffer} from 'buffer';\n\nimport * as Layout from './layout';\nimport {PublicKey} from './publickey';\nimport type {FeeCalculator} from './fee-calculator';\nimport {FeeCalculatorLayout} from './fee-calculator';\nimport {toBuffer} from './utils/to-buffer';\n\n/**\n * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32\n *\n * @internal\n */\nconst NonceAccountLayout = BufferLayout.struct<\n  Readonly<{\n    authorizedPubkey: Uint8Array;\n    feeCalculator: Readonly<{\n      lamportsPerSignature: number;\n    }>;\n    nonce: Uint8Array;\n    state: number;\n    version: number;\n  }>\n>([\n  BufferLayout.u32('version'),\n  BufferLayout.u32('state'),\n  Layout.publicKey('authorizedPubkey'),\n  Layout.publicKey('nonce'),\n  BufferLayout.struct<Readonly<{lamportsPerSignature: number}>>(\n    [FeeCalculatorLayout],\n    'feeCalculator',\n  ),\n]);\n\nexport const NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span;\n\n/**\n * A durable nonce is a 32 byte value encoded as a base58 string.\n */\nexport type DurableNonce = string;\n\ntype NonceAccountArgs = {\n  authorizedPubkey: PublicKey;\n  nonce: DurableNonce;\n  feeCalculator: FeeCalculator;\n};\n\n/**\n * NonceAccount class\n */\nexport class NonceAccount {\n  authorizedPubkey: PublicKey;\n  nonce: DurableNonce;\n  feeCalculator: FeeCalculator;\n\n  /**\n   * @internal\n   */\n  constructor(args: NonceAccountArgs) {\n    this.authorizedPubkey = args.authorizedPubkey;\n    this.nonce = args.nonce;\n    this.feeCalculator = args.feeCalculator;\n  }\n\n  /**\n   * Deserialize NonceAccount from the account data.\n   *\n   * @param buffer account data\n   * @return NonceAccount\n   */\n  static fromAccountData(\n    buffer: Buffer | Uint8Array | Array<number>,\n  ): NonceAccount {\n    const nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0);\n    return new NonceAccount({\n      authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey),\n      nonce: new PublicKey(nonceAccount.nonce).toString(),\n      feeCalculator: nonceAccount.feeCalculator,\n    });\n  }\n}\n","import {Buffer} from 'buffer';\nimport {blob, Layout} from '@solana/buffer-layout';\nimport {toBigIntLE, toBufferLE} from 'bigint-buffer';\n\ninterface EncodeDecode<T> {\n  decode(buffer: Buffer, offset?: number): T;\n  encode(src: T, buffer: Buffer, offset?: number): number;\n}\n\nconst encodeDecode = <T>(layout: Layout<T>): EncodeDecode<T> => {\n  const decode = layout.decode.bind(layout);\n  const encode = layout.encode.bind(layout);\n  return {decode, encode};\n};\n\nconst bigInt =\n  (length: number) =>\n  (property?: string): Layout<bigint> => {\n    const layout = blob(length, property);\n    const {encode, decode} = encodeDecode(layout);\n\n    const bigIntLayout = layout as Layout<unknown> as Layout<bigint>;\n\n    bigIntLayout.decode = (buffer: Buffer, offset: number) => {\n      const src = decode(buffer, offset);\n      return toBigIntLE(Buffer.from(src));\n    };\n\n    bigIntLayout.encode = (bigInt: bigint, buffer: Buffer, offset: number) => {\n      const src = toBufferLE(bigInt, length);\n      return encode(src, buffer, offset);\n    };\n\n    return bigIntLayout;\n  };\n\nexport const u64 = bigInt(8);\n\nexport const u128 = bigInt(16);\n\nexport const u192 = bigInt(24);\n\nexport const u256 = bigInt(32);\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n  encodeData,\n  decodeData,\n  InstructionType,\n  IInstructionInputData,\n} from '../instruction';\nimport * as Layout from '../layout';\nimport {NONCE_ACCOUNT_LENGTH} from '../nonce-account';\nimport {PublicKey} from '../publickey';\nimport {SYSVAR_RECENT_BLOCKHASHES_PUBKEY, SYSVAR_RENT_PUBKEY} from '../sysvar';\nimport {Transaction, TransactionInstruction} from '../transaction';\nimport {toBuffer} from '../utils/to-buffer';\nimport {u64} from '../utils/bigint';\n\n/**\n * Create account system transaction params\n */\nexport type CreateAccountParams = {\n  /** The account that will transfer lamports to the created account */\n  fromPubkey: PublicKey;\n  /** Public key of the created account */\n  newAccountPubkey: PublicKey;\n  /** Amount of lamports to transfer to the created account */\n  lamports: number;\n  /** Amount of space in bytes to allocate to the created account */\n  space: number;\n  /** Public key of the program to assign as the owner of the created account */\n  programId: PublicKey;\n};\n\n/**\n * Transfer system transaction params\n */\nexport type TransferParams = {\n  /** Account that will transfer lamports */\n  fromPubkey: PublicKey;\n  /** Account that will receive transferred lamports */\n  toPubkey: PublicKey;\n  /** Amount of lamports to transfer */\n  lamports: number | bigint;\n};\n\n/**\n * Assign system transaction params\n */\nexport type AssignParams = {\n  /** Public key of the account which will be assigned a new owner */\n  accountPubkey: PublicKey;\n  /** Public key of the program to assign as the owner */\n  programId: PublicKey;\n};\n\n/**\n * Create account with seed system transaction params\n */\nexport type CreateAccountWithSeedParams = {\n  /** The account that will transfer lamports to the created account */\n  fromPubkey: PublicKey;\n  /** Public key of the created account. Must be pre-calculated with PublicKey.createWithSeed() */\n  newAccountPubkey: PublicKey;\n  /** Base public key to use to derive the address of the created account. Must be the same as the base key used to create `newAccountPubkey` */\n  basePubkey: PublicKey;\n  /** Seed to use to derive the address of the created account. Must be the same as the seed used to create `newAccountPubkey` */\n  seed: string;\n  /** Amount of lamports to transfer to the created account */\n  lamports: number;\n  /** Amount of space in bytes to allocate to the created account */\n  space: number;\n  /** Public key of the program to assign as the owner of the created account */\n  programId: PublicKey;\n};\n\n/**\n * Create nonce account system transaction params\n */\nexport type CreateNonceAccountParams = {\n  /** The account that will transfer lamports to the created nonce account */\n  fromPubkey: PublicKey;\n  /** Public key of the created nonce account */\n  noncePubkey: PublicKey;\n  /** Public key to set as authority of the created nonce account */\n  authorizedPubkey: PublicKey;\n  /** Amount of lamports to transfer to the created nonce account */\n  lamports: number;\n};\n\n/**\n * Create nonce account with seed system transaction params\n */\nexport type CreateNonceAccountWithSeedParams = {\n  /** The account that will transfer lamports to the created nonce account */\n  fromPubkey: PublicKey;\n  /** Public key of the created nonce account */\n  noncePubkey: PublicKey;\n  /** Public key to set as authority of the created nonce account */\n  authorizedPubkey: PublicKey;\n  /** Amount of lamports to transfer to the created nonce account */\n  lamports: number;\n  /** Base public key to use to derive the address of the nonce account */\n  basePubkey: PublicKey;\n  /** Seed to use to derive the address of the nonce account */\n  seed: string;\n};\n\n/**\n * Initialize nonce account system instruction params\n */\nexport type InitializeNonceParams = {\n  /** Nonce account which will be initialized */\n  noncePubkey: PublicKey;\n  /** Public key to set as authority of the initialized nonce account */\n  authorizedPubkey: PublicKey;\n};\n\n/**\n * Advance nonce account system instruction params\n */\nexport type AdvanceNonceParams = {\n  /** Nonce account */\n  noncePubkey: PublicKey;\n  /** Public key of the nonce authority */\n  authorizedPubkey: PublicKey;\n};\n\n/**\n * Withdraw nonce account system transaction params\n */\nexport type WithdrawNonceParams = {\n  /** Nonce account */\n  noncePubkey: PublicKey;\n  /** Public key of the nonce authority */\n  authorizedPubkey: PublicKey;\n  /** Public key of the account which will receive the withdrawn nonce account balance */\n  toPubkey: PublicKey;\n  /** Amount of lamports to withdraw from the nonce account */\n  lamports: number;\n};\n\n/**\n * Authorize nonce account system transaction params\n */\nexport type AuthorizeNonceParams = {\n  /** Nonce account */\n  noncePubkey: PublicKey;\n  /** Public key of the current nonce authority */\n  authorizedPubkey: PublicKey;\n  /** Public key to set as the new nonce authority */\n  newAuthorizedPubkey: PublicKey;\n};\n\n/**\n * Allocate account system transaction params\n */\nexport type AllocateParams = {\n  /** Account to allocate */\n  accountPubkey: PublicKey;\n  /** Amount of space in bytes to allocate */\n  space: number;\n};\n\n/**\n * Allocate account with seed system transaction params\n */\nexport type AllocateWithSeedParams = {\n  /** Account to allocate */\n  accountPubkey: PublicKey;\n  /** Base public key to use to derive the address of the allocated account */\n  basePubkey: PublicKey;\n  /** Seed to use to derive the address of the allocated account */\n  seed: string;\n  /** Amount of space in bytes to allocate */\n  space: number;\n  /** Public key of the program to assign as the owner of the allocated account */\n  programId: PublicKey;\n};\n\n/**\n * Assign account with seed system transaction params\n */\nexport type AssignWithSeedParams = {\n  /** Public key of the account which will be assigned a new owner */\n  accountPubkey: PublicKey;\n  /** Base public key to use to derive the address of the assigned account */\n  basePubkey: PublicKey;\n  /** Seed to use to derive the address of the assigned account */\n  seed: string;\n  /** Public key of the program to assign as the owner */\n  programId: PublicKey;\n};\n\n/**\n * Transfer with seed system transaction params\n */\nexport type TransferWithSeedParams = {\n  /** Account that will transfer lamports */\n  fromPubkey: PublicKey;\n  /** Base public key to use to derive the funding account address */\n  basePubkey: PublicKey;\n  /** Account that will receive transferred lamports */\n  toPubkey: PublicKey;\n  /** Amount of lamports to transfer */\n  lamports: number | bigint;\n  /** Seed to use to derive the funding account address */\n  seed: string;\n  /** Program id to use to derive the funding account address */\n  programId: PublicKey;\n};\n\n/** Decoded transfer system transaction instruction */\nexport type DecodedTransferInstruction = {\n  /** Account that will transfer lamports */\n  fromPubkey: PublicKey;\n  /** Account that will receive transferred lamports */\n  toPubkey: PublicKey;\n  /** Amount of lamports to transfer */\n  lamports: bigint;\n};\n\n/** Decoded transferWithSeed system transaction instruction */\nexport type DecodedTransferWithSeedInstruction = {\n  /** Account that will transfer lamports */\n  fromPubkey: PublicKey;\n  /** Base public key to use to derive the funding account address */\n  basePubkey: PublicKey;\n  /** Account that will receive transferred lamports */\n  toPubkey: PublicKey;\n  /** Amount of lamports to transfer */\n  lamports: bigint;\n  /** Seed to use to derive the funding account address */\n  seed: string;\n  /** Program id to use to derive the funding account address */\n  programId: PublicKey;\n};\n\n/**\n * System Instruction class\n */\nexport class SystemInstruction {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Decode a system instruction and retrieve the instruction type.\n   */\n  static decodeInstructionType(\n    instruction: TransactionInstruction,\n  ): SystemInstructionType {\n    this.checkProgramId(instruction.programId);\n\n    const instructionTypeLayout = BufferLayout.u32('instruction');\n    const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n    let type: SystemInstructionType | undefined;\n    for (const [ixType, layout] of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)) {\n      if (layout.index == typeIndex) {\n        type = ixType as SystemInstructionType;\n        break;\n      }\n    }\n\n    if (!type) {\n      throw new Error('Instruction type incorrect; not a SystemInstruction');\n    }\n\n    return type;\n  }\n\n  /**\n   * Decode a create account system instruction and retrieve the instruction params.\n   */\n  static decodeCreateAccount(\n    instruction: TransactionInstruction,\n  ): CreateAccountParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 2);\n\n    const {lamports, space, programId} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.Create,\n      instruction.data,\n    );\n\n    return {\n      fromPubkey: instruction.keys[0].pubkey,\n      newAccountPubkey: instruction.keys[1].pubkey,\n      lamports,\n      space,\n      programId: new PublicKey(programId),\n    };\n  }\n\n  /**\n   * Decode a transfer system instruction and retrieve the instruction params.\n   */\n  static decodeTransfer(\n    instruction: TransactionInstruction,\n  ): DecodedTransferInstruction {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 2);\n\n    const {lamports} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.Transfer,\n      instruction.data,\n    );\n\n    return {\n      fromPubkey: instruction.keys[0].pubkey,\n      toPubkey: instruction.keys[1].pubkey,\n      lamports,\n    };\n  }\n\n  /**\n   * Decode a transfer with seed system instruction and retrieve the instruction params.\n   */\n  static decodeTransferWithSeed(\n    instruction: TransactionInstruction,\n  ): DecodedTransferWithSeedInstruction {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n\n    const {lamports, seed, programId} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed,\n      instruction.data,\n    );\n\n    return {\n      fromPubkey: instruction.keys[0].pubkey,\n      basePubkey: instruction.keys[1].pubkey,\n      toPubkey: instruction.keys[2].pubkey,\n      lamports,\n      seed,\n      programId: new PublicKey(programId),\n    };\n  }\n\n  /**\n   * Decode an allocate system instruction and retrieve the instruction params.\n   */\n  static decodeAllocate(instruction: TransactionInstruction): AllocateParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 1);\n\n    const {space} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.Allocate,\n      instruction.data,\n    );\n\n    return {\n      accountPubkey: instruction.keys[0].pubkey,\n      space,\n    };\n  }\n\n  /**\n   * Decode an allocate with seed system instruction and retrieve the instruction params.\n   */\n  static decodeAllocateWithSeed(\n    instruction: TransactionInstruction,\n  ): AllocateWithSeedParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 1);\n\n    const {base, seed, space, programId} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed,\n      instruction.data,\n    );\n\n    return {\n      accountPubkey: instruction.keys[0].pubkey,\n      basePubkey: new PublicKey(base),\n      seed,\n      space,\n      programId: new PublicKey(programId),\n    };\n  }\n\n  /**\n   * Decode an assign system instruction and retrieve the instruction params.\n   */\n  static decodeAssign(instruction: TransactionInstruction): AssignParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 1);\n\n    const {programId} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.Assign,\n      instruction.data,\n    );\n\n    return {\n      accountPubkey: instruction.keys[0].pubkey,\n      programId: new PublicKey(programId),\n    };\n  }\n\n  /**\n   * Decode an assign with seed system instruction and retrieve the instruction params.\n   */\n  static decodeAssignWithSeed(\n    instruction: TransactionInstruction,\n  ): AssignWithSeedParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 1);\n\n    const {base, seed, programId} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed,\n      instruction.data,\n    );\n\n    return {\n      accountPubkey: instruction.keys[0].pubkey,\n      basePubkey: new PublicKey(base),\n      seed,\n      programId: new PublicKey(programId),\n    };\n  }\n\n  /**\n   * Decode a create account with seed system instruction and retrieve the instruction params.\n   */\n  static decodeCreateWithSeed(\n    instruction: TransactionInstruction,\n  ): CreateAccountWithSeedParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 2);\n\n    const {base, seed, lamports, space, programId} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed,\n      instruction.data,\n    );\n\n    return {\n      fromPubkey: instruction.keys[0].pubkey,\n      newAccountPubkey: instruction.keys[1].pubkey,\n      basePubkey: new PublicKey(base),\n      seed,\n      lamports,\n      space,\n      programId: new PublicKey(programId),\n    };\n  }\n\n  /**\n   * Decode a nonce initialize system instruction and retrieve the instruction params.\n   */\n  static decodeNonceInitialize(\n    instruction: TransactionInstruction,\n  ): InitializeNonceParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n\n    const {authorized} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount,\n      instruction.data,\n    );\n\n    return {\n      noncePubkey: instruction.keys[0].pubkey,\n      authorizedPubkey: new PublicKey(authorized),\n    };\n  }\n\n  /**\n   * Decode a nonce advance system instruction and retrieve the instruction params.\n   */\n  static decodeNonceAdvance(\n    instruction: TransactionInstruction,\n  ): AdvanceNonceParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n\n    decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount,\n      instruction.data,\n    );\n\n    return {\n      noncePubkey: instruction.keys[0].pubkey,\n      authorizedPubkey: instruction.keys[2].pubkey,\n    };\n  }\n\n  /**\n   * Decode a nonce withdraw system instruction and retrieve the instruction params.\n   */\n  static decodeNonceWithdraw(\n    instruction: TransactionInstruction,\n  ): WithdrawNonceParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 5);\n\n    const {lamports} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount,\n      instruction.data,\n    );\n\n    return {\n      noncePubkey: instruction.keys[0].pubkey,\n      toPubkey: instruction.keys[1].pubkey,\n      authorizedPubkey: instruction.keys[4].pubkey,\n      lamports,\n    };\n  }\n\n  /**\n   * Decode a nonce authorize system instruction and retrieve the instruction params.\n   */\n  static decodeNonceAuthorize(\n    instruction: TransactionInstruction,\n  ): AuthorizeNonceParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 2);\n\n    const {authorized} = decodeData(\n      SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount,\n      instruction.data,\n    );\n\n    return {\n      noncePubkey: instruction.keys[0].pubkey,\n      authorizedPubkey: instruction.keys[1].pubkey,\n      newAuthorizedPubkey: new PublicKey(authorized),\n    };\n  }\n\n  /**\n   * @internal\n   */\n  static checkProgramId(programId: PublicKey) {\n    if (!programId.equals(SystemProgram.programId)) {\n      throw new Error('invalid instruction; programId is not SystemProgram');\n    }\n  }\n\n  /**\n   * @internal\n   */\n  static checkKeyLength(keys: Array<any>, expectedLength: number) {\n    if (keys.length < expectedLength) {\n      throw new Error(\n        `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n      );\n    }\n  }\n}\n\n/**\n * An enumeration of valid SystemInstructionType's\n */\nexport type SystemInstructionType =\n  // FIXME\n  // It would be preferable for this type to be `keyof SystemInstructionInputData`\n  // but Typedoc does not transpile `keyof` expressions.\n  // See https://github.com/TypeStrong/typedoc/issues/1894\n  | 'AdvanceNonceAccount'\n  | 'Allocate'\n  | 'AllocateWithSeed'\n  | 'Assign'\n  | 'AssignWithSeed'\n  | 'AuthorizeNonceAccount'\n  | 'Create'\n  | 'CreateWithSeed'\n  | 'InitializeNonceAccount'\n  | 'Transfer'\n  | 'TransferWithSeed'\n  | 'WithdrawNonceAccount'\n  | 'UpgradeNonceAccount';\n\ntype SystemInstructionInputData = {\n  AdvanceNonceAccount: IInstructionInputData;\n  Allocate: IInstructionInputData & {\n    space: number;\n  };\n  AllocateWithSeed: IInstructionInputData & {\n    base: Uint8Array;\n    programId: Uint8Array;\n    seed: string;\n    space: number;\n  };\n  Assign: IInstructionInputData & {\n    programId: Uint8Array;\n  };\n  AssignWithSeed: IInstructionInputData & {\n    base: Uint8Array;\n    seed: string;\n    programId: Uint8Array;\n  };\n  AuthorizeNonceAccount: IInstructionInputData & {\n    authorized: Uint8Array;\n  };\n  Create: IInstructionInputData & {\n    lamports: number;\n    programId: Uint8Array;\n    space: number;\n  };\n  CreateWithSeed: IInstructionInputData & {\n    base: Uint8Array;\n    lamports: number;\n    programId: Uint8Array;\n    seed: string;\n    space: number;\n  };\n  InitializeNonceAccount: IInstructionInputData & {\n    authorized: Uint8Array;\n  };\n  Transfer: IInstructionInputData & {\n    lamports: bigint;\n  };\n  TransferWithSeed: IInstructionInputData & {\n    lamports: bigint;\n    programId: Uint8Array;\n    seed: string;\n  };\n  WithdrawNonceAccount: IInstructionInputData & {\n    lamports: number;\n  };\n  UpgradeNonceAccount: IInstructionInputData;\n};\n\n/**\n * An enumeration of valid system InstructionType's\n * @internal\n */\nexport const SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze<{\n  [Instruction in SystemInstructionType]: InstructionType<\n    SystemInstructionInputData[Instruction]\n  >;\n}>({\n  Create: {\n    index: 0,\n    layout: BufferLayout.struct<SystemInstructionInputData['Create']>([\n      BufferLayout.u32('instruction'),\n      BufferLayout.ns64('lamports'),\n      BufferLayout.ns64('space'),\n      Layout.publicKey('programId'),\n    ]),\n  },\n  Assign: {\n    index: 1,\n    layout: BufferLayout.struct<SystemInstructionInputData['Assign']>([\n      BufferLayout.u32('instruction'),\n      Layout.publicKey('programId'),\n    ]),\n  },\n  Transfer: {\n    index: 2,\n    layout: BufferLayout.struct<SystemInstructionInputData['Transfer']>([\n      BufferLayout.u32('instruction'),\n      u64('lamports'),\n    ]),\n  },\n  CreateWithSeed: {\n    index: 3,\n    layout: BufferLayout.struct<SystemInstructionInputData['CreateWithSeed']>([\n      BufferLayout.u32('instruction'),\n      Layout.publicKey('base'),\n      Layout.rustString('seed'),\n      BufferLayout.ns64('lamports'),\n      BufferLayout.ns64('space'),\n      Layout.publicKey('programId'),\n    ]),\n  },\n  AdvanceNonceAccount: {\n    index: 4,\n    layout: BufferLayout.struct<\n      SystemInstructionInputData['AdvanceNonceAccount']\n    >([BufferLayout.u32('instruction')]),\n  },\n  WithdrawNonceAccount: {\n    index: 5,\n    layout: BufferLayout.struct<\n      SystemInstructionInputData['WithdrawNonceAccount']\n    >([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')]),\n  },\n  InitializeNonceAccount: {\n    index: 6,\n    layout: BufferLayout.struct<\n      SystemInstructionInputData['InitializeNonceAccount']\n    >([BufferLayout.u32('instruction'), Layout.publicKey('authorized')]),\n  },\n  AuthorizeNonceAccount: {\n    index: 7,\n    layout: BufferLayout.struct<\n      SystemInstructionInputData['AuthorizeNonceAccount']\n    >([BufferLayout.u32('instruction'), Layout.publicKey('authorized')]),\n  },\n  Allocate: {\n    index: 8,\n    layout: BufferLayout.struct<SystemInstructionInputData['Allocate']>([\n      BufferLayout.u32('instruction'),\n      BufferLayout.ns64('space'),\n    ]),\n  },\n  AllocateWithSeed: {\n    index: 9,\n    layout: BufferLayout.struct<SystemInstructionInputData['AllocateWithSeed']>(\n      [\n        BufferLayout.u32('instruction'),\n        Layout.publicKey('base'),\n        Layout.rustString('seed'),\n        BufferLayout.ns64('space'),\n        Layout.publicKey('programId'),\n      ],\n    ),\n  },\n  AssignWithSeed: {\n    index: 10,\n    layout: BufferLayout.struct<SystemInstructionInputData['AssignWithSeed']>([\n      BufferLayout.u32('instruction'),\n      Layout.publicKey('base'),\n      Layout.rustString('seed'),\n      Layout.publicKey('programId'),\n    ]),\n  },\n  TransferWithSeed: {\n    index: 11,\n    layout: BufferLayout.struct<SystemInstructionInputData['TransferWithSeed']>(\n      [\n        BufferLayout.u32('instruction'),\n        u64('lamports'),\n        Layout.rustString('seed'),\n        Layout.publicKey('programId'),\n      ],\n    ),\n  },\n  UpgradeNonceAccount: {\n    index: 12,\n    layout: BufferLayout.struct<\n      SystemInstructionInputData['UpgradeNonceAccount']\n    >([BufferLayout.u32('instruction')]),\n  },\n});\n\n/**\n * Factory class for transactions to interact with the System program\n */\nexport class SystemProgram {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Public key that identifies the System program\n   */\n  static programId: PublicKey = new PublicKey(\n    '11111111111111111111111111111111',\n  );\n\n  /**\n   * Generate a transaction instruction that creates a new account\n   */\n  static createAccount(params: CreateAccountParams): TransactionInstruction {\n    const type = SYSTEM_INSTRUCTION_LAYOUTS.Create;\n    const data = encodeData(type, {\n      lamports: params.lamports,\n      space: params.space,\n      programId: toBuffer(params.programId.toBuffer()),\n    });\n\n    return new TransactionInstruction({\n      keys: [\n        {pubkey: params.fromPubkey, isSigner: true, isWritable: true},\n        {pubkey: params.newAccountPubkey, isSigner: true, isWritable: true},\n      ],\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a transaction instruction that transfers lamports from one account to another\n   */\n  static transfer(\n    params: TransferParams | TransferWithSeedParams,\n  ): TransactionInstruction {\n    let data;\n    let keys;\n    if ('basePubkey' in params) {\n      const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;\n      data = encodeData(type, {\n        lamports: BigInt(params.lamports),\n        seed: params.seed,\n        programId: toBuffer(params.programId.toBuffer()),\n      });\n      keys = [\n        {pubkey: params.fromPubkey, isSigner: false, isWritable: true},\n        {pubkey: params.basePubkey, isSigner: true, isWritable: false},\n        {pubkey: params.toPubkey, isSigner: false, isWritable: true},\n      ];\n    } else {\n      const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;\n      data = encodeData(type, {lamports: BigInt(params.lamports)});\n      keys = [\n        {pubkey: params.fromPubkey, isSigner: true, isWritable: true},\n        {pubkey: params.toPubkey, isSigner: false, isWritable: true},\n      ];\n    }\n\n    return new TransactionInstruction({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a transaction instruction that assigns an account to a program\n   */\n  static assign(\n    params: AssignParams | AssignWithSeedParams,\n  ): TransactionInstruction {\n    let data;\n    let keys;\n    if ('basePubkey' in params) {\n      const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;\n      data = encodeData(type, {\n        base: toBuffer(params.basePubkey.toBuffer()),\n        seed: params.seed,\n        programId: toBuffer(params.programId.toBuffer()),\n      });\n      keys = [\n        {pubkey: params.accountPubkey, isSigner: false, isWritable: true},\n        {pubkey: params.basePubkey, isSigner: true, isWritable: false},\n      ];\n    } else {\n      const type = SYSTEM_INSTRUCTION_LAYOUTS.Assign;\n      data = encodeData(type, {\n        programId: toBuffer(params.programId.toBuffer()),\n      });\n      keys = [{pubkey: params.accountPubkey, isSigner: true, isWritable: true}];\n    }\n\n    return new TransactionInstruction({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a transaction instruction that creates a new account at\n   *   an address generated with `from`, a seed, and programId\n   */\n  static createAccountWithSeed(\n    params: CreateAccountWithSeedParams,\n  ): TransactionInstruction {\n    const type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;\n    const data = encodeData(type, {\n      base: toBuffer(params.basePubkey.toBuffer()),\n      seed: params.seed,\n      lamports: params.lamports,\n      space: params.space,\n      programId: toBuffer(params.programId.toBuffer()),\n    });\n    let keys = [\n      {pubkey: params.fromPubkey, isSigner: true, isWritable: true},\n      {pubkey: params.newAccountPubkey, isSigner: false, isWritable: true},\n    ];\n    if (params.basePubkey != params.fromPubkey) {\n      keys.push({\n        pubkey: params.basePubkey,\n        isSigner: true,\n        isWritable: false,\n      });\n    }\n\n    return new TransactionInstruction({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a transaction that creates a new Nonce account\n   */\n  static createNonceAccount(\n    params: CreateNonceAccountParams | CreateNonceAccountWithSeedParams,\n  ): Transaction {\n    const transaction = new Transaction();\n    if ('basePubkey' in params && 'seed' in params) {\n      transaction.add(\n        SystemProgram.createAccountWithSeed({\n          fromPubkey: params.fromPubkey,\n          newAccountPubkey: params.noncePubkey,\n          basePubkey: params.basePubkey,\n          seed: params.seed,\n          lamports: params.lamports,\n          space: NONCE_ACCOUNT_LENGTH,\n          programId: this.programId,\n        }),\n      );\n    } else {\n      transaction.add(\n        SystemProgram.createAccount({\n          fromPubkey: params.fromPubkey,\n          newAccountPubkey: params.noncePubkey,\n          lamports: params.lamports,\n          space: NONCE_ACCOUNT_LENGTH,\n          programId: this.programId,\n        }),\n      );\n    }\n\n    const initParams = {\n      noncePubkey: params.noncePubkey,\n      authorizedPubkey: params.authorizedPubkey,\n    };\n\n    transaction.add(this.nonceInitialize(initParams));\n    return transaction;\n  }\n\n  /**\n   * Generate an instruction to initialize a Nonce account\n   */\n  static nonceInitialize(\n    params: InitializeNonceParams,\n  ): TransactionInstruction {\n    const type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;\n    const data = encodeData(type, {\n      authorized: toBuffer(params.authorizedPubkey.toBuffer()),\n    });\n    const instructionData = {\n      keys: [\n        {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n        {\n          pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n          isSigner: false,\n          isWritable: false,\n        },\n        {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    };\n    return new TransactionInstruction(instructionData);\n  }\n\n  /**\n   * Generate an instruction to advance the nonce in a Nonce account\n   */\n  static nonceAdvance(params: AdvanceNonceParams): TransactionInstruction {\n    const type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount;\n    const data = encodeData(type);\n    const instructionData = {\n      keys: [\n        {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n        {\n          pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n          isSigner: false,\n          isWritable: false,\n        },\n        {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    };\n    return new TransactionInstruction(instructionData);\n  }\n\n  /**\n   * Generate a transaction instruction that withdraws lamports from a Nonce account\n   */\n  static nonceWithdraw(params: WithdrawNonceParams): TransactionInstruction {\n    const type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount;\n    const data = encodeData(type, {lamports: params.lamports});\n\n    return new TransactionInstruction({\n      keys: [\n        {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n        {pubkey: params.toPubkey, isSigner: false, isWritable: true},\n        {\n          pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n          isSigner: false,\n          isWritable: false,\n        },\n        {\n          pubkey: SYSVAR_RENT_PUBKEY,\n          isSigner: false,\n          isWritable: false,\n        },\n        {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a transaction instruction that authorizes a new PublicKey as the authority\n   * on a Nonce account.\n   */\n  static nonceAuthorize(params: AuthorizeNonceParams): TransactionInstruction {\n    const type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;\n    const data = encodeData(type, {\n      authorized: toBuffer(params.newAuthorizedPubkey.toBuffer()),\n    });\n\n    return new TransactionInstruction({\n      keys: [\n        {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n        {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a transaction instruction that allocates space in an account without funding\n   */\n  static allocate(\n    params: AllocateParams | AllocateWithSeedParams,\n  ): TransactionInstruction {\n    let data;\n    let keys;\n    if ('basePubkey' in params) {\n      const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;\n      data = encodeData(type, {\n        base: toBuffer(params.basePubkey.toBuffer()),\n        seed: params.seed,\n        space: params.space,\n        programId: toBuffer(params.programId.toBuffer()),\n      });\n      keys = [\n        {pubkey: params.accountPubkey, isSigner: false, isWritable: true},\n        {pubkey: params.basePubkey, isSigner: true, isWritable: false},\n      ];\n    } else {\n      const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;\n      data = encodeData(type, {\n        space: params.space,\n      });\n      keys = [{pubkey: params.accountPubkey, isSigner: true, isWritable: true}];\n    }\n\n    return new TransactionInstruction({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {PublicKey} from './publickey';\nimport {Transaction, PACKET_DATA_SIZE} from './transaction';\nimport {MS_PER_SLOT} from './timing';\nimport {SYSVAR_RENT_PUBKEY} from './sysvar';\nimport {sendAndConfirmTransaction} from './utils/send-and-confirm-transaction';\nimport {sleep} from './utils/sleep';\nimport type {Connection} from './connection';\nimport type {Signer} from './keypair';\nimport {SystemProgram} from './programs/system';\nimport {IInstructionInputData} from './instruction';\n\n// Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the\n// rest of the Transaction fields\n//\n// TODO: replace 300 with a proper constant for the size of the other\n// Transaction fields\nconst CHUNK_SIZE = PACKET_DATA_SIZE - 300;\n\n/**\n * Program loader interface\n */\nexport class Loader {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Amount of program data placed in each load Transaction\n   */\n  static chunkSize: number = CHUNK_SIZE;\n\n  /**\n   * Minimum number of signatures required to load a program not including\n   * retries\n   *\n   * Can be used to calculate transaction fees\n   */\n  static getMinNumSignatures(dataLength: number): number {\n    return (\n      2 * // Every transaction requires two signatures (payer + program)\n      (Math.ceil(dataLength / Loader.chunkSize) +\n        1 + // Add one for Create transaction\n        1) // Add one for Finalize transaction\n    );\n  }\n\n  /**\n   * Loads a generic program\n   *\n   * @param connection The connection to use\n   * @param payer System account that pays to load the program\n   * @param program Account to load the program into\n   * @param programId Public key that identifies the loader\n   * @param data Program octets\n   * @return true if program was loaded successfully, false if program was already loaded\n   */\n  static async load(\n    connection: Connection,\n    payer: Signer,\n    program: Signer,\n    programId: PublicKey,\n    data: Buffer | Uint8Array | Array<number>,\n  ): Promise<boolean> {\n    {\n      const balanceNeeded = await connection.getMinimumBalanceForRentExemption(\n        data.length,\n      );\n\n      // Fetch program account info to check if it has already been created\n      const programInfo = await connection.getAccountInfo(\n        program.publicKey,\n        'confirmed',\n      );\n\n      let transaction: Transaction | null = null;\n      if (programInfo !== null) {\n        if (programInfo.executable) {\n          console.error('Program load failed, account is already executable');\n          return false;\n        }\n\n        if (programInfo.data.length !== data.length) {\n          transaction = transaction || new Transaction();\n          transaction.add(\n            SystemProgram.allocate({\n              accountPubkey: program.publicKey,\n              space: data.length,\n            }),\n          );\n        }\n\n        if (!programInfo.owner.equals(programId)) {\n          transaction = transaction || new Transaction();\n          transaction.add(\n            SystemProgram.assign({\n              accountPubkey: program.publicKey,\n              programId,\n            }),\n          );\n        }\n\n        if (programInfo.lamports < balanceNeeded) {\n          transaction = transaction || new Transaction();\n          transaction.add(\n            SystemProgram.transfer({\n              fromPubkey: payer.publicKey,\n              toPubkey: program.publicKey,\n              lamports: balanceNeeded - programInfo.lamports,\n            }),\n          );\n        }\n      } else {\n        transaction = new Transaction().add(\n          SystemProgram.createAccount({\n            fromPubkey: payer.publicKey,\n            newAccountPubkey: program.publicKey,\n            lamports: balanceNeeded > 0 ? balanceNeeded : 1,\n            space: data.length,\n            programId,\n          }),\n        );\n      }\n\n      // If the account is already created correctly, skip this step\n      // and proceed directly to loading instructions\n      if (transaction !== null) {\n        await sendAndConfirmTransaction(\n          connection,\n          transaction,\n          [payer, program],\n          {\n            commitment: 'confirmed',\n          },\n        );\n      }\n    }\n\n    const dataLayout = BufferLayout.struct<\n      Readonly<{\n        bytes: number[];\n        bytesLength: number;\n        bytesLengthPadding: number;\n        instruction: number;\n        offset: number;\n      }>\n    >([\n      BufferLayout.u32('instruction'),\n      BufferLayout.u32('offset'),\n      BufferLayout.u32('bytesLength'),\n      BufferLayout.u32('bytesLengthPadding'),\n      BufferLayout.seq(\n        BufferLayout.u8('byte'),\n        BufferLayout.offset(BufferLayout.u32(), -8),\n        'bytes',\n      ),\n    ]);\n\n    const chunkSize = Loader.chunkSize;\n    let offset = 0;\n    let array = data;\n    let transactions = [];\n    while (array.length > 0) {\n      const bytes = array.slice(0, chunkSize);\n      const data = Buffer.alloc(chunkSize + 16);\n      dataLayout.encode(\n        {\n          instruction: 0, // Load instruction\n          offset,\n          bytes: bytes as number[],\n          bytesLength: 0,\n          bytesLengthPadding: 0,\n        },\n        data,\n      );\n\n      const transaction = new Transaction().add({\n        keys: [{pubkey: program.publicKey, isSigner: true, isWritable: true}],\n        programId,\n        data,\n      });\n      transactions.push(\n        sendAndConfirmTransaction(connection, transaction, [payer, program], {\n          commitment: 'confirmed',\n        }),\n      );\n\n      // Delay between sends in an attempt to reduce rate limit errors\n      if (connection._rpcEndpoint.includes('solana.com')) {\n        const REQUESTS_PER_SECOND = 4;\n        await sleep(1000 / REQUESTS_PER_SECOND);\n      }\n\n      offset += chunkSize;\n      array = array.slice(chunkSize);\n    }\n    await Promise.all(transactions);\n\n    // Finalize the account loaded with program data for execution\n    {\n      const dataLayout = BufferLayout.struct<IInstructionInputData>([\n        BufferLayout.u32('instruction'),\n      ]);\n\n      const data = Buffer.alloc(dataLayout.span);\n      dataLayout.encode(\n        {\n          instruction: 1, // Finalize instruction\n        },\n        data,\n      );\n\n      const transaction = new Transaction().add({\n        keys: [\n          {pubkey: program.publicKey, isSigner: true, isWritable: true},\n          {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n        ],\n        programId,\n        data,\n      });\n      const deployCommitment = 'processed';\n      const finalizeSignature = await connection.sendTransaction(\n        transaction,\n        [payer, program],\n        {preflightCommitment: deployCommitment},\n      );\n      const {context, value} = await connection.confirmTransaction(\n        {\n          signature: finalizeSignature,\n          lastValidBlockHeight: transaction.lastValidBlockHeight!,\n          blockhash: transaction.recentBlockhash!,\n        },\n        deployCommitment,\n      );\n      if (value.err) {\n        throw new Error(\n          `Transaction ${finalizeSignature} failed (${JSON.stringify(value)})`,\n        );\n      }\n      // We prevent programs from being usable until the slot after their deployment.\n      // See https://github.com/solana-labs/solana/pull/29654\n      while (\n        true // eslint-disable-line no-constant-condition\n      ) {\n        try {\n          const currentSlot = await connection.getSlot({\n            commitment: deployCommitment,\n          });\n          if (currentSlot > context.slot) {\n            break;\n          }\n        } catch {\n          /* empty */\n        }\n        await new Promise(resolve =>\n          setTimeout(resolve, Math.round(MS_PER_SLOT / 2)),\n        );\n      }\n    }\n\n    // success\n    return true;\n  }\n}\n","import type {Buffer} from 'buffer';\n\nimport {PublicKey} from './publickey';\nimport {Loader} from './loader';\nimport type {Connection} from './connection';\nimport type {Signer} from './keypair';\n\nexport const BPF_LOADER_PROGRAM_ID = new PublicKey(\n  'BPFLoader2111111111111111111111111111111111',\n);\n\n/**\n * Factory class for transactions to interact with a program loader\n */\nexport class BpfLoader {\n  /**\n   * Minimum number of signatures required to load a program not including\n   * retries\n   *\n   * Can be used to calculate transaction fees\n   */\n  static getMinNumSignatures(dataLength: number): number {\n    return Loader.getMinNumSignatures(dataLength);\n  }\n\n  /**\n   * Load a SBF program\n   *\n   * @param connection The connection to use\n   * @param payer Account that will pay program loading fees\n   * @param program Account to load the program into\n   * @param elf The entire ELF containing the SBF program\n   * @param loaderProgramId The program id of the BPF loader to use\n   * @return true if program was loaded successfully, false if program was already loaded\n   */\n  static load(\n    connection: Connection,\n    payer: Signer,\n    program: Signer,\n    elf: Buffer | Uint8Array | Array<number>,\n    loaderProgramId: PublicKey,\n  ): Promise<boolean> {\n    return Loader.load(connection, payer, program, loaderProgramId, elf);\n  }\n}\n","var objToString = Object.prototype.toString;\nvar objKeys = Object.keys || function(obj) {\n\t\tvar keys = [];\n\t\tfor (var name in obj) {\n\t\t\tkeys.push(name);\n\t\t}\n\t\treturn keys;\n\t};\n\nfunction stringify(val, isArrayProp) {\n\tvar i, max, str, keys, key, propVal, toStr;\n\tif (val === true) {\n\t\treturn \"true\";\n\t}\n\tif (val === false) {\n\t\treturn \"false\";\n\t}\n\tswitch (typeof val) {\n\t\tcase \"object\":\n\t\t\tif (val === null) {\n\t\t\t\treturn null;\n\t\t\t} else if (val.toJSON && typeof val.toJSON === \"function\") {\n\t\t\t\treturn stringify(val.toJSON(), isArrayProp);\n\t\t\t} else {\n\t\t\t\ttoStr = objToString.call(val);\n\t\t\t\tif (toStr === \"[object Array]\") {\n\t\t\t\t\tstr = '[';\n\t\t\t\t\tmax = val.length - 1;\n\t\t\t\t\tfor(i = 0; i < max; i++) {\n\t\t\t\t\t\tstr += stringify(val[i], true) + ',';\n\t\t\t\t\t}\n\t\t\t\t\tif (max > -1) {\n\t\t\t\t\t\tstr += stringify(val[i], true);\n\t\t\t\t\t}\n\t\t\t\t\treturn str + ']';\n\t\t\t\t} else if (toStr === \"[object Object]\") {\n\t\t\t\t\t// only object is left\n\t\t\t\t\tkeys = objKeys(val).sort();\n\t\t\t\t\tmax = keys.length;\n\t\t\t\t\tstr = \"\";\n\t\t\t\t\ti = 0;\n\t\t\t\t\twhile (i < max) {\n\t\t\t\t\t\tkey = keys[i];\n\t\t\t\t\t\tpropVal = stringify(val[key], false);\n\t\t\t\t\t\tif (propVal !== undefined) {\n\t\t\t\t\t\t\tif (str) {\n\t\t\t\t\t\t\t\tstr += ',';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstr += JSON.stringify(key) + ':' + propVal;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\treturn '{' + str + '}';\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON.stringify(val);\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"function\":\n\t\tcase \"undefined\":\n\t\t\treturn isArrayProp ? null : undefined;\n\t\tcase \"string\":\n\t\t\treturn JSON.stringify(val);\n\t\tdefault:\n\t\t\treturn isFinite(val) ? val : null;\n\t}\n}\n\nmodule.exports = function(val) {\n\tvar returnVal = stringify(val, false);\n\tif (returnVal !== undefined) {\n\t\treturn ''+ returnVal;\n\t}\n};\n","const MINIMUM_SLOT_PER_EPOCH = 32;\n\n// Returns the number of trailing zeros in the binary representation of self.\nfunction trailingZeros(n: number) {\n  let trailingZeros = 0;\n  while (n > 1) {\n    n /= 2;\n    trailingZeros++;\n  }\n  return trailingZeros;\n}\n\n// Returns the smallest power of two greater than or equal to n\nfunction nextPowerOfTwo(n: number) {\n  if (n === 0) return 1;\n  n--;\n  n |= n >> 1;\n  n |= n >> 2;\n  n |= n >> 4;\n  n |= n >> 8;\n  n |= n >> 16;\n  n |= n >> 32;\n  return n + 1;\n}\n\n/**\n * Epoch schedule\n * (see https://docs.solana.com/terminology#epoch)\n * Can be retrieved with the {@link Connection.getEpochSchedule} method\n */\nexport class EpochSchedule {\n  /** The maximum number of slots in each epoch */\n  public slotsPerEpoch: number;\n  /** The number of slots before beginning of an epoch to calculate a leader schedule for that epoch */\n  public leaderScheduleSlotOffset: number;\n  /** Indicates whether epochs start short and grow */\n  public warmup: boolean;\n  /** The first epoch with `slotsPerEpoch` slots */\n  public firstNormalEpoch: number;\n  /** The first slot of `firstNormalEpoch` */\n  public firstNormalSlot: number;\n\n  constructor(\n    slotsPerEpoch: number,\n    leaderScheduleSlotOffset: number,\n    warmup: boolean,\n    firstNormalEpoch: number,\n    firstNormalSlot: number,\n  ) {\n    this.slotsPerEpoch = slotsPerEpoch;\n    this.leaderScheduleSlotOffset = leaderScheduleSlotOffset;\n    this.warmup = warmup;\n    this.firstNormalEpoch = firstNormalEpoch;\n    this.firstNormalSlot = firstNormalSlot;\n  }\n\n  getEpoch(slot: number): number {\n    return this.getEpochAndSlotIndex(slot)[0];\n  }\n\n  getEpochAndSlotIndex(slot: number): [number, number] {\n    if (slot < this.firstNormalSlot) {\n      const epoch =\n        trailingZeros(nextPowerOfTwo(slot + MINIMUM_SLOT_PER_EPOCH + 1)) -\n        trailingZeros(MINIMUM_SLOT_PER_EPOCH) -\n        1;\n\n      const epochLen = this.getSlotsInEpoch(epoch);\n      const slotIndex = slot - (epochLen - MINIMUM_SLOT_PER_EPOCH);\n      return [epoch, slotIndex];\n    } else {\n      const normalSlotIndex = slot - this.firstNormalSlot;\n      const normalEpochIndex = Math.floor(normalSlotIndex / this.slotsPerEpoch);\n      const epoch = this.firstNormalEpoch + normalEpochIndex;\n      const slotIndex = normalSlotIndex % this.slotsPerEpoch;\n      return [epoch, slotIndex];\n    }\n  }\n\n  getFirstSlotInEpoch(epoch: number): number {\n    if (epoch <= this.firstNormalEpoch) {\n      return (Math.pow(2, epoch) - 1) * MINIMUM_SLOT_PER_EPOCH;\n    } else {\n      return (\n        (epoch - this.firstNormalEpoch) * this.slotsPerEpoch +\n        this.firstNormalSlot\n      );\n    }\n  }\n\n  getLastSlotInEpoch(epoch: number): number {\n    return this.getFirstSlotInEpoch(epoch) + this.getSlotsInEpoch(epoch) - 1;\n  }\n\n  getSlotsInEpoch(epoch: number) {\n    if (epoch < this.firstNormalEpoch) {\n      return Math.pow(2, epoch + trailingZeros(MINIMUM_SLOT_PER_EPOCH));\n    } else {\n      return this.slotsPerEpoch;\n    }\n  }\n}\n","export class SendTransactionError extends Error {\n  logs: string[] | undefined;\n\n  constructor(message: string, logs?: string[]) {\n    super(message);\n\n    this.logs = logs;\n  }\n}\n\n// Keep in sync with client/src/rpc_custom_errors.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nexport const SolanaJSONRPCErrorCode = {\n  JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n  JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n  JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n  JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n  JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n  JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n  JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n  JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n  JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n  JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n  JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n  JSON_RPC_SCAN_ERROR: -32012,\n  JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n  JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n  JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n  JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016,\n} as const;\nexport type SolanaJSONRPCErrorCodeEnum =\n  (typeof SolanaJSONRPCErrorCode)[keyof typeof SolanaJSONRPCErrorCode];\n\nexport class SolanaJSONRPCError extends Error {\n  code: SolanaJSONRPCErrorCodeEnum | unknown;\n  data?: any;\n  constructor(\n    {\n      code,\n      message,\n      data,\n    }: Readonly<{code: unknown; message: string; data?: any}>,\n    customMessage?: string,\n  ) {\n    super(customMessage != null ? `${customMessage}: ${message}` : message);\n    this.code = code;\n    this.data = data;\n    this.name = 'SolanaJSONRPCError';\n  }\n}\n","export const Headers = globalThis.Headers;\nexport const Request = globalThis.Request;\nexport const Response = globalThis.Response;\nexport default globalThis.fetch;\n","import RpcWebSocketCommonClient from 'rpc-websockets/dist/lib/client';\nimport RpcWebSocketBrowserFactory from 'rpc-websockets/dist/lib/client/websocket.browser';\nimport {\n  ICommonWebSocket,\n  IWSClientAdditionalOptions,\n  NodeWebSocketType,\n  NodeWebSocketTypeOptions,\n} from 'rpc-websockets/dist/lib/client/client.types';\n\nimport createRpc from './rpc-websocket-factory';\n\ninterface IHasReadyState {\n  readyState: WebSocket['readyState'];\n}\n\nexport default class RpcWebSocketClient extends RpcWebSocketCommonClient {\n  private underlyingSocket: IHasReadyState | undefined;\n  constructor(\n    address?: string,\n    options?: IWSClientAdditionalOptions & NodeWebSocketTypeOptions,\n    generate_request_id?: (\n      method: string,\n      params: object | Array<any>,\n    ) => number,\n  ) {\n    const webSocketFactory = (url: string) => {\n      const rpc = createRpc(url, {\n        autoconnect: true,\n        max_reconnects: 5,\n        reconnect: true,\n        reconnect_interval: 1000,\n        ...options,\n      });\n      if ('socket' in rpc) {\n        this.underlyingSocket = (\n          rpc as ReturnType<typeof RpcWebSocketBrowserFactory>\n        ).socket;\n      } else {\n        this.underlyingSocket = rpc as NodeWebSocketType;\n      }\n      return rpc as ICommonWebSocket;\n    };\n    super(webSocketFactory, address, options, generate_request_id);\n  }\n  call(\n    ...args: Parameters<RpcWebSocketCommonClient['call']>\n  ): ReturnType<RpcWebSocketCommonClient['call']> {\n    const readyState = this.underlyingSocket?.readyState;\n    if (readyState === 1 /* WebSocket.OPEN */) {\n      return super.call(...args);\n    }\n    return Promise.reject(\n      new Error(\n        'Tried to call a JSON-RPC method `' +\n          args[0] +\n          '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' +\n          readyState +\n          ')',\n      ),\n    );\n  }\n  notify(\n    ...args: Parameters<RpcWebSocketCommonClient['notify']>\n  ): ReturnType<RpcWebSocketCommonClient['notify']> {\n    const readyState = this.underlyingSocket?.readyState;\n    if (readyState === 1 /* WebSocket.OPEN */) {\n      return super.notify(...args);\n    }\n    return Promise.reject(\n      new Error(\n        'Tried to send a JSON-RPC notification `' +\n          args[0] +\n          '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' +\n          readyState +\n          ')',\n      ),\n    );\n  }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport assert from '../../utils/assert';\nimport * as Layout from '../../layout';\nimport {PublicKey} from '../../publickey';\nimport {u64} from '../../utils/bigint';\nimport {decodeData} from '../../account-data';\n\nexport type AddressLookupTableState = {\n  deactivationSlot: bigint;\n  lastExtendedSlot: number;\n  lastExtendedSlotStartIndex: number;\n  authority?: PublicKey;\n  addresses: Array<PublicKey>;\n};\n\nexport type AddressLookupTableAccountArgs = {\n  key: PublicKey;\n  state: AddressLookupTableState;\n};\n\n/// The serialized size of lookup table metadata\nconst LOOKUP_TABLE_META_SIZE = 56;\n\nexport class AddressLookupTableAccount {\n  key: PublicKey;\n  state: AddressLookupTableState;\n\n  constructor(args: AddressLookupTableAccountArgs) {\n    this.key = args.key;\n    this.state = args.state;\n  }\n\n  isActive(): boolean {\n    const U64_MAX = BigInt('0xffffffffffffffff');\n    return this.state.deactivationSlot === U64_MAX;\n  }\n\n  static deserialize(accountData: Uint8Array): AddressLookupTableState {\n    const meta = decodeData(LookupTableMetaLayout, accountData);\n\n    const serializedAddressesLen = accountData.length - LOOKUP_TABLE_META_SIZE;\n    assert(serializedAddressesLen >= 0, 'lookup table is invalid');\n    assert(serializedAddressesLen % 32 === 0, 'lookup table is invalid');\n\n    const numSerializedAddresses = serializedAddressesLen / 32;\n    const {addresses} = BufferLayout.struct<{addresses: Array<Uint8Array>}>([\n      BufferLayout.seq(Layout.publicKey(), numSerializedAddresses, 'addresses'),\n    ]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE));\n\n    return {\n      deactivationSlot: meta.deactivationSlot,\n      lastExtendedSlot: meta.lastExtendedSlot,\n      lastExtendedSlotStartIndex: meta.lastExtendedStartIndex,\n      authority:\n        meta.authority.length !== 0\n          ? new PublicKey(meta.authority[0])\n          : undefined,\n      addresses: addresses.map(address => new PublicKey(address)),\n    };\n  }\n}\n\nconst LookupTableMetaLayout = {\n  index: 1,\n  layout: BufferLayout.struct<{\n    typeIndex: number;\n    deactivationSlot: bigint;\n    lastExtendedSlot: number;\n    lastExtendedStartIndex: number;\n    authority: Array<Uint8Array>;\n  }>([\n    BufferLayout.u32('typeIndex'),\n    u64('deactivationSlot'),\n    BufferLayout.nu64('lastExtendedSlot'),\n    BufferLayout.u8('lastExtendedStartIndex'),\n    BufferLayout.u8(), // option\n    BufferLayout.seq(\n      Layout.publicKey(),\n      BufferLayout.offset(BufferLayout.u8(), -1),\n      'authority',\n    ),\n  ]),\n};\n","import * as BufferLayout from '@solana/buffer-layout';\n\nexport interface IAccountStateData {\n  readonly typeIndex: number;\n}\n\n/**\n * @internal\n */\nexport type AccountType<TInputData extends IAccountStateData> = {\n  /** The account type index (from solana upstream program) */\n  index: number;\n  /** The BufferLayout to use to build data */\n  layout: BufferLayout.Layout<TInputData>;\n};\n\n/**\n * Decode account data buffer using an AccountType\n * @internal\n */\nexport function decodeData<TAccountStateData extends IAccountStateData>(\n  type: AccountType<TAccountStateData>,\n  data: Uint8Array,\n): TAccountStateData {\n  let decoded: TAccountStateData;\n  try {\n    decoded = type.layout.decode(data);\n  } catch (err) {\n    throw new Error('invalid instruction; ' + err);\n  }\n\n  if (decoded.typeIndex !== type.index) {\n    throw new Error(\n      `invalid account data; account type mismatch ${decoded.typeIndex} != ${type.index}`,\n    );\n  }\n\n  return decoded;\n}\n","const URL_RE = /^[^:]+:\\/\\/([^:[]+|\\[[^\\]]+\\])(:\\d+)?(.*)/i;\n\nexport function makeWebsocketUrl(endpoint: string) {\n  const matches = endpoint.match(URL_RE);\n  if (matches == null) {\n    throw TypeError(`Failed to validate endpoint URL \\`${endpoint}\\``);\n  }\n  const [\n    _, // eslint-disable-line @typescript-eslint/no-unused-vars\n    hostish,\n    portWithColon,\n    rest,\n  ] = matches;\n  const protocol = endpoint.startsWith('https:') ? 'wss:' : 'ws:';\n  const startPort =\n    portWithColon == null ? null : parseInt(portWithColon.slice(1), 10);\n  const websocketPort =\n    // Only shift the port by +1 as a convention for ws(s) only if given endpoint\n    // is explicitly specifying the endpoint port (HTTP-based RPC), assuming\n    // we're directly trying to connect to solana-validator's ws listening port.\n    // When the endpoint omits the port, we're connecting to the protocol\n    // default ports: http(80) or https(443) and it's assumed we're behind a reverse\n    // proxy which manages WebSocket upgrade and backend port redirection.\n    startPort == null ? '' : `:${startPort + 1}`;\n  return `${protocol}//${hostish}${websocketPort}${rest}`;\n}\n","import HttpKeepAliveAgent, {\n  HttpsAgent as HttpsKeepAliveAgent,\n} from 'agentkeepalive';\nimport bs58 from 'bs58';\nimport {Buffer} from 'buffer';\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\nimport type {Agent as NodeHttpAgent} from 'http';\nimport {Agent as NodeHttpsAgent} from 'https';\nimport {\n  type as pick,\n  number,\n  string,\n  array,\n  boolean,\n  literal,\n  record,\n  union,\n  optional,\n  nullable,\n  coerce,\n  instance,\n  create,\n  tuple,\n  unknown,\n  any,\n} from 'superstruct';\nimport type {Struct} from 'superstruct';\nimport RpcClient from 'jayson/lib/client/browser';\nimport {JSONRPCError} from 'jayson';\n\nimport {EpochSchedule} from './epoch-schedule';\nimport {SendTransactionError, SolanaJSONRPCError} from './errors';\nimport fetchImpl from './fetch-impl';\nimport {DurableNonce, NonceAccount} from './nonce-account';\nimport {PublicKey} from './publickey';\nimport {Signer} from './keypair';\nimport RpcWebSocketClient from './rpc-websocket';\nimport {MS_PER_SLOT} from './timing';\nimport {\n  Transaction,\n  TransactionStatus,\n  TransactionVersion,\n  VersionedTransaction,\n} from './transaction';\nimport {Message, MessageHeader, MessageV0, VersionedMessage} from './message';\nimport {AddressLookupTableAccount} from './programs/address-lookup-table/state';\nimport assert from './utils/assert';\nimport {sleep} from './utils/sleep';\nimport {toBuffer} from './utils/to-buffer';\nimport {\n  TransactionExpiredBlockheightExceededError,\n  TransactionExpiredNonceInvalidError,\n  TransactionExpiredTimeoutError,\n} from './transaction/expiry-custom-errors';\nimport {makeWebsocketUrl} from './utils/makeWebsocketUrl';\nimport type {Blockhash} from './blockhash';\nimport type {FeeCalculator} from './fee-calculator';\nimport type {TransactionSignature} from './transaction';\nimport type {CompiledInstruction} from './message';\n\nconst PublicKeyFromString = coerce(\n  instance(PublicKey),\n  string(),\n  value => new PublicKey(value),\n);\n\nconst RawAccountDataResult = tuple([string(), literal('base64')]);\n\nconst BufferFromRawAccountData = coerce(\n  instance(Buffer),\n  RawAccountDataResult,\n  value => Buffer.from(value[0], 'base64'),\n);\n\n/**\n * Attempt to use a recent blockhash for up to 30 seconds\n * @internal\n */\nexport const BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000;\n\n/**\n * HACK.\n * Copied from rpc-websockets/dist/lib/client.\n * Otherwise, `yarn build` fails with:\n * https://gist.github.com/steveluscher/c057eca81d479ef705cdb53162f9971d\n */\ninterface IWSRequestParams {\n  [x: string]: any;\n  [x: number]: any;\n}\n\ntype ClientSubscriptionId = number;\n/** @internal */ type ServerSubscriptionId = number;\n/** @internal */ type SubscriptionConfigHash = string;\n/** @internal */ type SubscriptionDisposeFn = () => Promise<void>;\n/** @internal */ type SubscriptionStateChangeCallback = (\n  nextState: StatefulSubscription['state'],\n) => void;\n/** @internal */ type SubscriptionStateChangeDisposeFn = () => void;\n/**\n * @internal\n * Every subscription contains the args used to open the subscription with\n * the server, and a list of callers interested in notifications.\n */\ntype BaseSubscription<TMethod = SubscriptionConfig['method']> = Readonly<{\n  args: IWSRequestParams;\n  callbacks: Set<Extract<SubscriptionConfig, {method: TMethod}>['callback']>;\n}>;\n/**\n * @internal\n * A subscription may be in various states of connectedness. Only when it is\n * fully connected will it have a server subscription id associated with it.\n * This id can be returned to the server to unsubscribe the client entirely.\n */\ntype StatefulSubscription = Readonly<\n  // New subscriptions that have not yet been\n  // sent to the server start in this state.\n  | {\n      state: 'pending';\n    }\n  // These subscriptions have been sent to the server\n  // and are waiting for the server to acknowledge them.\n  | {\n      state: 'subscribing';\n    }\n  // These subscriptions have been acknowledged by the\n  // server and have been assigned server subscription ids.\n  | {\n      serverSubscriptionId: ServerSubscriptionId;\n      state: 'subscribed';\n    }\n  // These subscriptions are intended to be torn down and\n  // are waiting on an acknowledgement from the server.\n  | {\n      serverSubscriptionId: ServerSubscriptionId;\n      state: 'unsubscribing';\n    }\n  // The request to tear down these subscriptions has been\n  // acknowledged by the server. The `serverSubscriptionId`\n  // is the id of the now-dead subscription.\n  | {\n      serverSubscriptionId: ServerSubscriptionId;\n      state: 'unsubscribed';\n    }\n>;\n/**\n * A type that encapsulates a subscription's RPC method\n * names and notification (callback) signature.\n */\ntype SubscriptionConfig = Readonly<\n  | {\n      callback: AccountChangeCallback;\n      method: 'accountSubscribe';\n      unsubscribeMethod: 'accountUnsubscribe';\n    }\n  | {\n      callback: LogsCallback;\n      method: 'logsSubscribe';\n      unsubscribeMethod: 'logsUnsubscribe';\n    }\n  | {\n      callback: ProgramAccountChangeCallback;\n      method: 'programSubscribe';\n      unsubscribeMethod: 'programUnsubscribe';\n    }\n  | {\n      callback: RootChangeCallback;\n      method: 'rootSubscribe';\n      unsubscribeMethod: 'rootUnsubscribe';\n    }\n  | {\n      callback: SignatureSubscriptionCallback;\n      method: 'signatureSubscribe';\n      unsubscribeMethod: 'signatureUnsubscribe';\n    }\n  | {\n      callback: SlotChangeCallback;\n      method: 'slotSubscribe';\n      unsubscribeMethod: 'slotUnsubscribe';\n    }\n  | {\n      callback: SlotUpdateCallback;\n      method: 'slotsUpdatesSubscribe';\n      unsubscribeMethod: 'slotsUpdatesUnsubscribe';\n    }\n>;\n/**\n * @internal\n * Utility type that keeps tagged unions intact while omitting properties.\n */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n  ? Omit<T, K>\n  : never;\n/**\n * @internal\n * This type represents a single subscribable 'topic.' It's made up of:\n *\n * - The args used to open the subscription with the server,\n * - The state of the subscription, in terms of its connectedness, and\n * - The set of callbacks to call when the server publishes notifications\n *\n * This record gets indexed by `SubscriptionConfigHash` and is used to\n * set up subscriptions, fan out notifications, and track subscription state.\n */\ntype Subscription = BaseSubscription &\n  StatefulSubscription &\n  DistributiveOmit<SubscriptionConfig, 'callback'>;\n\ntype RpcRequest = (methodName: string, args: Array<any>) => Promise<any>;\n\ntype RpcBatchRequest = (requests: RpcParams[]) => Promise<any[]>;\n\n/**\n * @internal\n */\nexport type RpcParams = {\n  methodName: string;\n  args: Array<any>;\n};\n\nexport type TokenAccountsFilter =\n  | {\n      mint: PublicKey;\n    }\n  | {\n      programId: PublicKey;\n    };\n\n/**\n * Extra contextual information for RPC responses\n */\nexport type Context = {\n  slot: number;\n};\n\n/**\n * Options for sending transactions\n */\nexport type SendOptions = {\n  /** disable transaction verification step */\n  skipPreflight?: boolean;\n  /** preflight commitment level */\n  preflightCommitment?: Commitment;\n  /** Maximum number of times for the RPC node to retry sending the transaction to the leader. */\n  maxRetries?: number;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Options for confirming transactions\n */\nexport type ConfirmOptions = {\n  /** disable transaction verification step */\n  skipPreflight?: boolean;\n  /** desired commitment level */\n  commitment?: Commitment;\n  /** preflight commitment level */\n  preflightCommitment?: Commitment;\n  /** Maximum number of times for the RPC node to retry sending the transaction to the leader. */\n  maxRetries?: number;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Options for getConfirmedSignaturesForAddress2\n */\nexport type ConfirmedSignaturesForAddress2Options = {\n  /**\n   * Start searching backwards from this transaction signature.\n   * @remark If not provided the search starts from the highest max confirmed block.\n   */\n  before?: TransactionSignature;\n  /** Search until this transaction signature is reached, if found before `limit`. */\n  until?: TransactionSignature;\n  /** Maximum transaction signatures to return (between 1 and 1,000, default: 1,000). */\n  limit?: number;\n};\n\n/**\n * Options for getSignaturesForAddress\n */\nexport type SignaturesForAddressOptions = {\n  /**\n   * Start searching backwards from this transaction signature.\n   * @remark If not provided the search starts from the highest max confirmed block.\n   */\n  before?: TransactionSignature;\n  /** Search until this transaction signature is reached, if found before `limit`. */\n  until?: TransactionSignature;\n  /** Maximum transaction signatures to return (between 1 and 1,000, default: 1,000). */\n  limit?: number;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * RPC Response with extra contextual information\n */\nexport type RpcResponseAndContext<T> = {\n  /** response context */\n  context: Context;\n  /** response value */\n  value: T;\n};\n\nexport type BlockhashWithExpiryBlockHeight = Readonly<{\n  blockhash: Blockhash;\n  lastValidBlockHeight: number;\n}>;\n\n/**\n * A strategy for confirming transactions that uses the last valid\n * block height for a given blockhash to check for transaction expiration.\n */\nexport type BlockheightBasedTransactionConfirmationStrategy =\n  BaseTransactionConfirmationStrategy & BlockhashWithExpiryBlockHeight;\n\n/**\n * A strategy for confirming durable nonce transactions.\n */\nexport type DurableNonceTransactionConfirmationStrategy =\n  BaseTransactionConfirmationStrategy & {\n    /**\n     * The lowest slot at which to fetch the nonce value from the\n     * nonce account. This should be no lower than the slot at\n     * which the last-known value of the nonce was fetched.\n     */\n    minContextSlot: number;\n    /**\n     * The account where the current value of the nonce is stored.\n     */\n    nonceAccountPubkey: PublicKey;\n    /**\n     * The nonce value that was used to sign the transaction\n     * for which confirmation is being sought.\n     */\n    nonceValue: DurableNonce;\n  };\n\n/**\n * Properties shared by all transaction confirmation strategies\n */\nexport type BaseTransactionConfirmationStrategy = Readonly<{\n  /** A signal that, when aborted, cancels any outstanding transaction confirmation operations */\n  abortSignal?: AbortSignal;\n  signature: TransactionSignature;\n}>;\n\n/**\n * This type represents all transaction confirmation strategies\n */\nexport type TransactionConfirmationStrategy =\n  | BlockheightBasedTransactionConfirmationStrategy\n  | DurableNonceTransactionConfirmationStrategy;\n\n/* @internal */\nfunction assertEndpointUrl(putativeUrl: string) {\n  if (/^https?:/.test(putativeUrl) === false) {\n    throw new TypeError('Endpoint URL must start with `http:` or `https:`.');\n  }\n  return putativeUrl;\n}\n\n/** @internal */\nfunction extractCommitmentFromConfig<TConfig>(\n  commitmentOrConfig?: Commitment | ({commitment?: Commitment} & TConfig),\n) {\n  let commitment: Commitment | undefined;\n  let config: Omit<TConfig, 'commitment'> | undefined;\n  if (typeof commitmentOrConfig === 'string') {\n    commitment = commitmentOrConfig;\n  } else if (commitmentOrConfig) {\n    const {commitment: specifiedCommitment, ...specifiedConfig} =\n      commitmentOrConfig;\n    commitment = specifiedCommitment;\n    config = specifiedConfig;\n  }\n  return {commitment, config};\n}\n\n/**\n * @internal\n */\nfunction createRpcResult<T, U>(result: Struct<T, U>) {\n  return union([\n    pick({\n      jsonrpc: literal('2.0'),\n      id: string(),\n      result,\n    }),\n    pick({\n      jsonrpc: literal('2.0'),\n      id: string(),\n      error: pick({\n        code: unknown(),\n        message: string(),\n        data: optional(any()),\n      }),\n    }),\n  ]);\n}\n\nconst UnknownRpcResult = createRpcResult(unknown());\n\n/**\n * @internal\n */\nfunction jsonRpcResult<T, U>(schema: Struct<T, U>) {\n  return coerce(createRpcResult(schema), UnknownRpcResult, value => {\n    if ('error' in value) {\n      return value;\n    } else {\n      return {\n        ...value,\n        result: create(value.result, schema),\n      };\n    }\n  });\n}\n\n/**\n * @internal\n */\nfunction jsonRpcResultAndContext<T, U>(value: Struct<T, U>) {\n  return jsonRpcResult(\n    pick({\n      context: pick({\n        slot: number(),\n      }),\n      value,\n    }),\n  );\n}\n\n/**\n * @internal\n */\nfunction notificationResultAndContext<T, U>(value: Struct<T, U>) {\n  return pick({\n    context: pick({\n      slot: number(),\n    }),\n    value,\n  });\n}\n\n/**\n * @internal\n */\nfunction versionedMessageFromResponse(\n  version: TransactionVersion | undefined,\n  response: MessageResponse,\n): VersionedMessage {\n  if (version === 0) {\n    return new MessageV0({\n      header: response.header,\n      staticAccountKeys: response.accountKeys.map(\n        accountKey => new PublicKey(accountKey),\n      ),\n      recentBlockhash: response.recentBlockhash,\n      compiledInstructions: response.instructions.map(ix => ({\n        programIdIndex: ix.programIdIndex,\n        accountKeyIndexes: ix.accounts,\n        data: bs58.decode(ix.data),\n      })),\n      addressTableLookups: response.addressTableLookups!,\n    });\n  } else {\n    return new Message(response);\n  }\n}\n\n/**\n * The level of commitment desired when querying state\n * <pre>\n *   'processed': Query the most recent block which has reached 1 confirmation by the connected node\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * </pre>\n */\nexport type Commitment =\n  | 'processed'\n  | 'confirmed'\n  | 'finalized'\n  | 'recent' // Deprecated as of v1.5.5\n  | 'single' // Deprecated as of v1.5.5\n  | 'singleGossip' // Deprecated as of v1.5.5\n  | 'root' // Deprecated as of v1.5.5\n  | 'max'; // Deprecated as of v1.5.5\n\n/**\n * A subset of Commitment levels, which are at least optimistically confirmed\n * <pre>\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * </pre>\n */\nexport type Finality = 'confirmed' | 'finalized';\n\n/**\n * Filter for largest accounts query\n * <pre>\n *   'circulating':    Return the largest accounts that are part of the circulating supply\n *   'nonCirculating': Return the largest accounts that are not part of the circulating supply\n * </pre>\n */\nexport type LargestAccountsFilter = 'circulating' | 'nonCirculating';\n\n/**\n * Configuration object for changing `getAccountInfo` query behavior\n */\nexport type GetAccountInfoConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n  /** Optional data slice to limit the returned account data */\n  dataSlice?: DataSlice;\n};\n\n/**\n * Configuration object for changing `getBalance` query behavior\n */\nexport type GetBalanceConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\nexport type GetBlockConfig = {\n  /** The level of finality desired */\n  commitment?: Finality;\n  /**\n   * Whether to populate the rewards array. If parameter not provided, the default includes rewards.\n   */\n  rewards?: boolean;\n  /**\n   * Level of transaction detail to return, either \"full\", \"accounts\", \"signatures\", or \"none\". If\n   * parameter not provided, the default detail level is \"full\". If \"accounts\" are requested,\n   * transaction details only include signatures and an annotated list of accounts in each\n   * transaction. Transaction metadata is limited to only: fee, err, pre_balances, post_balances,\n   * pre_token_balances, and post_token_balances.\n   */\n  transactionDetails?: 'accounts' | 'full' | 'none' | 'signatures';\n};\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\nexport type GetVersionedBlockConfig = {\n  /** The level of finality desired */\n  commitment?: Finality;\n  /** The max transaction version to return in responses. If the requested transaction is a higher version, an error will be returned */\n  maxSupportedTransactionVersion?: number;\n  /**\n   * Whether to populate the rewards array. If parameter not provided, the default includes rewards.\n   */\n  rewards?: boolean;\n  /**\n   * Level of transaction detail to return, either \"full\", \"accounts\", \"signatures\", or \"none\". If\n   * parameter not provided, the default detail level is \"full\". If \"accounts\" are requested,\n   * transaction details only include signatures and an annotated list of accounts in each\n   * transaction. Transaction metadata is limited to only: fee, err, pre_balances, post_balances,\n   * pre_token_balances, and post_token_balances.\n   */\n  transactionDetails?: 'accounts' | 'full' | 'none' | 'signatures';\n};\n\n/**\n * Configuration object for changing `getStakeMinimumDelegation` query behavior\n */\nexport type GetStakeMinimumDelegationConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n};\n\n/**\n * Configuration object for changing `getBlockHeight` query behavior\n */\nexport type GetBlockHeightConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getEpochInfo` query behavior\n */\nexport type GetEpochInfoConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getInflationReward` query behavior\n */\nexport type GetInflationRewardConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** An epoch for which the reward occurs. If omitted, the previous epoch will be used */\n  epoch?: number;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getLatestBlockhash` query behavior\n */\nexport type GetLatestBlockhashConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `isBlockhashValid` query behavior\n */\nexport type IsBlockhashValidConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getSlot` query behavior\n */\nexport type GetSlotConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getSlotLeader` query behavior\n */\nexport type GetSlotLeaderConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\nexport type GetTransactionConfig = {\n  /** The level of finality desired */\n  commitment?: Finality;\n};\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\nexport type GetVersionedTransactionConfig = {\n  /** The level of finality desired */\n  commitment?: Finality;\n  /** The max transaction version to return in responses. If the requested transaction is a higher version, an error will be returned */\n  maxSupportedTransactionVersion?: number;\n};\n\n/**\n * Configuration object for changing `getLargestAccounts` query behavior\n */\nexport type GetLargestAccountsConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** Filter largest accounts by whether they are part of the circulating supply */\n  filter?: LargestAccountsFilter;\n};\n\n/**\n * Configuration object for changing `getSupply` request behavior\n */\nexport type GetSupplyConfig = {\n  /** The level of commitment desired */\n  commitment?: Commitment;\n  /** Exclude non circulating accounts list from response */\n  excludeNonCirculatingAccountsList?: boolean;\n};\n\n/**\n * Configuration object for changing query behavior\n */\nexport type SignatureStatusConfig = {\n  /** enable searching status history, not needed for recent transactions */\n  searchTransactionHistory: boolean;\n};\n\n/**\n * Information describing a cluster node\n */\nexport type ContactInfo = {\n  /** Identity public key of the node */\n  pubkey: string;\n  /** Gossip network address for the node */\n  gossip: string | null;\n  /** TPU network address for the node (null if not available) */\n  tpu: string | null;\n  /** JSON RPC network address for the node (null if not available) */\n  rpc: string | null;\n  /** Software version of the node (null if not available) */\n  version: string | null;\n};\n\n/**\n * Information describing a vote account\n */\nexport type VoteAccountInfo = {\n  /** Public key of the vote account */\n  votePubkey: string;\n  /** Identity public key of the node voting with this account */\n  nodePubkey: string;\n  /** The stake, in lamports, delegated to this vote account and activated */\n  activatedStake: number;\n  /** Whether the vote account is staked for this epoch */\n  epochVoteAccount: boolean;\n  /** Recent epoch voting credit history for this voter */\n  epochCredits: Array<[number, number, number]>;\n  /** A percentage (0-100) of rewards payout owed to the voter */\n  commission: number;\n  /** Most recent slot voted on by this vote account */\n  lastVote: number;\n};\n\n/**\n * A collection of cluster vote accounts\n */\nexport type VoteAccountStatus = {\n  /** Active vote accounts */\n  current: Array<VoteAccountInfo>;\n  /** Inactive vote accounts */\n  delinquent: Array<VoteAccountInfo>;\n};\n\n/**\n * Network Inflation\n * (see https://docs.solana.com/implemented-proposals/ed_overview)\n */\nexport type InflationGovernor = {\n  foundation: number;\n  foundationTerm: number;\n  initial: number;\n  taper: number;\n  terminal: number;\n};\n\nconst GetInflationGovernorResult = pick({\n  foundation: number(),\n  foundationTerm: number(),\n  initial: number(),\n  taper: number(),\n  terminal: number(),\n});\n\n/**\n * The inflation reward for an epoch\n */\nexport type InflationReward = {\n  /** epoch for which the reward occurs */\n  epoch: number;\n  /** the slot in which the rewards are effective */\n  effectiveSlot: number;\n  /** reward amount in lamports */\n  amount: number;\n  /** post balance of the account in lamports */\n  postBalance: number;\n  /** vote account commission when the reward was credited */\n  commission?: number | null;\n};\n\n/**\n * Expected JSON RPC response for the \"getInflationReward\" message\n */\nconst GetInflationRewardResult = jsonRpcResult(\n  array(\n    nullable(\n      pick({\n        epoch: number(),\n        effectiveSlot: number(),\n        amount: number(),\n        postBalance: number(),\n        commission: optional(nullable(number())),\n      }),\n    ),\n  ),\n);\n\nexport type RecentPrioritizationFees = {\n  /** slot in which the fee was observed */\n  slot: number;\n  /** the per-compute-unit fee paid by at least one successfully landed transaction, specified in increments of 0.000001 lamports*/\n  prioritizationFee: number;\n};\n\n/**\n * Configuration object for changing `getRecentPrioritizationFees` query behavior\n */\nexport type GetRecentPrioritizationFeesConfig = {\n  /**\n   * If this parameter is provided, the response will reflect a fee to land a transaction locking\n   * all of the provided accounts as writable.\n   */\n  lockedWritableAccounts?: PublicKey[];\n};\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesResult = array(\n  pick({\n    slot: number(),\n    prioritizationFee: number(),\n  }),\n);\n\nexport type InflationRate = {\n  /** total inflation */\n  total: number;\n  /** inflation allocated to validators */\n  validator: number;\n  /** inflation allocated to the foundation */\n  foundation: number;\n  /** epoch for which these values are valid */\n  epoch: number;\n};\n\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateResult = pick({\n  total: number(),\n  validator: number(),\n  foundation: number(),\n  epoch: number(),\n});\n\n/**\n * Information about the current epoch\n */\nexport type EpochInfo = {\n  epoch: number;\n  slotIndex: number;\n  slotsInEpoch: number;\n  absoluteSlot: number;\n  blockHeight?: number;\n  transactionCount?: number;\n};\n\nconst GetEpochInfoResult = pick({\n  epoch: number(),\n  slotIndex: number(),\n  slotsInEpoch: number(),\n  absoluteSlot: number(),\n  blockHeight: optional(number()),\n  transactionCount: optional(number()),\n});\n\nconst GetEpochScheduleResult = pick({\n  slotsPerEpoch: number(),\n  leaderScheduleSlotOffset: number(),\n  warmup: boolean(),\n  firstNormalEpoch: number(),\n  firstNormalSlot: number(),\n});\n\n/**\n * Leader schedule\n * (see https://docs.solana.com/terminology#leader-schedule)\n */\nexport type LeaderSchedule = {\n  [address: string]: number[];\n};\n\nconst GetLeaderScheduleResult = record(string(), array(number()));\n\n/**\n * Transaction error or null\n */\nconst TransactionErrorResult = nullable(union([pick({}), string()]));\n\n/**\n * Signature status for a transaction\n */\nconst SignatureStatusResult = pick({\n  err: TransactionErrorResult,\n});\n\n/**\n * Transaction signature received notification\n */\nconst SignatureReceivedResult = literal('receivedSignature');\n\n/**\n * Version info for a node\n */\nexport type Version = {\n  /** Version of solana-core */\n  'solana-core': string;\n  'feature-set'?: number;\n};\n\nconst VersionResult = pick({\n  'solana-core': string(),\n  'feature-set': optional(number()),\n});\n\nexport type SimulatedTransactionAccountInfo = {\n  /** `true` if this account's data contains a loaded program */\n  executable: boolean;\n  /** Identifier of the program that owns the account */\n  owner: string;\n  /** Number of lamports assigned to the account */\n  lamports: number;\n  /** Optional data assigned to the account */\n  data: string[];\n  /** Optional rent epoch info for account */\n  rentEpoch?: number;\n};\n\nexport type TransactionReturnDataEncoding = 'base64';\n\nexport type TransactionReturnData = {\n  programId: string;\n  data: [string, TransactionReturnDataEncoding];\n};\n\nexport type SimulateTransactionConfig = {\n  /** Optional parameter used to enable signature verification before simulation */\n  sigVerify?: boolean;\n  /** Optional parameter used to replace the simulated transaction's recent blockhash with the latest blockhash */\n  replaceRecentBlockhash?: boolean;\n  /** Optional parameter used to set the commitment level when selecting the latest block */\n  commitment?: Commitment;\n  /** Optional parameter used to specify a list of account addresses to return post simulation state for */\n  accounts?: {\n    encoding: 'base64';\n    addresses: string[];\n  };\n  /** Optional parameter used to specify the minimum block slot that can be used for simulation */\n  minContextSlot?: number;\n};\n\nexport type SimulatedTransactionResponse = {\n  err: TransactionError | string | null;\n  logs: Array<string> | null;\n  accounts?: (SimulatedTransactionAccountInfo | null)[] | null;\n  unitsConsumed?: number;\n  returnData?: TransactionReturnData | null;\n};\nconst SimulatedTransactionResponseStruct = jsonRpcResultAndContext(\n  pick({\n    err: nullable(union([pick({}), string()])),\n    logs: nullable(array(string())),\n    accounts: optional(\n      nullable(\n        array(\n          nullable(\n            pick({\n              executable: boolean(),\n              owner: string(),\n              lamports: number(),\n              data: array(string()),\n              rentEpoch: optional(number()),\n            }),\n          ),\n        ),\n      ),\n    ),\n    unitsConsumed: optional(number()),\n    returnData: optional(\n      nullable(\n        pick({\n          programId: string(),\n          data: tuple([string(), literal('base64')]),\n        }),\n      ),\n    ),\n  }),\n);\n\nexport type ParsedInnerInstruction = {\n  index: number;\n  instructions: (ParsedInstruction | PartiallyDecodedInstruction)[];\n};\n\nexport type TokenBalance = {\n  accountIndex: number;\n  mint: string;\n  owner?: string;\n  uiTokenAmount: TokenAmount;\n};\n\n/**\n * Metadata for a parsed confirmed transaction on the ledger\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link ParsedTransactionMeta} instead.\n */\nexport type ParsedConfirmedTransactionMeta = ParsedTransactionMeta;\n\n/**\n * Collection of addresses loaded by a transaction using address table lookups\n */\nexport type LoadedAddresses = {\n  writable: Array<PublicKey>;\n  readonly: Array<PublicKey>;\n};\n\n/**\n * Metadata for a parsed transaction on the ledger\n */\nexport type ParsedTransactionMeta = {\n  /** The fee charged for processing the transaction */\n  fee: number;\n  /** An array of cross program invoked parsed instructions */\n  innerInstructions?: ParsedInnerInstruction[] | null;\n  /** The balances of the transaction accounts before processing */\n  preBalances: Array<number>;\n  /** The balances of the transaction accounts after processing */\n  postBalances: Array<number>;\n  /** An array of program log messages emitted during a transaction */\n  logMessages?: Array<string> | null;\n  /** The token balances of the transaction accounts before processing */\n  preTokenBalances?: Array<TokenBalance> | null;\n  /** The token balances of the transaction accounts after processing */\n  postTokenBalances?: Array<TokenBalance> | null;\n  /** The error result of transaction processing */\n  err: TransactionError | null;\n  /** The collection of addresses loaded using address lookup tables */\n  loadedAddresses?: LoadedAddresses;\n  /** The compute units consumed after processing the transaction */\n  computeUnitsConsumed?: number;\n};\n\nexport type CompiledInnerInstruction = {\n  index: number;\n  instructions: CompiledInstruction[];\n};\n\n/**\n * Metadata for a confirmed transaction on the ledger\n */\nexport type ConfirmedTransactionMeta = {\n  /** The fee charged for processing the transaction */\n  fee: number;\n  /** An array of cross program invoked instructions */\n  innerInstructions?: CompiledInnerInstruction[] | null;\n  /** The balances of the transaction accounts before processing */\n  preBalances: Array<number>;\n  /** The balances of the transaction accounts after processing */\n  postBalances: Array<number>;\n  /** An array of program log messages emitted during a transaction */\n  logMessages?: Array<string> | null;\n  /** The token balances of the transaction accounts before processing */\n  preTokenBalances?: Array<TokenBalance> | null;\n  /** The token balances of the transaction accounts after processing */\n  postTokenBalances?: Array<TokenBalance> | null;\n  /** The error result of transaction processing */\n  err: TransactionError | null;\n  /** The collection of addresses loaded using address lookup tables */\n  loadedAddresses?: LoadedAddresses;\n  /** The compute units consumed after processing the transaction */\n  computeUnitsConsumed?: number;\n};\n\n/**\n * A processed transaction from the RPC API\n */\nexport type TransactionResponse = {\n  /** The slot during which the transaction was processed */\n  slot: number;\n  /** The transaction */\n  transaction: {\n    /** The transaction message */\n    message: Message;\n    /** The transaction signatures */\n    signatures: string[];\n  };\n  /** Metadata produced from the transaction */\n  meta: ConfirmedTransactionMeta | null;\n  /** The unix timestamp of when the transaction was processed */\n  blockTime?: number | null;\n};\n\n/**\n * A processed transaction from the RPC API\n */\nexport type VersionedTransactionResponse = {\n  /** The slot during which the transaction was processed */\n  slot: number;\n  /** The transaction */\n  transaction: {\n    /** The transaction message */\n    message: VersionedMessage;\n    /** The transaction signatures */\n    signatures: string[];\n  };\n  /** Metadata produced from the transaction */\n  meta: ConfirmedTransactionMeta | null;\n  /** The unix timestamp of when the transaction was processed */\n  blockTime?: number | null;\n  /** The transaction version */\n  version?: TransactionVersion;\n};\n\n/**\n * A processed transaction message from the RPC API\n */\ntype MessageResponse = {\n  accountKeys: string[];\n  header: MessageHeader;\n  instructions: CompiledInstruction[];\n  recentBlockhash: string;\n  addressTableLookups?: ParsedAddressTableLookup[];\n};\n\n/**\n * A confirmed transaction on the ledger\n *\n * @deprecated Deprecated since Solana v1.8.0.\n */\nexport type ConfirmedTransaction = {\n  /** The slot during which the transaction was processed */\n  slot: number;\n  /** The details of the transaction */\n  transaction: Transaction;\n  /** Metadata produced from the transaction */\n  meta: ConfirmedTransactionMeta | null;\n  /** The unix timestamp of when the transaction was processed */\n  blockTime?: number | null;\n};\n\n/**\n * A partially decoded transaction instruction\n */\nexport type PartiallyDecodedInstruction = {\n  /** Program id called by this instruction */\n  programId: PublicKey;\n  /** Public keys of accounts passed to this instruction */\n  accounts: Array<PublicKey>;\n  /** Raw base-58 instruction data */\n  data: string;\n};\n\n/**\n * A parsed transaction message account\n */\nexport type ParsedMessageAccount = {\n  /** Public key of the account */\n  pubkey: PublicKey;\n  /** Indicates if the account signed the transaction */\n  signer: boolean;\n  /** Indicates if the account is writable for this transaction */\n  writable: boolean;\n  /** Indicates if the account key came from the transaction or a lookup table */\n  source?: 'transaction' | 'lookupTable';\n};\n\n/**\n * A parsed transaction instruction\n */\nexport type ParsedInstruction = {\n  /** Name of the program for this instruction */\n  program: string;\n  /** ID of the program for this instruction */\n  programId: PublicKey;\n  /** Parsed instruction info */\n  parsed: any;\n};\n\n/**\n * A parsed address table lookup\n */\nexport type ParsedAddressTableLookup = {\n  /** Address lookup table account key */\n  accountKey: PublicKey;\n  /** Parsed instruction info */\n  writableIndexes: number[];\n  /** Parsed instruction info */\n  readonlyIndexes: number[];\n};\n\n/**\n * A parsed transaction message\n */\nexport type ParsedMessage = {\n  /** Accounts used in the instructions */\n  accountKeys: ParsedMessageAccount[];\n  /** The atomically executed instructions for the transaction */\n  instructions: (ParsedInstruction | PartiallyDecodedInstruction)[];\n  /** Recent blockhash */\n  recentBlockhash: string;\n  /** Address table lookups used to load additional accounts */\n  addressTableLookups?: ParsedAddressTableLookup[] | null;\n};\n\n/**\n * A parsed transaction\n */\nexport type ParsedTransaction = {\n  /** Signatures for the transaction */\n  signatures: Array<string>;\n  /** Message of the transaction */\n  message: ParsedMessage;\n};\n\n/**\n * A parsed and confirmed transaction on the ledger\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link ParsedTransactionWithMeta} instead.\n */\nexport type ParsedConfirmedTransaction = ParsedTransactionWithMeta;\n\n/**\n * A parsed transaction on the ledger with meta\n */\nexport type ParsedTransactionWithMeta = {\n  /** The slot during which the transaction was processed */\n  slot: number;\n  /** The details of the transaction */\n  transaction: ParsedTransaction;\n  /** Metadata produced from the transaction */\n  meta: ParsedTransactionMeta | null;\n  /** The unix timestamp of when the transaction was processed */\n  blockTime?: number | null;\n  /** The version of the transaction message */\n  version?: TransactionVersion;\n};\n\n/**\n * A processed block fetched from the RPC API\n */\nexport type BlockResponse = {\n  /** Blockhash of this block */\n  blockhash: Blockhash;\n  /** Blockhash of this block's parent */\n  previousBlockhash: Blockhash;\n  /** Slot index of this block's parent */\n  parentSlot: number;\n  /** Vector of transactions with status meta and original message */\n  transactions: Array<{\n    /** The transaction */\n    transaction: {\n      /** The transaction message */\n      message: Message;\n      /** The transaction signatures */\n      signatures: string[];\n    };\n    /** Metadata produced from the transaction */\n    meta: ConfirmedTransactionMeta | null;\n    /** The transaction version */\n    version?: TransactionVersion;\n  }>;\n  /** Vector of block rewards */\n  rewards?: Array<{\n    /** Public key of reward recipient */\n    pubkey: string;\n    /** Reward value in lamports */\n    lamports: number;\n    /** Account balance after reward is applied */\n    postBalance: number | null;\n    /** Type of reward received */\n    rewardType: string | null;\n    /** Vote account commission when the reward was credited, only present for voting and staking rewards */\n    commission?: number | null;\n  }>;\n  /** The unix timestamp of when the block was processed */\n  blockTime: number | null;\n};\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\nexport type AccountsModeBlockResponse = VersionedAccountsModeBlockResponse;\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\nexport type NoneModeBlockResponse = VersionedNoneModeBlockResponse;\n\n/**\n * A block with parsed transactions\n */\nexport type ParsedBlockResponse = {\n  /** Blockhash of this block */\n  blockhash: Blockhash;\n  /** Blockhash of this block's parent */\n  previousBlockhash: Blockhash;\n  /** Slot index of this block's parent */\n  parentSlot: number;\n  /** Vector of transactions with status meta and original message */\n  transactions: Array<{\n    /** The details of the transaction */\n    transaction: ParsedTransaction;\n    /** Metadata produced from the transaction */\n    meta: ParsedTransactionMeta | null;\n    /** The transaction version */\n    version?: TransactionVersion;\n  }>;\n  /** Vector of block rewards */\n  rewards?: Array<{\n    /** Public key of reward recipient */\n    pubkey: string;\n    /** Reward value in lamports */\n    lamports: number;\n    /** Account balance after reward is applied */\n    postBalance: number | null;\n    /** Type of reward received */\n    rewardType: string | null;\n    /** Vote account commission when the reward was credited, only present for voting and staking rewards */\n    commission?: number | null;\n  }>;\n  /** The unix timestamp of when the block was processed */\n  blockTime: number | null;\n  /** The number of blocks beneath this block */\n  blockHeight: number | null;\n};\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `accounts`\n */\nexport type ParsedAccountsModeBlockResponse = Omit<\n  ParsedBlockResponse,\n  'transactions'\n> & {\n  transactions: Array<\n    Omit<ParsedBlockResponse['transactions'][number], 'transaction'> & {\n      transaction: Pick<\n        ParsedBlockResponse['transactions'][number]['transaction'],\n        'signatures'\n      > & {\n        accountKeys: ParsedMessageAccount[];\n      };\n    }\n  >;\n};\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `none`\n */\nexport type ParsedNoneModeBlockResponse = Omit<\n  ParsedBlockResponse,\n  'transactions'\n>;\n\n/**\n * A processed block fetched from the RPC API\n */\nexport type VersionedBlockResponse = {\n  /** Blockhash of this block */\n  blockhash: Blockhash;\n  /** Blockhash of this block's parent */\n  previousBlockhash: Blockhash;\n  /** Slot index of this block's parent */\n  parentSlot: number;\n  /** Vector of transactions with status meta and original message */\n  transactions: Array<{\n    /** The transaction */\n    transaction: {\n      /** The transaction message */\n      message: VersionedMessage;\n      /** The transaction signatures */\n      signatures: string[];\n    };\n    /** Metadata produced from the transaction */\n    meta: ConfirmedTransactionMeta | null;\n    /** The transaction version */\n    version?: TransactionVersion;\n  }>;\n  /** Vector of block rewards */\n  rewards?: Array<{\n    /** Public key of reward recipient */\n    pubkey: string;\n    /** Reward value in lamports */\n    lamports: number;\n    /** Account balance after reward is applied */\n    postBalance: number | null;\n    /** Type of reward received */\n    rewardType: string | null;\n    /** Vote account commission when the reward was credited, only present for voting and staking rewards */\n    commission?: number | null;\n  }>;\n  /** The unix timestamp of when the block was processed */\n  blockTime: number | null;\n};\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\nexport type VersionedAccountsModeBlockResponse = Omit<\n  VersionedBlockResponse,\n  'transactions'\n> & {\n  transactions: Array<\n    Omit<VersionedBlockResponse['transactions'][number], 'transaction'> & {\n      transaction: Pick<\n        VersionedBlockResponse['transactions'][number]['transaction'],\n        'signatures'\n      > & {\n        accountKeys: ParsedMessageAccount[];\n      };\n    }\n  >;\n};\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\nexport type VersionedNoneModeBlockResponse = Omit<\n  VersionedBlockResponse,\n  'transactions'\n>;\n\n/**\n * A confirmed block on the ledger\n *\n * @deprecated Deprecated since Solana v1.8.0.\n */\nexport type ConfirmedBlock = {\n  /** Blockhash of this block */\n  blockhash: Blockhash;\n  /** Blockhash of this block's parent */\n  previousBlockhash: Blockhash;\n  /** Slot index of this block's parent */\n  parentSlot: number;\n  /** Vector of transactions and status metas */\n  transactions: Array<{\n    transaction: Transaction;\n    meta: ConfirmedTransactionMeta | null;\n  }>;\n  /** Vector of block rewards */\n  rewards?: Array<{\n    pubkey: string;\n    lamports: number;\n    postBalance: number | null;\n    rewardType: string | null;\n    commission?: number | null;\n  }>;\n  /** The unix timestamp of when the block was processed */\n  blockTime: number | null;\n};\n\n/**\n * A Block on the ledger with signatures only\n */\nexport type BlockSignatures = {\n  /** Blockhash of this block */\n  blockhash: Blockhash;\n  /** Blockhash of this block's parent */\n  previousBlockhash: Blockhash;\n  /** Slot index of this block's parent */\n  parentSlot: number;\n  /** Vector of signatures */\n  signatures: Array<string>;\n  /** The unix timestamp of when the block was processed */\n  blockTime: number | null;\n};\n\n/**\n * recent block production information\n */\nexport type BlockProduction = Readonly<{\n  /** a dictionary of validator identities, as base-58 encoded strings. Value is a two element array containing the number of leader slots and the number of blocks produced */\n  byIdentity: Readonly<Record<string, ReadonlyArray<number>>>;\n  /** Block production slot range */\n  range: Readonly<{\n    /** first slot of the block production information (inclusive) */\n    firstSlot: number;\n    /** last slot of block production information (inclusive) */\n    lastSlot: number;\n  }>;\n}>;\n\nexport type GetBlockProductionConfig = {\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** Slot range to return block production for. If parameter not provided, defaults to current epoch. */\n  range?: {\n    /** first slot to return block production information for (inclusive) */\n    firstSlot: number;\n    /** last slot to return block production information for (inclusive). If parameter not provided, defaults to the highest slot */\n    lastSlot?: number;\n  };\n  /** Only return results for this validator identity (base-58 encoded) */\n  identity?: string;\n};\n\n/**\n * Expected JSON RPC response for the \"getBlockProduction\" message\n */\nconst BlockProductionResponseStruct = jsonRpcResultAndContext(\n  pick({\n    byIdentity: record(string(), array(number())),\n    range: pick({\n      firstSlot: number(),\n      lastSlot: number(),\n    }),\n  }),\n);\n\n/**\n * A performance sample\n */\nexport type PerfSample = {\n  /** Slot number of sample */\n  slot: number;\n  /** Number of transactions in a sample window */\n  numTransactions: number;\n  /** Number of slots in a sample window */\n  numSlots: number;\n  /** Sample window in seconds */\n  samplePeriodSecs: number;\n};\n\nfunction createRpcClient(\n  url: string,\n  httpHeaders?: HttpHeaders,\n  customFetch?: FetchFn,\n  fetchMiddleware?: FetchMiddleware,\n  disableRetryOnRateLimit?: boolean,\n  httpAgent?: NodeHttpAgent | NodeHttpsAgent | false,\n): RpcClient {\n  const fetch = customFetch ? customFetch : fetchImpl;\n  let agent: NodeHttpAgent | NodeHttpsAgent | undefined;\n  if (process.env.BROWSER) {\n    if (httpAgent != null) {\n      console.warn(\n        'You have supplied an `httpAgent` when creating a `Connection` in a browser environment.' +\n          'It has been ignored; `httpAgent` is only used in Node environments.',\n      );\n    }\n  } else {\n    if (httpAgent == null) {\n      if (process.env.NODE_ENV !== 'test') {\n        const agentOptions = {\n          // One second fewer than the Solana RPC's keepalive timeout.\n          // Read more: https://github.com/solana-labs/solana/issues/27859#issuecomment-1340097889\n          freeSocketTimeout: 19000,\n          keepAlive: true,\n          maxSockets: 25,\n        };\n        if (url.startsWith('https:')) {\n          agent = new HttpsKeepAliveAgent(agentOptions);\n        } else {\n          agent = new HttpKeepAliveAgent(agentOptions);\n        }\n      }\n    } else {\n      if (httpAgent !== false) {\n        const isHttps = url.startsWith('https:');\n        if (isHttps && !(httpAgent instanceof NodeHttpsAgent)) {\n          throw new Error(\n            'The endpoint `' +\n              url +\n              '` can only be paired with an `https.Agent`. You have, instead, supplied an ' +\n              '`http.Agent` through `httpAgent`.',\n          );\n        } else if (!isHttps && httpAgent instanceof NodeHttpsAgent) {\n          throw new Error(\n            'The endpoint `' +\n              url +\n              '` can only be paired with an `http.Agent`. You have, instead, supplied an ' +\n              '`https.Agent` through `httpAgent`.',\n          );\n        }\n        agent = httpAgent;\n      }\n    }\n  }\n\n  let fetchWithMiddleware: FetchFn | undefined;\n\n  if (fetchMiddleware) {\n    fetchWithMiddleware = async (info, init) => {\n      const modifiedFetchArgs = await new Promise<Parameters<FetchFn>>(\n        (resolve, reject) => {\n          try {\n            fetchMiddleware(info, init, (modifiedInfo, modifiedInit) =>\n              resolve([modifiedInfo, modifiedInit]),\n            );\n          } catch (error) {\n            reject(error);\n          }\n        },\n      );\n      return await fetch(...modifiedFetchArgs);\n    };\n  }\n\n  const clientBrowser = new RpcClient(async (request, callback) => {\n    const options = {\n      method: 'POST',\n      body: request,\n      agent,\n      headers: Object.assign(\n        {\n          'Content-Type': 'application/json',\n        },\n        httpHeaders || {},\n        COMMON_HTTP_HEADERS,\n      ),\n    };\n\n    try {\n      let too_many_requests_retries = 5;\n      let res: Response;\n      let waitTime = 500;\n      for (;;) {\n        if (fetchWithMiddleware) {\n          res = await fetchWithMiddleware(url, options);\n        } else {\n          res = await fetch(url, options);\n        }\n\n        if (res.status !== 429 /* Too many requests */) {\n          break;\n        }\n        if (disableRetryOnRateLimit === true) {\n          break;\n        }\n        too_many_requests_retries -= 1;\n        if (too_many_requests_retries === 0) {\n          break;\n        }\n        console.log(\n          `Server responded with ${res.status} ${res.statusText}.  Retrying after ${waitTime}ms delay...`,\n        );\n        await sleep(waitTime);\n        waitTime *= 2;\n      }\n\n      const text = await res.text();\n      if (res.ok) {\n        callback(null, text);\n      } else {\n        callback(new Error(`${res.status} ${res.statusText}: ${text}`));\n      }\n    } catch (err) {\n      if (err instanceof Error) callback(err);\n    }\n  }, {});\n\n  return clientBrowser;\n}\n\nfunction createRpcRequest(client: RpcClient): RpcRequest {\n  return (method, args) => {\n    return new Promise((resolve, reject) => {\n      client.request(method, args, (err: any, response: any) => {\n        if (err) {\n          reject(err);\n          return;\n        }\n        resolve(response);\n      });\n    });\n  };\n}\n\nfunction createRpcBatchRequest(client: RpcClient): RpcBatchRequest {\n  return (requests: RpcParams[]) => {\n    return new Promise((resolve, reject) => {\n      // Do nothing if requests is empty\n      if (requests.length === 0) resolve([]);\n\n      const batch = requests.map((params: RpcParams) => {\n        return client.request(params.methodName, params.args);\n      });\n\n      client.request(batch, (err: any, response: any) => {\n        if (err) {\n          reject(err);\n          return;\n        }\n        resolve(response);\n      });\n    });\n  };\n}\n\n/**\n * Expected JSON RPC response for the \"getInflationGovernor\" message\n */\nconst GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult);\n\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateRpcResult = jsonRpcResult(GetInflationRateResult);\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesRpcResult = jsonRpcResult(\n  GetRecentPrioritizationFeesResult,\n);\n\n/**\n * Expected JSON RPC response for the \"getEpochInfo\" message\n */\nconst GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult);\n\n/**\n * Expected JSON RPC response for the \"getEpochSchedule\" message\n */\nconst GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"getLeaderSchedule\" message\n */\nconst GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"minimumLedgerSlot\" and \"getFirstAvailableBlock\" messages\n */\nconst SlotRpcResult = jsonRpcResult(number());\n\n/**\n * Supply\n */\nexport type Supply = {\n  /** Total supply in lamports */\n  total: number;\n  /** Circulating supply in lamports */\n  circulating: number;\n  /** Non-circulating supply in lamports */\n  nonCirculating: number;\n  /** List of non-circulating account addresses */\n  nonCirculatingAccounts: Array<PublicKey>;\n};\n\n/**\n * Expected JSON RPC response for the \"getSupply\" message\n */\nconst GetSupplyRpcResult = jsonRpcResultAndContext(\n  pick({\n    total: number(),\n    circulating: number(),\n    nonCirculating: number(),\n    nonCirculatingAccounts: array(PublicKeyFromString),\n  }),\n);\n\n/**\n * Token amount object which returns a token amount in different formats\n * for various client use cases.\n */\nexport type TokenAmount = {\n  /** Raw amount of tokens as string ignoring decimals */\n  amount: string;\n  /** Number of decimals configured for token's mint */\n  decimals: number;\n  /** Token amount as float, accounts for decimals */\n  uiAmount: number | null;\n  /** Token amount as string, accounts for decimals */\n  uiAmountString?: string;\n};\n\n/**\n * Expected JSON RPC structure for token amounts\n */\nconst TokenAmountResult = pick({\n  amount: string(),\n  uiAmount: nullable(number()),\n  decimals: number(),\n  uiAmountString: optional(string()),\n});\n\n/**\n * Token address and balance.\n */\nexport type TokenAccountBalancePair = {\n  /** Address of the token account */\n  address: PublicKey;\n  /** Raw amount of tokens as string ignoring decimals */\n  amount: string;\n  /** Number of decimals configured for token's mint */\n  decimals: number;\n  /** Token amount as float, accounts for decimals */\n  uiAmount: number | null;\n  /** Token amount as string, accounts for decimals */\n  uiAmountString?: string;\n};\n\n/**\n * Expected JSON RPC response for the \"getTokenLargestAccounts\" message\n */\nconst GetTokenLargestAccountsResult = jsonRpcResultAndContext(\n  array(\n    pick({\n      address: PublicKeyFromString,\n      amount: string(),\n      uiAmount: nullable(number()),\n      decimals: number(),\n      uiAmountString: optional(string()),\n    }),\n  ),\n);\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message\n */\nconst GetTokenAccountsByOwner = jsonRpcResultAndContext(\n  array(\n    pick({\n      pubkey: PublicKeyFromString,\n      account: pick({\n        executable: boolean(),\n        owner: PublicKeyFromString,\n        lamports: number(),\n        data: BufferFromRawAccountData,\n        rentEpoch: number(),\n      }),\n    }),\n  ),\n);\n\nconst ParsedAccountDataResult = pick({\n  program: string(),\n  parsed: unknown(),\n  space: number(),\n});\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message with parsed data\n */\nconst GetParsedTokenAccountsByOwner = jsonRpcResultAndContext(\n  array(\n    pick({\n      pubkey: PublicKeyFromString,\n      account: pick({\n        executable: boolean(),\n        owner: PublicKeyFromString,\n        lamports: number(),\n        data: ParsedAccountDataResult,\n        rentEpoch: number(),\n      }),\n    }),\n  ),\n);\n\n/**\n * Pair of an account address and its balance\n */\nexport type AccountBalancePair = {\n  address: PublicKey;\n  lamports: number;\n};\n\n/**\n * Expected JSON RPC response for the \"getLargestAccounts\" message\n */\nconst GetLargestAccountsRpcResult = jsonRpcResultAndContext(\n  array(\n    pick({\n      lamports: number(),\n      address: PublicKeyFromString,\n    }),\n  ),\n);\n\n/**\n * @internal\n */\nconst AccountInfoResult = pick({\n  executable: boolean(),\n  owner: PublicKeyFromString,\n  lamports: number(),\n  data: BufferFromRawAccountData,\n  rentEpoch: number(),\n});\n\n/**\n * @internal\n */\nconst KeyedAccountInfoResult = pick({\n  pubkey: PublicKeyFromString,\n  account: AccountInfoResult,\n});\n\nconst ParsedOrRawAccountData = coerce(\n  union([instance(Buffer), ParsedAccountDataResult]),\n  union([RawAccountDataResult, ParsedAccountDataResult]),\n  value => {\n    if (Array.isArray(value)) {\n      return create(value, BufferFromRawAccountData);\n    } else {\n      return value;\n    }\n  },\n);\n\n/**\n * @internal\n */\nconst ParsedAccountInfoResult = pick({\n  executable: boolean(),\n  owner: PublicKeyFromString,\n  lamports: number(),\n  data: ParsedOrRawAccountData,\n  rentEpoch: number(),\n});\n\nconst KeyedParsedAccountInfoResult = pick({\n  pubkey: PublicKeyFromString,\n  account: ParsedAccountInfoResult,\n});\n\n/**\n * @internal\n */\nconst StakeActivationResult = pick({\n  state: union([\n    literal('active'),\n    literal('inactive'),\n    literal('activating'),\n    literal('deactivating'),\n  ]),\n  active: number(),\n  inactive: number(),\n});\n\n/**\n * Expected JSON RPC response for the \"getConfirmedSignaturesForAddress2\" message\n */\n\nconst GetConfirmedSignaturesForAddress2RpcResult = jsonRpcResult(\n  array(\n    pick({\n      signature: string(),\n      slot: number(),\n      err: TransactionErrorResult,\n      memo: nullable(string()),\n      blockTime: optional(nullable(number())),\n    }),\n  ),\n);\n\n/**\n * Expected JSON RPC response for the \"getSignaturesForAddress\" message\n */\nconst GetSignaturesForAddressRpcResult = jsonRpcResult(\n  array(\n    pick({\n      signature: string(),\n      slot: number(),\n      err: TransactionErrorResult,\n      memo: nullable(string()),\n      blockTime: optional(nullable(number())),\n    }),\n  ),\n);\n\n/***\n * Expected JSON RPC response for the \"accountNotification\" message\n */\nconst AccountNotificationResult = pick({\n  subscription: number(),\n  result: notificationResultAndContext(AccountInfoResult),\n});\n\n/**\n * @internal\n */\nconst ProgramAccountInfoResult = pick({\n  pubkey: PublicKeyFromString,\n  account: AccountInfoResult,\n});\n\n/***\n * Expected JSON RPC response for the \"programNotification\" message\n */\nconst ProgramAccountNotificationResult = pick({\n  subscription: number(),\n  result: notificationResultAndContext(ProgramAccountInfoResult),\n});\n\n/**\n * @internal\n */\nconst SlotInfoResult = pick({\n  parent: number(),\n  slot: number(),\n  root: number(),\n});\n\n/**\n * Expected JSON RPC response for the \"slotNotification\" message\n */\nconst SlotNotificationResult = pick({\n  subscription: number(),\n  result: SlotInfoResult,\n});\n\n/**\n * Slot updates which can be used for tracking the live progress of a cluster.\n * - `\"firstShredReceived\"`: connected node received the first shred of a block.\n * Indicates that a new block that is being produced.\n * - `\"completed\"`: connected node has received all shreds of a block. Indicates\n * a block was recently produced.\n * - `\"optimisticConfirmation\"`: block was optimistically confirmed by the\n * cluster. It is not guaranteed that an optimistic confirmation notification\n * will be sent for every finalized blocks.\n * - `\"root\"`: the connected node rooted this block.\n * - `\"createdBank\"`: the connected node has started validating this block.\n * - `\"frozen\"`: the connected node has validated this block.\n * - `\"dead\"`: the connected node failed to validate this block.\n */\nexport type SlotUpdate =\n  | {\n      type: 'firstShredReceived';\n      slot: number;\n      timestamp: number;\n    }\n  | {\n      type: 'completed';\n      slot: number;\n      timestamp: number;\n    }\n  | {\n      type: 'createdBank';\n      slot: number;\n      timestamp: number;\n      parent: number;\n    }\n  | {\n      type: 'frozen';\n      slot: number;\n      timestamp: number;\n      stats: {\n        numTransactionEntries: number;\n        numSuccessfulTransactions: number;\n        numFailedTransactions: number;\n        maxTransactionsPerEntry: number;\n      };\n    }\n  | {\n      type: 'dead';\n      slot: number;\n      timestamp: number;\n      err: string;\n    }\n  | {\n      type: 'optimisticConfirmation';\n      slot: number;\n      timestamp: number;\n    }\n  | {\n      type: 'root';\n      slot: number;\n      timestamp: number;\n    };\n\n/**\n * @internal\n */\nconst SlotUpdateResult = union([\n  pick({\n    type: union([\n      literal('firstShredReceived'),\n      literal('completed'),\n      literal('optimisticConfirmation'),\n      literal('root'),\n    ]),\n    slot: number(),\n    timestamp: number(),\n  }),\n  pick({\n    type: literal('createdBank'),\n    parent: number(),\n    slot: number(),\n    timestamp: number(),\n  }),\n  pick({\n    type: literal('frozen'),\n    slot: number(),\n    timestamp: number(),\n    stats: pick({\n      numTransactionEntries: number(),\n      numSuccessfulTransactions: number(),\n      numFailedTransactions: number(),\n      maxTransactionsPerEntry: number(),\n    }),\n  }),\n  pick({\n    type: literal('dead'),\n    slot: number(),\n    timestamp: number(),\n    err: string(),\n  }),\n]);\n\n/**\n * Expected JSON RPC response for the \"slotsUpdatesNotification\" message\n */\nconst SlotUpdateNotificationResult = pick({\n  subscription: number(),\n  result: SlotUpdateResult,\n});\n\n/**\n * Expected JSON RPC response for the \"signatureNotification\" message\n */\nconst SignatureNotificationResult = pick({\n  subscription: number(),\n  result: notificationResultAndContext(\n    union([SignatureStatusResult, SignatureReceivedResult]),\n  ),\n});\n\n/**\n * Expected JSON RPC response for the \"rootNotification\" message\n */\nconst RootNotificationResult = pick({\n  subscription: number(),\n  result: number(),\n});\n\nconst ContactInfoResult = pick({\n  pubkey: string(),\n  gossip: nullable(string()),\n  tpu: nullable(string()),\n  rpc: nullable(string()),\n  version: nullable(string()),\n});\n\nconst VoteAccountInfoResult = pick({\n  votePubkey: string(),\n  nodePubkey: string(),\n  activatedStake: number(),\n  epochVoteAccount: boolean(),\n  epochCredits: array(tuple([number(), number(), number()])),\n  commission: number(),\n  lastVote: number(),\n  rootSlot: nullable(number()),\n});\n\n/**\n * Expected JSON RPC response for the \"getVoteAccounts\" message\n */\nconst GetVoteAccounts = jsonRpcResult(\n  pick({\n    current: array(VoteAccountInfoResult),\n    delinquent: array(VoteAccountInfoResult),\n  }),\n);\n\nconst ConfirmationStatus = union([\n  literal('processed'),\n  literal('confirmed'),\n  literal('finalized'),\n]);\n\nconst SignatureStatusResponse = pick({\n  slot: number(),\n  confirmations: nullable(number()),\n  err: TransactionErrorResult,\n  confirmationStatus: optional(ConfirmationStatus),\n});\n\n/**\n * Expected JSON RPC response for the \"getSignatureStatuses\" message\n */\nconst GetSignatureStatusesRpcResult = jsonRpcResultAndContext(\n  array(nullable(SignatureStatusResponse)),\n);\n\n/**\n * Expected JSON RPC response for the \"getMinimumBalanceForRentExemption\" message\n */\nconst GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number());\n\nconst AddressTableLookupStruct = pick({\n  accountKey: PublicKeyFromString,\n  writableIndexes: array(number()),\n  readonlyIndexes: array(number()),\n});\n\nconst ConfirmedTransactionResult = pick({\n  signatures: array(string()),\n  message: pick({\n    accountKeys: array(string()),\n    header: pick({\n      numRequiredSignatures: number(),\n      numReadonlySignedAccounts: number(),\n      numReadonlyUnsignedAccounts: number(),\n    }),\n    instructions: array(\n      pick({\n        accounts: array(number()),\n        data: string(),\n        programIdIndex: number(),\n      }),\n    ),\n    recentBlockhash: string(),\n    addressTableLookups: optional(array(AddressTableLookupStruct)),\n  }),\n});\n\nconst AnnotatedAccountKey = pick({\n  pubkey: PublicKeyFromString,\n  signer: boolean(),\n  writable: boolean(),\n  source: optional(union([literal('transaction'), literal('lookupTable')])),\n});\n\nconst ConfirmedTransactionAccountsModeResult = pick({\n  accountKeys: array(AnnotatedAccountKey),\n  signatures: array(string()),\n});\n\nconst ParsedInstructionResult = pick({\n  parsed: unknown(),\n  program: string(),\n  programId: PublicKeyFromString,\n});\n\nconst RawInstructionResult = pick({\n  accounts: array(PublicKeyFromString),\n  data: string(),\n  programId: PublicKeyFromString,\n});\n\nconst InstructionResult = union([\n  RawInstructionResult,\n  ParsedInstructionResult,\n]);\n\nconst UnknownInstructionResult = union([\n  pick({\n    parsed: unknown(),\n    program: string(),\n    programId: string(),\n  }),\n  pick({\n    accounts: array(string()),\n    data: string(),\n    programId: string(),\n  }),\n]);\n\nconst ParsedOrRawInstruction = coerce(\n  InstructionResult,\n  UnknownInstructionResult,\n  value => {\n    if ('accounts' in value) {\n      return create(value, RawInstructionResult);\n    } else {\n      return create(value, ParsedInstructionResult);\n    }\n  },\n);\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionResult = pick({\n  signatures: array(string()),\n  message: pick({\n    accountKeys: array(AnnotatedAccountKey),\n    instructions: array(ParsedOrRawInstruction),\n    recentBlockhash: string(),\n    addressTableLookups: optional(nullable(array(AddressTableLookupStruct))),\n  }),\n});\n\nconst TokenBalanceResult = pick({\n  accountIndex: number(),\n  mint: string(),\n  owner: optional(string()),\n  uiTokenAmount: TokenAmountResult,\n});\n\nconst LoadedAddressesResult = pick({\n  writable: array(PublicKeyFromString),\n  readonly: array(PublicKeyFromString),\n});\n\n/**\n * @internal\n */\nconst ConfirmedTransactionMetaResult = pick({\n  err: TransactionErrorResult,\n  fee: number(),\n  innerInstructions: optional(\n    nullable(\n      array(\n        pick({\n          index: number(),\n          instructions: array(\n            pick({\n              accounts: array(number()),\n              data: string(),\n              programIdIndex: number(),\n            }),\n          ),\n        }),\n      ),\n    ),\n  ),\n  preBalances: array(number()),\n  postBalances: array(number()),\n  logMessages: optional(nullable(array(string()))),\n  preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n  postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n  loadedAddresses: optional(LoadedAddressesResult),\n  computeUnitsConsumed: optional(number()),\n});\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionMetaResult = pick({\n  err: TransactionErrorResult,\n  fee: number(),\n  innerInstructions: optional(\n    nullable(\n      array(\n        pick({\n          index: number(),\n          instructions: array(ParsedOrRawInstruction),\n        }),\n      ),\n    ),\n  ),\n  preBalances: array(number()),\n  postBalances: array(number()),\n  logMessages: optional(nullable(array(string()))),\n  preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n  postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n  loadedAddresses: optional(LoadedAddressesResult),\n  computeUnitsConsumed: optional(number()),\n});\n\nconst TransactionVersionStruct = union([literal(0), literal('legacy')]);\n\n/** @internal */\nconst RewardsResult = pick({\n  pubkey: string(),\n  lamports: number(),\n  postBalance: nullable(number()),\n  rewardType: nullable(string()),\n  commission: optional(nullable(number())),\n});\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      blockhash: string(),\n      previousBlockhash: string(),\n      parentSlot: number(),\n      transactions: array(\n        pick({\n          transaction: ConfirmedTransactionResult,\n          meta: nullable(ConfirmedTransactionMetaResult),\n          version: optional(TransactionVersionStruct),\n        }),\n      ),\n      rewards: optional(array(RewardsResult)),\n      blockTime: nullable(number()),\n      blockHeight: nullable(number()),\n    }),\n  ),\n);\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `none`\n */\nconst GetNoneModeBlockRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      blockhash: string(),\n      previousBlockhash: string(),\n      parentSlot: number(),\n      rewards: optional(array(RewardsResult)),\n      blockTime: nullable(number()),\n      blockHeight: nullable(number()),\n    }),\n  ),\n);\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `accounts`\n */\nconst GetAccountsModeBlockRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      blockhash: string(),\n      previousBlockhash: string(),\n      parentSlot: number(),\n      transactions: array(\n        pick({\n          transaction: ConfirmedTransactionAccountsModeResult,\n          meta: nullable(ConfirmedTransactionMetaResult),\n          version: optional(TransactionVersionStruct),\n        }),\n      ),\n      rewards: optional(array(RewardsResult)),\n      blockTime: nullable(number()),\n      blockHeight: nullable(number()),\n    }),\n  ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message\n */\nconst GetParsedBlockRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      blockhash: string(),\n      previousBlockhash: string(),\n      parentSlot: number(),\n      transactions: array(\n        pick({\n          transaction: ParsedConfirmedTransactionResult,\n          meta: nullable(ParsedConfirmedTransactionMetaResult),\n          version: optional(TransactionVersionStruct),\n        }),\n      ),\n      rewards: optional(array(RewardsResult)),\n      blockTime: nullable(number()),\n      blockHeight: nullable(number()),\n    }),\n  ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message  when `transactionDetails` is `accounts`\n */\nconst GetParsedAccountsModeBlockRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      blockhash: string(),\n      previousBlockhash: string(),\n      parentSlot: number(),\n      transactions: array(\n        pick({\n          transaction: ConfirmedTransactionAccountsModeResult,\n          meta: nullable(ParsedConfirmedTransactionMetaResult),\n          version: optional(TransactionVersionStruct),\n        }),\n      ),\n      rewards: optional(array(RewardsResult)),\n      blockTime: nullable(number()),\n      blockHeight: nullable(number()),\n    }),\n  ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message  when `transactionDetails` is `none`\n */\nconst GetParsedNoneModeBlockRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      blockhash: string(),\n      previousBlockhash: string(),\n      parentSlot: number(),\n      rewards: optional(array(RewardsResult)),\n      blockTime: nullable(number()),\n      blockHeight: nullable(number()),\n    }),\n  ),\n);\n\n/**\n * Expected JSON RPC response for the \"getConfirmedBlock\" message\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetBlockRpcResult} instead.\n */\nconst GetConfirmedBlockRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      blockhash: string(),\n      previousBlockhash: string(),\n      parentSlot: number(),\n      transactions: array(\n        pick({\n          transaction: ConfirmedTransactionResult,\n          meta: nullable(ConfirmedTransactionMetaResult),\n        }),\n      ),\n      rewards: optional(array(RewardsResult)),\n      blockTime: nullable(number()),\n    }),\n  ),\n);\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockSignaturesRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      blockhash: string(),\n      previousBlockhash: string(),\n      parentSlot: number(),\n      signatures: array(string()),\n      blockTime: nullable(number()),\n    }),\n  ),\n);\n\n/**\n * Expected JSON RPC response for the \"getTransaction\" message\n */\nconst GetTransactionRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      slot: number(),\n      meta: nullable(ConfirmedTransactionMetaResult),\n      blockTime: optional(nullable(number())),\n      transaction: ConfirmedTransactionResult,\n      version: optional(TransactionVersionStruct),\n    }),\n  ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getTransaction\" message\n */\nconst GetParsedTransactionRpcResult = jsonRpcResult(\n  nullable(\n    pick({\n      slot: number(),\n      transaction: ParsedConfirmedTransactionResult,\n      meta: nullable(ParsedConfirmedTransactionMetaResult),\n      blockTime: optional(nullable(number())),\n      version: optional(TransactionVersionStruct),\n    }),\n  ),\n);\n\n/**\n * Expected JSON RPC response for the \"getRecentBlockhash\" message\n *\n * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetLatestBlockhashRpcResult} instead.\n */\nconst GetRecentBlockhashAndContextRpcResult = jsonRpcResultAndContext(\n  pick({\n    blockhash: string(),\n    feeCalculator: pick({\n      lamportsPerSignature: number(),\n    }),\n  }),\n);\n\n/**\n * Expected JSON RPC response for the \"getLatestBlockhash\" message\n */\nconst GetLatestBlockhashRpcResult = jsonRpcResultAndContext(\n  pick({\n    blockhash: string(),\n    lastValidBlockHeight: number(),\n  }),\n);\n\n/**\n * Expected JSON RPC response for the \"isBlockhashValid\" message\n */\nconst IsBlockhashValidRpcResult = jsonRpcResultAndContext(boolean());\n\nconst PerfSampleResult = pick({\n  slot: number(),\n  numTransactions: number(),\n  numSlots: number(),\n  samplePeriodSecs: number(),\n});\n\n/*\n * Expected JSON RPC response for \"getRecentPerformanceSamples\" message\n */\nconst GetRecentPerformanceSamplesRpcResult = jsonRpcResult(\n  array(PerfSampleResult),\n);\n\n/**\n * Expected JSON RPC response for the \"getFeeCalculatorForBlockhash\" message\n */\nconst GetFeeCalculatorRpcResult = jsonRpcResultAndContext(\n  nullable(\n    pick({\n      feeCalculator: pick({\n        lamportsPerSignature: number(),\n      }),\n    }),\n  ),\n);\n\n/**\n * Expected JSON RPC response for the \"requestAirdrop\" message\n */\nconst RequestAirdropRpcResult = jsonRpcResult(string());\n\n/**\n * Expected JSON RPC response for the \"sendTransaction\" message\n */\nconst SendTransactionRpcResult = jsonRpcResult(string());\n\n/**\n * Information about the latest slot being processed by a node\n */\nexport type SlotInfo = {\n  /** Currently processing slot */\n  slot: number;\n  /** Parent of the current slot */\n  parent: number;\n  /** The root block of the current slot's fork */\n  root: number;\n};\n\n/**\n * Parsed account data\n */\nexport type ParsedAccountData = {\n  /** Name of the program that owns this account */\n  program: string;\n  /** Parsed account data */\n  parsed: any;\n  /** Space used by account data */\n  space: number;\n};\n\n/**\n * Stake Activation data\n */\nexport type StakeActivationData = {\n  /** the stake account's activation state */\n  state: 'active' | 'inactive' | 'activating' | 'deactivating';\n  /** stake active during the epoch */\n  active: number;\n  /** stake inactive during the epoch */\n  inactive: number;\n};\n\n/**\n * Data slice argument for getProgramAccounts\n */\nexport type DataSlice = {\n  /** offset of data slice */\n  offset: number;\n  /** length of data slice */\n  length: number;\n};\n\n/**\n * Memory comparison filter for getProgramAccounts\n */\nexport type MemcmpFilter = {\n  memcmp: {\n    /** offset into program account data to start comparison */\n    offset: number;\n    /** data to match, as base-58 encoded string and limited to less than 129 bytes */\n    bytes: string;\n  };\n};\n\n/**\n * Data size comparison filter for getProgramAccounts\n */\nexport type DataSizeFilter = {\n  /** Size of data for program account data length comparison */\n  dataSize: number;\n};\n\n/**\n * A filter object for getProgramAccounts\n */\nexport type GetProgramAccountsFilter = MemcmpFilter | DataSizeFilter;\n\n/**\n * Configuration object for getProgramAccounts requests\n */\nexport type GetProgramAccountsConfig = {\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** Optional encoding for account data (default base64)\n   * To use \"jsonParsed\" encoding, please refer to `getParsedProgramAccounts` in connection.ts\n   * */\n  encoding?: 'base64';\n  /** Optional data slice to limit the returned account data */\n  dataSlice?: DataSlice;\n  /** Optional array of filters to apply to accounts */\n  filters?: GetProgramAccountsFilter[];\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n  /** wrap the result in an RpcResponse JSON object */\n  withContext?: boolean;\n};\n\nexport type GetProgramAccountsResponse = readonly Readonly<{\n  account: AccountInfo<Buffer>;\n  /** the account Pubkey as base-58 encoded string */\n  pubkey: PublicKey;\n}>[];\n\n/**\n * Configuration object for getParsedProgramAccounts\n */\nexport type GetParsedProgramAccountsConfig = {\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** Optional array of filters to apply to accounts */\n  filters?: GetProgramAccountsFilter[];\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for getMultipleAccounts\n */\nexport type GetMultipleAccountsConfig = {\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n  /** Optional data slice to limit the returned account data */\n  dataSlice?: DataSlice;\n};\n\n/**\n * Configuration object for `getStakeActivation`\n */\nexport type GetStakeActivationConfig = {\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** Epoch for which to calculate activation details. If parameter not provided, defaults to current epoch */\n  epoch?: number;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getStakeActivation`\n */\nexport type GetTokenAccountsByOwnerConfig = {\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getStakeActivation`\n */\nexport type GetTransactionCountConfig = {\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getNonce`\n */\nexport type GetNonceConfig = {\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getNonceAndContext`\n */\nexport type GetNonceAndContextConfig = {\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** The minimum slot that the request can be evaluated at */\n  minContextSlot?: number;\n};\n\n/**\n * Information describing an account\n */\nexport type AccountInfo<T> = {\n  /** `true` if this account's data contains a loaded program */\n  executable: boolean;\n  /** Identifier of the program that owns the account */\n  owner: PublicKey;\n  /** Number of lamports assigned to the account */\n  lamports: number;\n  /** Optional data assigned to the account */\n  data: T;\n  /** Optional rent epoch info for account */\n  rentEpoch?: number;\n};\n\n/**\n * Account information identified by pubkey\n */\nexport type KeyedAccountInfo = {\n  accountId: PublicKey;\n  accountInfo: AccountInfo<Buffer>;\n};\n\n/**\n * Callback function for account change notifications\n */\nexport type AccountChangeCallback = (\n  accountInfo: AccountInfo<Buffer>,\n  context: Context,\n) => void;\n\n/**\n * Callback function for program account change notifications\n */\nexport type ProgramAccountChangeCallback = (\n  keyedAccountInfo: KeyedAccountInfo,\n  context: Context,\n) => void;\n\n/**\n * Callback function for slot change notifications\n */\nexport type SlotChangeCallback = (slotInfo: SlotInfo) => void;\n\n/**\n * Callback function for slot update notifications\n */\nexport type SlotUpdateCallback = (slotUpdate: SlotUpdate) => void;\n\n/**\n * Callback function for signature status notifications\n */\nexport type SignatureResultCallback = (\n  signatureResult: SignatureResult,\n  context: Context,\n) => void;\n\n/**\n * Signature status notification with transaction result\n */\nexport type SignatureStatusNotification = {\n  type: 'status';\n  result: SignatureResult;\n};\n\n/**\n * Signature received notification\n */\nexport type SignatureReceivedNotification = {\n  type: 'received';\n};\n\n/**\n * Callback function for signature notifications\n */\nexport type SignatureSubscriptionCallback = (\n  notification: SignatureStatusNotification | SignatureReceivedNotification,\n  context: Context,\n) => void;\n\n/**\n * Signature subscription options\n */\nexport type SignatureSubscriptionOptions = {\n  commitment?: Commitment;\n  enableReceivedNotification?: boolean;\n};\n\n/**\n * Callback function for root change notifications\n */\nexport type RootChangeCallback = (root: number) => void;\n\n/**\n * @internal\n */\nconst LogsResult = pick({\n  err: TransactionErrorResult,\n  logs: array(string()),\n  signature: string(),\n});\n\n/**\n * Logs result.\n */\nexport type Logs = {\n  err: TransactionError | null;\n  logs: string[];\n  signature: string;\n};\n\n/**\n * Expected JSON RPC response for the \"logsNotification\" message.\n */\nconst LogsNotificationResult = pick({\n  result: notificationResultAndContext(LogsResult),\n  subscription: number(),\n});\n\n/**\n * Filter for log subscriptions.\n */\nexport type LogsFilter = PublicKey | 'all' | 'allWithVotes';\n\n/**\n * Callback function for log notifications.\n */\nexport type LogsCallback = (logs: Logs, ctx: Context) => void;\n\n/**\n * Signature result\n */\nexport type SignatureResult = {\n  err: TransactionError | null;\n};\n\n/**\n * Transaction error\n */\nexport type TransactionError = {} | string;\n\n/**\n * Transaction confirmation status\n * <pre>\n *   'processed': Transaction landed in a block which has reached 1 confirmation by the connected node\n *   'confirmed': Transaction landed in a block which has reached 1 confirmation by the cluster\n *   'finalized': Transaction landed in a block which has been finalized by the cluster\n * </pre>\n */\nexport type TransactionConfirmationStatus =\n  | 'processed'\n  | 'confirmed'\n  | 'finalized';\n\n/**\n * Signature status\n */\nexport type SignatureStatus = {\n  /** when the transaction was processed */\n  slot: number;\n  /** the number of blocks that have been confirmed and voted on in the fork containing `slot` */\n  confirmations: number | null;\n  /** transaction error, if any */\n  err: TransactionError | null;\n  /** cluster confirmation status, if data available. Possible responses: `processed`, `confirmed`, `finalized` */\n  confirmationStatus?: TransactionConfirmationStatus;\n};\n\n/**\n * A confirmed signature with its status\n */\nexport type ConfirmedSignatureInfo = {\n  /** the transaction signature */\n  signature: string;\n  /** when the transaction was processed */\n  slot: number;\n  /** error, if any */\n  err: TransactionError | null;\n  /** memo associated with the transaction, if any */\n  memo: string | null;\n  /** The unix timestamp of when the transaction was processed */\n  blockTime?: number | null;\n  /** Cluster confirmation status, if available. Possible values: `processed`, `confirmed`, `finalized` */\n  confirmationStatus?: TransactionConfirmationStatus;\n};\n\n/**\n * An object defining headers to be passed to the RPC server\n */\nexport type HttpHeaders = {\n  [header: string]: string;\n} & {\n  // Prohibited headers; for internal use only.\n  'solana-client'?: never;\n};\n\n/**\n * The type of the JavaScript `fetch()` API\n */\nexport type FetchFn = typeof fetchImpl;\n\n/**\n * A callback used to augment the outgoing HTTP request\n */\nexport type FetchMiddleware = (\n  info: Parameters<FetchFn>[0],\n  init: Parameters<FetchFn>[1],\n  fetch: (...a: Parameters<FetchFn>) => void,\n) => void;\n\n/**\n * Configuration for instantiating a Connection\n */\nexport type ConnectionConfig = {\n  /**\n   * An `http.Agent` that will be used to manage socket connections (eg. to implement connection\n   * persistence). Set this to `false` to create a connection that uses no agent. This applies to\n   * Node environments only.\n   */\n  httpAgent?: NodeHttpAgent | NodeHttpsAgent | false;\n  /** Optional commitment level */\n  commitment?: Commitment;\n  /** Optional endpoint URL to the fullnode JSON RPC PubSub WebSocket Endpoint */\n  wsEndpoint?: string;\n  /** Optional HTTP headers object */\n  httpHeaders?: HttpHeaders;\n  /** Optional custom fetch function */\n  fetch?: FetchFn;\n  /** Optional fetch middleware callback */\n  fetchMiddleware?: FetchMiddleware;\n  /** Optional Disable retrying calls when server responds with HTTP 429 (Too Many Requests) */\n  disableRetryOnRateLimit?: boolean;\n  /** time to allow for the server to initially process a transaction (in milliseconds) */\n  confirmTransactionInitialTimeout?: number;\n};\n\n/** @internal */\nconst COMMON_HTTP_HEADERS = {\n  'solana-client': `js/${process.env.npm_package_version ?? 'UNKNOWN'}`,\n};\n\n/**\n * A connection to a fullnode JSON RPC endpoint\n */\nexport class Connection {\n  /** @internal */ _commitment?: Commitment;\n  /** @internal */ _confirmTransactionInitialTimeout?: number;\n  /** @internal */ _rpcEndpoint: string;\n  /** @internal */ _rpcWsEndpoint: string;\n  /** @internal */ _rpcClient: RpcClient;\n  /** @internal */ _rpcRequest: RpcRequest;\n  /** @internal */ _rpcBatchRequest: RpcBatchRequest;\n  /** @internal */ _rpcWebSocket: RpcWebSocketClient;\n  /** @internal */ _rpcWebSocketConnected: boolean = false;\n  /** @internal */ _rpcWebSocketHeartbeat: ReturnType<\n    typeof setInterval\n  > | null = null;\n  /** @internal */ _rpcWebSocketIdleTimeout: ReturnType<\n    typeof setTimeout\n  > | null = null;\n  /** @internal\n   * A number that we increment every time an active connection closes.\n   * Used to determine whether the same socket connection that was open\n   * when an async operation started is the same one that's active when\n   * its continuation fires.\n   *\n   */ private _rpcWebSocketGeneration: number = 0;\n\n  /** @internal */ _disableBlockhashCaching: boolean = false;\n  /** @internal */ _pollingBlockhash: boolean = false;\n  /** @internal */ _blockhashInfo: {\n    latestBlockhash: BlockhashWithExpiryBlockHeight | null;\n    lastFetch: number;\n    simulatedSignatures: Array<string>;\n    transactionSignatures: Array<string>;\n  } = {\n    latestBlockhash: null,\n    lastFetch: 0,\n    transactionSignatures: [],\n    simulatedSignatures: [],\n  };\n\n  /** @internal */ private _nextClientSubscriptionId: ClientSubscriptionId = 0;\n  /** @internal */ private _subscriptionDisposeFunctionsByClientSubscriptionId: {\n    [clientSubscriptionId: ClientSubscriptionId]:\n      | SubscriptionDisposeFn\n      | undefined;\n  } = {};\n  /** @internal */ private _subscriptionHashByClientSubscriptionId: {\n    [clientSubscriptionId: ClientSubscriptionId]:\n      | SubscriptionConfigHash\n      | undefined;\n  } = {};\n  /** @internal */ private _subscriptionStateChangeCallbacksByHash: {\n    [hash: SubscriptionConfigHash]:\n      | Set<SubscriptionStateChangeCallback>\n      | undefined;\n  } = {};\n  /** @internal */ private _subscriptionCallbacksByServerSubscriptionId: {\n    [serverSubscriptionId: ServerSubscriptionId]:\n      | Set<SubscriptionConfig['callback']>\n      | undefined;\n  } = {};\n  /** @internal */ private _subscriptionsByHash: {\n    [hash: SubscriptionConfigHash]: Subscription | undefined;\n  } = {};\n  /**\n   * Special case.\n   * After a signature is processed, RPCs automatically dispose of the\n   * subscription on the server side. We need to track which of these\n   * subscriptions have been disposed in such a way, so that we know\n   * whether the client is dealing with a not-yet-processed signature\n   * (in which case we must tear down the server subscription) or an\n   * already-processed signature (in which case the client can simply\n   * clear out the subscription locally without telling the server).\n   *\n   * NOTE: There is a proposal to eliminate this special case, here:\n   * https://github.com/solana-labs/solana/issues/18892\n   */\n  /** @internal */ private _subscriptionsAutoDisposedByRpc: Set<ServerSubscriptionId> =\n    new Set();\n\n  /**\n   * Establish a JSON RPC connection\n   *\n   * @param endpoint URL to the fullnode JSON RPC endpoint\n   * @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object\n   */\n  constructor(\n    endpoint: string,\n    commitmentOrConfig?: Commitment | ConnectionConfig,\n  ) {\n    let wsEndpoint;\n    let httpHeaders;\n    let fetch;\n    let fetchMiddleware;\n    let disableRetryOnRateLimit;\n    let httpAgent;\n    if (commitmentOrConfig && typeof commitmentOrConfig === 'string') {\n      this._commitment = commitmentOrConfig;\n    } else if (commitmentOrConfig) {\n      this._commitment = commitmentOrConfig.commitment;\n      this._confirmTransactionInitialTimeout =\n        commitmentOrConfig.confirmTransactionInitialTimeout;\n      wsEndpoint = commitmentOrConfig.wsEndpoint;\n      httpHeaders = commitmentOrConfig.httpHeaders;\n      fetch = commitmentOrConfig.fetch;\n      fetchMiddleware = commitmentOrConfig.fetchMiddleware;\n      disableRetryOnRateLimit = commitmentOrConfig.disableRetryOnRateLimit;\n      httpAgent = commitmentOrConfig.httpAgent;\n    }\n\n    this._rpcEndpoint = assertEndpointUrl(endpoint);\n    this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint);\n\n    this._rpcClient = createRpcClient(\n      endpoint,\n      httpHeaders,\n      fetch,\n      fetchMiddleware,\n      disableRetryOnRateLimit,\n      httpAgent,\n    );\n    this._rpcRequest = createRpcRequest(this._rpcClient);\n    this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient);\n\n    this._rpcWebSocket = new RpcWebSocketClient(this._rpcWsEndpoint, {\n      autoconnect: false,\n      max_reconnects: Infinity,\n    });\n    this._rpcWebSocket.on('open', this._wsOnOpen.bind(this));\n    this._rpcWebSocket.on('error', this._wsOnError.bind(this));\n    this._rpcWebSocket.on('close', this._wsOnClose.bind(this));\n    this._rpcWebSocket.on(\n      'accountNotification',\n      this._wsOnAccountNotification.bind(this),\n    );\n    this._rpcWebSocket.on(\n      'programNotification',\n      this._wsOnProgramAccountNotification.bind(this),\n    );\n    this._rpcWebSocket.on(\n      'slotNotification',\n      this._wsOnSlotNotification.bind(this),\n    );\n    this._rpcWebSocket.on(\n      'slotsUpdatesNotification',\n      this._wsOnSlotUpdatesNotification.bind(this),\n    );\n    this._rpcWebSocket.on(\n      'signatureNotification',\n      this._wsOnSignatureNotification.bind(this),\n    );\n    this._rpcWebSocket.on(\n      'rootNotification',\n      this._wsOnRootNotification.bind(this),\n    );\n    this._rpcWebSocket.on(\n      'logsNotification',\n      this._wsOnLogsNotification.bind(this),\n    );\n  }\n\n  /**\n   * The default commitment used for requests\n   */\n  get commitment(): Commitment | undefined {\n    return this._commitment;\n  }\n\n  /**\n   * The RPC endpoint\n   */\n  get rpcEndpoint(): string {\n    return this._rpcEndpoint;\n  }\n\n  /**\n   * Fetch the balance for the specified public key, return with context\n   */\n  async getBalanceAndContext(\n    publicKey: PublicKey,\n    commitmentOrConfig?: Commitment | GetBalanceConfig,\n  ): Promise<RpcResponseAndContext<number>> {\n    /** @internal */\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [publicKey.toBase58()],\n      commitment,\n      undefined /* encoding */,\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getBalance', args);\n    const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get balance for ${publicKey.toBase58()}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the balance for the specified public key\n   */\n  async getBalance(\n    publicKey: PublicKey,\n    commitmentOrConfig?: Commitment | GetBalanceConfig,\n  ): Promise<number> {\n    return await this.getBalanceAndContext(publicKey, commitmentOrConfig)\n      .then(x => x.value)\n      .catch(e => {\n        throw new Error(\n          'failed to get balance of account ' + publicKey.toBase58() + ': ' + e,\n        );\n      });\n  }\n\n  /**\n   * Fetch the estimated production time of a block\n   */\n  async getBlockTime(slot: number): Promise<number | null> {\n    const unsafeRes = await this._rpcRequest('getBlockTime', [slot]);\n    const res = create(unsafeRes, jsonRpcResult(nullable(number())));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get block time for slot ${slot}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the lowest slot that the node has information about in its ledger.\n   * This value may increase over time if the node is configured to purge older ledger data\n   */\n  async getMinimumLedgerSlot(): Promise<number> {\n    const unsafeRes = await this._rpcRequest('minimumLedgerSlot', []);\n    const res = create(unsafeRes, jsonRpcResult(number()));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get minimum ledger slot',\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the slot of the lowest confirmed block that has not been purged from the ledger\n   */\n  async getFirstAvailableBlock(): Promise<number> {\n    const unsafeRes = await this._rpcRequest('getFirstAvailableBlock', []);\n    const res = create(unsafeRes, SlotRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get first available block',\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch information about the current supply\n   */\n  async getSupply(\n    config?: GetSupplyConfig | Commitment,\n  ): Promise<RpcResponseAndContext<Supply>> {\n    let configArg: GetSupplyConfig = {};\n    if (typeof config === 'string') {\n      configArg = {commitment: config};\n    } else if (config) {\n      configArg = {\n        ...config,\n        commitment: (config && config.commitment) || this.commitment,\n      };\n    } else {\n      configArg = {\n        commitment: this.commitment,\n      };\n    }\n\n    const unsafeRes = await this._rpcRequest('getSupply', [configArg]);\n    const res = create(unsafeRes, GetSupplyRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get supply');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the current supply of a token mint\n   */\n  async getTokenSupply(\n    tokenMintAddress: PublicKey,\n    commitment?: Commitment,\n  ): Promise<RpcResponseAndContext<TokenAmount>> {\n    const args = this._buildArgs([tokenMintAddress.toBase58()], commitment);\n    const unsafeRes = await this._rpcRequest('getTokenSupply', args);\n    const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get token supply');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the current balance of a token account\n   */\n  async getTokenAccountBalance(\n    tokenAddress: PublicKey,\n    commitment?: Commitment,\n  ): Promise<RpcResponseAndContext<TokenAmount>> {\n    const args = this._buildArgs([tokenAddress.toBase58()], commitment);\n    const unsafeRes = await this._rpcRequest('getTokenAccountBalance', args);\n    const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get token account balance',\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch all the token accounts owned by the specified account\n   *\n   * @return {Promise<RpcResponseAndContext<GetProgramAccountsResponse>}\n   */\n  async getTokenAccountsByOwner(\n    ownerAddress: PublicKey,\n    filter: TokenAccountsFilter,\n    commitmentOrConfig?: Commitment | GetTokenAccountsByOwnerConfig,\n  ): Promise<RpcResponseAndContext<GetProgramAccountsResponse>> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    let _args: any[] = [ownerAddress.toBase58()];\n    if ('mint' in filter) {\n      _args.push({mint: filter.mint.toBase58()});\n    } else {\n      _args.push({programId: filter.programId.toBase58()});\n    }\n\n    const args = this._buildArgs(_args, commitment, 'base64', config);\n    const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n    const res = create(unsafeRes, GetTokenAccountsByOwner);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get token accounts owned by account ${ownerAddress.toBase58()}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch parsed token accounts owned by the specified account\n   *\n   * @return {Promise<RpcResponseAndContext<Array<{pubkey: PublicKey, account: AccountInfo<ParsedAccountData>}>>>}\n   */\n  async getParsedTokenAccountsByOwner(\n    ownerAddress: PublicKey,\n    filter: TokenAccountsFilter,\n    commitment?: Commitment,\n  ): Promise<\n    RpcResponseAndContext<\n      Array<{pubkey: PublicKey; account: AccountInfo<ParsedAccountData>}>\n    >\n  > {\n    let _args: any[] = [ownerAddress.toBase58()];\n    if ('mint' in filter) {\n      _args.push({mint: filter.mint.toBase58()});\n    } else {\n      _args.push({programId: filter.programId.toBase58()});\n    }\n\n    const args = this._buildArgs(_args, commitment, 'jsonParsed');\n    const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n    const res = create(unsafeRes, GetParsedTokenAccountsByOwner);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get token accounts owned by account ${ownerAddress.toBase58()}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the 20 largest accounts with their current balances\n   */\n  async getLargestAccounts(\n    config?: GetLargestAccountsConfig,\n  ): Promise<RpcResponseAndContext<Array<AccountBalancePair>>> {\n    const arg = {\n      ...config,\n      commitment: (config && config.commitment) || this.commitment,\n    };\n    const args = arg.filter || arg.commitment ? [arg] : [];\n    const unsafeRes = await this._rpcRequest('getLargestAccounts', args);\n    const res = create(unsafeRes, GetLargestAccountsRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get largest accounts');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the 20 largest token accounts with their current balances\n   * for a given mint.\n   */\n  async getTokenLargestAccounts(\n    mintAddress: PublicKey,\n    commitment?: Commitment,\n  ): Promise<RpcResponseAndContext<Array<TokenAccountBalancePair>>> {\n    const args = this._buildArgs([mintAddress.toBase58()], commitment);\n    const unsafeRes = await this._rpcRequest('getTokenLargestAccounts', args);\n    const res = create(unsafeRes, GetTokenLargestAccountsResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get token largest accounts',\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch all the account info for the specified public key, return with context\n   */\n  async getAccountInfoAndContext(\n    publicKey: PublicKey,\n    commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n  ): Promise<RpcResponseAndContext<AccountInfo<Buffer> | null>> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [publicKey.toBase58()],\n      commitment,\n      'base64',\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n    const res = create(\n      unsafeRes,\n      jsonRpcResultAndContext(nullable(AccountInfoResult)),\n    );\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get info about account ${publicKey.toBase58()}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch parsed account info for the specified public key\n   */\n  async getParsedAccountInfo(\n    publicKey: PublicKey,\n    commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n  ): Promise<\n    RpcResponseAndContext<AccountInfo<Buffer | ParsedAccountData> | null>\n  > {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [publicKey.toBase58()],\n      commitment,\n      'jsonParsed',\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n    const res = create(\n      unsafeRes,\n      jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)),\n    );\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get info about account ${publicKey.toBase58()}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch all the account info for the specified public key\n   */\n  async getAccountInfo(\n    publicKey: PublicKey,\n    commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n  ): Promise<AccountInfo<Buffer> | null> {\n    try {\n      const res = await this.getAccountInfoAndContext(\n        publicKey,\n        commitmentOrConfig,\n      );\n      return res.value;\n    } catch (e) {\n      throw new Error(\n        'failed to get info about account ' + publicKey.toBase58() + ': ' + e,\n      );\n    }\n  }\n\n  /**\n   * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n   */\n  async getMultipleParsedAccounts(\n    publicKeys: PublicKey[],\n    rawConfig?: GetMultipleAccountsConfig,\n  ): Promise<\n    RpcResponseAndContext<(AccountInfo<Buffer | ParsedAccountData> | null)[]>\n  > {\n    const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n    const keys = publicKeys.map(key => key.toBase58());\n    const args = this._buildArgs([keys], commitment, 'jsonParsed', config);\n    const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n    const res = create(\n      unsafeRes,\n      jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult))),\n    );\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get info for accounts ${keys}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n   */\n  async getMultipleAccountsInfoAndContext(\n    publicKeys: PublicKey[],\n    commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n  ): Promise<RpcResponseAndContext<(AccountInfo<Buffer> | null)[]>> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const keys = publicKeys.map(key => key.toBase58());\n    const args = this._buildArgs([keys], commitment, 'base64', config);\n    const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n    const res = create(\n      unsafeRes,\n      jsonRpcResultAndContext(array(nullable(AccountInfoResult))),\n    );\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get info for accounts ${keys}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch all the account info for multiple accounts specified by an array of public keys\n   */\n  async getMultipleAccountsInfo(\n    publicKeys: PublicKey[],\n    commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n  ): Promise<(AccountInfo<Buffer> | null)[]> {\n    const res = await this.getMultipleAccountsInfoAndContext(\n      publicKeys,\n      commitmentOrConfig,\n    );\n    return res.value;\n  }\n\n  /**\n   * Returns epoch activation information for a stake account that has been delegated\n   */\n  async getStakeActivation(\n    publicKey: PublicKey,\n    commitmentOrConfig?: Commitment | GetStakeActivationConfig,\n    epoch?: number,\n  ): Promise<StakeActivationData> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [publicKey.toBase58()],\n      commitment,\n      undefined /* encoding */,\n      {\n        ...config,\n        epoch: epoch != null ? epoch : config?.epoch,\n      },\n    );\n\n    const unsafeRes = await this._rpcRequest('getStakeActivation', args);\n    const res = create(unsafeRes, jsonRpcResult(StakeActivationResult));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get Stake Activation ${publicKey.toBase58()}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch all the accounts owned by the specified program id\n   *\n   * @return {Promise<Array<{pubkey: PublicKey, account: AccountInfo<Buffer>}>>}\n   */\n  async getProgramAccounts(\n    programId: PublicKey,\n    configOrCommitment: GetProgramAccountsConfig &\n      Readonly<{withContext: true}>,\n  ): Promise<RpcResponseAndContext<GetProgramAccountsResponse>>;\n  // eslint-disable-next-line no-dupe-class-members\n  async getProgramAccounts(\n    programId: PublicKey,\n    configOrCommitment?: GetProgramAccountsConfig | Commitment,\n  ): Promise<GetProgramAccountsResponse>;\n  // eslint-disable-next-line no-dupe-class-members\n  async getProgramAccounts(\n    programId: PublicKey,\n    configOrCommitment?: GetProgramAccountsConfig | Commitment,\n  ): Promise<\n    | GetProgramAccountsResponse\n    | RpcResponseAndContext<GetProgramAccountsResponse>\n  > {\n    const {commitment, config} =\n      extractCommitmentFromConfig(configOrCommitment);\n    const {encoding, ...configWithoutEncoding} = config || {};\n    const args = this._buildArgs(\n      [programId.toBase58()],\n      commitment,\n      encoding || 'base64',\n      configWithoutEncoding,\n    );\n    const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n    const baseSchema = array(KeyedAccountInfoResult);\n    const res =\n      configWithoutEncoding.withContext === true\n        ? create(unsafeRes, jsonRpcResultAndContext(baseSchema))\n        : create(unsafeRes, jsonRpcResult(baseSchema));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get accounts owned by program ${programId.toBase58()}`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch and parse all the accounts owned by the specified program id\n   *\n   * @return {Promise<Array<{pubkey: PublicKey, account: AccountInfo<Buffer | ParsedAccountData>}>>}\n   */\n  async getParsedProgramAccounts(\n    programId: PublicKey,\n    configOrCommitment?: GetParsedProgramAccountsConfig | Commitment,\n  ): Promise<\n    Array<{\n      pubkey: PublicKey;\n      account: AccountInfo<Buffer | ParsedAccountData>;\n    }>\n  > {\n    const {commitment, config} =\n      extractCommitmentFromConfig(configOrCommitment);\n    const args = this._buildArgs(\n      [programId.toBase58()],\n      commitment,\n      'jsonParsed',\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n    const res = create(\n      unsafeRes,\n      jsonRpcResult(array(KeyedParsedAccountInfoResult)),\n    );\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get accounts owned by program ${programId.toBase58()}`,\n      );\n    }\n    return res.result;\n  }\n\n  confirmTransaction(\n    strategy: TransactionConfirmationStrategy,\n    commitment?: Commitment,\n  ): Promise<RpcResponseAndContext<SignatureResult>>;\n\n  /** @deprecated Instead, call `confirmTransaction` and pass in {@link TransactionConfirmationStrategy} */\n  // eslint-disable-next-line no-dupe-class-members\n  confirmTransaction(\n    strategy: TransactionSignature,\n    commitment?: Commitment,\n  ): Promise<RpcResponseAndContext<SignatureResult>>;\n\n  // eslint-disable-next-line no-dupe-class-members\n  async confirmTransaction(\n    strategy: TransactionConfirmationStrategy | TransactionSignature,\n    commitment?: Commitment,\n  ): Promise<RpcResponseAndContext<SignatureResult>> {\n    let rawSignature: string;\n\n    if (typeof strategy == 'string') {\n      rawSignature = strategy;\n    } else {\n      const config = strategy as TransactionConfirmationStrategy;\n\n      if (config.abortSignal?.aborted) {\n        return Promise.reject(config.abortSignal.reason);\n      }\n      rawSignature = config.signature;\n    }\n\n    let decodedSignature;\n\n    try {\n      decodedSignature = bs58.decode(rawSignature);\n    } catch (err) {\n      throw new Error('signature must be base58 encoded: ' + rawSignature);\n    }\n\n    assert(decodedSignature.length === 64, 'signature has invalid length');\n\n    if (typeof strategy === 'string') {\n      return await this.confirmTransactionUsingLegacyTimeoutStrategy({\n        commitment: commitment || this.commitment,\n        signature: rawSignature,\n      });\n    } else if ('lastValidBlockHeight' in strategy) {\n      return await this.confirmTransactionUsingBlockHeightExceedanceStrategy({\n        commitment: commitment || this.commitment,\n        strategy,\n      });\n    } else {\n      return await this.confirmTransactionUsingDurableNonceStrategy({\n        commitment: commitment || this.commitment,\n        strategy,\n      });\n    }\n  }\n\n  private getCancellationPromise(signal?: AbortSignal): Promise<never> {\n    return new Promise<never>((_, reject) => {\n      if (signal == null) {\n        return;\n      }\n      if (signal.aborted) {\n        reject(signal.reason);\n      } else {\n        signal.addEventListener('abort', () => {\n          reject(signal.reason);\n        });\n      }\n    });\n  }\n\n  private getTransactionConfirmationPromise({\n    commitment,\n    signature,\n  }: {\n    commitment?: Commitment;\n    signature: string;\n  }): {\n    abortConfirmation(): void;\n    confirmationPromise: Promise<{\n      __type: TransactionStatus.PROCESSED;\n      response: RpcResponseAndContext<SignatureResult>;\n    }>;\n  } {\n    let signatureSubscriptionId: number | undefined;\n    let disposeSignatureSubscriptionStateChangeObserver:\n      | SubscriptionStateChangeDisposeFn\n      | undefined;\n    let done = false;\n    const confirmationPromise = new Promise<{\n      __type: TransactionStatus.PROCESSED;\n      response: RpcResponseAndContext<SignatureResult>;\n    }>((resolve, reject) => {\n      try {\n        signatureSubscriptionId = this.onSignature(\n          signature,\n          (result: SignatureResult, context: Context) => {\n            signatureSubscriptionId = undefined;\n            const response = {\n              context,\n              value: result,\n            };\n            resolve({__type: TransactionStatus.PROCESSED, response});\n          },\n          commitment,\n        );\n        const subscriptionSetupPromise = new Promise<void>(\n          resolveSubscriptionSetup => {\n            if (signatureSubscriptionId == null) {\n              resolveSubscriptionSetup();\n            } else {\n              disposeSignatureSubscriptionStateChangeObserver =\n                this._onSubscriptionStateChange(\n                  signatureSubscriptionId,\n                  nextState => {\n                    if (nextState === 'subscribed') {\n                      resolveSubscriptionSetup();\n                    }\n                  },\n                );\n            }\n          },\n        );\n        (async () => {\n          await subscriptionSetupPromise;\n          if (done) return;\n          const response = await this.getSignatureStatus(signature);\n          if (done) return;\n          if (response == null) {\n            return;\n          }\n          const {context, value} = response;\n          if (value == null) {\n            return;\n          }\n          if (value?.err) {\n            reject(value.err);\n          } else {\n            switch (commitment) {\n              case 'confirmed':\n              case 'single':\n              case 'singleGossip': {\n                if (value.confirmationStatus === 'processed') {\n                  return;\n                }\n                break;\n              }\n              case 'finalized':\n              case 'max':\n              case 'root': {\n                if (\n                  value.confirmationStatus === 'processed' ||\n                  value.confirmationStatus === 'confirmed'\n                ) {\n                  return;\n                }\n                break;\n              }\n              // exhaust enums to ensure full coverage\n              case 'processed':\n              case 'recent':\n            }\n            done = true;\n            resolve({\n              __type: TransactionStatus.PROCESSED,\n              response: {\n                context,\n                value,\n              },\n            });\n          }\n        })();\n      } catch (err) {\n        reject(err);\n      }\n    });\n    const abortConfirmation = () => {\n      if (disposeSignatureSubscriptionStateChangeObserver) {\n        disposeSignatureSubscriptionStateChangeObserver();\n        disposeSignatureSubscriptionStateChangeObserver = undefined;\n      }\n      if (signatureSubscriptionId != null) {\n        this.removeSignatureListener(signatureSubscriptionId);\n        signatureSubscriptionId = undefined;\n      }\n    };\n    return {abortConfirmation, confirmationPromise};\n  }\n\n  private async confirmTransactionUsingBlockHeightExceedanceStrategy({\n    commitment,\n    strategy: {abortSignal, lastValidBlockHeight, signature},\n  }: {\n    commitment?: Commitment;\n    strategy: BlockheightBasedTransactionConfirmationStrategy;\n  }) {\n    let done: boolean = false;\n    const expiryPromise = new Promise<{\n      __type: TransactionStatus.BLOCKHEIGHT_EXCEEDED;\n    }>(resolve => {\n      const checkBlockHeight = async () => {\n        try {\n          const blockHeight = await this.getBlockHeight(commitment);\n          return blockHeight;\n        } catch (_e) {\n          return -1;\n        }\n      };\n      (async () => {\n        let currentBlockHeight = await checkBlockHeight();\n        if (done) return;\n        while (currentBlockHeight <= lastValidBlockHeight) {\n          await sleep(1000);\n          if (done) return;\n          currentBlockHeight = await checkBlockHeight();\n          if (done) return;\n        }\n        resolve({__type: TransactionStatus.BLOCKHEIGHT_EXCEEDED});\n      })();\n    });\n    const {abortConfirmation, confirmationPromise} =\n      this.getTransactionConfirmationPromise({commitment, signature});\n    const cancellationPromise = this.getCancellationPromise(abortSignal);\n    let result: RpcResponseAndContext<SignatureResult>;\n    try {\n      const outcome = await Promise.race([\n        cancellationPromise,\n        confirmationPromise,\n        expiryPromise,\n      ]);\n      if (outcome.__type === TransactionStatus.PROCESSED) {\n        result = outcome.response;\n      } else {\n        throw new TransactionExpiredBlockheightExceededError(signature);\n      }\n    } finally {\n      done = true;\n      abortConfirmation();\n    }\n    return result;\n  }\n\n  private async confirmTransactionUsingDurableNonceStrategy({\n    commitment,\n    strategy: {\n      abortSignal,\n      minContextSlot,\n      nonceAccountPubkey,\n      nonceValue,\n      signature,\n    },\n  }: {\n    commitment?: Commitment;\n    strategy: DurableNonceTransactionConfirmationStrategy;\n  }) {\n    let done: boolean = false;\n    const expiryPromise = new Promise<{\n      __type: TransactionStatus.NONCE_INVALID;\n      slotInWhichNonceDidAdvance: number | null;\n    }>(resolve => {\n      let currentNonceValue: string | undefined = nonceValue;\n      let lastCheckedSlot: number | null = null;\n      const getCurrentNonceValue = async () => {\n        try {\n          const {context, value: nonceAccount} = await this.getNonceAndContext(\n            nonceAccountPubkey,\n            {\n              commitment,\n              minContextSlot,\n            },\n          );\n          lastCheckedSlot = context.slot;\n          return nonceAccount?.nonce;\n        } catch (e) {\n          // If for whatever reason we can't reach/read the nonce\n          // account, just keep using the last-known value.\n          return currentNonceValue;\n        }\n      };\n      (async () => {\n        currentNonceValue = await getCurrentNonceValue();\n        if (done) return;\n        while (\n          true // eslint-disable-line no-constant-condition\n        ) {\n          if (nonceValue !== currentNonceValue) {\n            resolve({\n              __type: TransactionStatus.NONCE_INVALID,\n              slotInWhichNonceDidAdvance: lastCheckedSlot,\n            });\n            return;\n          }\n          await sleep(2000);\n          if (done) return;\n          currentNonceValue = await getCurrentNonceValue();\n          if (done) return;\n        }\n      })();\n    });\n    const {abortConfirmation, confirmationPromise} =\n      this.getTransactionConfirmationPromise({commitment, signature});\n    const cancellationPromise = this.getCancellationPromise(abortSignal);\n    let result: RpcResponseAndContext<SignatureResult>;\n    try {\n      const outcome = await Promise.race([\n        cancellationPromise,\n        confirmationPromise,\n        expiryPromise,\n      ]);\n      if (outcome.__type === TransactionStatus.PROCESSED) {\n        result = outcome.response;\n      } else {\n        // Double check that the transaction is indeed unconfirmed.\n        let signatureStatus:\n          | RpcResponseAndContext<SignatureStatus | null>\n          | null\n          | undefined;\n        while (\n          true // eslint-disable-line no-constant-condition\n        ) {\n          const status = await this.getSignatureStatus(signature);\n          if (status == null) {\n            break;\n          }\n          if (\n            status.context.slot <\n            (outcome.slotInWhichNonceDidAdvance ?? minContextSlot)\n          ) {\n            await sleep(400);\n            continue;\n          }\n          signatureStatus = status;\n          break;\n        }\n        if (signatureStatus?.value) {\n          const commitmentForStatus = commitment || 'finalized';\n          const {confirmationStatus} = signatureStatus.value;\n          switch (commitmentForStatus) {\n            case 'processed':\n            case 'recent':\n              if (\n                confirmationStatus !== 'processed' &&\n                confirmationStatus !== 'confirmed' &&\n                confirmationStatus !== 'finalized'\n              ) {\n                throw new TransactionExpiredNonceInvalidError(signature);\n              }\n              break;\n            case 'confirmed':\n            case 'single':\n            case 'singleGossip':\n              if (\n                confirmationStatus !== 'confirmed' &&\n                confirmationStatus !== 'finalized'\n              ) {\n                throw new TransactionExpiredNonceInvalidError(signature);\n              }\n              break;\n            case 'finalized':\n            case 'max':\n            case 'root':\n              if (confirmationStatus !== 'finalized') {\n                throw new TransactionExpiredNonceInvalidError(signature);\n              }\n              break;\n            default:\n              // Exhaustive switch.\n              // eslint-disable-next-line @typescript-eslint/no-unused-vars\n              ((_: never) => {})(commitmentForStatus);\n          }\n          result = {\n            context: signatureStatus.context,\n            value: {err: signatureStatus.value.err},\n          };\n        } else {\n          throw new TransactionExpiredNonceInvalidError(signature);\n        }\n      }\n    } finally {\n      done = true;\n      abortConfirmation();\n    }\n    return result;\n  }\n\n  private async confirmTransactionUsingLegacyTimeoutStrategy({\n    commitment,\n    signature,\n  }: {\n    commitment?: Commitment;\n    signature: string;\n  }) {\n    let timeoutId;\n    const expiryPromise = new Promise<{\n      __type: TransactionStatus.TIMED_OUT;\n      timeoutMs: number;\n    }>(resolve => {\n      let timeoutMs = this._confirmTransactionInitialTimeout || 60 * 1000;\n      switch (commitment) {\n        case 'processed':\n        case 'recent':\n        case 'single':\n        case 'confirmed':\n        case 'singleGossip': {\n          timeoutMs = this._confirmTransactionInitialTimeout || 30 * 1000;\n          break;\n        }\n        // exhaust enums to ensure full coverage\n        case 'finalized':\n        case 'max':\n        case 'root':\n      }\n      timeoutId = setTimeout(\n        () => resolve({__type: TransactionStatus.TIMED_OUT, timeoutMs}),\n        timeoutMs,\n      );\n    });\n    const {abortConfirmation, confirmationPromise} =\n      this.getTransactionConfirmationPromise({\n        commitment,\n        signature,\n      });\n    let result: RpcResponseAndContext<SignatureResult>;\n    try {\n      const outcome = await Promise.race([confirmationPromise, expiryPromise]);\n      if (outcome.__type === TransactionStatus.PROCESSED) {\n        result = outcome.response;\n      } else {\n        throw new TransactionExpiredTimeoutError(\n          signature,\n          outcome.timeoutMs / 1000,\n        );\n      }\n    } finally {\n      clearTimeout(timeoutId);\n      abortConfirmation();\n    }\n    return result;\n  }\n\n  /**\n   * Return the list of nodes that are currently participating in the cluster\n   */\n  async getClusterNodes(): Promise<Array<ContactInfo>> {\n    const unsafeRes = await this._rpcRequest('getClusterNodes', []);\n    const res = create(unsafeRes, jsonRpcResult(array(ContactInfoResult)));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get cluster nodes');\n    }\n    return res.result;\n  }\n\n  /**\n   * Return the list of nodes that are currently participating in the cluster\n   */\n  async getVoteAccounts(commitment?: Commitment): Promise<VoteAccountStatus> {\n    const args = this._buildArgs([], commitment);\n    const unsafeRes = await this._rpcRequest('getVoteAccounts', args);\n    const res = create(unsafeRes, GetVoteAccounts);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get vote accounts');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the current slot that the node is processing\n   */\n  async getSlot(\n    commitmentOrConfig?: Commitment | GetSlotConfig,\n  ): Promise<number> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [],\n      commitment,\n      undefined /* encoding */,\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getSlot', args);\n    const res = create(unsafeRes, jsonRpcResult(number()));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get slot');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the current slot leader of the cluster\n   */\n  async getSlotLeader(\n    commitmentOrConfig?: Commitment | GetSlotLeaderConfig,\n  ): Promise<string> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [],\n      commitment,\n      undefined /* encoding */,\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getSlotLeader', args);\n    const res = create(unsafeRes, jsonRpcResult(string()));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get slot leader');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch `limit` number of slot leaders starting from `startSlot`\n   *\n   * @param startSlot fetch slot leaders starting from this slot\n   * @param limit number of slot leaders to return\n   */\n  async getSlotLeaders(\n    startSlot: number,\n    limit: number,\n  ): Promise<Array<PublicKey>> {\n    const args = [startSlot, limit];\n    const unsafeRes = await this._rpcRequest('getSlotLeaders', args);\n    const res = create(unsafeRes, jsonRpcResult(array(PublicKeyFromString)));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get slot leaders');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the current status of a signature\n   */\n  async getSignatureStatus(\n    signature: TransactionSignature,\n    config?: SignatureStatusConfig,\n  ): Promise<RpcResponseAndContext<SignatureStatus | null>> {\n    const {context, value: values} = await this.getSignatureStatuses(\n      [signature],\n      config,\n    );\n    assert(values.length === 1);\n    const value = values[0];\n    return {context, value};\n  }\n\n  /**\n   * Fetch the current statuses of a batch of signatures\n   */\n  async getSignatureStatuses(\n    signatures: Array<TransactionSignature>,\n    config?: SignatureStatusConfig,\n  ): Promise<RpcResponseAndContext<Array<SignatureStatus | null>>> {\n    const params: any[] = [signatures];\n    if (config) {\n      params.push(config);\n    }\n    const unsafeRes = await this._rpcRequest('getSignatureStatuses', params);\n    const res = create(unsafeRes, GetSignatureStatusesRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get signature status');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the current transaction count of the cluster\n   */\n  async getTransactionCount(\n    commitmentOrConfig?: Commitment | GetTransactionCountConfig,\n  ): Promise<number> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [],\n      commitment,\n      undefined /* encoding */,\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getTransactionCount', args);\n    const res = create(unsafeRes, jsonRpcResult(number()));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get transaction count',\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the current total currency supply of the cluster in lamports\n   *\n   * @deprecated Deprecated since v1.2.8. Please use {@link getSupply} instead.\n   */\n  async getTotalSupply(commitment?: Commitment): Promise<number> {\n    const result = await this.getSupply({\n      commitment,\n      excludeNonCirculatingAccountsList: true,\n    });\n    return result.value.total;\n  }\n\n  /**\n   * Fetch the cluster InflationGovernor parameters\n   */\n  async getInflationGovernor(\n    commitment?: Commitment,\n  ): Promise<InflationGovernor> {\n    const args = this._buildArgs([], commitment);\n    const unsafeRes = await this._rpcRequest('getInflationGovernor', args);\n    const res = create(unsafeRes, GetInflationGovernorRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get inflation');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the inflation reward for a list of addresses for an epoch\n   */\n  async getInflationReward(\n    addresses: PublicKey[],\n    epoch?: number,\n    commitmentOrConfig?: Commitment | GetInflationRewardConfig,\n  ): Promise<(InflationReward | null)[]> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [addresses.map(pubkey => pubkey.toBase58())],\n      commitment,\n      undefined /* encoding */,\n      {\n        ...config,\n        epoch: epoch != null ? epoch : config?.epoch,\n      },\n    );\n    const unsafeRes = await this._rpcRequest('getInflationReward', args);\n    const res = create(unsafeRes, GetInflationRewardResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get inflation reward');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the specific inflation values for the current epoch\n   */\n  async getInflationRate(): Promise<InflationRate> {\n    const unsafeRes = await this._rpcRequest('getInflationRate', []);\n    const res = create(unsafeRes, GetInflationRateRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get inflation rate');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the Epoch Info parameters\n   */\n  async getEpochInfo(\n    commitmentOrConfig?: Commitment | GetEpochInfoConfig,\n  ): Promise<EpochInfo> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [],\n      commitment,\n      undefined /* encoding */,\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getEpochInfo', args);\n    const res = create(unsafeRes, GetEpochInfoRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get epoch info');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the Epoch Schedule parameters\n   */\n  async getEpochSchedule(): Promise<EpochSchedule> {\n    const unsafeRes = await this._rpcRequest('getEpochSchedule', []);\n    const res = create(unsafeRes, GetEpochScheduleRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get epoch schedule');\n    }\n    const epochSchedule = res.result;\n    return new EpochSchedule(\n      epochSchedule.slotsPerEpoch,\n      epochSchedule.leaderScheduleSlotOffset,\n      epochSchedule.warmup,\n      epochSchedule.firstNormalEpoch,\n      epochSchedule.firstNormalSlot,\n    );\n  }\n\n  /**\n   * Fetch the leader schedule for the current epoch\n   * @return {Promise<RpcResponseAndContext<LeaderSchedule>>}\n   */\n  async getLeaderSchedule(): Promise<LeaderSchedule> {\n    const unsafeRes = await this._rpcRequest('getLeaderSchedule', []);\n    const res = create(unsafeRes, GetLeaderScheduleRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get leader schedule');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the minimum balance needed to exempt an account of `dataLength`\n   * size from rent\n   */\n  async getMinimumBalanceForRentExemption(\n    dataLength: number,\n    commitment?: Commitment,\n  ): Promise<number> {\n    const args = this._buildArgs([dataLength], commitment);\n    const unsafeRes = await this._rpcRequest(\n      'getMinimumBalanceForRentExemption',\n      args,\n    );\n    const res = create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult);\n    if ('error' in res) {\n      console.warn('Unable to fetch minimum balance for rent exemption');\n      return 0;\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch a recent blockhash from the cluster, return with context\n   * @return {Promise<RpcResponseAndContext<{blockhash: Blockhash, feeCalculator: FeeCalculator}>>}\n   *\n   * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead.\n   */\n  async getRecentBlockhashAndContext(commitment?: Commitment): Promise<\n    RpcResponseAndContext<{\n      blockhash: Blockhash;\n      feeCalculator: FeeCalculator;\n    }>\n  > {\n    const args = this._buildArgs([], commitment);\n    const unsafeRes = await this._rpcRequest('getRecentBlockhash', args);\n    const res = create(unsafeRes, GetRecentBlockhashAndContextRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get recent blockhash');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch recent performance samples\n   * @return {Promise<Array<PerfSample>>}\n   */\n  async getRecentPerformanceSamples(\n    limit?: number,\n  ): Promise<Array<PerfSample>> {\n    const unsafeRes = await this._rpcRequest(\n      'getRecentPerformanceSamples',\n      limit ? [limit] : [],\n    );\n    const res = create(unsafeRes, GetRecentPerformanceSamplesRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get recent performance samples',\n      );\n    }\n\n    return res.result;\n  }\n\n  /**\n   * Fetch the fee calculator for a recent blockhash from the cluster, return with context\n   *\n   * @deprecated Deprecated since Solana v1.8.0. Please use {@link getFeeForMessage} instead.\n   */\n  async getFeeCalculatorForBlockhash(\n    blockhash: Blockhash,\n    commitment?: Commitment,\n  ): Promise<RpcResponseAndContext<FeeCalculator | null>> {\n    const args = this._buildArgs([blockhash], commitment);\n    const unsafeRes = await this._rpcRequest(\n      'getFeeCalculatorForBlockhash',\n      args,\n    );\n\n    const res = create(unsafeRes, GetFeeCalculatorRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get fee calculator');\n    }\n    const {context, value} = res.result;\n    return {\n      context,\n      value: value !== null ? value.feeCalculator : null,\n    };\n  }\n\n  /**\n   * Fetch the fee for a message from the cluster, return with context\n   */\n  async getFeeForMessage(\n    message: VersionedMessage,\n    commitment?: Commitment,\n  ): Promise<RpcResponseAndContext<number | null>> {\n    const wireMessage = toBuffer(message.serialize()).toString('base64');\n    const args = this._buildArgs([wireMessage], commitment);\n    const unsafeRes = await this._rpcRequest('getFeeForMessage', args);\n\n    const res = create(unsafeRes, jsonRpcResultAndContext(nullable(number())));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get fee for message');\n    }\n    if (res.result === null) {\n      throw new Error('invalid blockhash');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch a list of prioritization fees from recent blocks.\n   */\n  async getRecentPrioritizationFees(\n    config?: GetRecentPrioritizationFeesConfig,\n  ): Promise<RecentPrioritizationFees[]> {\n    const accounts = config?.lockedWritableAccounts?.map(key => key.toBase58());\n    const args = accounts?.length ? [accounts] : [];\n    const unsafeRes = await this._rpcRequest(\n      'getRecentPrioritizationFees',\n      args,\n    );\n    const res = create(unsafeRes, GetRecentPrioritizationFeesRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get recent prioritization fees',\n      );\n    }\n    return res.result;\n  }\n  /**\n   * Fetch a recent blockhash from the cluster\n   * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>}\n   *\n   * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead.\n   */\n  async getRecentBlockhash(\n    commitment?: Commitment,\n  ): Promise<{blockhash: Blockhash; feeCalculator: FeeCalculator}> {\n    try {\n      const res = await this.getRecentBlockhashAndContext(commitment);\n      return res.value;\n    } catch (e) {\n      throw new Error('failed to get recent blockhash: ' + e);\n    }\n  }\n\n  /**\n   * Fetch the latest blockhash from the cluster\n   * @return {Promise<BlockhashWithExpiryBlockHeight>}\n   */\n  async getLatestBlockhash(\n    commitmentOrConfig?: Commitment | GetLatestBlockhashConfig,\n  ): Promise<BlockhashWithExpiryBlockHeight> {\n    try {\n      const res = await this.getLatestBlockhashAndContext(commitmentOrConfig);\n      return res.value;\n    } catch (e) {\n      throw new Error('failed to get recent blockhash: ' + e);\n    }\n  }\n\n  /**\n   * Fetch the latest blockhash from the cluster\n   * @return {Promise<BlockhashWithExpiryBlockHeight>}\n   */\n  async getLatestBlockhashAndContext(\n    commitmentOrConfig?: Commitment | GetLatestBlockhashConfig,\n  ): Promise<RpcResponseAndContext<BlockhashWithExpiryBlockHeight>> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgs(\n      [],\n      commitment,\n      undefined /* encoding */,\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getLatestBlockhash', args);\n    const res = create(unsafeRes, GetLatestBlockhashRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get latest blockhash');\n    }\n    return res.result;\n  }\n\n  /**\n   * Returns whether a blockhash is still valid or not\n   */\n  async isBlockhashValid(\n    blockhash: Blockhash,\n    rawConfig?: IsBlockhashValidConfig,\n  ): Promise<RpcResponseAndContext<boolean>> {\n    const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n    const args = this._buildArgs(\n      [blockhash],\n      commitment,\n      undefined /* encoding */,\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('isBlockhashValid', args);\n    const res = create(unsafeRes, IsBlockhashValidRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to determine if the blockhash `' + blockhash + '`is valid',\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the node version\n   */\n  async getVersion(): Promise<Version> {\n    const unsafeRes = await this._rpcRequest('getVersion', []);\n    const res = create(unsafeRes, jsonRpcResult(VersionResult));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get version');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch the genesis hash\n   */\n  async getGenesisHash(): Promise<string> {\n    const unsafeRes = await this._rpcRequest('getGenesisHash', []);\n    const res = create(unsafeRes, jsonRpcResult(string()));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get genesis hash');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch a processed block from the cluster.\n   *\n   * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n   * setting the `maxSupportedTransactionVersion` property.\n   */\n  async getBlock(\n    slot: number,\n    rawConfig?: GetBlockConfig,\n  ): Promise<BlockResponse | null>;\n\n  /**\n   * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n   * setting the `maxSupportedTransactionVersion` property.\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async getBlock(\n    slot: number,\n    rawConfig: GetBlockConfig & {transactionDetails: 'accounts'},\n  ): Promise<AccountsModeBlockResponse | null>;\n\n  /**\n   * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n   * setting the `maxSupportedTransactionVersion` property.\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async getBlock(\n    slot: number,\n    rawConfig: GetBlockConfig & {transactionDetails: 'none'},\n  ): Promise<NoneModeBlockResponse | null>;\n\n  /**\n   * Fetch a processed block from the cluster.\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async getBlock(\n    slot: number,\n    rawConfig?: GetVersionedBlockConfig,\n  ): Promise<VersionedBlockResponse | null>;\n\n  // eslint-disable-next-line no-dupe-class-members\n  async getBlock(\n    slot: number,\n    rawConfig: GetVersionedBlockConfig & {transactionDetails: 'accounts'},\n  ): Promise<VersionedAccountsModeBlockResponse | null>;\n\n  // eslint-disable-next-line no-dupe-class-members\n  async getBlock(\n    slot: number,\n    rawConfig: GetVersionedBlockConfig & {transactionDetails: 'none'},\n  ): Promise<VersionedNoneModeBlockResponse | null>;\n\n  /**\n   * Fetch a processed block from the cluster.\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async getBlock(\n    slot: number,\n    rawConfig?: GetVersionedBlockConfig,\n  ): Promise<\n    | VersionedBlockResponse\n    | VersionedAccountsModeBlockResponse\n    | VersionedNoneModeBlockResponse\n    | null\n  > {\n    const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n    const args = this._buildArgsAtLeastConfirmed(\n      [slot],\n      commitment as Finality,\n      undefined /* encoding */,\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getBlock', args);\n    try {\n      switch (config?.transactionDetails) {\n        case 'accounts': {\n          const res = create(unsafeRes, GetAccountsModeBlockRpcResult);\n          if ('error' in res) {\n            throw res.error;\n          }\n          return res.result;\n        }\n        case 'none': {\n          const res = create(unsafeRes, GetNoneModeBlockRpcResult);\n          if ('error' in res) {\n            throw res.error;\n          }\n          return res.result;\n        }\n        default: {\n          const res = create(unsafeRes, GetBlockRpcResult);\n          if ('error' in res) {\n            throw res.error;\n          }\n          const {result} = res;\n          return result\n            ? {\n                ...result,\n                transactions: result.transactions.map(\n                  ({transaction, meta, version}) => ({\n                    meta,\n                    transaction: {\n                      ...transaction,\n                      message: versionedMessageFromResponse(\n                        version,\n                        transaction.message,\n                      ),\n                    },\n                    version,\n                  }),\n                ),\n              }\n            : null;\n        }\n      }\n    } catch (e) {\n      throw new SolanaJSONRPCError(\n        e as JSONRPCError,\n        'failed to get confirmed block',\n      );\n    }\n  }\n\n  /**\n   * Fetch parsed transaction details for a confirmed or finalized block\n   */\n  async getParsedBlock(\n    slot: number,\n    rawConfig?: GetVersionedBlockConfig,\n  ): Promise<ParsedAccountsModeBlockResponse>;\n\n  // eslint-disable-next-line no-dupe-class-members\n  async getParsedBlock(\n    slot: number,\n    rawConfig: GetVersionedBlockConfig & {transactionDetails: 'accounts'},\n  ): Promise<ParsedAccountsModeBlockResponse>;\n\n  // eslint-disable-next-line no-dupe-class-members\n  async getParsedBlock(\n    slot: number,\n    rawConfig: GetVersionedBlockConfig & {transactionDetails: 'none'},\n  ): Promise<ParsedNoneModeBlockResponse>;\n  // eslint-disable-next-line no-dupe-class-members\n  async getParsedBlock(\n    slot: number,\n    rawConfig?: GetVersionedBlockConfig,\n  ): Promise<\n    | ParsedBlockResponse\n    | ParsedAccountsModeBlockResponse\n    | ParsedNoneModeBlockResponse\n    | null\n  > {\n    const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n    const args = this._buildArgsAtLeastConfirmed(\n      [slot],\n      commitment as Finality,\n      'jsonParsed',\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getBlock', args);\n    try {\n      switch (config?.transactionDetails) {\n        case 'accounts': {\n          const res = create(unsafeRes, GetParsedAccountsModeBlockRpcResult);\n          if ('error' in res) {\n            throw res.error;\n          }\n          return res.result;\n        }\n        case 'none': {\n          const res = create(unsafeRes, GetParsedNoneModeBlockRpcResult);\n          if ('error' in res) {\n            throw res.error;\n          }\n          return res.result;\n        }\n        default: {\n          const res = create(unsafeRes, GetParsedBlockRpcResult);\n          if ('error' in res) {\n            throw res.error;\n          }\n          return res.result;\n        }\n      }\n    } catch (e) {\n      throw new SolanaJSONRPCError(e as JSONRPCError, 'failed to get block');\n    }\n  }\n\n  /*\n   * Returns the current block height of the node\n   */\n  getBlockHeight = (() => {\n    const requestPromises: {[hash: string]: Promise<number>} = {};\n    return async (\n      commitmentOrConfig?: Commitment | GetBlockHeightConfig,\n    ): Promise<number> => {\n      const {commitment, config} =\n        extractCommitmentFromConfig(commitmentOrConfig);\n      const args = this._buildArgs(\n        [],\n        commitment,\n        undefined /* encoding */,\n        config,\n      );\n      const requestHash = fastStableStringify(args);\n      requestPromises[requestHash] =\n        requestPromises[requestHash] ??\n        (async () => {\n          try {\n            const unsafeRes = await this._rpcRequest('getBlockHeight', args);\n            const res = create(unsafeRes, jsonRpcResult(number()));\n            if ('error' in res) {\n              throw new SolanaJSONRPCError(\n                res.error,\n                'failed to get block height information',\n              );\n            }\n            return res.result;\n          } finally {\n            delete requestPromises[requestHash];\n          }\n        })();\n      return await requestPromises[requestHash];\n    };\n  })();\n\n  /*\n   * Returns recent block production information from the current or previous epoch\n   */\n  async getBlockProduction(\n    configOrCommitment?: GetBlockProductionConfig | Commitment,\n  ): Promise<RpcResponseAndContext<BlockProduction>> {\n    let extra: Omit<GetBlockProductionConfig, 'commitment'> | undefined;\n    let commitment: Commitment | undefined;\n\n    if (typeof configOrCommitment === 'string') {\n      commitment = configOrCommitment;\n    } else if (configOrCommitment) {\n      const {commitment: c, ...rest} = configOrCommitment;\n      commitment = c;\n      extra = rest;\n    }\n\n    const args = this._buildArgs([], commitment, 'base64', extra);\n    const unsafeRes = await this._rpcRequest('getBlockProduction', args);\n    const res = create(unsafeRes, BlockProductionResponseStruct);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get block production information',\n      );\n    }\n\n    return res.result;\n  }\n\n  /**\n   * Fetch a confirmed or finalized transaction from the cluster.\n   *\n   * @deprecated Instead, call `getTransaction` using a\n   * `GetVersionedTransactionConfig` by setting the\n   * `maxSupportedTransactionVersion` property.\n   */\n  async getTransaction(\n    signature: string,\n    rawConfig?: GetTransactionConfig,\n  ): Promise<TransactionResponse | null>;\n\n  /**\n   * Fetch a confirmed or finalized transaction from the cluster.\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async getTransaction(\n    signature: string,\n    rawConfig: GetVersionedTransactionConfig,\n  ): Promise<VersionedTransactionResponse | null>;\n\n  /**\n   * Fetch a confirmed or finalized transaction from the cluster.\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async getTransaction(\n    signature: string,\n    rawConfig?: GetVersionedTransactionConfig,\n  ): Promise<VersionedTransactionResponse | null> {\n    const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n    const args = this._buildArgsAtLeastConfirmed(\n      [signature],\n      commitment as Finality,\n      undefined /* encoding */,\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getTransaction', args);\n    const res = create(unsafeRes, GetTransactionRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n    }\n\n    const result = res.result;\n    if (!result) return result;\n\n    return {\n      ...result,\n      transaction: {\n        ...result.transaction,\n        message: versionedMessageFromResponse(\n          result.version,\n          result.transaction.message,\n        ),\n      },\n    };\n  }\n\n  /**\n   * Fetch parsed transaction details for a confirmed or finalized transaction\n   */\n  async getParsedTransaction(\n    signature: TransactionSignature,\n    commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n  ): Promise<ParsedTransactionWithMeta | null> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const args = this._buildArgsAtLeastConfirmed(\n      [signature],\n      commitment as Finality,\n      'jsonParsed',\n      config,\n    );\n    const unsafeRes = await this._rpcRequest('getTransaction', args);\n    const res = create(unsafeRes, GetParsedTransactionRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch parsed transaction details for a batch of confirmed transactions\n   */\n  async getParsedTransactions(\n    signatures: TransactionSignature[],\n    commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n  ): Promise<(ParsedTransactionWithMeta | null)[]> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const batch = signatures.map(signature => {\n      const args = this._buildArgsAtLeastConfirmed(\n        [signature],\n        commitment as Finality,\n        'jsonParsed',\n        config,\n      );\n      return {\n        methodName: 'getTransaction',\n        args,\n      };\n    });\n\n    const unsafeRes = await this._rpcBatchRequest(batch);\n    const res = unsafeRes.map((unsafeRes: any) => {\n      const res = create(unsafeRes, GetParsedTransactionRpcResult);\n      if ('error' in res) {\n        throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n      }\n      return res.result;\n    });\n\n    return res;\n  }\n\n  /**\n   * Fetch transaction details for a batch of confirmed transactions.\n   * Similar to {@link getParsedTransactions} but returns a {@link TransactionResponse}.\n   *\n   * @deprecated Instead, call `getTransactions` using a\n   * `GetVersionedTransactionConfig` by setting the\n   * `maxSupportedTransactionVersion` property.\n   */\n  async getTransactions(\n    signatures: TransactionSignature[],\n    commitmentOrConfig?: GetTransactionConfig | Finality,\n  ): Promise<(TransactionResponse | null)[]>;\n\n  /**\n   * Fetch transaction details for a batch of confirmed transactions.\n   * Similar to {@link getParsedTransactions} but returns a {@link\n   * VersionedTransactionResponse}.\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async getTransactions(\n    signatures: TransactionSignature[],\n    commitmentOrConfig: GetVersionedTransactionConfig | Finality,\n  ): Promise<(VersionedTransactionResponse | null)[]>;\n\n  /**\n   * Fetch transaction details for a batch of confirmed transactions.\n   * Similar to {@link getParsedTransactions} but returns a {@link\n   * VersionedTransactionResponse}.\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async getTransactions(\n    signatures: TransactionSignature[],\n    commitmentOrConfig: GetVersionedTransactionConfig | Finality,\n  ): Promise<(VersionedTransactionResponse | null)[]> {\n    const {commitment, config} =\n      extractCommitmentFromConfig(commitmentOrConfig);\n    const batch = signatures.map(signature => {\n      const args = this._buildArgsAtLeastConfirmed(\n        [signature],\n        commitment as Finality,\n        undefined /* encoding */,\n        config,\n      );\n      return {\n        methodName: 'getTransaction',\n        args,\n      };\n    });\n\n    const unsafeRes = await this._rpcBatchRequest(batch);\n    const res = unsafeRes.map((unsafeRes: any) => {\n      const res = create(unsafeRes, GetTransactionRpcResult);\n      if ('error' in res) {\n        throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n      }\n      const result = res.result;\n      if (!result) return result;\n\n      return {\n        ...result,\n        transaction: {\n          ...result.transaction,\n          message: versionedMessageFromResponse(\n            result.version,\n            result.transaction.message,\n          ),\n        },\n      };\n    });\n\n    return res;\n  }\n\n  /**\n   * Fetch a list of Transactions and transaction statuses from the cluster\n   * for a confirmed block.\n   *\n   * @deprecated Deprecated since v1.13.0. Please use {@link getBlock} instead.\n   */\n  async getConfirmedBlock(\n    slot: number,\n    commitment?: Finality,\n  ): Promise<ConfirmedBlock> {\n    const args = this._buildArgsAtLeastConfirmed([slot], commitment);\n    const unsafeRes = await this._rpcRequest('getConfirmedBlock', args);\n    const res = create(unsafeRes, GetConfirmedBlockRpcResult);\n\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n    }\n\n    const result = res.result;\n    if (!result) {\n      throw new Error('Confirmed block ' + slot + ' not found');\n    }\n\n    const block = {\n      ...result,\n      transactions: result.transactions.map(({transaction, meta}) => {\n        const message = new Message(transaction.message);\n        return {\n          meta,\n          transaction: {\n            ...transaction,\n            message,\n          },\n        };\n      }),\n    };\n\n    return {\n      ...block,\n      transactions: block.transactions.map(({transaction, meta}) => {\n        return {\n          meta,\n          transaction: Transaction.populate(\n            transaction.message,\n            transaction.signatures,\n          ),\n        };\n      }),\n    };\n  }\n\n  /**\n   * Fetch confirmed blocks between two slots\n   */\n  async getBlocks(\n    startSlot: number,\n    endSlot?: number,\n    commitment?: Finality,\n  ): Promise<Array<number>> {\n    const args = this._buildArgsAtLeastConfirmed(\n      endSlot !== undefined ? [startSlot, endSlot] : [startSlot],\n      commitment,\n    );\n    const unsafeRes = await this._rpcRequest('getBlocks', args);\n    const res = create(unsafeRes, jsonRpcResult(array(number())));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get blocks');\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch a list of Signatures from the cluster for a block, excluding rewards\n   */\n  async getBlockSignatures(\n    slot: number,\n    commitment?: Finality,\n  ): Promise<BlockSignatures> {\n    const args = this._buildArgsAtLeastConfirmed(\n      [slot],\n      commitment,\n      undefined,\n      {\n        transactionDetails: 'signatures',\n        rewards: false,\n      },\n    );\n    const unsafeRes = await this._rpcRequest('getBlock', args);\n    const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get block');\n    }\n    const result = res.result;\n    if (!result) {\n      throw new Error('Block ' + slot + ' not found');\n    }\n    return result;\n  }\n\n  /**\n   * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards\n   *\n   * @deprecated Deprecated since Solana v1.8.0. Please use {@link getBlockSignatures} instead.\n   */\n  async getConfirmedBlockSignatures(\n    slot: number,\n    commitment?: Finality,\n  ): Promise<BlockSignatures> {\n    const args = this._buildArgsAtLeastConfirmed(\n      [slot],\n      commitment,\n      undefined,\n      {\n        transactionDetails: 'signatures',\n        rewards: false,\n      },\n    );\n    const unsafeRes = await this._rpcRequest('getConfirmedBlock', args);\n    const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n    }\n    const result = res.result;\n    if (!result) {\n      throw new Error('Confirmed block ' + slot + ' not found');\n    }\n    return result;\n  }\n\n  /**\n   * Fetch a transaction details for a confirmed transaction\n   *\n   * @deprecated Deprecated since Solana v1.8.0. Please use {@link getTransaction} instead.\n   */\n  async getConfirmedTransaction(\n    signature: TransactionSignature,\n    commitment?: Finality,\n  ): Promise<ConfirmedTransaction | null> {\n    const args = this._buildArgsAtLeastConfirmed([signature], commitment);\n    const unsafeRes = await this._rpcRequest('getConfirmedTransaction', args);\n    const res = create(unsafeRes, GetTransactionRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n    }\n\n    const result = res.result;\n    if (!result) return result;\n\n    const message = new Message(result.transaction.message);\n    const signatures = result.transaction.signatures;\n    return {\n      ...result,\n      transaction: Transaction.populate(message, signatures),\n    };\n  }\n\n  /**\n   * Fetch parsed transaction details for a confirmed transaction\n   *\n   * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransaction} instead.\n   */\n  async getParsedConfirmedTransaction(\n    signature: TransactionSignature,\n    commitment?: Finality,\n  ): Promise<ParsedConfirmedTransaction | null> {\n    const args = this._buildArgsAtLeastConfirmed(\n      [signature],\n      commitment,\n      'jsonParsed',\n    );\n    const unsafeRes = await this._rpcRequest('getConfirmedTransaction', args);\n    const res = create(unsafeRes, GetParsedTransactionRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get confirmed transaction',\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Fetch parsed transaction details for a batch of confirmed transactions\n   *\n   * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransactions} instead.\n   */\n  async getParsedConfirmedTransactions(\n    signatures: TransactionSignature[],\n    commitment?: Finality,\n  ): Promise<(ParsedConfirmedTransaction | null)[]> {\n    const batch = signatures.map(signature => {\n      const args = this._buildArgsAtLeastConfirmed(\n        [signature],\n        commitment,\n        'jsonParsed',\n      );\n      return {\n        methodName: 'getConfirmedTransaction',\n        args,\n      };\n    });\n\n    const unsafeRes = await this._rpcBatchRequest(batch);\n    const res = unsafeRes.map((unsafeRes: any) => {\n      const res = create(unsafeRes, GetParsedTransactionRpcResult);\n      if ('error' in res) {\n        throw new SolanaJSONRPCError(\n          res.error,\n          'failed to get confirmed transactions',\n        );\n      }\n      return res.result;\n    });\n\n    return res;\n  }\n\n  /**\n   * Fetch a list of all the confirmed signatures for transactions involving an address\n   * within a specified slot range. Max range allowed is 10,000 slots.\n   *\n   * @deprecated Deprecated since v1.3. Please use {@link getConfirmedSignaturesForAddress2} instead.\n   *\n   * @param address queried address\n   * @param startSlot start slot, inclusive\n   * @param endSlot end slot, inclusive\n   */\n  async getConfirmedSignaturesForAddress(\n    address: PublicKey,\n    startSlot: number,\n    endSlot: number,\n  ): Promise<Array<TransactionSignature>> {\n    let options: any = {};\n\n    let firstAvailableBlock = await this.getFirstAvailableBlock();\n    while (!('until' in options)) {\n      startSlot--;\n      if (startSlot <= 0 || startSlot < firstAvailableBlock) {\n        break;\n      }\n\n      try {\n        const block = await this.getConfirmedBlockSignatures(\n          startSlot,\n          'finalized',\n        );\n        if (block.signatures.length > 0) {\n          options.until =\n            block.signatures[block.signatures.length - 1].toString();\n        }\n      } catch (err) {\n        if (err instanceof Error && err.message.includes('skipped')) {\n          continue;\n        } else {\n          throw err;\n        }\n      }\n    }\n\n    let highestConfirmedRoot = await this.getSlot('finalized');\n    while (!('before' in options)) {\n      endSlot++;\n      if (endSlot > highestConfirmedRoot) {\n        break;\n      }\n\n      try {\n        const block = await this.getConfirmedBlockSignatures(endSlot);\n        if (block.signatures.length > 0) {\n          options.before =\n            block.signatures[block.signatures.length - 1].toString();\n        }\n      } catch (err) {\n        if (err instanceof Error && err.message.includes('skipped')) {\n          continue;\n        } else {\n          throw err;\n        }\n      }\n    }\n\n    const confirmedSignatureInfo = await this.getConfirmedSignaturesForAddress2(\n      address,\n      options,\n    );\n    return confirmedSignatureInfo.map(info => info.signature);\n  }\n\n  /**\n   * Returns confirmed signatures for transactions involving an\n   * address backwards in time from the provided signature or most recent confirmed block\n   *\n   *\n   * @param address queried address\n   * @param options\n   */\n  async getConfirmedSignaturesForAddress2(\n    address: PublicKey,\n    options?: ConfirmedSignaturesForAddress2Options,\n    commitment?: Finality,\n  ): Promise<Array<ConfirmedSignatureInfo>> {\n    const args = this._buildArgsAtLeastConfirmed(\n      [address.toBase58()],\n      commitment,\n      undefined,\n      options,\n    );\n    const unsafeRes = await this._rpcRequest(\n      'getConfirmedSignaturesForAddress2',\n      args,\n    );\n    const res = create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get confirmed signatures for address',\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Returns confirmed signatures for transactions involving an\n   * address backwards in time from the provided signature or most recent confirmed block\n   *\n   *\n   * @param address queried address\n   * @param options\n   */\n  async getSignaturesForAddress(\n    address: PublicKey,\n    options?: SignaturesForAddressOptions,\n    commitment?: Finality,\n  ): Promise<Array<ConfirmedSignatureInfo>> {\n    const args = this._buildArgsAtLeastConfirmed(\n      [address.toBase58()],\n      commitment,\n      undefined,\n      options,\n    );\n    const unsafeRes = await this._rpcRequest('getSignaturesForAddress', args);\n    const res = create(unsafeRes, GetSignaturesForAddressRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        'failed to get signatures for address',\n      );\n    }\n    return res.result;\n  }\n\n  async getAddressLookupTable(\n    accountKey: PublicKey,\n    config?: GetAccountInfoConfig,\n  ): Promise<RpcResponseAndContext<AddressLookupTableAccount | null>> {\n    const {context, value: accountInfo} = await this.getAccountInfoAndContext(\n      accountKey,\n      config,\n    );\n\n    let value = null;\n    if (accountInfo !== null) {\n      value = new AddressLookupTableAccount({\n        key: accountKey,\n        state: AddressLookupTableAccount.deserialize(accountInfo.data),\n      });\n    }\n\n    return {\n      context,\n      value,\n    };\n  }\n\n  /**\n   * Fetch the contents of a Nonce account from the cluster, return with context\n   */\n  async getNonceAndContext(\n    nonceAccount: PublicKey,\n    commitmentOrConfig?: Commitment | GetNonceAndContextConfig,\n  ): Promise<RpcResponseAndContext<NonceAccount | null>> {\n    const {context, value: accountInfo} = await this.getAccountInfoAndContext(\n      nonceAccount,\n      commitmentOrConfig,\n    );\n\n    let value = null;\n    if (accountInfo !== null) {\n      value = NonceAccount.fromAccountData(accountInfo.data);\n    }\n\n    return {\n      context,\n      value,\n    };\n  }\n\n  /**\n   * Fetch the contents of a Nonce account from the cluster\n   */\n  async getNonce(\n    nonceAccount: PublicKey,\n    commitmentOrConfig?: Commitment | GetNonceConfig,\n  ): Promise<NonceAccount | null> {\n    return await this.getNonceAndContext(nonceAccount, commitmentOrConfig)\n      .then(x => x.value)\n      .catch(e => {\n        throw new Error(\n          'failed to get nonce for account ' +\n            nonceAccount.toBase58() +\n            ': ' +\n            e,\n        );\n      });\n  }\n\n  /**\n   * Request an allocation of lamports to the specified address\n   *\n   * ```typescript\n   * import { Connection, PublicKey, LAMPORTS_PER_SOL } from \"@solana/web3.js\";\n   *\n   * (async () => {\n   *   const connection = new Connection(\"https://api.testnet.solana.com\", \"confirmed\");\n   *   const myAddress = new PublicKey(\"2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM\");\n   *   const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL);\n   *   await connection.confirmTransaction(signature);\n   * })();\n   * ```\n   */\n  async requestAirdrop(\n    to: PublicKey,\n    lamports: number,\n  ): Promise<TransactionSignature> {\n    const unsafeRes = await this._rpcRequest('requestAirdrop', [\n      to.toBase58(),\n      lamports,\n    ]);\n    const res = create(unsafeRes, RequestAirdropRpcResult);\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `airdrop to ${to.toBase58()} failed`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * @internal\n   */\n  async _blockhashWithExpiryBlockHeight(\n    disableCache: boolean,\n  ): Promise<BlockhashWithExpiryBlockHeight> {\n    if (!disableCache) {\n      // Wait for polling to finish\n      while (this._pollingBlockhash) {\n        await sleep(100);\n      }\n      const timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch;\n      const expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS;\n      if (this._blockhashInfo.latestBlockhash !== null && !expired) {\n        return this._blockhashInfo.latestBlockhash;\n      }\n    }\n\n    return await this._pollNewBlockhash();\n  }\n\n  /**\n   * @internal\n   */\n  async _pollNewBlockhash(): Promise<BlockhashWithExpiryBlockHeight> {\n    this._pollingBlockhash = true;\n    try {\n      const startTime = Date.now();\n      const cachedLatestBlockhash = this._blockhashInfo.latestBlockhash;\n      const cachedBlockhash = cachedLatestBlockhash\n        ? cachedLatestBlockhash.blockhash\n        : null;\n      for (let i = 0; i < 50; i++) {\n        const latestBlockhash = await this.getLatestBlockhash('finalized');\n\n        if (cachedBlockhash !== latestBlockhash.blockhash) {\n          this._blockhashInfo = {\n            latestBlockhash,\n            lastFetch: Date.now(),\n            transactionSignatures: [],\n            simulatedSignatures: [],\n          };\n          return latestBlockhash;\n        }\n\n        // Sleep for approximately half a slot\n        await sleep(MS_PER_SLOT / 2);\n      }\n\n      throw new Error(\n        `Unable to obtain a new blockhash after ${Date.now() - startTime}ms`,\n      );\n    } finally {\n      this._pollingBlockhash = false;\n    }\n  }\n\n  /**\n   * get the stake minimum delegation\n   */\n  async getStakeMinimumDelegation(\n    config?: GetStakeMinimumDelegationConfig,\n  ): Promise<RpcResponseAndContext<number>> {\n    const {commitment, config: configArg} = extractCommitmentFromConfig(config);\n    const args = this._buildArgs([], commitment, 'base64', configArg);\n    const unsafeRes = await this._rpcRequest('getStakeMinimumDelegation', args);\n    const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n    if ('error' in res) {\n      throw new SolanaJSONRPCError(\n        res.error,\n        `failed to get stake minimum delegation`,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Simulate a transaction\n   *\n   * @deprecated Instead, call {@link simulateTransaction} with {@link\n   * VersionedTransaction} and {@link SimulateTransactionConfig} parameters\n   */\n  simulateTransaction(\n    transactionOrMessage: Transaction | Message,\n    signers?: Array<Signer>,\n    includeAccounts?: boolean | Array<PublicKey>,\n  ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>>;\n\n  /**\n   * Simulate a transaction\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  simulateTransaction(\n    transaction: VersionedTransaction,\n    config?: SimulateTransactionConfig,\n  ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>>;\n\n  /**\n   * Simulate a transaction\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async simulateTransaction(\n    transactionOrMessage: VersionedTransaction | Transaction | Message,\n    configOrSigners?: SimulateTransactionConfig | Array<Signer>,\n    includeAccounts?: boolean | Array<PublicKey>,\n  ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>> {\n    if ('message' in transactionOrMessage) {\n      const versionedTx = transactionOrMessage;\n      const wireTransaction = versionedTx.serialize();\n      const encodedTransaction =\n        Buffer.from(wireTransaction).toString('base64');\n      if (Array.isArray(configOrSigners) || includeAccounts !== undefined) {\n        throw new Error('Invalid arguments');\n      }\n\n      const config: any = configOrSigners || {};\n      config.encoding = 'base64';\n      if (!('commitment' in config)) {\n        config.commitment = this.commitment;\n      }\n\n      const args = [encodedTransaction, config];\n      const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n      const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n      if ('error' in res) {\n        throw new Error('failed to simulate transaction: ' + res.error.message);\n      }\n      return res.result;\n    }\n\n    let transaction;\n    if (transactionOrMessage instanceof Transaction) {\n      let originalTx: Transaction = transactionOrMessage;\n      transaction = new Transaction();\n      transaction.feePayer = originalTx.feePayer;\n      transaction.instructions = transactionOrMessage.instructions;\n      transaction.nonceInfo = originalTx.nonceInfo;\n      transaction.signatures = originalTx.signatures;\n    } else {\n      transaction = Transaction.populate(transactionOrMessage);\n      // HACK: this function relies on mutating the populated transaction\n      transaction._message = transaction._json = undefined;\n    }\n\n    if (configOrSigners !== undefined && !Array.isArray(configOrSigners)) {\n      throw new Error('Invalid arguments');\n    }\n\n    const signers = configOrSigners;\n    if (transaction.nonceInfo && signers) {\n      transaction.sign(...signers);\n    } else {\n      let disableCache = this._disableBlockhashCaching;\n      for (;;) {\n        const latestBlockhash = await this._blockhashWithExpiryBlockHeight(\n          disableCache,\n        );\n        transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n        transaction.recentBlockhash = latestBlockhash.blockhash;\n\n        if (!signers) break;\n\n        transaction.sign(...signers);\n        if (!transaction.signature) {\n          throw new Error('!signature'); // should never happen\n        }\n\n        const signature = transaction.signature.toString('base64');\n        if (\n          !this._blockhashInfo.simulatedSignatures.includes(signature) &&\n          !this._blockhashInfo.transactionSignatures.includes(signature)\n        ) {\n          // The signature of this transaction has not been seen before with the\n          // current recentBlockhash, all done. Let's break\n          this._blockhashInfo.simulatedSignatures.push(signature);\n          break;\n        } else {\n          // This transaction would be treated as duplicate (its derived signature\n          // matched to one of already recorded signatures).\n          // So, we must fetch a new blockhash for a different signature by disabling\n          // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n          disableCache = true;\n        }\n      }\n    }\n\n    const message = transaction._compile();\n    const signData = message.serialize();\n    const wireTransaction = transaction._serialize(signData);\n    const encodedTransaction = wireTransaction.toString('base64');\n    const config: any = {\n      encoding: 'base64',\n      commitment: this.commitment,\n    };\n\n    if (includeAccounts) {\n      const addresses = (\n        Array.isArray(includeAccounts)\n          ? includeAccounts\n          : message.nonProgramIds()\n      ).map(key => key.toBase58());\n\n      config['accounts'] = {\n        encoding: 'base64',\n        addresses,\n      };\n    }\n\n    if (signers) {\n      config.sigVerify = true;\n    }\n\n    const args = [encodedTransaction, config];\n    const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n    const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n    if ('error' in res) {\n      let logs;\n      if ('data' in res.error) {\n        logs = res.error.data.logs;\n        if (logs && Array.isArray(logs)) {\n          const traceIndent = '\\n    ';\n          const logTrace = traceIndent + logs.join(traceIndent);\n          console.error(res.error.message, logTrace);\n        }\n      }\n      throw new SendTransactionError(\n        'failed to simulate transaction: ' + res.error.message,\n        logs,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * Sign and send a transaction\n   *\n   * @deprecated Instead, call {@link sendTransaction} with a {@link\n   * VersionedTransaction}\n   */\n  sendTransaction(\n    transaction: Transaction,\n    signers: Array<Signer>,\n    options?: SendOptions,\n  ): Promise<TransactionSignature>;\n\n  /**\n   * Send a signed transaction\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  sendTransaction(\n    transaction: VersionedTransaction,\n    options?: SendOptions,\n  ): Promise<TransactionSignature>;\n\n  /**\n   * Sign and send a transaction\n   */\n  // eslint-disable-next-line no-dupe-class-members\n  async sendTransaction(\n    transaction: VersionedTransaction | Transaction,\n    signersOrOptions?: Array<Signer> | SendOptions,\n    options?: SendOptions,\n  ): Promise<TransactionSignature> {\n    if ('version' in transaction) {\n      if (signersOrOptions && Array.isArray(signersOrOptions)) {\n        throw new Error('Invalid arguments');\n      }\n\n      const wireTransaction = transaction.serialize();\n      return await this.sendRawTransaction(wireTransaction, signersOrOptions);\n    }\n\n    if (signersOrOptions === undefined || !Array.isArray(signersOrOptions)) {\n      throw new Error('Invalid arguments');\n    }\n\n    const signers = signersOrOptions;\n    if (transaction.nonceInfo) {\n      transaction.sign(...signers);\n    } else {\n      let disableCache = this._disableBlockhashCaching;\n      for (;;) {\n        const latestBlockhash = await this._blockhashWithExpiryBlockHeight(\n          disableCache,\n        );\n        transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n        transaction.recentBlockhash = latestBlockhash.blockhash;\n        transaction.sign(...signers);\n        if (!transaction.signature) {\n          throw new Error('!signature'); // should never happen\n        }\n\n        const signature = transaction.signature.toString('base64');\n        if (!this._blockhashInfo.transactionSignatures.includes(signature)) {\n          // The signature of this transaction has not been seen before with the\n          // current recentBlockhash, all done. Let's break\n          this._blockhashInfo.transactionSignatures.push(signature);\n          break;\n        } else {\n          // This transaction would be treated as duplicate (its derived signature\n          // matched to one of already recorded signatures).\n          // So, we must fetch a new blockhash for a different signature by disabling\n          // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n          disableCache = true;\n        }\n      }\n    }\n\n    const wireTransaction = transaction.serialize();\n    return await this.sendRawTransaction(wireTransaction, options);\n  }\n\n  /**\n   * Send a transaction that has already been signed and serialized into the\n   * wire format\n   */\n  async sendRawTransaction(\n    rawTransaction: Buffer | Uint8Array | Array<number>,\n    options?: SendOptions,\n  ): Promise<TransactionSignature> {\n    const encodedTransaction = toBuffer(rawTransaction).toString('base64');\n    const result = await this.sendEncodedTransaction(\n      encodedTransaction,\n      options,\n    );\n    return result;\n  }\n\n  /**\n   * Send a transaction that has already been signed, serialized into the\n   * wire format, and encoded as a base64 string\n   */\n  async sendEncodedTransaction(\n    encodedTransaction: string,\n    options?: SendOptions,\n  ): Promise<TransactionSignature> {\n    const config: any = {encoding: 'base64'};\n    const skipPreflight = options && options.skipPreflight;\n    const preflightCommitment =\n      (options && options.preflightCommitment) || this.commitment;\n\n    if (options && options.maxRetries != null) {\n      config.maxRetries = options.maxRetries;\n    }\n    if (options && options.minContextSlot != null) {\n      config.minContextSlot = options.minContextSlot;\n    }\n    if (skipPreflight) {\n      config.skipPreflight = skipPreflight;\n    }\n    if (preflightCommitment) {\n      config.preflightCommitment = preflightCommitment;\n    }\n\n    const args = [encodedTransaction, config];\n    const unsafeRes = await this._rpcRequest('sendTransaction', args);\n    const res = create(unsafeRes, SendTransactionRpcResult);\n    if ('error' in res) {\n      let logs;\n      if ('data' in res.error) {\n        logs = res.error.data.logs;\n      }\n      throw new SendTransactionError(\n        'failed to send transaction: ' + res.error.message,\n        logs,\n      );\n    }\n    return res.result;\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnOpen() {\n    this._rpcWebSocketConnected = true;\n    this._rpcWebSocketHeartbeat = setInterval(() => {\n      // Ping server every 5s to prevent idle timeouts\n      (async () => {\n        try {\n          await this._rpcWebSocket.notify('ping');\n          // eslint-disable-next-line no-empty\n        } catch {}\n      })();\n    }, 5000);\n    this._updateSubscriptions();\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnError(err: Error) {\n    this._rpcWebSocketConnected = false;\n    console.error('ws error:', err.message);\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnClose(code: number) {\n    this._rpcWebSocketConnected = false;\n    this._rpcWebSocketGeneration =\n      (this._rpcWebSocketGeneration + 1) % Number.MAX_SAFE_INTEGER;\n    if (this._rpcWebSocketIdleTimeout) {\n      clearTimeout(this._rpcWebSocketIdleTimeout);\n      this._rpcWebSocketIdleTimeout = null;\n    }\n    if (this._rpcWebSocketHeartbeat) {\n      clearInterval(this._rpcWebSocketHeartbeat);\n      this._rpcWebSocketHeartbeat = null;\n    }\n\n    if (code === 1000) {\n      // explicit close, check if any subscriptions have been made since close\n      this._updateSubscriptions();\n      return;\n    }\n\n    // implicit close, prepare subscriptions for auto-reconnect\n    this._subscriptionCallbacksByServerSubscriptionId = {};\n    Object.entries(\n      this._subscriptionsByHash as Record<SubscriptionConfigHash, Subscription>,\n    ).forEach(([hash, subscription]) => {\n      this._setSubscription(hash, {\n        ...subscription,\n        state: 'pending',\n      });\n    });\n  }\n\n  /**\n   * @internal\n   */\n  private _setSubscription(\n    hash: SubscriptionConfigHash,\n    nextSubscription: Subscription,\n  ) {\n    const prevState = this._subscriptionsByHash[hash]?.state;\n    this._subscriptionsByHash[hash] = nextSubscription;\n    if (prevState !== nextSubscription.state) {\n      const stateChangeCallbacks =\n        this._subscriptionStateChangeCallbacksByHash[hash];\n      if (stateChangeCallbacks) {\n        stateChangeCallbacks.forEach(cb => {\n          try {\n            cb(nextSubscription.state);\n            // eslint-disable-next-line no-empty\n          } catch {}\n        });\n      }\n    }\n  }\n\n  /**\n   * @internal\n   */\n  private _onSubscriptionStateChange(\n    clientSubscriptionId: ClientSubscriptionId,\n    callback: SubscriptionStateChangeCallback,\n  ): SubscriptionStateChangeDisposeFn {\n    const hash =\n      this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n    if (hash == null) {\n      return () => {};\n    }\n    const stateChangeCallbacks = (this._subscriptionStateChangeCallbacksByHash[\n      hash\n    ] ||= new Set());\n    stateChangeCallbacks.add(callback);\n    return () => {\n      stateChangeCallbacks.delete(callback);\n      if (stateChangeCallbacks.size === 0) {\n        delete this._subscriptionStateChangeCallbacksByHash[hash];\n      }\n    };\n  }\n\n  /**\n   * @internal\n   */\n  async _updateSubscriptions() {\n    if (Object.keys(this._subscriptionsByHash).length === 0) {\n      if (this._rpcWebSocketConnected) {\n        this._rpcWebSocketConnected = false;\n        this._rpcWebSocketIdleTimeout = setTimeout(() => {\n          this._rpcWebSocketIdleTimeout = null;\n          try {\n            this._rpcWebSocket.close();\n          } catch (err) {\n            // swallow error if socket has already been closed.\n            if (err instanceof Error) {\n              console.log(\n                `Error when closing socket connection: ${err.message}`,\n              );\n            }\n          }\n        }, 500);\n      }\n      return;\n    }\n\n    if (this._rpcWebSocketIdleTimeout !== null) {\n      clearTimeout(this._rpcWebSocketIdleTimeout);\n      this._rpcWebSocketIdleTimeout = null;\n      this._rpcWebSocketConnected = true;\n    }\n\n    if (!this._rpcWebSocketConnected) {\n      this._rpcWebSocket.connect();\n      return;\n    }\n\n    const activeWebSocketGeneration = this._rpcWebSocketGeneration;\n    const isCurrentConnectionStillActive = () => {\n      return activeWebSocketGeneration === this._rpcWebSocketGeneration;\n    };\n\n    await Promise.all(\n      // Don't be tempted to change this to `Object.entries`. We call\n      // `_updateSubscriptions` recursively when processing the state,\n      // so it's important that we look up the *current* version of\n      // each subscription, every time we process a hash.\n      Object.keys(this._subscriptionsByHash).map(async hash => {\n        const subscription = this._subscriptionsByHash[hash];\n        if (subscription === undefined) {\n          // This entry has since been deleted. Skip.\n          return;\n        }\n        switch (subscription.state) {\n          case 'pending':\n          case 'unsubscribed':\n            if (subscription.callbacks.size === 0) {\n              /**\n               * You can end up here when:\n               *\n               * - a subscription has recently unsubscribed\n               *   without having new callbacks added to it\n               *   while the unsubscribe was in flight, or\n               * - when a pending subscription has its\n               *   listeners removed before a request was\n               *   sent to the server.\n               *\n               * Being that nobody is interested in this\n               * subscription any longer, delete it.\n               */\n              delete this._subscriptionsByHash[hash];\n              if (subscription.state === 'unsubscribed') {\n                delete this._subscriptionCallbacksByServerSubscriptionId[\n                  subscription.serverSubscriptionId\n                ];\n              }\n              await this._updateSubscriptions();\n              return;\n            }\n            await (async () => {\n              const {args, method} = subscription;\n              try {\n                this._setSubscription(hash, {\n                  ...subscription,\n                  state: 'subscribing',\n                });\n                const serverSubscriptionId: ServerSubscriptionId =\n                  (await this._rpcWebSocket.call(method, args)) as number;\n                this._setSubscription(hash, {\n                  ...subscription,\n                  serverSubscriptionId,\n                  state: 'subscribed',\n                });\n                this._subscriptionCallbacksByServerSubscriptionId[\n                  serverSubscriptionId\n                ] = subscription.callbacks;\n                await this._updateSubscriptions();\n              } catch (e) {\n                if (e instanceof Error) {\n                  console.error(\n                    `${method} error for argument`,\n                    args,\n                    e.message,\n                  );\n                }\n                if (!isCurrentConnectionStillActive()) {\n                  return;\n                }\n                // TODO: Maybe add an 'errored' state or a retry limit?\n                this._setSubscription(hash, {\n                  ...subscription,\n                  state: 'pending',\n                });\n                await this._updateSubscriptions();\n              }\n            })();\n            break;\n          case 'subscribed':\n            if (subscription.callbacks.size === 0) {\n              // By the time we successfully set up a subscription\n              // with the server, the client stopped caring about it.\n              // Tear it down now.\n              await (async () => {\n                const {serverSubscriptionId, unsubscribeMethod} = subscription;\n                if (\n                  this._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)\n                ) {\n                  /**\n                   * Special case.\n                   * If we're dealing with a subscription that has been auto-\n                   * disposed by the RPC, then we can skip the RPC call to\n                   * tear down the subscription here.\n                   *\n                   * NOTE: There is a proposal to eliminate this special case, here:\n                   * https://github.com/solana-labs/solana/issues/18892\n                   */\n                  this._subscriptionsAutoDisposedByRpc.delete(\n                    serverSubscriptionId,\n                  );\n                } else {\n                  this._setSubscription(hash, {\n                    ...subscription,\n                    state: 'unsubscribing',\n                  });\n                  this._setSubscription(hash, {\n                    ...subscription,\n                    state: 'unsubscribing',\n                  });\n                  try {\n                    await this._rpcWebSocket.call(unsubscribeMethod, [\n                      serverSubscriptionId,\n                    ]);\n                  } catch (e) {\n                    if (e instanceof Error) {\n                      console.error(`${unsubscribeMethod} error:`, e.message);\n                    }\n                    if (!isCurrentConnectionStillActive()) {\n                      return;\n                    }\n                    // TODO: Maybe add an 'errored' state or a retry limit?\n                    this._setSubscription(hash, {\n                      ...subscription,\n                      state: 'subscribed',\n                    });\n                    await this._updateSubscriptions();\n                    return;\n                  }\n                }\n                this._setSubscription(hash, {\n                  ...subscription,\n                  state: 'unsubscribed',\n                });\n                await this._updateSubscriptions();\n              })();\n            }\n            break;\n          case 'subscribing':\n          case 'unsubscribing':\n            break;\n        }\n      }),\n    );\n  }\n\n  /**\n   * @internal\n   */\n  private _handleServerNotification<\n    TCallback extends SubscriptionConfig['callback'],\n  >(\n    serverSubscriptionId: ServerSubscriptionId,\n    callbackArgs: Parameters<TCallback>,\n  ): void {\n    const callbacks =\n      this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId];\n    if (callbacks === undefined) {\n      return;\n    }\n    callbacks.forEach(cb => {\n      try {\n        cb(\n          // I failed to find a way to convince TypeScript that `cb` is of type\n          // `TCallback` which is certainly compatible with `Parameters<TCallback>`.\n          // See https://github.com/microsoft/TypeScript/issues/47615\n          // @ts-ignore\n          ...callbackArgs,\n        );\n      } catch (e) {\n        console.error(e);\n      }\n    });\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnAccountNotification(notification: object) {\n    const {result, subscription} = create(\n      notification,\n      AccountNotificationResult,\n    );\n    this._handleServerNotification<AccountChangeCallback>(subscription, [\n      result.value,\n      result.context,\n    ]);\n  }\n\n  /**\n   * @internal\n   */\n  private _makeSubscription(\n    subscriptionConfig: SubscriptionConfig,\n    /**\n     * When preparing `args` for a call to `_makeSubscription`, be sure\n     * to carefully apply a default `commitment` property, if necessary.\n     *\n     * - If the user supplied a `commitment` use that.\n     * - Otherwise, if the `Connection::commitment` is set, use that.\n     * - Otherwise, set it to the RPC server default: `finalized`.\n     *\n     * This is extremely important to ensure that these two fundamentally\n     * identical subscriptions produce the same identifying hash:\n     *\n     * - A subscription made without specifying a commitment.\n     * - A subscription made where the commitment specified is the same\n     *   as the default applied to the subscription above.\n     *\n     * Example; these two subscriptions must produce the same hash:\n     *\n     * - An `accountSubscribe` subscription for `'PUBKEY'`\n     * - An `accountSubscribe` subscription for `'PUBKEY'` with commitment\n     *   `'finalized'`.\n     *\n     * See the 'making a subscription with defaulted params omitted' test\n     * in `connection-subscriptions.ts` for more.\n     */\n    args: IWSRequestParams,\n  ): ClientSubscriptionId {\n    const clientSubscriptionId = this._nextClientSubscriptionId++;\n    const hash = fastStableStringify(\n      [subscriptionConfig.method, args],\n      true /* isArrayProp */,\n    );\n    const existingSubscription = this._subscriptionsByHash[hash];\n    if (existingSubscription === undefined) {\n      this._subscriptionsByHash[hash] = {\n        ...subscriptionConfig,\n        args,\n        callbacks: new Set([subscriptionConfig.callback]),\n        state: 'pending',\n      };\n    } else {\n      existingSubscription.callbacks.add(subscriptionConfig.callback);\n    }\n    this._subscriptionHashByClientSubscriptionId[clientSubscriptionId] = hash;\n    this._subscriptionDisposeFunctionsByClientSubscriptionId[\n      clientSubscriptionId\n    ] = async () => {\n      delete this._subscriptionDisposeFunctionsByClientSubscriptionId[\n        clientSubscriptionId\n      ];\n      delete this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n      const subscription = this._subscriptionsByHash[hash];\n      assert(\n        subscription !== undefined,\n        `Could not find a \\`Subscription\\` when tearing down client subscription #${clientSubscriptionId}`,\n      );\n      subscription.callbacks.delete(subscriptionConfig.callback);\n      await this._updateSubscriptions();\n    };\n    this._updateSubscriptions();\n    return clientSubscriptionId;\n  }\n\n  /**\n   * Register a callback to be invoked whenever the specified account changes\n   *\n   * @param publicKey Public key of the account to monitor\n   * @param callback Function to invoke whenever the account is changed\n   * @param commitment Specify the commitment level account changes must reach before notification\n   * @return subscription id\n   */\n  onAccountChange(\n    publicKey: PublicKey,\n    callback: AccountChangeCallback,\n    commitment?: Commitment,\n  ): ClientSubscriptionId {\n    const args = this._buildArgs(\n      [publicKey.toBase58()],\n      commitment || this._commitment || 'finalized', // Apply connection/server default.\n      'base64',\n    );\n    return this._makeSubscription(\n      {\n        callback,\n        method: 'accountSubscribe',\n        unsubscribeMethod: 'accountUnsubscribe',\n      },\n      args,\n    );\n  }\n\n  /**\n   * Deregister an account notification callback\n   *\n   * @param id client subscription id to deregister\n   */\n  async removeAccountChangeListener(\n    clientSubscriptionId: ClientSubscriptionId,\n  ): Promise<void> {\n    await this._unsubscribeClientSubscription(\n      clientSubscriptionId,\n      'account change',\n    );\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnProgramAccountNotification(notification: Object) {\n    const {result, subscription} = create(\n      notification,\n      ProgramAccountNotificationResult,\n    );\n    this._handleServerNotification<ProgramAccountChangeCallback>(subscription, [\n      {\n        accountId: result.value.pubkey,\n        accountInfo: result.value.account,\n      },\n      result.context,\n    ]);\n  }\n\n  /**\n   * Register a callback to be invoked whenever accounts owned by the\n   * specified program change\n   *\n   * @param programId Public key of the program to monitor\n   * @param callback Function to invoke whenever the account is changed\n   * @param commitment Specify the commitment level account changes must reach before notification\n   * @param filters The program account filters to pass into the RPC method\n   * @return subscription id\n   */\n  onProgramAccountChange(\n    programId: PublicKey,\n    callback: ProgramAccountChangeCallback,\n    commitment?: Commitment,\n    filters?: GetProgramAccountsFilter[],\n  ): ClientSubscriptionId {\n    const args = this._buildArgs(\n      [programId.toBase58()],\n      commitment || this._commitment || 'finalized', // Apply connection/server default.\n      'base64' /* encoding */,\n      filters ? {filters: filters} : undefined /* extra */,\n    );\n    return this._makeSubscription(\n      {\n        callback,\n        method: 'programSubscribe',\n        unsubscribeMethod: 'programUnsubscribe',\n      },\n      args,\n    );\n  }\n\n  /**\n   * Deregister an account notification callback\n   *\n   * @param id client subscription id to deregister\n   */\n  async removeProgramAccountChangeListener(\n    clientSubscriptionId: ClientSubscriptionId,\n  ): Promise<void> {\n    await this._unsubscribeClientSubscription(\n      clientSubscriptionId,\n      'program account change',\n    );\n  }\n\n  /**\n   * Registers a callback to be invoked whenever logs are emitted.\n   */\n  onLogs(\n    filter: LogsFilter,\n    callback: LogsCallback,\n    commitment?: Commitment,\n  ): ClientSubscriptionId {\n    const args = this._buildArgs(\n      [typeof filter === 'object' ? {mentions: [filter.toString()]} : filter],\n      commitment || this._commitment || 'finalized', // Apply connection/server default.\n    );\n    return this._makeSubscription(\n      {\n        callback,\n        method: 'logsSubscribe',\n        unsubscribeMethod: 'logsUnsubscribe',\n      },\n      args,\n    );\n  }\n\n  /**\n   * Deregister a logs callback.\n   *\n   * @param id client subscription id to deregister.\n   */\n  async removeOnLogsListener(\n    clientSubscriptionId: ClientSubscriptionId,\n  ): Promise<void> {\n    await this._unsubscribeClientSubscription(clientSubscriptionId, 'logs');\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnLogsNotification(notification: Object) {\n    const {result, subscription} = create(notification, LogsNotificationResult);\n    this._handleServerNotification<LogsCallback>(subscription, [\n      result.value,\n      result.context,\n    ]);\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnSlotNotification(notification: Object) {\n    const {result, subscription} = create(notification, SlotNotificationResult);\n    this._handleServerNotification<SlotChangeCallback>(subscription, [result]);\n  }\n\n  /**\n   * Register a callback to be invoked upon slot changes\n   *\n   * @param callback Function to invoke whenever the slot changes\n   * @return subscription id\n   */\n  onSlotChange(callback: SlotChangeCallback): ClientSubscriptionId {\n    return this._makeSubscription(\n      {\n        callback,\n        method: 'slotSubscribe',\n        unsubscribeMethod: 'slotUnsubscribe',\n      },\n      [] /* args */,\n    );\n  }\n\n  /**\n   * Deregister a slot notification callback\n   *\n   * @param id client subscription id to deregister\n   */\n  async removeSlotChangeListener(\n    clientSubscriptionId: ClientSubscriptionId,\n  ): Promise<void> {\n    await this._unsubscribeClientSubscription(\n      clientSubscriptionId,\n      'slot change',\n    );\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnSlotUpdatesNotification(notification: Object) {\n    const {result, subscription} = create(\n      notification,\n      SlotUpdateNotificationResult,\n    );\n    this._handleServerNotification<SlotUpdateCallback>(subscription, [result]);\n  }\n\n  /**\n   * Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s\n   * may be useful to track live progress of a cluster.\n   *\n   * @param callback Function to invoke whenever the slot updates\n   * @return subscription id\n   */\n  onSlotUpdate(callback: SlotUpdateCallback): ClientSubscriptionId {\n    return this._makeSubscription(\n      {\n        callback,\n        method: 'slotsUpdatesSubscribe',\n        unsubscribeMethod: 'slotsUpdatesUnsubscribe',\n      },\n      [] /* args */,\n    );\n  }\n\n  /**\n   * Deregister a slot update notification callback\n   *\n   * @param id client subscription id to deregister\n   */\n  async removeSlotUpdateListener(\n    clientSubscriptionId: ClientSubscriptionId,\n  ): Promise<void> {\n    await this._unsubscribeClientSubscription(\n      clientSubscriptionId,\n      'slot update',\n    );\n  }\n\n  /**\n   * @internal\n   */\n\n  private async _unsubscribeClientSubscription(\n    clientSubscriptionId: ClientSubscriptionId,\n    subscriptionName: string,\n  ) {\n    const dispose =\n      this._subscriptionDisposeFunctionsByClientSubscriptionId[\n        clientSubscriptionId\n      ];\n    if (dispose) {\n      await dispose();\n    } else {\n      console.warn(\n        'Ignored unsubscribe request because an active subscription with id ' +\n          `\\`${clientSubscriptionId}\\` for '${subscriptionName}' events ` +\n          'could not be found.',\n      );\n    }\n  }\n\n  _buildArgs(\n    args: Array<any>,\n    override?: Commitment,\n    encoding?: 'jsonParsed' | 'base64',\n    extra?: any,\n  ): Array<any> {\n    const commitment = override || this._commitment;\n    if (commitment || encoding || extra) {\n      let options: any = {};\n      if (encoding) {\n        options.encoding = encoding;\n      }\n      if (commitment) {\n        options.commitment = commitment;\n      }\n      if (extra) {\n        options = Object.assign(options, extra);\n      }\n      args.push(options);\n    }\n    return args;\n  }\n\n  /**\n   * @internal\n   */\n  _buildArgsAtLeastConfirmed(\n    args: Array<any>,\n    override?: Finality,\n    encoding?: 'jsonParsed' | 'base64',\n    extra?: any,\n  ): Array<any> {\n    const commitment = override || this._commitment;\n    if (commitment && !['confirmed', 'finalized'].includes(commitment)) {\n      throw new Error(\n        'Using Connection with default commitment: `' +\n          this._commitment +\n          '`, but method requires at least `confirmed`',\n      );\n    }\n    return this._buildArgs(args, override, encoding, extra);\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnSignatureNotification(notification: Object) {\n    const {result, subscription} = create(\n      notification,\n      SignatureNotificationResult,\n    );\n    if (result.value !== 'receivedSignature') {\n      /**\n       * Special case.\n       * After a signature is processed, RPCs automatically dispose of the\n       * subscription on the server side. We need to track which of these\n       * subscriptions have been disposed in such a way, so that we know\n       * whether the client is dealing with a not-yet-processed signature\n       * (in which case we must tear down the server subscription) or an\n       * already-processed signature (in which case the client can simply\n       * clear out the subscription locally without telling the server).\n       *\n       * NOTE: There is a proposal to eliminate this special case, here:\n       * https://github.com/solana-labs/solana/issues/18892\n       */\n      this._subscriptionsAutoDisposedByRpc.add(subscription);\n    }\n    this._handleServerNotification<SignatureSubscriptionCallback>(\n      subscription,\n      result.value === 'receivedSignature'\n        ? [{type: 'received'}, result.context]\n        : [{type: 'status', result: result.value}, result.context],\n    );\n  }\n\n  /**\n   * Register a callback to be invoked upon signature updates\n   *\n   * @param signature Transaction signature string in base 58\n   * @param callback Function to invoke on signature notifications\n   * @param commitment Specify the commitment level signature must reach before notification\n   * @return subscription id\n   */\n  onSignature(\n    signature: TransactionSignature,\n    callback: SignatureResultCallback,\n    commitment?: Commitment,\n  ): ClientSubscriptionId {\n    const args = this._buildArgs(\n      [signature],\n      commitment || this._commitment || 'finalized', // Apply connection/server default.\n    );\n    const clientSubscriptionId = this._makeSubscription(\n      {\n        callback: (notification, context) => {\n          if (notification.type === 'status') {\n            callback(notification.result, context);\n            // Signatures subscriptions are auto-removed by the RPC service\n            // so no need to explicitly send an unsubscribe message.\n            try {\n              this.removeSignatureListener(clientSubscriptionId);\n              // eslint-disable-next-line no-empty\n            } catch (_err) {\n              // Already removed.\n            }\n          }\n        },\n        method: 'signatureSubscribe',\n        unsubscribeMethod: 'signatureUnsubscribe',\n      },\n      args,\n    );\n    return clientSubscriptionId;\n  }\n\n  /**\n   * Register a callback to be invoked when a transaction is\n   * received and/or processed.\n   *\n   * @param signature Transaction signature string in base 58\n   * @param callback Function to invoke on signature notifications\n   * @param options Enable received notifications and set the commitment\n   *   level that signature must reach before notification\n   * @return subscription id\n   */\n  onSignatureWithOptions(\n    signature: TransactionSignature,\n    callback: SignatureSubscriptionCallback,\n    options?: SignatureSubscriptionOptions,\n  ): ClientSubscriptionId {\n    const {commitment, ...extra} = {\n      ...options,\n      commitment:\n        (options && options.commitment) || this._commitment || 'finalized', // Apply connection/server default.\n    };\n    const args = this._buildArgs(\n      [signature],\n      commitment,\n      undefined /* encoding */,\n      extra,\n    );\n    const clientSubscriptionId = this._makeSubscription(\n      {\n        callback: (notification, context) => {\n          callback(notification, context);\n          // Signatures subscriptions are auto-removed by the RPC service\n          // so no need to explicitly send an unsubscribe message.\n          try {\n            this.removeSignatureListener(clientSubscriptionId);\n            // eslint-disable-next-line no-empty\n          } catch (_err) {\n            // Already removed.\n          }\n        },\n        method: 'signatureSubscribe',\n        unsubscribeMethod: 'signatureUnsubscribe',\n      },\n      args,\n    );\n    return clientSubscriptionId;\n  }\n\n  /**\n   * Deregister a signature notification callback\n   *\n   * @param id client subscription id to deregister\n   */\n  async removeSignatureListener(\n    clientSubscriptionId: ClientSubscriptionId,\n  ): Promise<void> {\n    await this._unsubscribeClientSubscription(\n      clientSubscriptionId,\n      'signature result',\n    );\n  }\n\n  /**\n   * @internal\n   */\n  _wsOnRootNotification(notification: Object) {\n    const {result, subscription} = create(notification, RootNotificationResult);\n    this._handleServerNotification<RootChangeCallback>(subscription, [result]);\n  }\n\n  /**\n   * Register a callback to be invoked upon root changes\n   *\n   * @param callback Function to invoke whenever the root changes\n   * @return subscription id\n   */\n  onRootChange(callback: RootChangeCallback): ClientSubscriptionId {\n    return this._makeSubscription(\n      {\n        callback,\n        method: 'rootSubscribe',\n        unsubscribeMethod: 'rootUnsubscribe',\n      },\n      [] /* args */,\n    );\n  }\n\n  /**\n   * Deregister a root notification callback\n   *\n   * @param id client subscription id to deregister\n   */\n  async removeRootChangeListener(\n    clientSubscriptionId: ClientSubscriptionId,\n  ): Promise<void> {\n    await this._unsubscribeClientSubscription(\n      clientSubscriptionId,\n      'root change',\n    );\n  }\n}\n","import {generateKeypair, getPublicKey, Ed25519Keypair} from './utils/ed25519';\nimport {PublicKey} from './publickey';\n\n/**\n * Keypair signer interface\n */\nexport interface Signer {\n  publicKey: PublicKey;\n  secretKey: Uint8Array;\n}\n\n/**\n * An account keypair used for signing transactions.\n */\nexport class Keypair {\n  private _keypair: Ed25519Keypair;\n\n  /**\n   * Create a new keypair instance.\n   * Generate random keypair if no {@link Ed25519Keypair} is provided.\n   *\n   * @param {Ed25519Keypair} keypair ed25519 keypair\n   */\n  constructor(keypair?: Ed25519Keypair) {\n    this._keypair = keypair ?? generateKeypair();\n  }\n\n  /**\n   * Generate a new random keypair\n   *\n   * @returns {Keypair} Keypair\n   */\n  static generate(): Keypair {\n    return new Keypair(generateKeypair());\n  }\n\n  /**\n   * Create a keypair from a raw secret key byte array.\n   *\n   * This method should only be used to recreate a keypair from a previously\n   * generated secret key. Generating keypairs from a random seed should be done\n   * with the {@link Keypair.fromSeed} method.\n   *\n   * @throws error if the provided secret key is invalid and validation is not skipped.\n   *\n   * @param secretKey secret key byte array\n   * @param options skip secret key validation\n   *\n   * @returns {Keypair} Keypair\n   */\n  static fromSecretKey(\n    secretKey: Uint8Array,\n    options?: {skipValidation?: boolean},\n  ): Keypair {\n    if (secretKey.byteLength !== 64) {\n      throw new Error('bad secret key size');\n    }\n    const publicKey = secretKey.slice(32, 64);\n    if (!options || !options.skipValidation) {\n      const privateScalar = secretKey.slice(0, 32);\n      const computedPublicKey = getPublicKey(privateScalar);\n      for (let ii = 0; ii < 32; ii++) {\n        if (publicKey[ii] !== computedPublicKey[ii]) {\n          throw new Error('provided secretKey is invalid');\n        }\n      }\n    }\n    return new Keypair({publicKey, secretKey});\n  }\n\n  /**\n   * Generate a keypair from a 32 byte seed.\n   *\n   * @param seed seed byte array\n   *\n   * @returns {Keypair} Keypair\n   */\n  static fromSeed(seed: Uint8Array): Keypair {\n    const publicKey = getPublicKey(seed);\n    const secretKey = new Uint8Array(64);\n    secretKey.set(seed);\n    secretKey.set(publicKey, 32);\n    return new Keypair({publicKey, secretKey});\n  }\n\n  /**\n   * The public key for this keypair\n   *\n   * @returns {PublicKey} PublicKey\n   */\n  get publicKey(): PublicKey {\n    return new PublicKey(this._keypair.publicKey);\n  }\n\n  /**\n   * The raw secret key for this keypair\n   * @returns {Uint8Array} Secret key in an array of Uint8 bytes\n   */\n  get secretKey(): Uint8Array {\n    return new Uint8Array(this._keypair.secretKey);\n  }\n}\n","import {toBufferLE} from 'bigint-buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport * as Layout from '../../layout';\nimport {PublicKey} from '../../publickey';\nimport * as bigintLayout from '../../utils/bigint';\nimport {SystemProgram} from '../system';\nimport {TransactionInstruction} from '../../transaction';\nimport {decodeData, encodeData, IInstructionInputData} from '../../instruction';\n\nexport * from './state';\n\nexport type CreateLookupTableParams = {\n  /** Account used to derive and control the new address lookup table. */\n  authority: PublicKey;\n  /** Account that will fund the new address lookup table. */\n  payer: PublicKey;\n  /** A recent slot must be used in the derivation path for each initialized table. */\n  recentSlot: bigint | number;\n};\n\nexport type FreezeLookupTableParams = {\n  /** Address lookup table account to freeze. */\n  lookupTable: PublicKey;\n  /** Account which is the current authority. */\n  authority: PublicKey;\n};\n\nexport type ExtendLookupTableParams = {\n  /** Address lookup table account to extend. */\n  lookupTable: PublicKey;\n  /** Account which is the current authority. */\n  authority: PublicKey;\n  /** Account that will fund the table reallocation.\n   * Not required if the reallocation has already been funded. */\n  payer?: PublicKey;\n  /** List of Public Keys to be added to the lookup table. */\n  addresses: Array<PublicKey>;\n};\n\nexport type DeactivateLookupTableParams = {\n  /** Address lookup table account to deactivate. */\n  lookupTable: PublicKey;\n  /** Account which is the current authority. */\n  authority: PublicKey;\n};\n\nexport type CloseLookupTableParams = {\n  /** Address lookup table account to close. */\n  lookupTable: PublicKey;\n  /** Account which is the current authority. */\n  authority: PublicKey;\n  /** Recipient of closed account lamports. */\n  recipient: PublicKey;\n};\n\n/**\n * An enumeration of valid LookupTableInstructionType's\n */\nexport type LookupTableInstructionType =\n  | 'CreateLookupTable'\n  | 'ExtendLookupTable'\n  | 'CloseLookupTable'\n  | 'FreezeLookupTable'\n  | 'DeactivateLookupTable';\n\ntype LookupTableInstructionInputData = {\n  CreateLookupTable: IInstructionInputData &\n    Readonly<{\n      recentSlot: bigint;\n      bumpSeed: number;\n    }>;\n  FreezeLookupTable: IInstructionInputData;\n  ExtendLookupTable: IInstructionInputData &\n    Readonly<{\n      numberOfAddresses: bigint;\n      addresses: Array<Uint8Array>;\n    }>;\n  DeactivateLookupTable: IInstructionInputData;\n  CloseLookupTable: IInstructionInputData;\n};\n\n/**\n * An enumeration of valid address lookup table InstructionType's\n * @internal\n */\nexport const LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({\n  CreateLookupTable: {\n    index: 0,\n    layout: BufferLayout.struct<\n      LookupTableInstructionInputData['CreateLookupTable']\n    >([\n      BufferLayout.u32('instruction'),\n      bigintLayout.u64('recentSlot'),\n      BufferLayout.u8('bumpSeed'),\n    ]),\n  },\n  FreezeLookupTable: {\n    index: 1,\n    layout: BufferLayout.struct<\n      LookupTableInstructionInputData['FreezeLookupTable']\n    >([BufferLayout.u32('instruction')]),\n  },\n  ExtendLookupTable: {\n    index: 2,\n    layout: BufferLayout.struct<\n      LookupTableInstructionInputData['ExtendLookupTable']\n    >([\n      BufferLayout.u32('instruction'),\n      bigintLayout.u64(),\n      BufferLayout.seq(\n        Layout.publicKey(),\n        BufferLayout.offset(BufferLayout.u32(), -8),\n        'addresses',\n      ),\n    ]),\n  },\n  DeactivateLookupTable: {\n    index: 3,\n    layout: BufferLayout.struct<\n      LookupTableInstructionInputData['DeactivateLookupTable']\n    >([BufferLayout.u32('instruction')]),\n  },\n  CloseLookupTable: {\n    index: 4,\n    layout: BufferLayout.struct<\n      LookupTableInstructionInputData['CloseLookupTable']\n    >([BufferLayout.u32('instruction')]),\n  },\n});\n\nexport class AddressLookupTableInstruction {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  static decodeInstructionType(\n    instruction: TransactionInstruction,\n  ): LookupTableInstructionType {\n    this.checkProgramId(instruction.programId);\n\n    const instructionTypeLayout = BufferLayout.u32('instruction');\n    const index = instructionTypeLayout.decode(instruction.data);\n\n    let type: LookupTableInstructionType | undefined;\n    for (const [layoutType, layout] of Object.entries(\n      LOOKUP_TABLE_INSTRUCTION_LAYOUTS,\n    )) {\n      if ((layout as any).index == index) {\n        type = layoutType as LookupTableInstructionType;\n        break;\n      }\n    }\n    if (!type) {\n      throw new Error(\n        'Invalid Instruction. Should be a LookupTable Instruction',\n      );\n    }\n    return type;\n  }\n\n  static decodeCreateLookupTable(\n    instruction: TransactionInstruction,\n  ): CreateLookupTableParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeysLength(instruction.keys, 4);\n\n    const {recentSlot} = decodeData(\n      LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable,\n      instruction.data,\n    );\n\n    return {\n      authority: instruction.keys[1].pubkey,\n      payer: instruction.keys[2].pubkey,\n      recentSlot: Number(recentSlot),\n    };\n  }\n\n  static decodeExtendLookupTable(\n    instruction: TransactionInstruction,\n  ): ExtendLookupTableParams {\n    this.checkProgramId(instruction.programId);\n    if (instruction.keys.length < 2) {\n      throw new Error(\n        `invalid instruction; found ${instruction.keys.length} keys, expected at least 2`,\n      );\n    }\n\n    const {addresses} = decodeData(\n      LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable,\n      instruction.data,\n    );\n    return {\n      lookupTable: instruction.keys[0].pubkey,\n      authority: instruction.keys[1].pubkey,\n      payer:\n        instruction.keys.length > 2 ? instruction.keys[2].pubkey : undefined,\n      addresses: addresses.map(buffer => new PublicKey(buffer)),\n    };\n  }\n\n  static decodeCloseLookupTable(\n    instruction: TransactionInstruction,\n  ): CloseLookupTableParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeysLength(instruction.keys, 3);\n\n    return {\n      lookupTable: instruction.keys[0].pubkey,\n      authority: instruction.keys[1].pubkey,\n      recipient: instruction.keys[2].pubkey,\n    };\n  }\n\n  static decodeFreezeLookupTable(\n    instruction: TransactionInstruction,\n  ): FreezeLookupTableParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeysLength(instruction.keys, 2);\n\n    return {\n      lookupTable: instruction.keys[0].pubkey,\n      authority: instruction.keys[1].pubkey,\n    };\n  }\n\n  static decodeDeactivateLookupTable(\n    instruction: TransactionInstruction,\n  ): DeactivateLookupTableParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeysLength(instruction.keys, 2);\n\n    return {\n      lookupTable: instruction.keys[0].pubkey,\n      authority: instruction.keys[1].pubkey,\n    };\n  }\n\n  /**\n   * @internal\n   */\n  static checkProgramId(programId: PublicKey) {\n    if (!programId.equals(AddressLookupTableProgram.programId)) {\n      throw new Error(\n        'invalid instruction; programId is not AddressLookupTable Program',\n      );\n    }\n  }\n  /**\n   * @internal\n   */\n  static checkKeysLength(keys: Array<any>, expectedLength: number) {\n    if (keys.length < expectedLength) {\n      throw new Error(\n        `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n      );\n    }\n  }\n}\n\nexport class AddressLookupTableProgram {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  static programId: PublicKey = new PublicKey(\n    'AddressLookupTab1e1111111111111111111111111',\n  );\n\n  static createLookupTable(params: CreateLookupTableParams) {\n    const [lookupTableAddress, bumpSeed] = PublicKey.findProgramAddressSync(\n      [params.authority.toBuffer(), toBufferLE(BigInt(params.recentSlot), 8)],\n      this.programId,\n    );\n\n    const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;\n    const data = encodeData(type, {\n      recentSlot: BigInt(params.recentSlot),\n      bumpSeed: bumpSeed,\n    });\n\n    const keys = [\n      {\n        pubkey: lookupTableAddress,\n        isSigner: false,\n        isWritable: true,\n      },\n      {\n        pubkey: params.authority,\n        isSigner: true,\n        isWritable: false,\n      },\n      {\n        pubkey: params.payer,\n        isSigner: true,\n        isWritable: true,\n      },\n      {\n        pubkey: SystemProgram.programId,\n        isSigner: false,\n        isWritable: false,\n      },\n    ];\n\n    return [\n      new TransactionInstruction({\n        programId: this.programId,\n        keys: keys,\n        data: data,\n      }),\n      lookupTableAddress,\n    ] as [TransactionInstruction, PublicKey];\n  }\n\n  static freezeLookupTable(params: FreezeLookupTableParams) {\n    const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;\n    const data = encodeData(type);\n\n    const keys = [\n      {\n        pubkey: params.lookupTable,\n        isSigner: false,\n        isWritable: true,\n      },\n      {\n        pubkey: params.authority,\n        isSigner: true,\n        isWritable: false,\n      },\n    ];\n\n    return new TransactionInstruction({\n      programId: this.programId,\n      keys: keys,\n      data: data,\n    });\n  }\n\n  static extendLookupTable(params: ExtendLookupTableParams) {\n    const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;\n    const data = encodeData(type, {\n      addresses: params.addresses.map(addr => addr.toBytes()),\n    });\n\n    const keys = [\n      {\n        pubkey: params.lookupTable,\n        isSigner: false,\n        isWritable: true,\n      },\n      {\n        pubkey: params.authority,\n        isSigner: true,\n        isWritable: false,\n      },\n    ];\n\n    if (params.payer) {\n      keys.push(\n        {\n          pubkey: params.payer,\n          isSigner: true,\n          isWritable: true,\n        },\n        {\n          pubkey: SystemProgram.programId,\n          isSigner: false,\n          isWritable: false,\n        },\n      );\n    }\n\n    return new TransactionInstruction({\n      programId: this.programId,\n      keys: keys,\n      data: data,\n    });\n  }\n\n  static deactivateLookupTable(params: DeactivateLookupTableParams) {\n    const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;\n    const data = encodeData(type);\n\n    const keys = [\n      {\n        pubkey: params.lookupTable,\n        isSigner: false,\n        isWritable: true,\n      },\n      {\n        pubkey: params.authority,\n        isSigner: true,\n        isWritable: false,\n      },\n    ];\n\n    return new TransactionInstruction({\n      programId: this.programId,\n      keys: keys,\n      data: data,\n    });\n  }\n\n  static closeLookupTable(params: CloseLookupTableParams) {\n    const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;\n    const data = encodeData(type);\n\n    const keys = [\n      {\n        pubkey: params.lookupTable,\n        isSigner: false,\n        isWritable: true,\n      },\n      {\n        pubkey: params.authority,\n        isSigner: true,\n        isWritable: false,\n      },\n      {\n        pubkey: params.recipient,\n        isSigner: false,\n        isWritable: true,\n      },\n    ];\n\n    return new TransactionInstruction({\n      programId: this.programId,\n      keys: keys,\n      data: data,\n    });\n  }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n  encodeData,\n  decodeData,\n  InstructionType,\n  IInstructionInputData,\n} from '../instruction';\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport {u64} from '../utils/bigint';\n\n/**\n * Compute Budget Instruction class\n */\nexport class ComputeBudgetInstruction {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Decode a compute budget instruction and retrieve the instruction type.\n   */\n  static decodeInstructionType(\n    instruction: TransactionInstruction,\n  ): ComputeBudgetInstructionType {\n    this.checkProgramId(instruction.programId);\n\n    const instructionTypeLayout = BufferLayout.u8('instruction');\n    const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n    let type: ComputeBudgetInstructionType | undefined;\n    for (const [ixType, layout] of Object.entries(\n      COMPUTE_BUDGET_INSTRUCTION_LAYOUTS,\n    )) {\n      if (layout.index == typeIndex) {\n        type = ixType as ComputeBudgetInstructionType;\n        break;\n      }\n    }\n\n    if (!type) {\n      throw new Error(\n        'Instruction type incorrect; not a ComputeBudgetInstruction',\n      );\n    }\n\n    return type;\n  }\n\n  /**\n   * Decode request units compute budget instruction and retrieve the instruction params.\n   */\n  static decodeRequestUnits(\n    instruction: TransactionInstruction,\n  ): RequestUnitsParams {\n    this.checkProgramId(instruction.programId);\n    const {units, additionalFee} = decodeData(\n      COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits,\n      instruction.data,\n    );\n    return {units, additionalFee};\n  }\n\n  /**\n   * Decode request heap frame compute budget instruction and retrieve the instruction params.\n   */\n  static decodeRequestHeapFrame(\n    instruction: TransactionInstruction,\n  ): RequestHeapFrameParams {\n    this.checkProgramId(instruction.programId);\n    const {bytes} = decodeData(\n      COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame,\n      instruction.data,\n    );\n    return {bytes};\n  }\n\n  /**\n   * Decode set compute unit limit compute budget instruction and retrieve the instruction params.\n   */\n  static decodeSetComputeUnitLimit(\n    instruction: TransactionInstruction,\n  ): SetComputeUnitLimitParams {\n    this.checkProgramId(instruction.programId);\n    const {units} = decodeData(\n      COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit,\n      instruction.data,\n    );\n    return {units};\n  }\n\n  /**\n   * Decode set compute unit price compute budget instruction and retrieve the instruction params.\n   */\n  static decodeSetComputeUnitPrice(\n    instruction: TransactionInstruction,\n  ): SetComputeUnitPriceParams {\n    this.checkProgramId(instruction.programId);\n    const {microLamports} = decodeData(\n      COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice,\n      instruction.data,\n    );\n    return {microLamports};\n  }\n\n  /**\n   * @internal\n   */\n  static checkProgramId(programId: PublicKey) {\n    if (!programId.equals(ComputeBudgetProgram.programId)) {\n      throw new Error(\n        'invalid instruction; programId is not ComputeBudgetProgram',\n      );\n    }\n  }\n}\n\n/**\n * An enumeration of valid ComputeBudgetInstructionType's\n */\nexport type ComputeBudgetInstructionType =\n  // FIXME\n  // It would be preferable for this type to be `keyof ComputeBudgetInstructionInputData`\n  // but Typedoc does not transpile `keyof` expressions.\n  // See https://github.com/TypeStrong/typedoc/issues/1894\n  | 'RequestUnits'\n  | 'RequestHeapFrame'\n  | 'SetComputeUnitLimit'\n  | 'SetComputeUnitPrice';\n\ntype ComputeBudgetInstructionInputData = {\n  RequestUnits: IInstructionInputData & Readonly<RequestUnitsParams>;\n  RequestHeapFrame: IInstructionInputData & Readonly<RequestHeapFrameParams>;\n  SetComputeUnitLimit: IInstructionInputData &\n    Readonly<SetComputeUnitLimitParams>;\n  SetComputeUnitPrice: IInstructionInputData &\n    Readonly<SetComputeUnitPriceParams>;\n};\n\n/**\n * Request units instruction params\n */\nexport interface RequestUnitsParams {\n  /** Units to request for transaction-wide compute */\n  units: number;\n  /** Prioritization fee lamports */\n  additionalFee: number;\n}\n\n/**\n * Request heap frame instruction params\n */\nexport type RequestHeapFrameParams = {\n  /** Requested transaction-wide program heap size in bytes. Must be multiple of 1024. Applies to each program, including CPIs. */\n  bytes: number;\n};\n\n/**\n * Set compute unit limit instruction params\n */\nexport interface SetComputeUnitLimitParams {\n  /** Transaction-wide compute unit limit */\n  units: number;\n}\n\n/**\n * Set compute unit price instruction params\n */\nexport interface SetComputeUnitPriceParams {\n  /** Transaction compute unit price used for prioritization fees */\n  microLamports: number | bigint;\n}\n\n/**\n * An enumeration of valid ComputeBudget InstructionType's\n * @internal\n */\nexport const COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze<{\n  [Instruction in ComputeBudgetInstructionType]: InstructionType<\n    ComputeBudgetInstructionInputData[Instruction]\n  >;\n}>({\n  RequestUnits: {\n    index: 0,\n    layout: BufferLayout.struct<\n      ComputeBudgetInstructionInputData['RequestUnits']\n    >([\n      BufferLayout.u8('instruction'),\n      BufferLayout.u32('units'),\n      BufferLayout.u32('additionalFee'),\n    ]),\n  },\n  RequestHeapFrame: {\n    index: 1,\n    layout: BufferLayout.struct<\n      ComputeBudgetInstructionInputData['RequestHeapFrame']\n    >([BufferLayout.u8('instruction'), BufferLayout.u32('bytes')]),\n  },\n  SetComputeUnitLimit: {\n    index: 2,\n    layout: BufferLayout.struct<\n      ComputeBudgetInstructionInputData['SetComputeUnitLimit']\n    >([BufferLayout.u8('instruction'), BufferLayout.u32('units')]),\n  },\n  SetComputeUnitPrice: {\n    index: 3,\n    layout: BufferLayout.struct<\n      ComputeBudgetInstructionInputData['SetComputeUnitPrice']\n    >([BufferLayout.u8('instruction'), u64('microLamports')]),\n  },\n});\n\n/**\n * Factory class for transaction instructions to interact with the Compute Budget program\n */\nexport class ComputeBudgetProgram {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Public key that identifies the Compute Budget program\n   */\n  static programId: PublicKey = new PublicKey(\n    'ComputeBudget111111111111111111111111111111',\n  );\n\n  /**\n   * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}\n   */\n  static requestUnits(params: RequestUnitsParams): TransactionInstruction {\n    const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;\n    const data = encodeData(type, params);\n    return new TransactionInstruction({\n      keys: [],\n      programId: this.programId,\n      data,\n    });\n  }\n\n  static requestHeapFrame(\n    params: RequestHeapFrameParams,\n  ): TransactionInstruction {\n    const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;\n    const data = encodeData(type, params);\n    return new TransactionInstruction({\n      keys: [],\n      programId: this.programId,\n      data,\n    });\n  }\n\n  static setComputeUnitLimit(\n    params: SetComputeUnitLimitParams,\n  ): TransactionInstruction {\n    const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;\n    const data = encodeData(type, params);\n    return new TransactionInstruction({\n      keys: [],\n      programId: this.programId,\n      data,\n    });\n  }\n\n  static setComputeUnitPrice(\n    params: SetComputeUnitPriceParams,\n  ): TransactionInstruction {\n    const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;\n    const data = encodeData(type, {\n      microLamports: BigInt(params.microLamports),\n    });\n    return new TransactionInstruction({\n      keys: [],\n      programId: this.programId,\n      data,\n    });\n  }\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {Keypair} from '../keypair';\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport assert from '../utils/assert';\nimport {sign} from '../utils/ed25519';\n\nconst PRIVATE_KEY_BYTES = 64;\nconst PUBLIC_KEY_BYTES = 32;\nconst SIGNATURE_BYTES = 64;\n\n/**\n * Params for creating an ed25519 instruction using a public key\n */\nexport type CreateEd25519InstructionWithPublicKeyParams = {\n  publicKey: Uint8Array;\n  message: Uint8Array;\n  signature: Uint8Array;\n  instructionIndex?: number;\n};\n\n/**\n * Params for creating an ed25519 instruction using a private key\n */\nexport type CreateEd25519InstructionWithPrivateKeyParams = {\n  privateKey: Uint8Array;\n  message: Uint8Array;\n  instructionIndex?: number;\n};\n\nconst ED25519_INSTRUCTION_LAYOUT = BufferLayout.struct<\n  Readonly<{\n    messageDataOffset: number;\n    messageDataSize: number;\n    messageInstructionIndex: number;\n    numSignatures: number;\n    padding: number;\n    publicKeyInstructionIndex: number;\n    publicKeyOffset: number;\n    signatureInstructionIndex: number;\n    signatureOffset: number;\n  }>\n>([\n  BufferLayout.u8('numSignatures'),\n  BufferLayout.u8('padding'),\n  BufferLayout.u16('signatureOffset'),\n  BufferLayout.u16('signatureInstructionIndex'),\n  BufferLayout.u16('publicKeyOffset'),\n  BufferLayout.u16('publicKeyInstructionIndex'),\n  BufferLayout.u16('messageDataOffset'),\n  BufferLayout.u16('messageDataSize'),\n  BufferLayout.u16('messageInstructionIndex'),\n]);\n\nexport class Ed25519Program {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Public key that identifies the ed25519 program\n   */\n  static programId: PublicKey = new PublicKey(\n    'Ed25519SigVerify111111111111111111111111111',\n  );\n\n  /**\n   * Create an ed25519 instruction with a public key and signature. The\n   * public key must be a buffer that is 32 bytes long, and the signature\n   * must be a buffer of 64 bytes.\n   */\n  static createInstructionWithPublicKey(\n    params: CreateEd25519InstructionWithPublicKeyParams,\n  ): TransactionInstruction {\n    const {publicKey, message, signature, instructionIndex} = params;\n\n    assert(\n      publicKey.length === PUBLIC_KEY_BYTES,\n      `Public Key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`,\n    );\n\n    assert(\n      signature.length === SIGNATURE_BYTES,\n      `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`,\n    );\n\n    const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;\n    const signatureOffset = publicKeyOffset + publicKey.length;\n    const messageDataOffset = signatureOffset + signature.length;\n    const numSignatures = 1;\n\n    const instructionData = Buffer.alloc(messageDataOffset + message.length);\n\n    const index =\n      instructionIndex == null\n        ? 0xffff // An index of `u16::MAX` makes it default to the current instruction.\n        : instructionIndex;\n\n    ED25519_INSTRUCTION_LAYOUT.encode(\n      {\n        numSignatures,\n        padding: 0,\n        signatureOffset,\n        signatureInstructionIndex: index,\n        publicKeyOffset,\n        publicKeyInstructionIndex: index,\n        messageDataOffset,\n        messageDataSize: message.length,\n        messageInstructionIndex: index,\n      },\n      instructionData,\n    );\n\n    instructionData.fill(publicKey, publicKeyOffset);\n    instructionData.fill(signature, signatureOffset);\n    instructionData.fill(message, messageDataOffset);\n\n    return new TransactionInstruction({\n      keys: [],\n      programId: Ed25519Program.programId,\n      data: instructionData,\n    });\n  }\n\n  /**\n   * Create an ed25519 instruction with a private key. The private key\n   * must be a buffer that is 64 bytes long.\n   */\n  static createInstructionWithPrivateKey(\n    params: CreateEd25519InstructionWithPrivateKeyParams,\n  ): TransactionInstruction {\n    const {privateKey, message, instructionIndex} = params;\n\n    assert(\n      privateKey.length === PRIVATE_KEY_BYTES,\n      `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${privateKey.length} bytes`,\n    );\n\n    try {\n      const keypair = Keypair.fromSecretKey(privateKey);\n      const publicKey = keypair.publicKey.toBytes();\n      const signature = sign(message, keypair.secretKey);\n\n      return this.createInstructionWithPublicKey({\n        publicKey,\n        message,\n        signature,\n        instructionIndex,\n      });\n    } catch (error) {\n      throw new Error(`Error creating instruction; ${error}`);\n    }\n  }\n}\n","import {secp256k1} from '@noble/curves/secp256k1';\n\nexport const ecdsaSign = (\n  msgHash: Parameters<typeof secp256k1.sign>[0],\n  privKey: Parameters<typeof secp256k1.sign>[1],\n) => {\n  const signature = secp256k1.sign(msgHash, privKey);\n  return [signature.toCompactRawBytes(), signature.recovery!] as const;\n};\nexport const isValidPrivateKey = secp256k1.utils.isValidPrivateKey;\nexport const publicKeyCreate = secp256k1.getPublicKey;\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\nimport {keccak_256} from '@noble/hashes/sha3';\n\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport assert from '../utils/assert';\nimport {publicKeyCreate, ecdsaSign} from '../utils/secp256k1';\nimport {toBuffer} from '../utils/to-buffer';\n\nconst PRIVATE_KEY_BYTES = 32;\nconst ETHEREUM_ADDRESS_BYTES = 20;\nconst PUBLIC_KEY_BYTES = 64;\nconst SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;\n\n/**\n * Params for creating an secp256k1 instruction using a public key\n */\nexport type CreateSecp256k1InstructionWithPublicKeyParams = {\n  publicKey: Buffer | Uint8Array | Array<number>;\n  message: Buffer | Uint8Array | Array<number>;\n  signature: Buffer | Uint8Array | Array<number>;\n  recoveryId: number;\n  instructionIndex?: number;\n};\n\n/**\n * Params for creating an secp256k1 instruction using an Ethereum address\n */\nexport type CreateSecp256k1InstructionWithEthAddressParams = {\n  ethAddress: Buffer | Uint8Array | Array<number> | string;\n  message: Buffer | Uint8Array | Array<number>;\n  signature: Buffer | Uint8Array | Array<number>;\n  recoveryId: number;\n  instructionIndex?: number;\n};\n\n/**\n * Params for creating an secp256k1 instruction using a private key\n */\nexport type CreateSecp256k1InstructionWithPrivateKeyParams = {\n  privateKey: Buffer | Uint8Array | Array<number>;\n  message: Buffer | Uint8Array | Array<number>;\n  instructionIndex?: number;\n};\n\nconst SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct<\n  Readonly<{\n    ethAddress: Uint8Array;\n    ethAddressInstructionIndex: number;\n    ethAddressOffset: number;\n    messageDataOffset: number;\n    messageDataSize: number;\n    messageInstructionIndex: number;\n    numSignatures: number;\n    recoveryId: number;\n    signature: Uint8Array;\n    signatureInstructionIndex: number;\n    signatureOffset: number;\n  }>\n>([\n  BufferLayout.u8('numSignatures'),\n  BufferLayout.u16('signatureOffset'),\n  BufferLayout.u8('signatureInstructionIndex'),\n  BufferLayout.u16('ethAddressOffset'),\n  BufferLayout.u8('ethAddressInstructionIndex'),\n  BufferLayout.u16('messageDataOffset'),\n  BufferLayout.u16('messageDataSize'),\n  BufferLayout.u8('messageInstructionIndex'),\n  BufferLayout.blob(20, 'ethAddress'),\n  BufferLayout.blob(64, 'signature'),\n  BufferLayout.u8('recoveryId'),\n]);\n\nexport class Secp256k1Program {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Public key that identifies the secp256k1 program\n   */\n  static programId: PublicKey = new PublicKey(\n    'KeccakSecp256k11111111111111111111111111111',\n  );\n\n  /**\n   * Construct an Ethereum address from a secp256k1 public key buffer.\n   * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer\n   */\n  static publicKeyToEthAddress(\n    publicKey: Buffer | Uint8Array | Array<number>,\n  ): Buffer {\n    assert(\n      publicKey.length === PUBLIC_KEY_BYTES,\n      `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`,\n    );\n\n    try {\n      return Buffer.from(keccak_256(toBuffer(publicKey))).slice(\n        -ETHEREUM_ADDRESS_BYTES,\n      );\n    } catch (error) {\n      throw new Error(`Error constructing Ethereum address: ${error}`);\n    }\n  }\n\n  /**\n   * Create an secp256k1 instruction with a public key. The public key\n   * must be a buffer that is 64 bytes long.\n   */\n  static createInstructionWithPublicKey(\n    params: CreateSecp256k1InstructionWithPublicKeyParams,\n  ): TransactionInstruction {\n    const {publicKey, message, signature, recoveryId, instructionIndex} =\n      params;\n    return Secp256k1Program.createInstructionWithEthAddress({\n      ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey),\n      message,\n      signature,\n      recoveryId,\n      instructionIndex,\n    });\n  }\n\n  /**\n   * Create an secp256k1 instruction with an Ethereum address. The address\n   * must be a hex string or a buffer that is 20 bytes long.\n   */\n  static createInstructionWithEthAddress(\n    params: CreateSecp256k1InstructionWithEthAddressParams,\n  ): TransactionInstruction {\n    const {\n      ethAddress: rawAddress,\n      message,\n      signature,\n      recoveryId,\n      instructionIndex = 0,\n    } = params;\n\n    let ethAddress;\n    if (typeof rawAddress === 'string') {\n      if (rawAddress.startsWith('0x')) {\n        ethAddress = Buffer.from(rawAddress.substr(2), 'hex');\n      } else {\n        ethAddress = Buffer.from(rawAddress, 'hex');\n      }\n    } else {\n      ethAddress = rawAddress;\n    }\n\n    assert(\n      ethAddress.length === ETHEREUM_ADDRESS_BYTES,\n      `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`,\n    );\n\n    const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;\n    const ethAddressOffset = dataStart;\n    const signatureOffset = dataStart + ethAddress.length;\n    const messageDataOffset = signatureOffset + signature.length + 1;\n    const numSignatures = 1;\n\n    const instructionData = Buffer.alloc(\n      SECP256K1_INSTRUCTION_LAYOUT.span + message.length,\n    );\n\n    SECP256K1_INSTRUCTION_LAYOUT.encode(\n      {\n        numSignatures,\n        signatureOffset,\n        signatureInstructionIndex: instructionIndex,\n        ethAddressOffset,\n        ethAddressInstructionIndex: instructionIndex,\n        messageDataOffset,\n        messageDataSize: message.length,\n        messageInstructionIndex: instructionIndex,\n        signature: toBuffer(signature),\n        ethAddress: toBuffer(ethAddress),\n        recoveryId,\n      },\n      instructionData,\n    );\n\n    instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);\n\n    return new TransactionInstruction({\n      keys: [],\n      programId: Secp256k1Program.programId,\n      data: instructionData,\n    });\n  }\n\n  /**\n   * Create an secp256k1 instruction with a private key. The private key\n   * must be a buffer that is 32 bytes long.\n   */\n  static createInstructionWithPrivateKey(\n    params: CreateSecp256k1InstructionWithPrivateKeyParams,\n  ): TransactionInstruction {\n    const {privateKey: pkey, message, instructionIndex} = params;\n\n    assert(\n      pkey.length === PRIVATE_KEY_BYTES,\n      `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`,\n    );\n\n    try {\n      const privateKey = toBuffer(pkey);\n      const publicKey = publicKeyCreate(\n        privateKey,\n        false /* isCompressed */,\n      ).slice(1); // throw away leading byte\n      const messageHash = Buffer.from(keccak_256(toBuffer(message)));\n      const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);\n\n      return this.createInstructionWithPublicKey({\n        publicKey,\n        message,\n        signature,\n        recoveryId,\n        instructionIndex,\n      });\n    } catch (error) {\n      throw new Error(`Error creating instruction; ${error}`);\n    }\n  }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n  encodeData,\n  decodeData,\n  InstructionType,\n  IInstructionInputData,\n} from '../instruction';\nimport * as Layout from '../layout';\nimport {PublicKey} from '../publickey';\nimport {SystemProgram} from './system';\nimport {\n  SYSVAR_CLOCK_PUBKEY,\n  SYSVAR_RENT_PUBKEY,\n  SYSVAR_STAKE_HISTORY_PUBKEY,\n} from '../sysvar';\nimport {Transaction, TransactionInstruction} from '../transaction';\nimport {toBuffer} from '../utils/to-buffer';\n\n/**\n * Address of the stake config account which configures the rate\n * of stake warmup and cooldown as well as the slashing penalty.\n */\nexport const STAKE_CONFIG_ID = new PublicKey(\n  'StakeConfig11111111111111111111111111111111',\n);\n\n/**\n * Stake account authority info\n */\nexport class Authorized {\n  /** stake authority */\n  staker: PublicKey;\n  /** withdraw authority */\n  withdrawer: PublicKey;\n\n  /**\n   * Create a new Authorized object\n   * @param staker the stake authority\n   * @param withdrawer the withdraw authority\n   */\n  constructor(staker: PublicKey, withdrawer: PublicKey) {\n    this.staker = staker;\n    this.withdrawer = withdrawer;\n  }\n}\n\ntype AuthorizedRaw = Readonly<{\n  staker: Uint8Array;\n  withdrawer: Uint8Array;\n}>;\n\n/**\n * Stake account lockup info\n */\nexport class Lockup {\n  /** Unix timestamp of lockup expiration */\n  unixTimestamp: number;\n  /** Epoch of lockup expiration */\n  epoch: number;\n  /** Lockup custodian authority */\n  custodian: PublicKey;\n\n  /**\n   * Create a new Lockup object\n   */\n  constructor(unixTimestamp: number, epoch: number, custodian: PublicKey) {\n    this.unixTimestamp = unixTimestamp;\n    this.epoch = epoch;\n    this.custodian = custodian;\n  }\n\n  /**\n   * Default, inactive Lockup value\n   */\n  static default: Lockup = new Lockup(0, 0, PublicKey.default);\n}\n\ntype LockupRaw = Readonly<{\n  custodian: Uint8Array;\n  epoch: number;\n  unixTimestamp: number;\n}>;\n\n/**\n * Create stake account transaction params\n */\nexport type CreateStakeAccountParams = {\n  /** Address of the account which will fund creation */\n  fromPubkey: PublicKey;\n  /** Address of the new stake account */\n  stakePubkey: PublicKey;\n  /** Authorities of the new stake account */\n  authorized: Authorized;\n  /** Lockup of the new stake account */\n  lockup?: Lockup;\n  /** Funding amount */\n  lamports: number;\n};\n\n/**\n * Create stake account with seed transaction params\n */\nexport type CreateStakeAccountWithSeedParams = {\n  fromPubkey: PublicKey;\n  stakePubkey: PublicKey;\n  basePubkey: PublicKey;\n  seed: string;\n  authorized: Authorized;\n  lockup?: Lockup;\n  lamports: number;\n};\n\n/**\n * Initialize stake instruction params\n */\nexport type InitializeStakeParams = {\n  stakePubkey: PublicKey;\n  authorized: Authorized;\n  lockup?: Lockup;\n};\n\n/**\n * Delegate stake instruction params\n */\nexport type DelegateStakeParams = {\n  stakePubkey: PublicKey;\n  authorizedPubkey: PublicKey;\n  votePubkey: PublicKey;\n};\n\n/**\n * Authorize stake instruction params\n */\nexport type AuthorizeStakeParams = {\n  stakePubkey: PublicKey;\n  authorizedPubkey: PublicKey;\n  newAuthorizedPubkey: PublicKey;\n  stakeAuthorizationType: StakeAuthorizationType;\n  custodianPubkey?: PublicKey;\n};\n\n/**\n * Authorize stake instruction params using a derived key\n */\nexport type AuthorizeWithSeedStakeParams = {\n  stakePubkey: PublicKey;\n  authorityBase: PublicKey;\n  authoritySeed: string;\n  authorityOwner: PublicKey;\n  newAuthorizedPubkey: PublicKey;\n  stakeAuthorizationType: StakeAuthorizationType;\n  custodianPubkey?: PublicKey;\n};\n\n/**\n * Split stake instruction params\n */\nexport type SplitStakeParams = {\n  stakePubkey: PublicKey;\n  authorizedPubkey: PublicKey;\n  splitStakePubkey: PublicKey;\n  lamports: number;\n};\n\n/**\n * Split with seed transaction params\n */\nexport type SplitStakeWithSeedParams = {\n  stakePubkey: PublicKey;\n  authorizedPubkey: PublicKey;\n  splitStakePubkey: PublicKey;\n  basePubkey: PublicKey;\n  seed: string;\n  lamports: number;\n};\n\n/**\n * Withdraw stake instruction params\n */\nexport type WithdrawStakeParams = {\n  stakePubkey: PublicKey;\n  authorizedPubkey: PublicKey;\n  toPubkey: PublicKey;\n  lamports: number;\n  custodianPubkey?: PublicKey;\n};\n\n/**\n * Deactivate stake instruction params\n */\nexport type DeactivateStakeParams = {\n  stakePubkey: PublicKey;\n  authorizedPubkey: PublicKey;\n};\n\n/**\n * Merge stake instruction params\n */\nexport type MergeStakeParams = {\n  stakePubkey: PublicKey;\n  sourceStakePubKey: PublicKey;\n  authorizedPubkey: PublicKey;\n};\n\n/**\n * Stake Instruction class\n */\nexport class StakeInstruction {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Decode a stake instruction and retrieve the instruction type.\n   */\n  static decodeInstructionType(\n    instruction: TransactionInstruction,\n  ): StakeInstructionType {\n    this.checkProgramId(instruction.programId);\n\n    const instructionTypeLayout = BufferLayout.u32('instruction');\n    const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n    let type: StakeInstructionType | undefined;\n    for (const [ixType, layout] of Object.entries(STAKE_INSTRUCTION_LAYOUTS)) {\n      if (layout.index == typeIndex) {\n        type = ixType as StakeInstructionType;\n        break;\n      }\n    }\n\n    if (!type) {\n      throw new Error('Instruction type incorrect; not a StakeInstruction');\n    }\n\n    return type;\n  }\n\n  /**\n   * Decode a initialize stake instruction and retrieve the instruction params.\n   */\n  static decodeInitialize(\n    instruction: TransactionInstruction,\n  ): InitializeStakeParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 2);\n\n    const {authorized, lockup} = decodeData(\n      STAKE_INSTRUCTION_LAYOUTS.Initialize,\n      instruction.data,\n    );\n\n    return {\n      stakePubkey: instruction.keys[0].pubkey,\n      authorized: new Authorized(\n        new PublicKey(authorized.staker),\n        new PublicKey(authorized.withdrawer),\n      ),\n      lockup: new Lockup(\n        lockup.unixTimestamp,\n        lockup.epoch,\n        new PublicKey(lockup.custodian),\n      ),\n    };\n  }\n\n  /**\n   * Decode a delegate stake instruction and retrieve the instruction params.\n   */\n  static decodeDelegate(\n    instruction: TransactionInstruction,\n  ): DelegateStakeParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 6);\n    decodeData(STAKE_INSTRUCTION_LAYOUTS.Delegate, instruction.data);\n\n    return {\n      stakePubkey: instruction.keys[0].pubkey,\n      votePubkey: instruction.keys[1].pubkey,\n      authorizedPubkey: instruction.keys[5].pubkey,\n    };\n  }\n\n  /**\n   * Decode an authorize stake instruction and retrieve the instruction params.\n   */\n  static decodeAuthorize(\n    instruction: TransactionInstruction,\n  ): AuthorizeStakeParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n    const {newAuthorized, stakeAuthorizationType} = decodeData(\n      STAKE_INSTRUCTION_LAYOUTS.Authorize,\n      instruction.data,\n    );\n\n    const o: AuthorizeStakeParams = {\n      stakePubkey: instruction.keys[0].pubkey,\n      authorizedPubkey: instruction.keys[2].pubkey,\n      newAuthorizedPubkey: new PublicKey(newAuthorized),\n      stakeAuthorizationType: {\n        index: stakeAuthorizationType,\n      },\n    };\n    if (instruction.keys.length > 3) {\n      o.custodianPubkey = instruction.keys[3].pubkey;\n    }\n    return o;\n  }\n\n  /**\n   * Decode an authorize-with-seed stake instruction and retrieve the instruction params.\n   */\n  static decodeAuthorizeWithSeed(\n    instruction: TransactionInstruction,\n  ): AuthorizeWithSeedStakeParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 2);\n\n    const {\n      newAuthorized,\n      stakeAuthorizationType,\n      authoritySeed,\n      authorityOwner,\n    } = decodeData(\n      STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,\n      instruction.data,\n    );\n\n    const o: AuthorizeWithSeedStakeParams = {\n      stakePubkey: instruction.keys[0].pubkey,\n      authorityBase: instruction.keys[1].pubkey,\n      authoritySeed: authoritySeed,\n      authorityOwner: new PublicKey(authorityOwner),\n      newAuthorizedPubkey: new PublicKey(newAuthorized),\n      stakeAuthorizationType: {\n        index: stakeAuthorizationType,\n      },\n    };\n    if (instruction.keys.length > 3) {\n      o.custodianPubkey = instruction.keys[3].pubkey;\n    }\n    return o;\n  }\n\n  /**\n   * Decode a split stake instruction and retrieve the instruction params.\n   */\n  static decodeSplit(instruction: TransactionInstruction): SplitStakeParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n    const {lamports} = decodeData(\n      STAKE_INSTRUCTION_LAYOUTS.Split,\n      instruction.data,\n    );\n\n    return {\n      stakePubkey: instruction.keys[0].pubkey,\n      splitStakePubkey: instruction.keys[1].pubkey,\n      authorizedPubkey: instruction.keys[2].pubkey,\n      lamports,\n    };\n  }\n\n  /**\n   * Decode a merge stake instruction and retrieve the instruction params.\n   */\n  static decodeMerge(instruction: TransactionInstruction): MergeStakeParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n    decodeData(STAKE_INSTRUCTION_LAYOUTS.Merge, instruction.data);\n\n    return {\n      stakePubkey: instruction.keys[0].pubkey,\n      sourceStakePubKey: instruction.keys[1].pubkey,\n      authorizedPubkey: instruction.keys[4].pubkey,\n    };\n  }\n\n  /**\n   * Decode a withdraw stake instruction and retrieve the instruction params.\n   */\n  static decodeWithdraw(\n    instruction: TransactionInstruction,\n  ): WithdrawStakeParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 5);\n    const {lamports} = decodeData(\n      STAKE_INSTRUCTION_LAYOUTS.Withdraw,\n      instruction.data,\n    );\n\n    const o: WithdrawStakeParams = {\n      stakePubkey: instruction.keys[0].pubkey,\n      toPubkey: instruction.keys[1].pubkey,\n      authorizedPubkey: instruction.keys[4].pubkey,\n      lamports,\n    };\n    if (instruction.keys.length > 5) {\n      o.custodianPubkey = instruction.keys[5].pubkey;\n    }\n    return o;\n  }\n\n  /**\n   * Decode a deactivate stake instruction and retrieve the instruction params.\n   */\n  static decodeDeactivate(\n    instruction: TransactionInstruction,\n  ): DeactivateStakeParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n    decodeData(STAKE_INSTRUCTION_LAYOUTS.Deactivate, instruction.data);\n\n    return {\n      stakePubkey: instruction.keys[0].pubkey,\n      authorizedPubkey: instruction.keys[2].pubkey,\n    };\n  }\n\n  /**\n   * @internal\n   */\n  static checkProgramId(programId: PublicKey) {\n    if (!programId.equals(StakeProgram.programId)) {\n      throw new Error('invalid instruction; programId is not StakeProgram');\n    }\n  }\n\n  /**\n   * @internal\n   */\n  static checkKeyLength(keys: Array<any>, expectedLength: number) {\n    if (keys.length < expectedLength) {\n      throw new Error(\n        `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n      );\n    }\n  }\n}\n\n/**\n * An enumeration of valid StakeInstructionType's\n */\nexport type StakeInstructionType =\n  // FIXME\n  // It would be preferable for this type to be `keyof StakeInstructionInputData`\n  // but Typedoc does not transpile `keyof` expressions.\n  // See https://github.com/TypeStrong/typedoc/issues/1894\n  | 'Authorize'\n  | 'AuthorizeWithSeed'\n  | 'Deactivate'\n  | 'Delegate'\n  | 'Initialize'\n  | 'Merge'\n  | 'Split'\n  | 'Withdraw';\n\ntype StakeInstructionInputData = {\n  Authorize: IInstructionInputData &\n    Readonly<{\n      newAuthorized: Uint8Array;\n      stakeAuthorizationType: number;\n    }>;\n  AuthorizeWithSeed: IInstructionInputData &\n    Readonly<{\n      authorityOwner: Uint8Array;\n      authoritySeed: string;\n      instruction: number;\n      newAuthorized: Uint8Array;\n      stakeAuthorizationType: number;\n    }>;\n  Deactivate: IInstructionInputData;\n  Delegate: IInstructionInputData;\n  Initialize: IInstructionInputData &\n    Readonly<{\n      authorized: AuthorizedRaw;\n      lockup: LockupRaw;\n    }>;\n  Merge: IInstructionInputData;\n  Split: IInstructionInputData &\n    Readonly<{\n      lamports: number;\n    }>;\n  Withdraw: IInstructionInputData &\n    Readonly<{\n      lamports: number;\n    }>;\n};\n\n/**\n * An enumeration of valid stake InstructionType's\n * @internal\n */\nexport const STAKE_INSTRUCTION_LAYOUTS = Object.freeze<{\n  [Instruction in StakeInstructionType]: InstructionType<\n    StakeInstructionInputData[Instruction]\n  >;\n}>({\n  Initialize: {\n    index: 0,\n    layout: BufferLayout.struct<StakeInstructionInputData['Initialize']>([\n      BufferLayout.u32('instruction'),\n      Layout.authorized(),\n      Layout.lockup(),\n    ]),\n  },\n  Authorize: {\n    index: 1,\n    layout: BufferLayout.struct<StakeInstructionInputData['Authorize']>([\n      BufferLayout.u32('instruction'),\n      Layout.publicKey('newAuthorized'),\n      BufferLayout.u32('stakeAuthorizationType'),\n    ]),\n  },\n  Delegate: {\n    index: 2,\n    layout: BufferLayout.struct<StakeInstructionInputData['Delegate']>([\n      BufferLayout.u32('instruction'),\n    ]),\n  },\n  Split: {\n    index: 3,\n    layout: BufferLayout.struct<StakeInstructionInputData['Split']>([\n      BufferLayout.u32('instruction'),\n      BufferLayout.ns64('lamports'),\n    ]),\n  },\n  Withdraw: {\n    index: 4,\n    layout: BufferLayout.struct<StakeInstructionInputData['Withdraw']>([\n      BufferLayout.u32('instruction'),\n      BufferLayout.ns64('lamports'),\n    ]),\n  },\n  Deactivate: {\n    index: 5,\n    layout: BufferLayout.struct<StakeInstructionInputData['Deactivate']>([\n      BufferLayout.u32('instruction'),\n    ]),\n  },\n  Merge: {\n    index: 7,\n    layout: BufferLayout.struct<StakeInstructionInputData['Merge']>([\n      BufferLayout.u32('instruction'),\n    ]),\n  },\n  AuthorizeWithSeed: {\n    index: 8,\n    layout: BufferLayout.struct<StakeInstructionInputData['AuthorizeWithSeed']>(\n      [\n        BufferLayout.u32('instruction'),\n        Layout.publicKey('newAuthorized'),\n        BufferLayout.u32('stakeAuthorizationType'),\n        Layout.rustString('authoritySeed'),\n        Layout.publicKey('authorityOwner'),\n      ],\n    ),\n  },\n});\n\n/**\n * Stake authorization type\n */\nexport type StakeAuthorizationType = {\n  /** The Stake Authorization index (from solana-stake-program) */\n  index: number;\n};\n\n/**\n * An enumeration of valid StakeAuthorizationLayout's\n */\nexport const StakeAuthorizationLayout = Object.freeze({\n  Staker: {\n    index: 0,\n  },\n  Withdrawer: {\n    index: 1,\n  },\n});\n\n/**\n * Factory class for transactions to interact with the Stake program\n */\nexport class StakeProgram {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Public key that identifies the Stake program\n   */\n  static programId: PublicKey = new PublicKey(\n    'Stake11111111111111111111111111111111111111',\n  );\n\n  /**\n   * Max space of a Stake account\n   *\n   * This is generated from the solana-stake-program StakeState struct as\n   * `StakeState::size_of()`:\n   * https://docs.rs/solana-stake-program/latest/solana_stake_program/stake_state/enum.StakeState.html\n   */\n  static space: number = 200;\n\n  /**\n   * Generate an Initialize instruction to add to a Stake Create transaction\n   */\n  static initialize(params: InitializeStakeParams): TransactionInstruction {\n    const {stakePubkey, authorized, lockup: maybeLockup} = params;\n    const lockup: Lockup = maybeLockup || Lockup.default;\n    const type = STAKE_INSTRUCTION_LAYOUTS.Initialize;\n    const data = encodeData(type, {\n      authorized: {\n        staker: toBuffer(authorized.staker.toBuffer()),\n        withdrawer: toBuffer(authorized.withdrawer.toBuffer()),\n      },\n      lockup: {\n        unixTimestamp: lockup.unixTimestamp,\n        epoch: lockup.epoch,\n        custodian: toBuffer(lockup.custodian.toBuffer()),\n      },\n    });\n    const instructionData = {\n      keys: [\n        {pubkey: stakePubkey, isSigner: false, isWritable: true},\n        {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    };\n    return new TransactionInstruction(instructionData);\n  }\n\n  /**\n   * Generate a Transaction that creates a new Stake account at\n   *   an address generated with `from`, a seed, and the Stake programId\n   */\n  static createAccountWithSeed(\n    params: CreateStakeAccountWithSeedParams,\n  ): Transaction {\n    const transaction = new Transaction();\n    transaction.add(\n      SystemProgram.createAccountWithSeed({\n        fromPubkey: params.fromPubkey,\n        newAccountPubkey: params.stakePubkey,\n        basePubkey: params.basePubkey,\n        seed: params.seed,\n        lamports: params.lamports,\n        space: this.space,\n        programId: this.programId,\n      }),\n    );\n\n    const {stakePubkey, authorized, lockup} = params;\n    return transaction.add(this.initialize({stakePubkey, authorized, lockup}));\n  }\n\n  /**\n   * Generate a Transaction that creates a new Stake account\n   */\n  static createAccount(params: CreateStakeAccountParams): Transaction {\n    const transaction = new Transaction();\n    transaction.add(\n      SystemProgram.createAccount({\n        fromPubkey: params.fromPubkey,\n        newAccountPubkey: params.stakePubkey,\n        lamports: params.lamports,\n        space: this.space,\n        programId: this.programId,\n      }),\n    );\n\n    const {stakePubkey, authorized, lockup} = params;\n    return transaction.add(this.initialize({stakePubkey, authorized, lockup}));\n  }\n\n  /**\n   * Generate a Transaction that delegates Stake tokens to a validator\n   * Vote PublicKey. This transaction can also be used to redelegate Stake\n   * to a new validator Vote PublicKey.\n   */\n  static delegate(params: DelegateStakeParams): Transaction {\n    const {stakePubkey, authorizedPubkey, votePubkey} = params;\n\n    const type = STAKE_INSTRUCTION_LAYOUTS.Delegate;\n    const data = encodeData(type);\n\n    return new Transaction().add({\n      keys: [\n        {pubkey: stakePubkey, isSigner: false, isWritable: true},\n        {pubkey: votePubkey, isSigner: false, isWritable: false},\n        {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n        {\n          pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n          isSigner: false,\n          isWritable: false,\n        },\n        {pubkey: STAKE_CONFIG_ID, isSigner: false, isWritable: false},\n        {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a Transaction that authorizes a new PublicKey as Staker\n   * or Withdrawer on the Stake account.\n   */\n  static authorize(params: AuthorizeStakeParams): Transaction {\n    const {\n      stakePubkey,\n      authorizedPubkey,\n      newAuthorizedPubkey,\n      stakeAuthorizationType,\n      custodianPubkey,\n    } = params;\n\n    const type = STAKE_INSTRUCTION_LAYOUTS.Authorize;\n    const data = encodeData(type, {\n      newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n      stakeAuthorizationType: stakeAuthorizationType.index,\n    });\n\n    const keys = [\n      {pubkey: stakePubkey, isSigner: false, isWritable: true},\n      {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: true},\n      {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n    ];\n    if (custodianPubkey) {\n      keys.push({\n        pubkey: custodianPubkey,\n        isSigner: false,\n        isWritable: false,\n      });\n    }\n    return new Transaction().add({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a Transaction that authorizes a new PublicKey as Staker\n   * or Withdrawer on the Stake account.\n   */\n  static authorizeWithSeed(params: AuthorizeWithSeedStakeParams): Transaction {\n    const {\n      stakePubkey,\n      authorityBase,\n      authoritySeed,\n      authorityOwner,\n      newAuthorizedPubkey,\n      stakeAuthorizationType,\n      custodianPubkey,\n    } = params;\n\n    const type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n    const data = encodeData(type, {\n      newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n      stakeAuthorizationType: stakeAuthorizationType.index,\n      authoritySeed: authoritySeed,\n      authorityOwner: toBuffer(authorityOwner.toBuffer()),\n    });\n\n    const keys = [\n      {pubkey: stakePubkey, isSigner: false, isWritable: true},\n      {pubkey: authorityBase, isSigner: true, isWritable: false},\n      {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n    ];\n    if (custodianPubkey) {\n      keys.push({\n        pubkey: custodianPubkey,\n        isSigner: false,\n        isWritable: false,\n      });\n    }\n    return new Transaction().add({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * @internal\n   */\n  static splitInstruction(params: SplitStakeParams): TransactionInstruction {\n    const {stakePubkey, authorizedPubkey, splitStakePubkey, lamports} = params;\n    const type = STAKE_INSTRUCTION_LAYOUTS.Split;\n    const data = encodeData(type, {lamports});\n    return new TransactionInstruction({\n      keys: [\n        {pubkey: stakePubkey, isSigner: false, isWritable: true},\n        {pubkey: splitStakePubkey, isSigner: false, isWritable: true},\n        {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a Transaction that splits Stake tokens into another stake account\n   */\n  static split(params: SplitStakeParams): Transaction {\n    const transaction = new Transaction();\n    transaction.add(\n      SystemProgram.createAccount({\n        fromPubkey: params.authorizedPubkey,\n        newAccountPubkey: params.splitStakePubkey,\n        lamports: 0,\n        space: this.space,\n        programId: this.programId,\n      }),\n    );\n    return transaction.add(this.splitInstruction(params));\n  }\n\n  /**\n   * Generate a Transaction that splits Stake tokens into another account\n   * derived from a base public key and seed\n   */\n  static splitWithSeed(params: SplitStakeWithSeedParams): Transaction {\n    const {\n      stakePubkey,\n      authorizedPubkey,\n      splitStakePubkey,\n      basePubkey,\n      seed,\n      lamports,\n    } = params;\n    const transaction = new Transaction();\n    transaction.add(\n      SystemProgram.allocate({\n        accountPubkey: splitStakePubkey,\n        basePubkey,\n        seed,\n        space: this.space,\n        programId: this.programId,\n      }),\n    );\n    return transaction.add(\n      this.splitInstruction({\n        stakePubkey,\n        authorizedPubkey,\n        splitStakePubkey,\n        lamports,\n      }),\n    );\n  }\n\n  /**\n   * Generate a Transaction that merges Stake accounts.\n   */\n  static merge(params: MergeStakeParams): Transaction {\n    const {stakePubkey, sourceStakePubKey, authorizedPubkey} = params;\n    const type = STAKE_INSTRUCTION_LAYOUTS.Merge;\n    const data = encodeData(type);\n\n    return new Transaction().add({\n      keys: [\n        {pubkey: stakePubkey, isSigner: false, isWritable: true},\n        {pubkey: sourceStakePubKey, isSigner: false, isWritable: true},\n        {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n        {\n          pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n          isSigner: false,\n          isWritable: false,\n        },\n        {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a Transaction that withdraws deactivated Stake tokens.\n   */\n  static withdraw(params: WithdrawStakeParams): Transaction {\n    const {stakePubkey, authorizedPubkey, toPubkey, lamports, custodianPubkey} =\n      params;\n    const type = STAKE_INSTRUCTION_LAYOUTS.Withdraw;\n    const data = encodeData(type, {lamports});\n\n    const keys = [\n      {pubkey: stakePubkey, isSigner: false, isWritable: true},\n      {pubkey: toPubkey, isSigner: false, isWritable: true},\n      {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n      {\n        pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n        isSigner: false,\n        isWritable: false,\n      },\n      {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n    ];\n    if (custodianPubkey) {\n      keys.push({\n        pubkey: custodianPubkey,\n        isSigner: false,\n        isWritable: false,\n      });\n    }\n    return new Transaction().add({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a Transaction that deactivates Stake tokens.\n   */\n  static deactivate(params: DeactivateStakeParams): Transaction {\n    const {stakePubkey, authorizedPubkey} = params;\n    const type = STAKE_INSTRUCTION_LAYOUTS.Deactivate;\n    const data = encodeData(type);\n\n    return new Transaction().add({\n      keys: [\n        {pubkey: stakePubkey, isSigner: false, isWritable: true},\n        {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n        {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    });\n  }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n  encodeData,\n  decodeData,\n  InstructionType,\n  IInstructionInputData,\n} from '../instruction';\nimport * as Layout from '../layout';\nimport {PublicKey} from '../publickey';\nimport {SystemProgram} from './system';\nimport {SYSVAR_CLOCK_PUBKEY, SYSVAR_RENT_PUBKEY} from '../sysvar';\nimport {Transaction, TransactionInstruction} from '../transaction';\nimport {toBuffer} from '../utils/to-buffer';\n\n/**\n * Vote account info\n */\nexport class VoteInit {\n  nodePubkey: PublicKey;\n  authorizedVoter: PublicKey;\n  authorizedWithdrawer: PublicKey;\n  commission: number; /** [0, 100] */\n\n  constructor(\n    nodePubkey: PublicKey,\n    authorizedVoter: PublicKey,\n    authorizedWithdrawer: PublicKey,\n    commission: number,\n  ) {\n    this.nodePubkey = nodePubkey;\n    this.authorizedVoter = authorizedVoter;\n    this.authorizedWithdrawer = authorizedWithdrawer;\n    this.commission = commission;\n  }\n}\n\n/**\n * Create vote account transaction params\n */\nexport type CreateVoteAccountParams = {\n  fromPubkey: PublicKey;\n  votePubkey: PublicKey;\n  voteInit: VoteInit;\n  lamports: number;\n};\n\n/**\n * InitializeAccount instruction params\n */\nexport type InitializeAccountParams = {\n  votePubkey: PublicKey;\n  nodePubkey: PublicKey;\n  voteInit: VoteInit;\n};\n\n/**\n * Authorize instruction params\n */\nexport type AuthorizeVoteParams = {\n  votePubkey: PublicKey;\n  /** Current vote or withdraw authority, depending on `voteAuthorizationType` */\n  authorizedPubkey: PublicKey;\n  newAuthorizedPubkey: PublicKey;\n  voteAuthorizationType: VoteAuthorizationType;\n};\n\n/**\n * AuthorizeWithSeed instruction params\n */\nexport type AuthorizeVoteWithSeedParams = {\n  currentAuthorityDerivedKeyBasePubkey: PublicKey;\n  currentAuthorityDerivedKeyOwnerPubkey: PublicKey;\n  currentAuthorityDerivedKeySeed: string;\n  newAuthorizedPubkey: PublicKey;\n  voteAuthorizationType: VoteAuthorizationType;\n  votePubkey: PublicKey;\n};\n\n/**\n * Withdraw from vote account transaction params\n */\nexport type WithdrawFromVoteAccountParams = {\n  votePubkey: PublicKey;\n  authorizedWithdrawerPubkey: PublicKey;\n  lamports: number;\n  toPubkey: PublicKey;\n};\n\n/**\n * Vote Instruction class\n */\nexport class VoteInstruction {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Decode a vote instruction and retrieve the instruction type.\n   */\n  static decodeInstructionType(\n    instruction: TransactionInstruction,\n  ): VoteInstructionType {\n    this.checkProgramId(instruction.programId);\n\n    const instructionTypeLayout = BufferLayout.u32('instruction');\n    const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n    let type: VoteInstructionType | undefined;\n    for (const [ixType, layout] of Object.entries(VOTE_INSTRUCTION_LAYOUTS)) {\n      if (layout.index == typeIndex) {\n        type = ixType as VoteInstructionType;\n        break;\n      }\n    }\n\n    if (!type) {\n      throw new Error('Instruction type incorrect; not a VoteInstruction');\n    }\n\n    return type;\n  }\n\n  /**\n   * Decode an initialize vote instruction and retrieve the instruction params.\n   */\n  static decodeInitializeAccount(\n    instruction: TransactionInstruction,\n  ): InitializeAccountParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 4);\n\n    const {voteInit} = decodeData(\n      VOTE_INSTRUCTION_LAYOUTS.InitializeAccount,\n      instruction.data,\n    );\n\n    return {\n      votePubkey: instruction.keys[0].pubkey,\n      nodePubkey: instruction.keys[3].pubkey,\n      voteInit: new VoteInit(\n        new PublicKey(voteInit.nodePubkey),\n        new PublicKey(voteInit.authorizedVoter),\n        new PublicKey(voteInit.authorizedWithdrawer),\n        voteInit.commission,\n      ),\n    };\n  }\n\n  /**\n   * Decode an authorize instruction and retrieve the instruction params.\n   */\n  static decodeAuthorize(\n    instruction: TransactionInstruction,\n  ): AuthorizeVoteParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n\n    const {newAuthorized, voteAuthorizationType} = decodeData(\n      VOTE_INSTRUCTION_LAYOUTS.Authorize,\n      instruction.data,\n    );\n\n    return {\n      votePubkey: instruction.keys[0].pubkey,\n      authorizedPubkey: instruction.keys[2].pubkey,\n      newAuthorizedPubkey: new PublicKey(newAuthorized),\n      voteAuthorizationType: {\n        index: voteAuthorizationType,\n      },\n    };\n  }\n\n  /**\n   * Decode an authorize instruction and retrieve the instruction params.\n   */\n  static decodeAuthorizeWithSeed(\n    instruction: TransactionInstruction,\n  ): AuthorizeVoteWithSeedParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n\n    const {\n      voteAuthorizeWithSeedArgs: {\n        currentAuthorityDerivedKeyOwnerPubkey,\n        currentAuthorityDerivedKeySeed,\n        newAuthorized,\n        voteAuthorizationType,\n      },\n    } = decodeData(\n      VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,\n      instruction.data,\n    );\n\n    return {\n      currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey,\n      currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(\n        currentAuthorityDerivedKeyOwnerPubkey,\n      ),\n      currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n      newAuthorizedPubkey: new PublicKey(newAuthorized),\n      voteAuthorizationType: {\n        index: voteAuthorizationType,\n      },\n      votePubkey: instruction.keys[0].pubkey,\n    };\n  }\n\n  /**\n   * Decode a withdraw instruction and retrieve the instruction params.\n   */\n  static decodeWithdraw(\n    instruction: TransactionInstruction,\n  ): WithdrawFromVoteAccountParams {\n    this.checkProgramId(instruction.programId);\n    this.checkKeyLength(instruction.keys, 3);\n\n    const {lamports} = decodeData(\n      VOTE_INSTRUCTION_LAYOUTS.Withdraw,\n      instruction.data,\n    );\n\n    return {\n      votePubkey: instruction.keys[0].pubkey,\n      authorizedWithdrawerPubkey: instruction.keys[2].pubkey,\n      lamports,\n      toPubkey: instruction.keys[1].pubkey,\n    };\n  }\n\n  /**\n   * @internal\n   */\n  static checkProgramId(programId: PublicKey) {\n    if (!programId.equals(VoteProgram.programId)) {\n      throw new Error('invalid instruction; programId is not VoteProgram');\n    }\n  }\n\n  /**\n   * @internal\n   */\n  static checkKeyLength(keys: Array<any>, expectedLength: number) {\n    if (keys.length < expectedLength) {\n      throw new Error(\n        `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n      );\n    }\n  }\n}\n\n/**\n * An enumeration of valid VoteInstructionType's\n */\nexport type VoteInstructionType =\n  // FIXME\n  // It would be preferable for this type to be `keyof VoteInstructionInputData`\n  // but Typedoc does not transpile `keyof` expressions.\n  // See https://github.com/TypeStrong/typedoc/issues/1894\n  'Authorize' | 'AuthorizeWithSeed' | 'InitializeAccount' | 'Withdraw';\n\n/** @internal */\nexport type VoteAuthorizeWithSeedArgs = Readonly<{\n  currentAuthorityDerivedKeyOwnerPubkey: Uint8Array;\n  currentAuthorityDerivedKeySeed: string;\n  newAuthorized: Uint8Array;\n  voteAuthorizationType: number;\n}>;\ntype VoteInstructionInputData = {\n  Authorize: IInstructionInputData & {\n    newAuthorized: Uint8Array;\n    voteAuthorizationType: number;\n  };\n  AuthorizeWithSeed: IInstructionInputData & {\n    voteAuthorizeWithSeedArgs: VoteAuthorizeWithSeedArgs;\n  };\n  InitializeAccount: IInstructionInputData & {\n    voteInit: Readonly<{\n      authorizedVoter: Uint8Array;\n      authorizedWithdrawer: Uint8Array;\n      commission: number;\n      nodePubkey: Uint8Array;\n    }>;\n  };\n  Withdraw: IInstructionInputData & {\n    lamports: number;\n  };\n};\n\nconst VOTE_INSTRUCTION_LAYOUTS = Object.freeze<{\n  [Instruction in VoteInstructionType]: InstructionType<\n    VoteInstructionInputData[Instruction]\n  >;\n}>({\n  InitializeAccount: {\n    index: 0,\n    layout: BufferLayout.struct<VoteInstructionInputData['InitializeAccount']>([\n      BufferLayout.u32('instruction'),\n      Layout.voteInit(),\n    ]),\n  },\n  Authorize: {\n    index: 1,\n    layout: BufferLayout.struct<VoteInstructionInputData['Authorize']>([\n      BufferLayout.u32('instruction'),\n      Layout.publicKey('newAuthorized'),\n      BufferLayout.u32('voteAuthorizationType'),\n    ]),\n  },\n  Withdraw: {\n    index: 3,\n    layout: BufferLayout.struct<VoteInstructionInputData['Withdraw']>([\n      BufferLayout.u32('instruction'),\n      BufferLayout.ns64('lamports'),\n    ]),\n  },\n  AuthorizeWithSeed: {\n    index: 10,\n    layout: BufferLayout.struct<VoteInstructionInputData['AuthorizeWithSeed']>([\n      BufferLayout.u32('instruction'),\n      Layout.voteAuthorizeWithSeedArgs(),\n    ]),\n  },\n});\n\n/**\n * VoteAuthorize type\n */\nexport type VoteAuthorizationType = {\n  /** The VoteAuthorize index (from solana-vote-program) */\n  index: number;\n};\n\n/**\n * An enumeration of valid VoteAuthorization layouts.\n */\nexport const VoteAuthorizationLayout = Object.freeze({\n  Voter: {\n    index: 0,\n  },\n  Withdrawer: {\n    index: 1,\n  },\n});\n\n/**\n * Factory class for transactions to interact with the Vote program\n */\nexport class VoteProgram {\n  /**\n   * @internal\n   */\n  constructor() {}\n\n  /**\n   * Public key that identifies the Vote program\n   */\n  static programId: PublicKey = new PublicKey(\n    'Vote111111111111111111111111111111111111111',\n  );\n\n  /**\n   * Max space of a Vote account\n   *\n   * This is generated from the solana-vote-program VoteState struct as\n   * `VoteState::size_of()`:\n   * https://docs.rs/solana-vote-program/1.9.5/solana_vote_program/vote_state/struct.VoteState.html#method.size_of\n   *\n   * KEEP IN SYNC WITH `VoteState::size_of()` in https://github.com/solana-labs/solana/blob/a474cb24b9238f5edcc982f65c0b37d4a1046f7e/sdk/program/src/vote/state/mod.rs#L340-L342\n   */\n  static space: number = process.env.TEST_LIVE ? 3762 : 3731;\n\n  /**\n   * Generate an Initialize instruction.\n   */\n  static initializeAccount(\n    params: InitializeAccountParams,\n  ): TransactionInstruction {\n    const {votePubkey, nodePubkey, voteInit} = params;\n    const type = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;\n    const data = encodeData(type, {\n      voteInit: {\n        nodePubkey: toBuffer(voteInit.nodePubkey.toBuffer()),\n        authorizedVoter: toBuffer(voteInit.authorizedVoter.toBuffer()),\n        authorizedWithdrawer: toBuffer(\n          voteInit.authorizedWithdrawer.toBuffer(),\n        ),\n        commission: voteInit.commission,\n      },\n    });\n    const instructionData = {\n      keys: [\n        {pubkey: votePubkey, isSigner: false, isWritable: true},\n        {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n        {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n        {pubkey: nodePubkey, isSigner: true, isWritable: false},\n      ],\n      programId: this.programId,\n      data,\n    };\n    return new TransactionInstruction(instructionData);\n  }\n\n  /**\n   * Generate a transaction that creates a new Vote account.\n   */\n  static createAccount(params: CreateVoteAccountParams): Transaction {\n    const transaction = new Transaction();\n    transaction.add(\n      SystemProgram.createAccount({\n        fromPubkey: params.fromPubkey,\n        newAccountPubkey: params.votePubkey,\n        lamports: params.lamports,\n        space: this.space,\n        programId: this.programId,\n      }),\n    );\n\n    return transaction.add(\n      this.initializeAccount({\n        votePubkey: params.votePubkey,\n        nodePubkey: params.voteInit.nodePubkey,\n        voteInit: params.voteInit,\n      }),\n    );\n  }\n\n  /**\n   * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.\n   */\n  static authorize(params: AuthorizeVoteParams): Transaction {\n    const {\n      votePubkey,\n      authorizedPubkey,\n      newAuthorizedPubkey,\n      voteAuthorizationType,\n    } = params;\n\n    const type = VOTE_INSTRUCTION_LAYOUTS.Authorize;\n    const data = encodeData(type, {\n      newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n      voteAuthorizationType: voteAuthorizationType.index,\n    });\n\n    const keys = [\n      {pubkey: votePubkey, isSigner: false, isWritable: true},\n      {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n      {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n    ];\n\n    return new Transaction().add({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account\n   * where the current Voter or Withdrawer authority is a derived key.\n   */\n  static authorizeWithSeed(params: AuthorizeVoteWithSeedParams): Transaction {\n    const {\n      currentAuthorityDerivedKeyBasePubkey,\n      currentAuthorityDerivedKeyOwnerPubkey,\n      currentAuthorityDerivedKeySeed,\n      newAuthorizedPubkey,\n      voteAuthorizationType,\n      votePubkey,\n    } = params;\n\n    const type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n    const data = encodeData(type, {\n      voteAuthorizeWithSeedArgs: {\n        currentAuthorityDerivedKeyOwnerPubkey: toBuffer(\n          currentAuthorityDerivedKeyOwnerPubkey.toBuffer(),\n        ),\n        currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n        newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n        voteAuthorizationType: voteAuthorizationType.index,\n      },\n    });\n\n    const keys = [\n      {pubkey: votePubkey, isSigner: false, isWritable: true},\n      {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n      {\n        pubkey: currentAuthorityDerivedKeyBasePubkey,\n        isSigner: true,\n        isWritable: false,\n      },\n    ];\n\n    return new Transaction().add({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a transaction to withdraw from a Vote account.\n   */\n  static withdraw(params: WithdrawFromVoteAccountParams): Transaction {\n    const {votePubkey, authorizedWithdrawerPubkey, lamports, toPubkey} = params;\n    const type = VOTE_INSTRUCTION_LAYOUTS.Withdraw;\n    const data = encodeData(type, {lamports});\n\n    const keys = [\n      {pubkey: votePubkey, isSigner: false, isWritable: true},\n      {pubkey: toPubkey, isSigner: false, isWritable: true},\n      {pubkey: authorizedWithdrawerPubkey, isSigner: true, isWritable: false},\n    ];\n\n    return new Transaction().add({\n      keys,\n      programId: this.programId,\n      data,\n    });\n  }\n\n  /**\n   * Generate a transaction to withdraw safely from a Vote account.\n   *\n   * This function was created as a safeguard for vote accounts running validators, `safeWithdraw`\n   * checks that the withdraw amount will not exceed the specified balance while leaving enough left\n   * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the\n   * `withdraw` method directly.\n   */\n  static safeWithdraw(\n    params: WithdrawFromVoteAccountParams,\n    currentVoteAccountBalance: number,\n    rentExemptMinimum: number,\n  ): Transaction {\n    if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {\n      throw new Error(\n        'Withdraw will leave vote account with insuffcient funds.',\n      );\n    }\n    return VoteProgram.withdraw(params);\n  }\n}\n","import {Buffer} from 'buffer';\nimport {\n  assert as assertType,\n  optional,\n  string,\n  type as pick,\n} from 'superstruct';\n\nimport * as Layout from './layout';\nimport * as shortvec from './utils/shortvec-encoding';\nimport {PublicKey, PUBLIC_KEY_LENGTH} from './publickey';\n\nexport const VALIDATOR_INFO_KEY = new PublicKey(\n  'Va1idator1nfo111111111111111111111111111111',\n);\n\n/**\n * @internal\n */\ntype ConfigKey = {\n  publicKey: PublicKey;\n  isSigner: boolean;\n};\n\n/**\n * Info used to identity validators.\n */\nexport type Info = {\n  /** validator name */\n  name: string;\n  /** optional, validator website */\n  website?: string;\n  /** optional, extra information the validator chose to share */\n  details?: string;\n  /** optional, used to identify validators on keybase.io */\n  keybaseUsername?: string;\n};\n\nconst InfoString = pick({\n  name: string(),\n  website: optional(string()),\n  details: optional(string()),\n  keybaseUsername: optional(string()),\n});\n\n/**\n * ValidatorInfo class\n */\nexport class ValidatorInfo {\n  /**\n   * validator public key\n   */\n  key: PublicKey;\n  /**\n   * validator information\n   */\n  info: Info;\n\n  /**\n   * Construct a valid ValidatorInfo\n   *\n   * @param key validator public key\n   * @param info validator information\n   */\n  constructor(key: PublicKey, info: Info) {\n    this.key = key;\n    this.info = info;\n  }\n\n  /**\n   * Deserialize ValidatorInfo from the config account data. Exactly two config\n   * keys are required in the data.\n   *\n   * @param buffer config account data\n   * @return null if info was not found\n   */\n  static fromConfigData(\n    buffer: Buffer | Uint8Array | Array<number>,\n  ): ValidatorInfo | null {\n    let byteArray = [...buffer];\n    const configKeyCount = shortvec.decodeLength(byteArray);\n    if (configKeyCount !== 2) return null;\n\n    const configKeys: Array<ConfigKey> = [];\n    for (let i = 0; i < 2; i++) {\n      const publicKey = new PublicKey(byteArray.slice(0, PUBLIC_KEY_LENGTH));\n      byteArray = byteArray.slice(PUBLIC_KEY_LENGTH);\n      const isSigner = byteArray.slice(0, 1)[0] === 1;\n      byteArray = byteArray.slice(1);\n      configKeys.push({publicKey, isSigner});\n    }\n\n    if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) {\n      if (configKeys[1].isSigner) {\n        const rawInfo: any = Layout.rustString().decode(Buffer.from(byteArray));\n        const info = JSON.parse(rawInfo as string);\n        assertType(info, InfoString);\n        return new ValidatorInfo(configKeys[1].publicKey, info);\n      }\n    }\n\n    return null;\n  }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\nimport type {Buffer} from 'buffer';\n\nimport * as Layout from './layout';\nimport {PublicKey} from './publickey';\nimport {toBuffer} from './utils/to-buffer';\n\nexport const VOTE_PROGRAM_ID = new PublicKey(\n  'Vote111111111111111111111111111111111111111',\n);\n\nexport type Lockout = {\n  slot: number;\n  confirmationCount: number;\n};\n\n/**\n * History of how many credits earned by the end of each epoch\n */\nexport type EpochCredits = Readonly<{\n  epoch: number;\n  credits: number;\n  prevCredits: number;\n}>;\n\nexport type AuthorizedVoter = Readonly<{\n  epoch: number;\n  authorizedVoter: PublicKey;\n}>;\n\ntype AuthorizedVoterRaw = Readonly<{\n  authorizedVoter: Uint8Array;\n  epoch: number;\n}>;\n\ntype PriorVoters = Readonly<{\n  buf: PriorVoterRaw[];\n  idx: number;\n  isEmpty: number;\n}>;\n\nexport type PriorVoter = Readonly<{\n  authorizedPubkey: PublicKey;\n  epochOfLastAuthorizedSwitch: number;\n  targetEpoch: number;\n}>;\n\ntype PriorVoterRaw = Readonly<{\n  authorizedPubkey: Uint8Array;\n  epochOfLastAuthorizedSwitch: number;\n  targetEpoch: number;\n}>;\n\nexport type BlockTimestamp = Readonly<{\n  slot: number;\n  timestamp: number;\n}>;\n\ntype VoteAccountData = Readonly<{\n  authorizedVoters: AuthorizedVoterRaw[];\n  authorizedWithdrawer: Uint8Array;\n  commission: number;\n  epochCredits: EpochCredits[];\n  lastTimestamp: BlockTimestamp;\n  nodePubkey: Uint8Array;\n  priorVoters: PriorVoters;\n  rootSlot: number;\n  rootSlotValid: number;\n  votes: Lockout[];\n}>;\n\n/**\n * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88\n *\n * @internal\n */\nconst VoteAccountLayout = BufferLayout.struct<VoteAccountData>([\n  Layout.publicKey('nodePubkey'),\n  Layout.publicKey('authorizedWithdrawer'),\n  BufferLayout.u8('commission'),\n  BufferLayout.nu64(), // votes.length\n  BufferLayout.seq<Lockout>(\n    BufferLayout.struct([\n      BufferLayout.nu64('slot'),\n      BufferLayout.u32('confirmationCount'),\n    ]),\n    BufferLayout.offset(BufferLayout.u32(), -8),\n    'votes',\n  ),\n  BufferLayout.u8('rootSlotValid'),\n  BufferLayout.nu64('rootSlot'),\n  BufferLayout.nu64(), // authorizedVoters.length\n  BufferLayout.seq<AuthorizedVoterRaw>(\n    BufferLayout.struct([\n      BufferLayout.nu64('epoch'),\n      Layout.publicKey('authorizedVoter'),\n    ]),\n    BufferLayout.offset(BufferLayout.u32(), -8),\n    'authorizedVoters',\n  ),\n  BufferLayout.struct<PriorVoters>(\n    [\n      BufferLayout.seq(\n        BufferLayout.struct([\n          Layout.publicKey('authorizedPubkey'),\n          BufferLayout.nu64('epochOfLastAuthorizedSwitch'),\n          BufferLayout.nu64('targetEpoch'),\n        ]),\n        32,\n        'buf',\n      ),\n      BufferLayout.nu64('idx'),\n      BufferLayout.u8('isEmpty'),\n    ],\n    'priorVoters',\n  ),\n  BufferLayout.nu64(), // epochCredits.length\n  BufferLayout.seq<EpochCredits>(\n    BufferLayout.struct([\n      BufferLayout.nu64('epoch'),\n      BufferLayout.nu64('credits'),\n      BufferLayout.nu64('prevCredits'),\n    ]),\n    BufferLayout.offset(BufferLayout.u32(), -8),\n    'epochCredits',\n  ),\n  BufferLayout.struct<BlockTimestamp>(\n    [BufferLayout.nu64('slot'), BufferLayout.nu64('timestamp')],\n    'lastTimestamp',\n  ),\n]);\n\ntype VoteAccountArgs = {\n  nodePubkey: PublicKey;\n  authorizedWithdrawer: PublicKey;\n  commission: number;\n  rootSlot: number | null;\n  votes: Lockout[];\n  authorizedVoters: AuthorizedVoter[];\n  priorVoters: PriorVoter[];\n  epochCredits: EpochCredits[];\n  lastTimestamp: BlockTimestamp;\n};\n\n/**\n * VoteAccount class\n */\nexport class VoteAccount {\n  nodePubkey: PublicKey;\n  authorizedWithdrawer: PublicKey;\n  commission: number;\n  rootSlot: number | null;\n  votes: Lockout[];\n  authorizedVoters: AuthorizedVoter[];\n  priorVoters: PriorVoter[];\n  epochCredits: EpochCredits[];\n  lastTimestamp: BlockTimestamp;\n\n  /**\n   * @internal\n   */\n  constructor(args: VoteAccountArgs) {\n    this.nodePubkey = args.nodePubkey;\n    this.authorizedWithdrawer = args.authorizedWithdrawer;\n    this.commission = args.commission;\n    this.rootSlot = args.rootSlot;\n    this.votes = args.votes;\n    this.authorizedVoters = args.authorizedVoters;\n    this.priorVoters = args.priorVoters;\n    this.epochCredits = args.epochCredits;\n    this.lastTimestamp = args.lastTimestamp;\n  }\n\n  /**\n   * Deserialize VoteAccount from the account data.\n   *\n   * @param buffer account data\n   * @return VoteAccount\n   */\n  static fromAccountData(\n    buffer: Buffer | Uint8Array | Array<number>,\n  ): VoteAccount {\n    const versionOffset = 4;\n    const va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset);\n\n    let rootSlot: number | null = va.rootSlot;\n    if (!va.rootSlotValid) {\n      rootSlot = null;\n    }\n\n    return new VoteAccount({\n      nodePubkey: new PublicKey(va.nodePubkey),\n      authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer),\n      commission: va.commission,\n      votes: va.votes,\n      rootSlot,\n      authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter),\n      priorVoters: getPriorVoters(va.priorVoters),\n      epochCredits: va.epochCredits,\n      lastTimestamp: va.lastTimestamp,\n    });\n  }\n}\n\nfunction parseAuthorizedVoter({\n  authorizedVoter,\n  epoch,\n}: AuthorizedVoterRaw): AuthorizedVoter {\n  return {\n    epoch,\n    authorizedVoter: new PublicKey(authorizedVoter),\n  };\n}\n\nfunction parsePriorVoters({\n  authorizedPubkey,\n  epochOfLastAuthorizedSwitch,\n  targetEpoch,\n}: PriorVoterRaw): PriorVoter {\n  return {\n    authorizedPubkey: new PublicKey(authorizedPubkey),\n    epochOfLastAuthorizedSwitch,\n    targetEpoch,\n  };\n}\n\nfunction getPriorVoters({buf, idx, isEmpty}: PriorVoters): PriorVoter[] {\n  if (isEmpty) {\n    return [];\n  }\n\n  return [\n    ...buf.slice(idx + 1).map(parsePriorVoters),\n    ...buf.slice(0, idx).map(parsePriorVoters),\n  ];\n}\n","const endpoint = {\n  http: {\n    devnet: 'http://api.devnet.solana.com',\n    testnet: 'http://api.testnet.solana.com',\n    'mainnet-beta': 'http://api.mainnet-beta.solana.com/',\n  },\n  https: {\n    devnet: 'https://api.devnet.solana.com',\n    testnet: 'https://api.testnet.solana.com',\n    'mainnet-beta': 'https://api.mainnet-beta.solana.com/',\n  },\n};\n\nexport type Cluster = 'devnet' | 'testnet' | 'mainnet-beta';\n\n/**\n * Retrieves the RPC API URL for the specified cluster\n * @param {Cluster} [cluster=\"devnet\"] - The cluster name of the RPC API URL to use. Possible options: 'devnet' | 'testnet' | 'mainnet-beta'\n * @param {boolean} [tls=\"http\"] - Use TLS when connecting to cluster.\n *\n * @returns {string} URL string of the RPC endpoint\n */\nexport function clusterApiUrl(cluster?: Cluster, tls?: boolean): string {\n  const key = tls === false ? 'http' : 'https';\n\n  if (!cluster) {\n    return endpoint[key]['devnet'];\n  }\n\n  const url = endpoint[key][cluster];\n  if (!url) {\n    throw new Error(`Unknown ${key} cluster: ${cluster}`);\n  }\n  return url;\n}\n","import type {Buffer} from 'buffer';\n\nimport {\n  BlockheightBasedTransactionConfirmationStrategy,\n  Connection,\n  DurableNonceTransactionConfirmationStrategy,\n  TransactionConfirmationStrategy,\n} from '../connection';\nimport type {TransactionSignature} from '../transaction';\nimport type {ConfirmOptions} from '../connection';\n\n/**\n * Send and confirm a raw transaction\n *\n * If `commitment` option is not specified, defaults to 'max' commitment.\n *\n * @param {Connection} connection\n * @param {Buffer} rawTransaction\n * @param {TransactionConfirmationStrategy} confirmationStrategy\n * @param {ConfirmOptions} [options]\n * @returns {Promise<TransactionSignature>}\n */\nexport async function sendAndConfirmRawTransaction(\n  connection: Connection,\n  rawTransaction: Buffer,\n  confirmationStrategy: TransactionConfirmationStrategy,\n  options?: ConfirmOptions,\n): Promise<TransactionSignature>;\n\n/**\n * @deprecated Calling `sendAndConfirmRawTransaction()` without a `confirmationStrategy`\n * is no longer supported and will be removed in a future version.\n */\n// eslint-disable-next-line no-redeclare\nexport async function sendAndConfirmRawTransaction(\n  connection: Connection,\n  rawTransaction: Buffer,\n  options?: ConfirmOptions,\n): Promise<TransactionSignature>;\n\n// eslint-disable-next-line no-redeclare\nexport async function sendAndConfirmRawTransaction(\n  connection: Connection,\n  rawTransaction: Buffer,\n  confirmationStrategyOrConfirmOptions:\n    | TransactionConfirmationStrategy\n    | ConfirmOptions\n    | undefined,\n  maybeConfirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n  let confirmationStrategy: TransactionConfirmationStrategy | undefined;\n  let options: ConfirmOptions | undefined;\n  if (\n    confirmationStrategyOrConfirmOptions &&\n    Object.prototype.hasOwnProperty.call(\n      confirmationStrategyOrConfirmOptions,\n      'lastValidBlockHeight',\n    )\n  ) {\n    confirmationStrategy =\n      confirmationStrategyOrConfirmOptions as BlockheightBasedTransactionConfirmationStrategy;\n    options = maybeConfirmOptions;\n  } else if (\n    confirmationStrategyOrConfirmOptions &&\n    Object.prototype.hasOwnProperty.call(\n      confirmationStrategyOrConfirmOptions,\n      'nonceValue',\n    )\n  ) {\n    confirmationStrategy =\n      confirmationStrategyOrConfirmOptions as DurableNonceTransactionConfirmationStrategy;\n    options = maybeConfirmOptions;\n  } else {\n    options = confirmationStrategyOrConfirmOptions as\n      | ConfirmOptions\n      | undefined;\n  }\n  const sendOptions = options && {\n    skipPreflight: options.skipPreflight,\n    preflightCommitment: options.preflightCommitment || options.commitment,\n    minContextSlot: options.minContextSlot,\n  };\n\n  const signature = await connection.sendRawTransaction(\n    rawTransaction,\n    sendOptions,\n  );\n\n  const commitment = options && options.commitment;\n  const confirmationPromise = confirmationStrategy\n    ? connection.confirmTransaction(confirmationStrategy, commitment)\n    : connection.confirmTransaction(signature, commitment);\n  const status = (await confirmationPromise).value;\n\n  if (status.err) {\n    throw new Error(\n      `Raw transaction ${signature} failed (${JSON.stringify(status)})`,\n    );\n  }\n\n  return signature;\n}\n","export * from './account';\nexport * from './blockhash';\nexport * from './bpf-loader-deprecated';\nexport * from './bpf-loader';\nexport * from './connection';\nexport * from './epoch-schedule';\nexport * from './errors';\nexport * from './fee-calculator';\nexport * from './keypair';\nexport * from './loader';\nexport * from './message';\nexport * from './nonce-account';\nexport * from './programs';\nexport * from './publickey';\nexport * from './transaction';\nexport * from './validator-info';\nexport * from './vote-account';\nexport * from './sysvar';\nexport * from './utils';\n\n/**\n * There are 1-billion lamports in one SOL\n */\nexport const LAMPORTS_PER_SOL = 1000000000;\n"]}