{"version":3,"sources":["../../src/hive-tx/Transaction.ts","../../src/hive-tx/helpers/ByteBuffer.ts","../../src/hive-tx/config.ts","../../src/hive-tx/helpers/Signature.ts","../../src/hive-tx/helpers/PublicKey.ts","../../src/hive-tx/helpers/Asset.ts","../../src/hive-tx/helpers/HexBuffer.ts","../../src/hive-tx/helpers/serializer.ts","../../src/hive-tx/helpers/sleep.ts","../../src/hive-tx/helpers/call.ts","../../src/hive-tx/helpers/PrivateKey.ts","../../src/hive-tx/helpers/aes.ts","../../src/hive-tx/helpers/deserializer.ts","../../src/hive-tx/helpers/memo.ts","../../src/hive-tx/helpers/utils.ts"],"names":["EMPTY_BUFFER","_encoder","_decoder","getEncoder","s","utf8","i","c","next","getDecoder","b","bytes","result","byte","codePoint","ByteBuffer","_ByteBuffer","capacity","littleEndian","buffers","buf","bb","view","offset","buffer","source","value","relative","src","copy","begin","end","target","targetOffset","sourceOffset","sourceLimit","targetRelative","len","current","length","forceCopy","limit","size","str","currentOffset","encoded","lenVarintSize","start","lenResult","lenValue","lenLength","config","DEFAULT_SERVER_RPC_PROXY_METHODS","serverRpcProxy","setServerRpcProxy","opts","url","headers","k","v","timeoutMs","methods","m","pos","fallback","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","r","bool","Signature","_Signature","data","recovery","compressed","string","temp","hexToBytes","bytesToHex","message","sig","secp256k1","PublicKey","_PublicKey","key","prefix","wif","expectedPrefix","bs58","checksum","expectedChecksum","ripemd160","isUint8ArrayEqual","signature","encodePublic","a","Asset","_Asset","amount","symbol","expectedSymbol","amountString","HexBuffer","_HexBuffer","OPERATION_IDS","VoidSerializer","StringSerializer","Int16Serializer","Int64Serializer","UInt8Serializer","UInt16Serializer","UInt32Serializer","UInt64Serializer","BooleanSerializer","StaticVariantSerializer","itemSerializers","id","item","AssetSerializer","asset","precision","DateSerializer","PublicKeySerializer","BinarySerializer","VariableBinarySerializer","FlatMapSerializer","keySerializer","valueSerializer","ArraySerializer","itemSerializer","ObjectSerializer","keySerializers","serializer","error","OptionalSerializer","AuthoritySerializer","BeneficiarySerializer","PriceSerializer","ChainPropertiesSerializer","OperationDataSerializer","operationId","definitions","objectSerializer","OperationSerializers","ProposalUpdateSerializer","OperationSerializer","operation","TransactionSerializer","EncryptedMemoSerializer","Serializer","sleep","ms","resolve","isNodeRuntime","serverIdentityHeaders","rpcProxyStats","ProxyMiss","reason","errorMessage","e","proxyConsecutiveMisses","proxyOpenUntil","resetRpcProxyBreaker","proxyRpcCall","proxy","method","params","callerTimeoutMs","externalSignal","validate","dot","tSignal","cleanupTimeout","createTimeoutSignal","signal","cleanupMerge","mergeSignals","res","relayed","RPCError","rpcError","NodeError","node","parseRetryAfterMs","header","secs","dateMs","delta","PRE_CONNECTION_ERRORS","BROWSER_NETWORK_ERRORS","flattenErrorText","parts","cause","depth","isBroadcastSafeToRetry","text","code","msg","isNodeLevelRPCError","apiOf","RATE_LIMIT_BASE_MS","RATE_LIMIT_MAX_MS","RATE_LIMIT_STREAK_RESET_MS","MAX_API_FAILURES_BEFORE_COOLDOWN","API_COOLDOWN_MS","HEAD_BLOCK_MAX_AGE_MS","STALE_BLOCK_THRESHOLD","LATENCY_EWMA_ALPHA","LATENCY_MIN_SAMPLES","LATENCY_MAX_AGE_MS","LATENCY_REPROBE_MS","LATENCY_UNPROVEN_PRIOR_MS","LATENCY_SLOW_FAILURE_MS","NodeHealthTracker","h","durationMs","profileKey","apiFail","now","p","elapsedMs","existing","retryAfterMs","hasHeader","cooldown","blockNum","recent","best","healthy","unhealthy","ordered","d","probe","threshold","cand","candTouch","touch","rpcHealthTracker","restHealthTracker","HedgeBudget","tokens","rpcHedgeBudget","adaptiveAttemptTimeout","tracker","callerTimeout","explicit","ewma","recordError","tryRecordHeadBlock","block","createTimeoutReason","err","controller","timer","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","timeout","shouldRetry","body","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","served","deadline","triedInRound","attempt","orderedNodes","callStart","callRPCBroadcast","triedNodes","apiMethods","callREST","endpoint","restProfileKey","apiNodes","alreadyRecorded","baseUrl","path","paramObj","processedPathParams","restSignal","restCleanup","restCallStart","response","callWithQuorum","quorum","allNodes","arr","j","currentBatchSize","allResults","batchNodes","promises","batchResults","consensusResult","findConsensus","results","resultGroups","consensusGroup","group","chainId","Transaction","_Transaction","options","operationName","operationBody","keys","digest","txId","checkStatus","maxPollAttempts","status","transactionData","sha256","expiration","props","refBlockPrefix","expirationIso","NETWORK_ID","PrivateKey","_PrivateKey","decodePrivate","seed","username","password","role","rv","encodePrivate","publicKey","sha512","doubleSha256","input","encodedKey","checksumVerify","encrypt","privateKey","nonce","uniqueNonce","crypt","decrypt","nonceL","S","ebuf","encryptionKey","iv","tag","check","cbuf","check32","cryptoJsDecrypt","cryptoJsEncrypt","messageBuffer","AESCBC","uniqueNonceEntropy","randomPrivateKey","long","entropy","PublicKeyDeserializer","fixedBuf","UInt64Deserializer","UInt32Deserializer","BinaryDeserializer","bCopy","BufferDeserializer","keyDeserializers","obj","deserializer","EncryptedMemoDeserializer","Deserializer","encode","memo","testNonce","checkEncryption","toPrivateObj","toPublicObj","mbuf","memoBuffer","mbuf2","decode","from","to","encrypted","otherpub","encodeTest","plaintext","cyphertext","o","Memo","utils_exports","__export","buildWitnessSetProperties","makeBitMaskFilter","operations","validateUsername","suffix","ref","label","allowedOperations","reduceFunction","low","high","allowedOperation","owner","type","serialize"],"mappings":"6QAAA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,IAAA,CAAA,IAAA,CAAA,CAAA,EAAA,CAAA,C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KAAK,CAACY,CAAAA,CAAK4V,GAAUD,CAAAA,CAAMxF,CAAAA,CAAMnQ,CAAG,CAAC,CAAC,CAAC,EACpD,CACA,OAAAZ,CAAAA,CAAK,MAAM,IAAA,CAAK,CAACuB,EAAQhG,CAAAA,GAAWgG,CAAAA,CAAE,CAAC,CAAA,CAAE,cAAchG,CAAAA,CAAE,CAAC,CAAC,CAAC,CAAA,CACrD,CAAC,wBAAA,CAA0ByE,CAAI,CACxC,CAAA,CAEMwW,GAAY,CAAC5S,CAAAA,CAAiB5D,IAAc,CAChD,IAAM3D,EAAS,IAAIT,CAAAA,CAAWA,CAAAA,CAAW,gBAAA,CAAkBA,EAAW,aAAa,CAAA,CACnF,OAAAgI,CAAAA,CAAWvH,CAAAA,CAAQ2D,CAAI,CAAA,CACvB3D,CAAAA,CAAO,IAAA,EAAK,CAELiE,WAAW,IAAI,UAAA,CAAWjE,EAAO,QAAA,EAAU,CAAC,CACrD,CAAA","file":"hive.mjs","sourcesContent":["import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\nimport { PrivateKey } from './helpers/PrivateKey'\nimport {\n  OperationName,\n  OperationBody,\n  TransactionType,\n  TransactionStatus,\n  BroadcastResult\n} from './types'\nimport { ByteBuffer } from './helpers/ByteBuffer'\nimport { Serializer } from './helpers/serializer'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { config } from './config'\nimport { callRPC, callRPCBroadcast, RPCError } from './helpers/call'\nimport { DigestData } from './types'\nimport { sleep } from './helpers/sleep'\n\nconst chainId = hexToBytes(config.chain_id)\n\ninterface TransactionOptions {\n  transaction?: TransactionType | Transaction\n  /**\n   * Transaction expiration in milliseconds (ms) - max 86400000 (24 hours)\n   * @default 60_000\n   */\n  expiration?: number\n}\n\nexport class Transaction {\n  transaction?: TransactionType\n\n  expiration: number = 60_000\n\n  private txId?: string\n\n  constructor(options?: TransactionOptions) {\n    if (options?.transaction) {\n      if (options.transaction instanceof Transaction) {\n        this.transaction = options.transaction.transaction\n        this.expiration = options.transaction.expiration\n      } else {\n        this.transaction = options.transaction\n      }\n      // A transaction built externally (e.g. from a hive-uri signing request)\n      // may omit the `signatures` array. sign(), addSignature() and broadcast()\n      // all assume it exists, so normalize it here to avoid\n      // \"Cannot read property 'push' of undefined\" on sign.\n      if (this.transaction && !Array.isArray(this.transaction.signatures)) {\n        this.transaction.signatures = []\n      }\n      this.txId = this.digest().txId\n    }\n    if (options?.expiration) {\n      this.expiration = options.expiration\n    }\n  }\n\n  /**\n   * Adds an operation to the transaction. If no transaction exists, creates one first.\n   * @template O Operation name type for type safety\n   * @param operationName The name/type of the operation to add (e.g., 'transfer', 'vote', 'comment')\n   * @param operationBody The operation data/body for the specified operation type\n   * @returns Promise that resolves when the operation is added\n   * @throws Error if transaction creation fails or global properties cannot be retrieved\n   */\n  async addOperation<O extends OperationName>(\n    operationName: O,\n    operationBody: OperationBody<O>\n  ): Promise<void> {\n    if (!this.transaction) {\n      await this.createTransaction(this.expiration)\n    }\n    this.transaction!.operations.push([operationName, operationBody])\n  }\n\n  /**\n   * Signs the transaction with the provided key(s), supporting both single and multi-signature transactions.\n   * For multi-signature, you can sign with all keys at once or sign individually by calling this method multiple times.\n   * @param keys Single PrivateKey or array of PrivateKeys to sign the transaction with\n   * @returns The signed transaction\n   * @throws Error if no transaction exists to sign\n   */\n  sign(keys: PrivateKey | PrivateKey[]): TransactionType {\n    if (!this.transaction) {\n      throw new Error('First create a transaction by .addOperation()')\n    }\n    if (this.transaction) {\n      const { digest, txId } = this.digest()\n      if (!Array.isArray(keys)) {\n        keys = [keys]\n      }\n      for (const key of keys) {\n        const signature = key.sign(digest)\n        this.transaction.signatures.push(signature.customToString())\n      }\n      this.txId = txId\n      return this.transaction\n    } else {\n      throw new Error('No transaction to sign')\n    }\n  }\n\n  /**\n   * Broadcasts the signed transaction to the Hive network.\n   * Automatically handles retries and duplicate transaction detection.\n   * @param checkStatus By default (false) the transaction is not guaranteed to be included in a block.\n   * For example the transaction can expire while waiting in mempool.\n   * If you pass true here, the function will wait for the transaction to be either included or dropped\n   * before returning a result.\n   * @returns Promise resolving to broadcast result\n   * @throws Error if no transaction exists or transaction is not signed or transaction got rejected\n   */\n  async broadcast(checkStatus = false): Promise<BroadcastResult> {\n    if (!this.transaction) {\n      throw new Error(\n        'Attempted to broadcast an empty transaction. Add operations by .addOperation()'\n      )\n    }\n    if (this.transaction.signatures.length === 0) {\n      throw new Error(\n        'Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)'\n      )\n    }\n    try {\n      await callRPCBroadcast('condenser_api.broadcast_transaction', [this.transaction])\n    } catch (e) {\n      if (e instanceof RPCError && e.message.includes('Duplicate transaction check failed')) {\n        // ignore duplicate transaction error as this can happen when we retry the broadcast\n      } else {\n        throw e\n      }\n    }\n    if (!this.txId) {\n      this.txId = this.digest().txId\n    }\n    if (!checkStatus) {\n      return { tx_id: this.txId, status: 'unknown' }\n    }\n    // Poll until the transaction reaches a final state or max attempts exceeded.\n    // With 60 attempts: delays grow from 1.3s to 19s, total wait ~10 minutes.\n    const maxPollAttempts = 60\n    await sleep(1000)\n    let status = await this.checkStatus()\n    let i = 1\n    while (\n      status?.status !== 'within_irreversible_block' &&\n      status?.status !== 'expired_irreversible' &&\n      status?.status !== 'too_old' &&\n      i < maxPollAttempts\n    ) {\n      await sleep(1000 + i * 300)\n      status = await this.checkStatus()\n      i++\n    }\n    return {\n      tx_id: this.txId,\n      status: (status?.status ?? 'unknown') as BroadcastResult['status']\n    }\n  }\n\n  /**\n   * Returns the transaction digest containing the transaction ID and hash.\n   * The digest can be used to verify signatures and for transaction identification.\n   * @returns DigestData containing transaction ID and hash\n   * @throws Error if no transaction exists\n   */\n  digest(): DigestData {\n    if (!this.transaction) {\n      throw new Error('First create a transaction by .addOperation()')\n    }\n    const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n    const temp = { ...this.transaction }\n    try {\n      Serializer.Transaction(buffer, temp)\n    } catch (cause) {\n      throw new Error('Unable to serialize transaction: ' + cause)\n    }\n    buffer.flip()\n    const transactionData = new Uint8Array(buffer.toBuffer())\n    const txId = bytesToHex(sha256(transactionData)).slice(0, 40)\n    const digest = sha256(new Uint8Array([...chainId, ...transactionData]))\n    return { digest, txId }\n  }\n\n  /**\n   * Adds a signature to an already created transaction. Useful when signing with external tools.\n   * Multiple signatures can be added one at a time for multi-signature transactions.\n   * @param signature The signature string in hex format (must be exactly 130 characters)\n   * @returns The transaction with the added signature\n   * @throws Error if no transaction exists or signature format is invalid\n   */\n  addSignature(signature: string): TransactionType {\n    if (!this.transaction) {\n      throw new Error('First create a transaction by .create(operations)')\n    }\n    if (typeof signature !== 'string') {\n      throw new Error('Signature must be string')\n    }\n    if (signature.length !== 130) {\n      throw new Error('Signature must be 130 characters long')\n    }\n    this.transaction.signatures.push(signature)\n    return this.transaction\n  }\n\n  /** Get status of this transaction. Usually called internally after broadcasting. */\n  async checkStatus(): Promise<TransactionStatus> {\n    if (!this.txId) {\n      this.txId = this.digest().txId\n    }\n    return callRPC('transaction_status_api.find_transaction', {\n      transaction_id: this.txId,\n      expiration: this.transaction?.expiration\n    })\n  }\n\n  /**\n   * Creates the transaction structure and initializes it with blockchain data.\n   * Retrieves current head block information and sets up reference block data.\n   * @private\n   * @param expiration Transaction expiration in milliseconds\n   */\n  private createTransaction = async (expiration: number) => {\n    const props = await callRPC('condenser_api.get_dynamic_global_properties', [])\n    const bytes = hexToBytes(props.head_block_id)\n    const refBlockPrefix = Number(new Uint32Array(bytes.buffer, bytes.byteOffset + 4, 1)[0])\n    const expirationIso = new Date(Date.now() + expiration).toISOString().slice(0, -5)\n    this.transaction = {\n      expiration: expirationIso,\n      extensions: [],\n      operations: [],\n      ref_block_num: props.head_block_number & 0xffff,\n      ref_block_prefix: refBlockPrefix,\n      signatures: []\n    }\n  }\n}\n","/**\n * @license bytebuffer.ts (c) 2015 Daniel Wirtz <dcode@dcode.io>\n * Backing buffer: ArrayBuffer, Accessor: DataView\n * Released under the Apache License, Version 2.0\n * see: https://github.com/dcodeIO/bytebuffer.ts for details\n * modified by @xmcl/bytebuffer\n * And customized for hive-tx\n */\n\nconst EMPTY_BUFFER = new ArrayBuffer(0)\n\n// Lazy-init to avoid crashing on runtimes that lack TextEncoder/TextDecoder\n// (notably React Native with Hermes). Falls back to manual UTF-8 encode/decode.\nlet _encoder: { encode(s: string): Uint8Array } | null = null\nlet _decoder: { decode(b: BufferSource): string } | null = null\n\nfunction getEncoder(): { encode(s: string): Uint8Array } {\n  if (!_encoder) {\n    if (typeof TextEncoder !== 'undefined') {\n      _encoder = new TextEncoder()\n    } else {\n      _encoder = {\n        encode(s: string): Uint8Array {\n          // Manual UTF-8 encode fallback\n          const utf8: number[] = []\n          for (let i = 0; i < s.length; i++) {\n            let c = s.charCodeAt(i)\n            if (c < 0x80) {\n              utf8.push(c)\n            } else if (c < 0x800) {\n              utf8.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n            } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n              const next = s.charCodeAt(++i)\n              c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n              utf8.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n            } else {\n              utf8.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n            }\n          }\n          return new Uint8Array(utf8)\n        },\n      }\n    }\n  }\n  return _encoder\n}\n\nfunction getDecoder(): { decode(b: BufferSource): string } {\n  if (!_decoder) {\n    if (typeof TextDecoder !== 'undefined') {\n      _decoder = new TextDecoder()\n    } else {\n      _decoder = {\n        decode(b: BufferSource): string {\n          const bytes = b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array((b as ArrayBufferView).buffer, (b as ArrayBufferView).byteOffset, (b as ArrayBufferView).byteLength)\n          let result = ''\n          for (let i = 0; i < bytes.length; ) {\n            const byte = bytes[i]\n            let codePoint: number\n            if (byte < 0x80) { codePoint = byte; i += 1 }\n            else if ((byte & 0xe0) === 0xc0) { codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f); i += 2 }\n            else if ((byte & 0xf0) === 0xe0) { codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f); i += 3 }\n            else { codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f); i += 4 }\n            if (codePoint <= 0xffff) { result += String.fromCharCode(codePoint) }\n            else { codePoint -= 0x10000; result += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) }\n          }\n          return result\n        },\n      }\n    }\n  }\n  return _decoder\n}\n\nexport class ByteBuffer {\n  static LITTLE_ENDIAN = true\n  static BIG_ENDIAN = false\n  static DEFAULT_CAPACITY = 16\n  static DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN\n\n  buffer: ArrayBufferLike\n  view: DataView\n  offset: number\n  markedOffset: number\n  limit: number\n  littleEndian: boolean\n\n  constructor(\n    capacity: number = ByteBuffer.DEFAULT_CAPACITY,\n    littleEndian: boolean = ByteBuffer.DEFAULT_ENDIAN\n  ) {\n    this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity)\n    this.view = capacity === 0 ? new DataView(EMPTY_BUFFER) : new DataView(this.buffer)\n    this.offset = 0\n    this.markedOffset = -1\n    this.limit = capacity\n    this.littleEndian = littleEndian\n  }\n\n  static allocate(capacity?: number, littleEndian?: boolean): ByteBuffer {\n    return new ByteBuffer(capacity, littleEndian)\n  }\n\n  static concat(\n    buffers: Array<ByteBuffer | ArrayBuffer | Uint8Array | number[]>,\n    littleEndian?: boolean\n  ): ByteBuffer {\n    let capacity = 0\n    for (let i = 0; i < buffers.length; ++i) {\n      const buf = buffers[i]\n      if (buf instanceof ByteBuffer) {\n        capacity += buf.limit - buf.offset\n      } else if (buf instanceof Uint8Array) {\n        capacity += buf.length\n      } else if (buf instanceof ArrayBuffer) {\n        capacity += buf.byteLength\n      } else if (Array.isArray(buf)) {\n        capacity += buf.length\n      } else {\n        throw TypeError('Illegal buffer')\n      }\n    }\n\n    if (capacity === 0) {\n      return new ByteBuffer(0, littleEndian)\n    }\n\n    const bb = new ByteBuffer(capacity, littleEndian)\n    const view = new Uint8Array(bb.buffer)\n    let offset = 0\n\n    for (let i = 0; i < buffers.length; ++i) {\n      let buf = buffers[i]\n      if (buf instanceof ByteBuffer) {\n        view.set(new Uint8Array(buf.buffer, buf.offset, buf.limit - buf.offset), offset)\n        offset += buf.limit - buf.offset\n      } else if (buf instanceof Uint8Array) {\n        view.set(buf, offset)\n        offset += buf.length\n      } else if (buf instanceof ArrayBuffer) {\n        view.set(new Uint8Array(buf), offset)\n        offset += buf.byteLength\n      } else {\n        // Array\n        view.set(buf as number[], offset)\n        offset += (buf as number[]).length\n      }\n    }\n\n    bb.limit = bb.offset = offset\n    bb.offset = 0\n    return bb\n  }\n\n  static wrap(\n    buffer: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n    littleEndian?: boolean\n  ): ByteBuffer {\n    if (buffer instanceof ByteBuffer) {\n      const bb = buffer.clone()\n      bb.markedOffset = -1\n      return bb\n    }\n\n    let bb: ByteBuffer\n    if (buffer instanceof Uint8Array) {\n      bb = new ByteBuffer(0, littleEndian)\n      if (buffer.length > 0) {\n        bb.buffer = buffer.buffer\n        bb.offset = buffer.byteOffset\n        bb.limit = buffer.byteOffset + buffer.byteLength\n        bb.view = new DataView(buffer.buffer)\n      }\n    } else if (buffer instanceof ArrayBuffer) {\n      bb = new ByteBuffer(0, littleEndian)\n      if (buffer.byteLength > 0) {\n        bb.buffer = buffer\n        bb.offset = 0\n        bb.limit = buffer.byteLength\n        bb.view = buffer.byteLength > 0 ? new DataView(buffer) : new DataView(EMPTY_BUFFER)\n      }\n    } else if (Array.isArray(buffer)) {\n      bb = new ByteBuffer(buffer.length, littleEndian)\n      bb.limit = buffer.length\n      new Uint8Array(bb.buffer).set(buffer)\n    } else {\n      throw TypeError('Illegal buffer')\n    }\n\n    return bb\n  }\n\n  writeBytes(\n    source: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n    offset?: number\n  ): ByteBuffer {\n    return this.append(source, offset)\n  }\n\n  writeInt8(value: number, offset?: number): ByteBuffer {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    if (offset + 1 > this.buffer.byteLength) {\n      this.resize(offset + 1)\n    }\n\n    this.view.setInt8(offset, value)\n\n    if (relative) this.offset += 1\n    return this\n  }\n\n  writeByte(value: number, offset?: number): ByteBuffer {\n    return this.writeInt8(value, offset)\n  }\n\n  writeUint8(value: number, offset?: number): ByteBuffer {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    if (offset + 1 > this.buffer.byteLength) {\n      this.resize(offset + 1)\n    }\n\n    this.view.setUint8(offset, value)\n\n    if (relative) this.offset += 1\n    return this\n  }\n\n  writeUInt8(value: number, offset?: number): ByteBuffer {\n    return this.writeUint8(value, offset)\n  }\n\n  readUint8(offset?: number): number {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    const value = this.view.getUint8(offset)\n    if (relative) this.offset += 1\n    return value\n  }\n\n  readUInt8(offset?: number): number {\n    return this.readUint8(offset)\n  }\n\n  writeInt16(value: number, offset?: number): ByteBuffer {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    if (offset + 2 > this.buffer.byteLength) {\n      this.resize(offset + 2)\n    }\n\n    this.view.setInt16(offset, value, this.littleEndian)\n\n    if (relative) this.offset += 2\n    return this\n  }\n\n  writeShort(value: number, offset?: number): ByteBuffer {\n    return this.writeInt16(value, offset)\n  }\n\n  writeUint16(value: number, offset?: number): ByteBuffer {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    if (offset + 2 > this.buffer.byteLength) {\n      this.resize(offset + 2)\n    }\n\n    this.view.setUint16(offset, value, this.littleEndian)\n\n    if (relative) this.offset += 2\n    return this\n  }\n\n  writeUInt16(value: number, offset?: number): ByteBuffer {\n    return this.writeUint16(value, offset)\n  }\n\n  writeInt32(value: number, offset?: number): ByteBuffer {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    if (offset + 4 > this.buffer.byteLength) {\n      this.resize(offset + 4)\n    }\n\n    this.view.setInt32(offset, value, this.littleEndian)\n\n    if (relative) this.offset += 4\n    return this\n  }\n\n  writeInt(value: number, offset?: number): ByteBuffer {\n    return this.writeInt32(value, offset)\n  }\n\n  writeUint32(value: number, offset?: number): ByteBuffer {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    if (offset + 4 > this.buffer.byteLength) {\n      this.resize(offset + 4)\n    }\n\n    this.view.setUint32(offset, value, this.littleEndian)\n\n    if (relative) this.offset += 4\n    return this\n  }\n\n  writeUInt32(value: number, offset?: number): ByteBuffer {\n    return this.writeUint32(value, offset)\n  }\n\n  readUint32(offset?: number): number {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    const value = this.view.getUint32(offset, this.littleEndian)\n    if (relative) {\n      this.offset += 4\n    }\n    return value\n  }\n\n  readUInt32 = this.readUint32\n\n  append(source: ByteBuffer | ArrayBuffer | Uint8Array | number[], offset?: number): ByteBuffer {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    let src: Uint8Array\n    if (source instanceof ByteBuffer) {\n      src = new Uint8Array(source.buffer, source.offset, source.limit - source.offset)\n      source.offset += src.length\n    } else if (source instanceof Uint8Array) {\n      src = source\n    } else if (source instanceof ArrayBuffer) {\n      src = new Uint8Array(source)\n    } else {\n      src = new Uint8Array(source)\n    }\n\n    if (src.length <= 0) return this\n\n    if (offset + src.length > this.buffer.byteLength) {\n      this.resize(offset + src.length)\n    }\n\n    new Uint8Array(this.buffer).set(src, offset)\n\n    if (relative) this.offset += src.length\n    return this\n  }\n\n  clone(copy?: boolean): ByteBuffer {\n    const bb = new ByteBuffer(0, this.littleEndian)\n    if (copy) {\n      bb.buffer = new ArrayBuffer(this.buffer.byteLength)\n      new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer))\n      bb.view = new DataView(bb.buffer)\n    } else {\n      bb.buffer = this.buffer\n      bb.view = this.view\n    }\n    bb.offset = this.offset\n    bb.markedOffset = this.markedOffset\n    bb.limit = this.limit\n    return bb\n  }\n\n  copy(begin?: number, end?: number): ByteBuffer {\n    if (begin === undefined) begin = this.offset\n    if (end === undefined) end = this.limit\n\n    if (begin === end) {\n      return new ByteBuffer(0, this.littleEndian)\n    }\n\n    const capacity = end - begin\n    const bb = new ByteBuffer(capacity, this.littleEndian)\n    bb.offset = 0\n    bb.limit = capacity\n\n    new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer).subarray(begin, end), 0)\n    return bb\n  }\n\n  copyTo(\n    target: ByteBuffer,\n    targetOffset?: number,\n    sourceOffset?: number,\n    sourceLimit?: number\n  ): ByteBuffer {\n    const targetRelative = typeof targetOffset === 'undefined'\n    const relative = typeof sourceOffset === 'undefined'\n    targetOffset = targetRelative ? target.offset : targetOffset!\n    sourceOffset = relative ? this.offset : sourceOffset!\n    sourceLimit = sourceLimit === undefined ? this.limit : sourceLimit\n\n    const len = sourceLimit - sourceOffset\n    if (len === 0) return target\n\n    target.ensureCapacity(targetOffset + len)\n    new Uint8Array(target.buffer).set(\n      new Uint8Array(this.buffer).subarray(sourceOffset, sourceLimit),\n      targetOffset\n    )\n\n    if (relative) this.offset += len\n    if (targetRelative) target.offset += len\n    return this\n  }\n\n  ensureCapacity(capacity: number): ByteBuffer {\n    let current = this.buffer.byteLength\n    if (current < capacity) {\n      return this.resize((current *= 2) > capacity ? current : capacity)\n    }\n    return this\n  }\n\n  flip(): ByteBuffer {\n    this.limit = this.offset\n    this.offset = 0\n    return this\n  }\n\n  resize(capacity: number): ByteBuffer {\n    if (this.buffer.byteLength < capacity) {\n      const buffer = new ArrayBuffer(capacity)\n      new Uint8Array(buffer).set(new Uint8Array(this.buffer))\n      this.buffer = buffer\n      this.view = new DataView(buffer)\n    }\n    return this\n  }\n\n  skip(length: number): ByteBuffer {\n    this.offset += length\n    return this\n  }\n\n  writeInt64(value: number | bigint, offset?: number): ByteBuffer {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    if (typeof value === 'number') value = BigInt(value)\n\n    if (offset + 8 > this.buffer.byteLength) {\n      this.resize(offset + 8)\n    }\n\n    this.view.setBigInt64(offset, value, this.littleEndian)\n\n    if (relative) this.offset += 8\n    return this\n  }\n\n  writeLong(value: number | bigint, offset?: number): ByteBuffer {\n    return this.writeInt64(value, offset)\n  }\n\n  readInt64(offset?: number): bigint {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    const value = this.view.getBigInt64(offset, this.littleEndian)\n    if (relative) this.offset += 8\n    return value\n  }\n\n  readLong(offset?: number): bigint {\n    return this.readInt64(offset)\n  }\n\n  writeUint64(value: number | bigint, offset?: number): ByteBuffer {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    if (typeof value === 'number') value = BigInt(value)\n\n    if (offset + 8 > this.buffer.byteLength) {\n      this.resize(offset + 8)\n    }\n\n    this.view.setBigUint64(offset, value, this.littleEndian)\n\n    if (relative) this.offset += 8\n    return this\n  }\n\n  writeUInt64(value: number | bigint, offset?: number): ByteBuffer {\n    return this.writeUint64(value, offset)\n  }\n\n  readUint64(offset?: number): bigint {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    const value = this.view.getBigUint64(offset, this.littleEndian)\n    if (relative) this.offset += 8\n    return value\n  }\n\n  readUInt64(offset?: number): bigint {\n    return this.readUint64(offset)\n  }\n\n  toBuffer(forceCopy?: boolean): ArrayBufferLike {\n    const offset = this.offset\n    const limit = this.limit\n    if (!forceCopy && offset === 0 && limit === this.buffer.byteLength) {\n      return this.buffer\n    }\n    if (offset === limit) return EMPTY_BUFFER\n    return this.buffer.slice(offset, limit)\n  }\n\n  toArrayBuffer(forceCopy?: boolean): ArrayBufferLike {\n    return this.toBuffer(forceCopy)\n  }\n\n  writeVarint32(value: number, offset?: number): ByteBuffer | number {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    const size = this.calculateVarint32(value)\n    if (offset + size > this.buffer.byteLength) {\n      this.resize(offset + size)\n    }\n\n    value >>>= 0\n    while (value >= 0x80) {\n      this.view.setUint8(offset++, (value & 0x7f) | 0x80)\n      value >>>= 7\n    }\n    this.view.setUint8(offset++, value)\n\n    if (relative) {\n      this.offset = offset\n      return this\n    }\n    return size\n  }\n\n  readVarint32(offset?: number): number | { value: number; length: number } {\n    const relative = typeof offset === 'undefined'\n    if (typeof offset === 'undefined') {\n      offset = this.offset\n    }\n    let c = 0\n    let value = 0 >>> 0\n    let b: number\n    do {\n      b = this.view.getUint8(offset++)\n      if (c < 5) {\n        value |= (b & 0x7f) << (7 * c)\n      }\n      ++c\n    } while ((b & 0x80) !== 0)\n    value |= 0\n\n    if (relative) {\n      this.offset = offset\n      return value\n    }\n    return { value, length: c }\n  }\n\n  calculateVarint32(value: number): number {\n    value = value >>> 0\n    if (value < 1 << 7) return 1\n    else if (value < 1 << 14) return 2\n    else if (value < 1 << 21) return 3\n    else if (value < 1 << 28) return 4\n    else return 5\n  }\n\n  writeVString(str: string, offset?: number): ByteBuffer | number {\n    const relative = typeof offset === 'undefined'\n    let currentOffset = relative ? this.offset : offset!\n\n    const encoded = getEncoder().encode(str)\n    const len = encoded.length\n    const lenVarintSize = this.calculateVarint32(len)\n\n    if (currentOffset + lenVarintSize + len > this.buffer.byteLength) {\n      this.resize(currentOffset + lenVarintSize + len)\n    }\n\n    this.writeVarint32(len, currentOffset)\n    currentOffset += lenVarintSize\n\n    new Uint8Array(this.buffer).set(encoded, currentOffset)\n    currentOffset += len\n\n    if (relative) {\n      this.offset = currentOffset\n      return this\n    }\n    return currentOffset - (offset || 0)\n  }\n\n  readVString(offset?: number): string | { string: string; length: number } {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    const start = offset\n    const lenResult = this.readVarint32(offset) as { value: number; length: number }\n    const lenValue = lenResult.value\n    const lenLength = lenResult.length\n\n    offset += lenLength\n\n    // TextDecoder can take Uint8Array view directly\n    const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, lenValue))\n    offset += lenValue\n\n    if (relative) {\n      this.offset = offset\n      return str\n    } else {\n      return {\n        string: str,\n        length: offset - start\n      }\n    }\n  }\n\n  readUTF8String(length: number, offset?: number): string | { string: string; length: number } {\n    const relative = typeof offset === 'undefined'\n    if (relative) offset = this.offset\n    else offset = offset!\n\n    // const strBuffer = this.buffer.slice(offset, end)\n    // Faster to view if Shared? No, Decoder takes buffer or view.\n    // Making a view is cheap.\n    // But DataView vs Uint8Array. TextDecoder takes BufferSource (ArrayBuffer or ArrayBufferView).\n    const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, length))\n\n    if (relative) {\n      this.offset += length\n      return str\n    } else {\n      return {\n        string: str,\n        length\n      }\n    }\n  }\n}\n","import type { APIMethods } from './api-types'\n\n/**\n * Unified configuration for Hive blockchain connectivity.\n * This is the single source of truth for node endpoints, timeouts, and chain settings.\n * Mutate this object directly or use ConfigManager.setHiveNodes() for validated updates.\n */\nexport const config = {\n  /**\n   * Array of Hive API node endpoints for load balancing and failover.\n   */\n  /*\n   * techcoderx.com is deliberately absent: its condenser_api.get_accounts serves\n   * account rows with posting_json_metadata stripped to \"\" while balances and\n   * reputation are correct. That is a well-formed result, so it passes shape\n   * validation and the health tracker keeps it ranked by latency alone.\n   *\n   * Wallet token visibility is read entirely from profile.tokens[].meta.show in\n   * that metadata, so a stripped row reads as \"this user enabled nothing\" and the\n   * wallet silently falls back to HIVE/HP/HBD/Points. getAccountFullQueryOptions\n   * cross-checks against the hivemind profile and re-reads, but that guard only\n   * fires when hivemind reports profile *values* — an account whose metadata is\n   * just `tokens` (no name/about/image) has none, so it would slip through.\n   * Keeping the node out of the pool removes the dependency on that guard.\n   *\n   * Note this is RPC-only: the same host serves full metadata over its REST\n   * (hafbe) endpoint, so it remains valid in `restNodes`.\n   */\n  nodes: [\n    'https://api.hive.blog',\n    'https://api.deathwing.me',\n    'https://api.openhive.network',\n    'https://api.syncad.com',\n    'https://rpc.mahdiyari.info',\n  ],\n\n  /**\n   * Array of Hive API node endpoints that support REST APIs.\n   * Note: Without the trailing /\n   */\n  restNodes: [\n    'https://api.hive.blog',\n    'https://rpc.mahdiyari.info',\n    'https://api.syncad.com',\n    'https://hiveapi.actifit.io',\n    'https://api.c0ff33a.uk'\n  ],\n\n  /**\n   * Per-API REST node override. Some APIs are served by only a subset of\n   * nodes; list just those capable hosts here so callREST never burns its\n   * (small) retry budget on nodes that 404/503 the API, and a cold start\n   * hits a capable node immediately. Any API not listed falls back to\n   * `restNodes`. The health tracker still orders *within* this list.\n   *\n   * hivesense: empirically only ~2 public nodes serve /hivesense-api (the\n   * other configured nodes 404/503 it; Ecency's own was decommissioned), so\n   * pin them — otherwise the health tracker keeps rediscovering incapable\n   * nodes each cooldown and cold starts waste attempts.\n   */\n  restNodesByApi: {\n    hivesense: ['https://api.hive.blog', 'https://api.syncad.com']\n  } as Partial<Record<APIMethods, string[]>>,\n\n  /**\n   * User-Agent sent on server-side (Node) HTTP requests to Hive nodes.\n   *\n   * Node's built-in fetch (undici) sends a bare `User-Agent: node` when none is\n   * set, which is indistinguishable from any random Node script in node/CDN\n   * analytics. A descriptive value lets operators tell their own SSR/server\n   * traffic apart from anonymous scrapers. Only applied in Node — browsers\n   * forbid overriding User-Agent (it is silently dropped) and React Native sets\n   * its own native UA, so client and mobile traffic are untouched. Override via\n   * `ConfigManager.setUserAgent()` (or `setUserAgent()` from `@ecency/sdk/hive`).\n   */\n  userAgent: 'ecency-sdk',\n\n  /**\n   * The Hive blockchain chain ID for transaction signing and verification.\n   */\n  chain_id: 'beeab0de00000000000000000000000000000000000000000000000000000000',\n\n  /**\n   * Address prefix used for public key formatting (STM for mainnet).\n   */\n  address_prefix: 'STM',\n\n  /**\n   * Timeout in milliseconds for read API calls (get_content, get_accounts, etc.).\n   * Kept short so the health tracker can fail over to another node quickly.\n   */\n  timeout: 5_000,\n\n  /**\n   * Timeout in milliseconds for broadcast API calls.\n   * Longer than read timeout because broadcast_transaction_synchronous waits\n   * for block inclusion, which depends on the 3-second block interval and\n   * network conditions.\n   */\n  broadcastTimeout: 15_000,\n\n  /**\n   * Number of retry attempts for failed API calls before throwing an error.\n   * Total attempts = retry + 1. With ~7 nodes in the list, a budget of 5\n   * means callRPC iterates through 6 distinct nodes before giving up, so a\n   * single sick node (or two) can't surface as an unhandled error to the\n   * caller while the rest of the list is healthy.\n   */\n  retry: 5,\n\n  /**\n   * Tail-latency resilience for READ calls. Motivation: on a shared public-node\n   * pool a node can slow down or throttle *mid-request*; a fixed `timeout` means\n   * the caller only notices after the full window, and under SSR concurrency\n   * those stalled renders pile up. Two mechanisms, both scoped to reads only\n   * (broadcasts never hedge and keep their fixed `broadcastTimeout`):\n   *\n   * - Adaptive per-attempt timeout (`adaptiveTimeout`, default ON): when a\n   *   node has a usable latency profile (EWMA), the per-attempt timeout becomes\n   *   `min(callerTimeout, max(floorMs, factor × EWMA))` — a node running far\n   *   above its own baseline is abandoned early and failover starts sooner.\n   *   Never *raises* the caller's timeout; unprofiled nodes keep it unchanged.\n   *\n   * - Hedged requests (`hedge`, default OFF — opt in via `setResilience`): if\n   *   the primary attempt is still pending after `max(hedgeDelayFloorMs,\n   *   hedgeDelayFactor × EWMA)`, a duplicate request is fired at the next\n   *   healthy untried node and the first success wins (the loser is aborted).\n   *   A token bucket (`hedgeBucketCapacity` burst, refilled by\n   *   `hedgeRefillPerSuccess` per un-hedged success) caps hedges to roughly\n   *   `hedgeRefillPerSuccess` of traffic, so only the slow tail hedges — and\n   *   under pool-wide slowness the bucket drains and hedging auto-disables\n   *   instead of amplifying load into public-node rate limits.\n   */\n  resilience: {\n    adaptiveTimeout: true,\n    adaptiveTimeoutFloorMs: 2_000,\n    adaptiveTimeoutFactor: 4,\n    hedge: false,\n    hedgeDelayFloorMs: 750,\n    hedgeDelayFactor: 2,\n    hedgeBucketCapacity: 10,\n    hedgeRefillPerSuccess: 0.1,\n    /**\n     * Wall-clock budget for one read call across ALL failover attempts, as a\n     * multiple of the per-attempt timeout: no NEW attempt starts past\n     * `totalBudgetFactor × timeout` (an in-flight attempt still finishes its\n     * own window). Bounds the pathological pool-wide-slowness walk — without\n     * it a read could hold its caller for (retry+1) × timeout ≈ 30s, which\n     * under SSR concurrency is a memory pile-up, the exact incident this\n     * feature exists for. Applies to reads only (callRPC / callREST);\n     * broadcasts keep their try-each-node-once semantics.\n     */\n    totalBudgetFactor: 2\n  }\n}\n\n/** Shape of the `config.resilience` bag (see its doc comment). */\nexport type ResilienceOptions = typeof config.resilience\n\n/**\n * Server-side read-through proxy for RPC reads (see `setServerRpcProxy`).\n * `methods` is the allowlist the proxy serves; a read outside it goes straight\n * to the node pool as before.\n */\nexport interface ServerRpcProxyOptions {\n  /** Absolute URL of the proxy endpoint (POST `{api, method, params}`). */\n  url: string\n  /** Headers sent with every proxy call (the shared internal secret). */\n  headers: Record<string, string>\n  /** Per-call timeout in ms; on expiry the read falls back to the node pool. */\n  timeoutMs: number\n  /** Fully qualified method names (`bridge.get_post`) the proxy may answer;\n   * omitted = DEFAULT_SERVER_RPC_PROXY_METHODS. An empty list is ignored. */\n  methods?: string[]\n  /**\n   * After this many consecutive proxy misses the proxy is skipped for\n   * `cooldownMs`, so a proxy that is down costs one failed call per cooldown\n   * window rather than one per read. Default 3 / 10s. A served call resets it.\n   */\n  failureThreshold?: number\n  cooldownMs?: number\n}\n\n/** Default allowlist: the reads a server render makes and the proxy caches. */\nexport const DEFAULT_SERVER_RPC_PROXY_METHODS: readonly string[] = [\n  'bridge.get_ranked_posts',\n  'bridge.get_account_posts',\n  'bridge.get_post',\n  'bridge.get_discussion',\n  'bridge.get_profile',\n  'bridge.get_profiles',\n  'bridge.get_community',\n  'bridge.list_communities',\n  'condenser_api.get_accounts',\n  'condenser_api.get_content',\n  'condenser_api.get_dynamic_global_properties',\n  'condenser_api.get_trending_tags'\n]\n\n/**\n * Active proxy configuration, or null (the default: every read goes to the node\n * pool). Lives outside `config` so the browser bundle never carries it; it is\n * only ever consulted under Node.\n */\nexport interface ServerRpcProxyState extends Required<ServerRpcProxyOptions> {\n  methodSet: Set<string>\n}\n\nexport let serverRpcProxy: ServerRpcProxyState | null = null\n\n/**\n * Route allowlisted server-side reads through a read-through cache in front\n * of the node pool. One cache per host answers the reads every renderer\n * process used to make on its own; a miss there is one upstream call shared by\n * every concurrent reader. The proxy is an optimization, never a dependency:\n * any failure (non-200, timeout, transport error, a response the caller's\n * validator rejects) falls straight through to the existing node loop, so the\n * worst case is the latency of a failed proxy call on top of what happens\n * today. Has no effect outside Node. Pass null to switch it off.\n */\nexport const setServerRpcProxy = (opts: ServerRpcProxyOptions | null): void => {\n  if (opts === null) {\n    serverRpcProxy = null\n    return\n  }\n  if (!opts || typeof opts !== 'object') return\n  const url = typeof opts.url === 'string' ? opts.url.trim() : ''\n  if (!/^https?:\\/\\//i.test(url)) return\n  const headers: Record<string, string> = {}\n  if (opts.headers && typeof opts.headers === 'object') {\n    for (const [k, v] of Object.entries(opts.headers)) {\n      if (typeof v === 'string' && v && !/[\\u0000-\\u001f\\u007f]/.test(v) && !/[\\u0000-\\u001f\\u007f]/.test(k)) {\n        headers[k] = v\n      }\n    }\n  }\n  const timeoutMs =\n    typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0\n      ? opts.timeoutMs\n      : 2_000\n  const methods =\n    opts.methods === undefined\n      ? [...DEFAULT_SERVER_RPC_PROXY_METHODS]\n      : Array.isArray(opts.methods)\n        ? opts.methods.filter((m): m is string => typeof m === 'string' && m.includes('.'))\n        : []\n  // Nothing to route through the proxy: keep whatever was configured before.\n  if (methods.length === 0) return\n  const pos = (v: unknown, fallback: number): number =>\n    typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback\n  serverRpcProxy = {\n    url,\n    headers,\n    timeoutMs,\n    methods,\n    failureThreshold: Math.floor(pos(opts.failureThreshold, 3)),\n    cooldownMs: pos(opts.cooldownMs, 10_000),\n    methodSet: new Set(methods)\n  }\n}\n\n/**\n * Validated setter for the Hive RPC node list — replaces `config.nodes`.\n * Trims, drops non-http(s) entries, and de-dupes (order-preserving). A no-op\n * if nothing valid remains, so a bad input can't empty the list.\n *\n * Lives here, in the React-free `hive-tx` core, on purpose: it must be\n * reachable from BOTH the full `@ecency/sdk` entry (via\n * `ConfigManager.setHiveNodes`, which delegates here) and the lean\n * `@ecency/sdk/hive` server/CLI entry — without dragging react-query or the\n * DMCA/ReDoS surface of `ConfigManager` into the lean entry. Within a single\n * bundle this mutates the one `config` instance `callRPC` reads; the\n * cross-bundle single-instance guarantee is a separate (build-level) concern.\n */\n/**\n * Trim, drop non-string / non-http(s), and de-dupe (order-preserving) a node\n * list. Shared by `setNodes` and the REST-node setters below so all three\n * normalize identically.\n */\nconst sanitizeNodeList = (nodes: unknown): string[] =>\n  Array.isArray(nodes)\n    ? [\n        ...new Set(\n          nodes\n            .filter((n): n is string => typeof n === 'string')\n            // Trim, then strip trailing slashes so REST paths concatenate cleanly:\n            // `callREST` builds `node + '/status-api'`, and a `https://host/` node would\n            // otherwise yield `https://host//status-api`, which several HAF nodes 404.\n            // De-dupe AFTER normalizing so `host` and `host/` collapse to one entry.\n            .map((n) => n.trim().replace(/\\/+$/, ''))\n            .filter((n) => n.length > 0 && /^https?:\\/\\/.+/.test(n))\n        )\n      ]\n    : []\n\nexport const setNodes = (nodes: string[]): void => {\n  const validNodes = sanitizeNodeList(nodes)\n  if (!validNodes.length) return\n  config.nodes = validNodes\n}\n\n/**\n * Validated setter for the REST-API node list — replaces `config.restNodes`.\n * Same shape/guarantees as `setNodes` (trim, drop non-http(s), de-dupe, no-op on\n * empty). Exists because `restNodes` is otherwise baked into the SDK: an app that\n * wants to add/remove a REST host (e.g. drop an own node it is decommissioning, or\n * widen the public pool) previously had to fork + republish the SDK. With this, the\n * REST pool is app-configurable at runtime exactly like the read pool. Lives in the\n * React-free `hive-tx` core so both the full `@ecency/sdk` entry and the lean\n * `@ecency/sdk/hive` entry can reach it.\n */\nexport const setRestNodes = (nodes: string[]): void => {\n  const valid = sanitizeNodeList(nodes)\n  if (!valid.length) return\n  config.restNodes = valid\n}\n\n/**\n * Merge validated per-API REST node overrides into `config.restNodesByApi`.\n * For each entry: a non-empty, valid list pins that API to those hosts; an empty or\n * all-invalid list REMOVES the pin so the API falls back to `restNodes`. Other APIs'\n * existing pins (e.g. the built-in `hivesense`) are preserved. Lets an app pin the\n * APIs it actually uses to known-capable hosts (so `callREST` never burns its small\n * retry budget on a node that 404/503s the API) without an SDK republish.\n */\nexport const setRestNodesByApi = (\n  map: Partial<Record<APIMethods, string[]>>\n): void => {\n  if (!map || typeof map !== 'object') return\n  const next: Partial<Record<APIMethods, string[]>> = { ...config.restNodesByApi }\n  for (const [api, list] of Object.entries(map)) {\n    const valid = sanitizeNodeList(list)\n    if (valid.length) {\n      next[api as APIMethods] = valid\n    } else {\n      delete next[api as APIMethods]\n    }\n  }\n  config.restNodesByApi = next\n}\n\n/**\n * Validated setter for the User-Agent sent on server-side (Node) requests.\n * Trims the input and ignores an empty value so a bad input can't blank out the\n * header. Like `setNodes`, it lives in the React-free `hive-tx` core so it is\n * reachable from both the full `@ecency/sdk` entry (via\n * `ConfigManager.setUserAgent`) and the lean `@ecency/sdk/hive` server/CLI entry.\n */\nexport const setUserAgent = (ua: string): void => {\n  // Defensive against plain-JS / React Native callers that may pass a non-string\n  // despite the `string` type (avoids throwing on `.trim()`).\n  if (typeof ua !== 'string') return\n  const value = ua.trim()\n  // Ignore blank values, and reject control characters (CR, LF, and other\n  // C0/DEL controls). An invalid header value would otherwise be stored and make\n  // every subsequent fetch throw, and rejecting CR/LF closes a header-injection\n  // vector for any caller that builds the UA from untrusted input.\n  if (!value || /[\\u0000-\\u001f\\u007f]/.test(value)) return\n  config.userAgent = value\n}\n\n/**\n * Validated partial setter for `config.resilience` (adaptive read timeouts +\n * hedged requests — see the field's doc comment). Booleans must be booleans;\n * numeric fields must be finite and positive, with the refill rate additionally\n * capped at 1 so a typo can't turn the tail-hedge into a traffic doubler\n * (refill ≤ 1 ⇒ hedges can never exceed un-hedged successes). Invalid values\n * are ignored field-by-field, so one bad entry can't block the rest. Lives in\n * the React-free `hive-tx` core (like the other setters) so both `@ecency/sdk`\n * (via `ConfigManager.setResilience`) and the lean `@ecency/sdk/hive` entry\n * can reach it.\n */\nexport const setResilience = (opts: Partial<ResilienceOptions>): void => {\n  if (!opts || typeof opts !== 'object') return\n  const r = config.resilience\n  const bool = (v: unknown): v is boolean => typeof v === 'boolean'\n  const pos = (v: unknown): v is number =>\n    typeof v === 'number' && Number.isFinite(v) && v > 0\n  if (bool(opts.adaptiveTimeout)) r.adaptiveTimeout = opts.adaptiveTimeout\n  // Floor must stay ≥ the tracker's slow-failure recording floor (2s): the\n  // safety argument for adaptive timeouts is that an abort at the window IS\n  // recorded as a slow sample, growing the EWMA so the window self-corrects\n  // upward. A floor below 2s would abort without recording — the window could\n  // never converge and a too-tight profile would starve that call forever.\n  if (pos(opts.adaptiveTimeoutFloorMs)) {\n    r.adaptiveTimeoutFloorMs = Math.max(opts.adaptiveTimeoutFloorMs, 2_000)\n  }\n  if (pos(opts.adaptiveTimeoutFactor)) r.adaptiveTimeoutFactor = opts.adaptiveTimeoutFactor\n  if (bool(opts.hedge)) r.hedge = opts.hedge\n  if (pos(opts.hedgeDelayFloorMs)) r.hedgeDelayFloorMs = opts.hedgeDelayFloorMs\n  if (pos(opts.hedgeDelayFactor)) r.hedgeDelayFactor = opts.hedgeDelayFactor\n  if (pos(opts.hedgeBucketCapacity)) r.hedgeBucketCapacity = opts.hedgeBucketCapacity\n  // Refill must stay ≤ 1: at 1 token per success the hedge rate could reach\n  // 100% of traffic, defeating the \"tail only\" contract. Cap rather than reject\n  // so a caller asking for \"more hedging\" gets the safe maximum.\n  if (pos(opts.hedgeRefillPerSuccess)) {\n    r.hedgeRefillPerSuccess = Math.min(opts.hedgeRefillPerSuccess, 1)\n  }\n  // Below 1 the budget could not even cover the configured per-attempt window.\n  if (pos(opts.totalBudgetFactor)) {\n    r.totalBudgetFactor = Math.max(opts.totalBudgetFactor, 1)\n  }\n}\n","import { PublicKey } from './PublicKey'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport class Signature {\n  data: Uint8Array\n  recovery: number\n  private compressed: boolean\n\n  /**\n   * Creates a new Signature instance.\n   * @param data Raw signature data (64 bytes)\n   * @param recovery Recovery byte (0-3)\n   * @param compressed Whether signature is compressed (default: true)\n   */\n  constructor(data: Uint8Array, recovery: number, compressed?: boolean) {\n    this.data = data\n    this.recovery = recovery\n    this.compressed = compressed ?? true\n  }\n\n  /**\n   * Creates a Signature from a hex string.\n   * @param string 130-character hex string containing signature and recovery data\n   * @returns New Signature instance\n   * @throws Error if input is not a string\n   */\n  static from(string: string) {\n    if (typeof string === 'string') {\n      const temp = hexToBytes(string)\n      let recovery = parseInt(bytesToHex(temp.subarray(0, 1)), 16) - 31\n      let compressed = true\n      // non-compressed signatures have -4\n      // https://github.com/bitcoin/bitcoin/blob/95ea54ba089610019a74c1176a2c7c0dba144b1c/src/key.cpp#L257\n      if (recovery < 0) {\n        compressed = false\n        recovery = recovery + 4\n      }\n      const data = temp.subarray(1)\n      return new Signature(data, recovery, compressed)\n    } else {\n      throw new Error('Expected string for data')\n    }\n  }\n\n  /**\n   * Converts signature to 65-byte buffer format.\n   * @returns 65-byte buffer containing recovery byte + signature data\n   */\n  toBuffer() {\n    const buffer = new Uint8Array(65).fill(0)\n    if (this.compressed) {\n      buffer[0] = (this.recovery + 31) & 0xff\n    } else {\n      buffer[0] = (this.recovery + 27) & 0xff\n    }\n    buffer.set(this.data, 1)\n    return buffer\n  }\n\n  /**\n   * Returns signature as 130-character hex string.\n   * @returns Hex string representation of signature\n   */\n  customToString() {\n    return bytesToHex(this.toBuffer())\n  }\n\n  /**\n   * Returns signature as 130-character hex string.\n   * Overrides Object.prototype.toString() so that String(sig) and\n   * template literals produce the hex representation instead of \"[object Object]\".\n   * @returns Hex string representation of signature\n   */\n  toString() {\n    return this.customToString()\n  }\n\n  /**\n   * Recovers the public key from this signature and message.\n   * @param message 32-byte message hash (Uint8Array) or 64-character hex string\n   * @returns PublicKey that created this signature\n   * @throws Error if message is not a valid 32-byte SHA256 hash\n   */\n  getPublicKey(message: Uint8Array | string): PublicKey {\n    if (\n      (message instanceof Uint8Array && message.length !== 32) ||\n      (typeof message === 'string' && message.length !== 64)\n    ) {\n      throw new Error('Expected a valid sha256 hash as message')\n    }\n    if (typeof message === 'string') {\n      message = hexToBytes(message)\n    }\n    const sig = secp256k1.Signature.fromBytes(this.data, 'compact')\n    const temp = new secp256k1.Signature(sig.r, sig.s, this.recovery)\n    return new PublicKey(temp.recoverPublicKey(message).toBytes())\n  }\n}\n","import { ripemd160 } from '@noble/hashes/legacy.js'\nimport bs58 from 'bs58'\nimport { config } from '../config'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { Signature } from './Signature'\n\nexport class PublicKey {\n  key: Uint8Array\n  prefix: string\n\n  /**\n   * Creates a new PublicKey instance from raw bytes.\n   * @param key Raw public key bytes (33 bytes, compressed format)\n   * @param prefix Optional address prefix (defaults to the current config.address_prefix)\n   */\n  constructor(key: Uint8Array, prefix?: string) {\n    this.key = key\n    // Read config at call time so runtime mutations to config.address_prefix\n    // (e.g. switching to a non-mainnet network) take effect for new instances.\n    this.prefix = prefix ?? config.address_prefix\n  }\n\n  /**\n   * Creates a PublicKey from a string representation.\n   * The expected prefix is read from config.address_prefix at call time, so\n   * consumers can switch networks at runtime.\n   * @param wif Public key string (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n   * @returns New PublicKey instance\n   * @throws Error if the prefix, length, checksum, or curve point is invalid\n   */\n  static fromString(wif: string): PublicKey {\n    const expectedPrefix = config.address_prefix\n    if (typeof wif !== 'string' || wif.length <= expectedPrefix.length) {\n      throw new Error('Invalid public key')\n    }\n    const prefix = wif.slice(0, expectedPrefix.length)\n    if (prefix !== expectedPrefix) {\n      throw new Error(`Public key must start with ${expectedPrefix}`)\n    }\n    let buffer: Uint8Array\n    try {\n      buffer = bs58.decode(wif.slice(expectedPrefix.length))\n    } catch {\n      throw new Error('Invalid public key encoding')\n    }\n    // 33-byte compressed secp256k1 point + 4-byte RIPEMD160 checksum\n    if (buffer.length !== 37) {\n      throw new Error('Invalid public key length')\n    }\n    const key = buffer.subarray(0, 33)\n    const checksum = buffer.subarray(33, 37)\n    const expectedChecksum = ripemd160(key).subarray(0, 4)\n    if (!isUint8ArrayEqual(checksum, expectedChecksum)) {\n      throw new Error('Public key checksum mismatch')\n    }\n    try {\n      secp256k1.Point.fromBytes(key)\n    } catch {\n      throw new Error('Invalid public key')\n    }\n    return new PublicKey(key, prefix)\n  }\n\n  /**\n   * Creates a PublicKey from a string or returns the instance if already a PublicKey.\n   * @param value Public key string or PublicKey instance\n   * @returns New or existing PublicKey instance\n   */\n  static from(value: string | PublicKey): PublicKey {\n    if (value instanceof PublicKey) {\n      return value\n    } else {\n      return PublicKey.fromString(value as string)\n    }\n  }\n\n  /**\n   * Verifies a signature against a message hash.\n   * @param message 32-byte message hash to verify\n   * @param signature Signature to verify\n   * @returns True if signature is valid, false otherwise\n   */\n  verify(message: Uint8Array, signature: Signature | string): boolean {\n    if (typeof signature === 'string') {\n      signature = Signature.from(signature)\n    }\n    return secp256k1.verify(signature.data, message, this.key, {\n      prehash: false,\n      format: 'compact'\n    })\n  }\n\n  /**\n   * Returns the public key as a string for storage or transmission.\n   * @returns Public key string with prefix (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n   */\n  toString(): string {\n    return encodePublic(this.key, this.prefix)\n  }\n\n  /**\n   * Returns JSON representation (same as toString()).\n   * @returns Public key string\n   */\n  toJSON(): string {\n    return this.toString()\n  }\n\n  /**\n   * Returns a string representation for debugging.\n   * @returns Formatted public key string\n   */\n  inspect(): string {\n    return `PublicKey: ${this.toString()}`\n  }\n}\n\nconst encodePublic = (key: Uint8Array, prefix: string): string => {\n  const checksum = ripemd160(key)\n  return prefix + bs58.encode(new Uint8Array([...key, ...checksum.subarray(0, 4)]))\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n  if (a.byteLength !== b.byteLength) return false\n  for (let i = 0; i < a.byteLength; i++) {\n    if (a[i] !== b[i]) return false\n  }\n  return true\n}\n","/** Class representing a hive asset,\n * e.g. `1.000 HIVE` or `12.112233 VESTS`. */\nexport class Asset {\n  amount: number\n  symbol: string\n\n  constructor(amount: number, symbol: string) {\n    this.amount = amount\n    this.symbol = symbol === 'HIVE' ? 'STEEM' : symbol === 'HBD' ? 'SBD' : symbol\n  }\n\n  /** Create a new Asset instance from a string, e.g. `42.000 HIVE`. */\n  static fromString(string: string, expectedSymbol: string | null = null): Asset {\n    const [amountString, symbol] = string.split(' ')\n    if (['STEEM', 'VESTS', 'SBD', 'TESTS', 'TBD', 'HIVE', 'HBD'].indexOf(symbol) === -1) {\n      throw new Error(`Invalid asset symbol: ${symbol}`)\n    }\n    if (expectedSymbol && symbol !== expectedSymbol) {\n      throw new Error(`Invalid asset, expected symbol: ${expectedSymbol} got: ${symbol}`)\n    }\n    const amount = Number.parseFloat(amountString)\n    if (!Number.isFinite(amount)) {\n      throw new Error(`Invalid asset amount: ${amountString}`)\n    }\n    return new Asset(amount, symbol)\n  }\n\n  /**\n   * Convenience to create new Asset.\n   * @param symbol Symbol to use when created from number. Will also be used to validate\n   *               the asset, throws if the passed value has a different symbol than this.\n   */\n  static from(value: number | string | Asset, symbol?: string | null): Asset {\n    if (value instanceof Asset) {\n      if (symbol && value.symbol !== symbol) {\n        throw new Error(`Invalid asset, expected symbol: ${symbol} got: ${value.symbol}`)\n      }\n      return value\n    } else if (typeof value === 'number' && Number.isFinite(value)) {\n      return new Asset(value, symbol || 'STEEM')\n    } else if (typeof value === 'string') {\n      return Asset.fromString(value, symbol)\n    } else {\n      throw new Error(`Invalid asset '${String(value)}'`)\n    }\n  }\n\n  // We convert HIVE & HBD strings to STEEM & SBD because the serialization should be based on STEEM & SBD\n\n  /** Return asset precision. */\n  getPrecision() {\n    switch (this.symbol) {\n      case 'TESTS':\n      case 'TBD':\n      case 'STEEM':\n      case 'SBD':\n      case 'HBD':\n      case 'HIVE':\n        return 3\n      case 'VESTS':\n        return 6\n      default:\n        return 3\n    }\n  }\n\n  /** Return a string representation of this asset, e.g. `42.000 HIVE`. */\n  toString() {\n    return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`\n  }\n\n  toJSON() {\n    return this.toString()\n  }\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\n/** Buffer wrapper that serializes to a hex-encoded string. */\nexport class HexBuffer {\n  buffer: Uint8Array\n  /** Convenience to create a new HexBuffer, does not copy data if value passed is already a buffer. */\n  static from(value: string | Uint8Array | HexBuffer) {\n    if (value instanceof HexBuffer) {\n      return value\n    } else if (value instanceof Uint8Array) {\n      return new HexBuffer(value)\n    } else if (typeof value === 'string') {\n      return new HexBuffer(hexToBytes(value))\n    } else {\n      return new HexBuffer(new Uint8Array(value))\n    }\n  }\n\n  constructor(buffer: Uint8Array) {\n    this.buffer = buffer\n  }\n\n  toString() {\n    return bytesToHex(this.buffer)\n  }\n\n  toJSON() {\n    return this.toString()\n  }\n}\n","import { PublicKey } from './PublicKey'\nimport { Asset } from './Asset'\nimport { HexBuffer } from './HexBuffer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Operation } from '../types'\n\n// Operation ID constants for better maintainability\nconst OPERATION_IDS = {\n  vote: 0,\n  comment: 1,\n  transfer: 2,\n  transfer_to_vesting: 3,\n  withdraw_vesting: 4,\n  limit_order_create: 5,\n  limit_order_cancel: 6,\n  feed_publish: 7,\n  convert: 8,\n  account_create: 9,\n  account_update: 10,\n  witness_update: 11,\n  account_witness_vote: 12,\n  account_witness_proxy: 13,\n  // pow: 14,\n  custom: 15,\n  // report_over_production: 16,\n  delete_comment: 17,\n  custom_json: 18,\n  comment_options: 19,\n  set_withdraw_vesting_route: 20,\n  limit_order_create2: 21,\n  claim_account: 22,\n  create_claimed_account: 23,\n  request_account_recovery: 24,\n  recover_account: 25,\n  change_recovery_account: 26,\n  escrow_transfer: 27,\n  escrow_dispute: 28,\n  escrow_release: 29,\n  // pow2: 30,\n  escrow_approve: 31,\n  transfer_to_savings: 32,\n  transfer_from_savings: 33,\n  cancel_transfer_from_savings: 34,\n  // custom_binary: 35,\n  decline_voting_rights: 36,\n  reset_account: 37,\n  set_reset_account: 38,\n  claim_reward_balance: 39,\n  delegate_vesting_shares: 40,\n  account_create_with_delegation: 41,\n  witness_set_properties: 42,\n  account_update2: 43,\n  create_proposal: 44,\n  update_proposal_votes: 45,\n  remove_proposal: 46,\n  update_proposal: 47,\n  collateralized_convert: 48,\n  recurrent_transfer: 49\n} as const\n\ntype OperationId = (typeof OPERATION_IDS)[keyof typeof OPERATION_IDS]\n\nconst VoidSerializer = () => {\n  throw new Error('Void can not be serialized')\n}\nconst StringSerializer = (buffer: ByteBuffer, data: string) => {\n  buffer.writeVString(data)\n}\n\nconst Int16Serializer = (buffer: ByteBuffer, data: number) => {\n  buffer.writeInt16(data)\n}\n\nconst Int64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n  buffer.writeInt64(data)\n}\n\nconst UInt8Serializer = (buffer: ByteBuffer, data: number) => {\n  buffer.writeUint8(data)\n}\n\nconst UInt16Serializer = (buffer: ByteBuffer, data: number) => {\n  buffer.writeUint16(data)\n}\n\nconst UInt32Serializer = (buffer: ByteBuffer, data: number) => {\n  buffer.writeUint32(data)\n}\n\nconst UInt64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n  buffer.writeUint64(data)\n}\n\nconst BooleanSerializer = (buffer: ByteBuffer, data: number | boolean) => {\n  buffer.writeByte(data ? 1 : 0)\n}\n\nconst StaticVariantSerializer = (itemSerializers: any) => {\n  // return (buffer: ByteBuffer, data: any[]) => {\n  //   let id = data[0]\n  //   const item = data[1]\n  //   // id was/is supposed to be 0 or integer here but seems to have been changed in e.g. comment_options\n  //   // extensions: [\n  //   //   [\n  //   //     \"comment_payout_beneficiaries\",\n  //   //     {\n  //   //       \"beneficiaries\": [\n  //   //         {\n  //   //           \"account\": \"vimm\",\n  //   //           \"weight\": 1000\n  //   //         }\n  //   //       ]\n  //   //     }\n  //   //   ]\n  //   // ]\n  //   // Keep it here just in case\n  //   // https://gitlab.syncad.com/hive/hive/-/issues/722\n  //   // \"comment_payout_beneficiaries\" was 0 and at some point it got changed\n  //   // It should still be serialized as a 0 or an integer\n  //   // Now the question is, always 0? will need an example transaction to prove otherwise\n  //   if (typeof id === 'string') {\n  //     if (id === 'update_proposal_end_date') {\n  //       id = 1\n  //     } else {\n  //       id = 0\n  //     }\n  //   }\n  //   buffer.writeVarint32(id)\n  //   itemSerializers[id](buffer, item)\n  return (buffer: ByteBuffer, data: any) => {\n    const [id, item] = data\n    buffer.writeVarint32(id)\n    itemSerializers[id](buffer, item)\n  }\n}\n\n/**\n * Serialize asset.\n * @note This looses precision for amounts larger than 2^53-1/10^precision.\n *       Should not be a problem in real-word usage.\n */\nconst AssetSerializer = (buffer: ByteBuffer, data: string | Asset) => {\n  const asset = Asset.from(data)\n  const precision = asset.getPrecision()\n  buffer.writeInt64(Math.round(asset.amount * Math.pow(10, precision)))\n  buffer.writeUint8(precision)\n  for (let i = 0; i < 7; i++) {\n    buffer.writeUint8(asset.symbol.charCodeAt(i) || 0)\n  }\n}\n\nconst DateSerializer = (buffer: ByteBuffer, data: string) => {\n  buffer.writeUint32(Math.floor(new Date(data + 'Z').getTime() / 1000))\n}\n\nconst PublicKeySerializer = (buffer: ByteBuffer, data: string | PublicKey) => {\n  if (\n    data === null ||\n    (typeof data === 'string' && data.slice(-39) === '1111111111111111111111111111111114T1Anm')\n  ) {\n    buffer.append(new Uint8Array(33).fill(0))\n  } else {\n    buffer.append(PublicKey.from(data).key)\n  }\n}\n\nconst BinarySerializer = (size: null | number = null) => {\n  return (buffer: ByteBuffer, data: string | Uint8Array | HexBuffer) => {\n    data = HexBuffer.from(data)\n    const len = data.buffer.length\n    if (size) {\n      if (len !== size) {\n        throw new Error(`Unable to serialize binary. Expected ${size} bytes, got ${len}`)\n      }\n    } else {\n      buffer.writeVarint32(len)\n    }\n    buffer.append(data.buffer)\n  }\n}\n\nconst VariableBinarySerializer = BinarySerializer()\n\nconst FlatMapSerializer = (keySerializer: any, valueSerializer: any) => {\n  return (buffer: ByteBuffer, data: any) => {\n    buffer.writeVarint32(data.length)\n    for (const [key, value] of data) {\n      keySerializer(buffer, key)\n      valueSerializer(buffer, value)\n    }\n  }\n}\n\nconst ArraySerializer = (itemSerializer: any) => {\n  return (buffer: ByteBuffer, data: any[]) => {\n    buffer.writeVarint32(data.length)\n    for (const item of data) {\n      itemSerializer(buffer, item)\n    }\n  }\n}\n\nconst ObjectSerializer = (keySerializers: any) => {\n  return (buffer: ByteBuffer, data: any) => {\n    for (const [key, serializer] of keySerializers) {\n      try {\n        serializer(buffer, data[key])\n      } catch (error: any) {\n        error.message = `${key}: ${error.message}`\n        throw error\n      }\n    }\n  }\n}\n\nconst OptionalSerializer = (valueSerializer: any) => {\n  return (buffer: ByteBuffer, data: any | undefined) => {\n    if (data !== undefined) {\n      buffer.writeByte(1)\n      valueSerializer(buffer, data)\n    } else {\n      buffer.writeByte(0)\n    }\n  }\n}\n\nconst AuthoritySerializer = ObjectSerializer([\n  ['weight_threshold', UInt32Serializer],\n  ['account_auths', FlatMapSerializer(StringSerializer, UInt16Serializer)],\n  ['key_auths', FlatMapSerializer(PublicKeySerializer, UInt16Serializer)]\n])\n\nconst BeneficiarySerializer = ObjectSerializer([\n  ['account', StringSerializer],\n  ['weight', UInt16Serializer]\n])\n\nconst PriceSerializer = ObjectSerializer([\n  ['base', AssetSerializer],\n  ['quote', AssetSerializer]\n])\n\n// const SignedBlockHeaderSerializer = ObjectSerializer([\n//   ['previous', BinarySerializer(20)],\n//   ['timestamp', DateSerializer],\n//   ['witness', StringSerializer],\n//   ['transaction_merkle_root', BinarySerializer(20)],\n//   ['extensions', ArraySerializer(VoidSerializer)],\n//   ['witness_signature', BinarySerializer(65)]\n// ])\n\nconst ChainPropertiesSerializer = ObjectSerializer([\n  ['account_creation_fee', AssetSerializer],\n  ['maximum_block_size', UInt32Serializer],\n  ['hbd_interest_rate', UInt16Serializer]\n])\n\nconst OperationDataSerializer = (operationId: OperationId, definitions: any) => {\n  const objectSerializer = ObjectSerializer(definitions)\n  return (buffer: ByteBuffer, data: any) => {\n    buffer.writeVarint32(operationId)\n    objectSerializer(buffer, data)\n  }\n}\n\nconst OperationSerializers: Record<string, ReturnType<typeof OperationDataSerializer>> = {}\n\nOperationSerializers.account_create = OperationDataSerializer(OPERATION_IDS.account_create, [\n  ['fee', AssetSerializer],\n  ['creator', StringSerializer],\n  ['new_account_name', StringSerializer],\n  ['owner', AuthoritySerializer],\n  ['active', AuthoritySerializer],\n  ['posting', AuthoritySerializer],\n  ['memo_key', PublicKeySerializer],\n  ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_create_with_delegation = OperationDataSerializer(\n  OPERATION_IDS.account_create_with_delegation,\n  [\n    ['fee', AssetSerializer],\n    ['delegation', AssetSerializer],\n    ['creator', StringSerializer],\n    ['new_account_name', StringSerializer],\n    ['owner', AuthoritySerializer],\n    ['active', AuthoritySerializer],\n    ['posting', AuthoritySerializer],\n    ['memo_key', PublicKeySerializer],\n    ['json_metadata', StringSerializer],\n    ['extensions', ArraySerializer(VoidSerializer)]\n  ]\n)\n\nOperationSerializers.account_update = OperationDataSerializer(OPERATION_IDS.account_update, [\n  ['account', StringSerializer],\n  ['owner', OptionalSerializer(AuthoritySerializer)],\n  ['active', OptionalSerializer(AuthoritySerializer)],\n  ['posting', OptionalSerializer(AuthoritySerializer)],\n  ['memo_key', PublicKeySerializer],\n  ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_witness_proxy = OperationDataSerializer(\n  OPERATION_IDS.account_witness_proxy,\n  [\n    ['account', StringSerializer],\n    ['proxy', StringSerializer]\n  ]\n)\n\nOperationSerializers.account_witness_vote = OperationDataSerializer(\n  OPERATION_IDS.account_witness_vote,\n  [\n    ['account', StringSerializer],\n    ['witness', StringSerializer],\n    ['approve', BooleanSerializer]\n  ]\n)\n\nOperationSerializers.cancel_transfer_from_savings = OperationDataSerializer(\n  OPERATION_IDS.cancel_transfer_from_savings,\n  [\n    ['from', StringSerializer],\n    ['request_id', UInt32Serializer]\n  ]\n)\n\nOperationSerializers.change_recovery_account = OperationDataSerializer(\n  OPERATION_IDS.change_recovery_account,\n  [\n    ['account_to_recover', StringSerializer],\n    ['new_recovery_account', StringSerializer],\n    ['extensions', ArraySerializer(VoidSerializer)]\n  ]\n)\n\nOperationSerializers.claim_account = OperationDataSerializer(OPERATION_IDS.claim_account, [\n  ['creator', StringSerializer],\n  ['fee', AssetSerializer],\n  ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.claim_reward_balance = OperationDataSerializer(\n  OPERATION_IDS.claim_reward_balance,\n  [\n    ['account', StringSerializer],\n    ['reward_hive', AssetSerializer],\n    ['reward_hbd', AssetSerializer],\n    ['reward_vests', AssetSerializer]\n  ]\n)\n\nOperationSerializers.comment = OperationDataSerializer(OPERATION_IDS.comment, [\n  ['parent_author', StringSerializer],\n  ['parent_permlink', StringSerializer],\n  ['author', StringSerializer],\n  ['permlink', StringSerializer],\n  ['title', StringSerializer],\n  ['body', StringSerializer],\n  ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.comment_options = OperationDataSerializer(OPERATION_IDS.comment_options, [\n  ['author', StringSerializer],\n  ['permlink', StringSerializer],\n  ['max_accepted_payout', AssetSerializer],\n  ['percent_hbd', UInt16Serializer],\n  ['allow_votes', BooleanSerializer],\n  ['allow_curation_rewards', BooleanSerializer],\n  [\n    'extensions',\n    ArraySerializer(\n      StaticVariantSerializer([\n        ObjectSerializer([['beneficiaries', ArraySerializer(BeneficiarySerializer)]])\n      ])\n    )\n  ]\n])\n\nOperationSerializers.convert = OperationDataSerializer(OPERATION_IDS.convert, [\n  ['owner', StringSerializer],\n  ['requestid', UInt32Serializer],\n  ['amount', AssetSerializer]\n])\n\nOperationSerializers.create_claimed_account = OperationDataSerializer(\n  OPERATION_IDS.create_claimed_account,\n  [\n    ['creator', StringSerializer],\n    ['new_account_name', StringSerializer],\n    ['owner', AuthoritySerializer],\n    ['active', AuthoritySerializer],\n    ['posting', AuthoritySerializer],\n    ['memo_key', PublicKeySerializer],\n    ['json_metadata', StringSerializer],\n    ['extensions', ArraySerializer(VoidSerializer)]\n  ]\n)\n\nOperationSerializers.custom = OperationDataSerializer(OPERATION_IDS.custom, [\n  ['required_auths', ArraySerializer(StringSerializer)],\n  ['id', UInt16Serializer],\n  ['data', VariableBinarySerializer]\n])\n\n// Not used on chain\n// OperationSerializers.custom_binary = OperationDataSerializer(OPERATION_IDS.custom_binary, [\n//   ['required_owner_auths', ArraySerializer(StringSerializer)],\n//   ['required_active_auths', ArraySerializer(StringSerializer)],\n//   ['required_posting_auths', ArraySerializer(StringSerializer)],\n//   ['required_auths', ArraySerializer(AuthoritySerializer)],\n//   ['id', StringSerializer],\n//   ['data', VariableBinarySerializer]\n// ])\n\nOperationSerializers.custom_json = OperationDataSerializer(OPERATION_IDS.custom_json, [\n  ['required_auths', ArraySerializer(StringSerializer)],\n  ['required_posting_auths', ArraySerializer(StringSerializer)],\n  ['id', StringSerializer],\n  ['json', StringSerializer]\n])\n\nOperationSerializers.decline_voting_rights = OperationDataSerializer(\n  OPERATION_IDS.decline_voting_rights,\n  [\n    ['account', StringSerializer],\n    ['decline', BooleanSerializer]\n  ]\n)\n\nOperationSerializers.delegate_vesting_shares = OperationDataSerializer(\n  OPERATION_IDS.delegate_vesting_shares,\n  [\n    ['delegator', StringSerializer],\n    ['delegatee', StringSerializer],\n    ['vesting_shares', AssetSerializer]\n  ]\n)\n\nOperationSerializers.delete_comment = OperationDataSerializer(OPERATION_IDS.delete_comment, [\n  ['author', StringSerializer],\n  ['permlink', StringSerializer]\n])\n\nOperationSerializers.escrow_approve = OperationDataSerializer(OPERATION_IDS.escrow_approve, [\n  ['from', StringSerializer],\n  ['to', StringSerializer],\n  ['agent', StringSerializer],\n  ['who', StringSerializer],\n  ['escrow_id', UInt32Serializer],\n  ['approve', BooleanSerializer]\n])\n\nOperationSerializers.escrow_dispute = OperationDataSerializer(OPERATION_IDS.escrow_dispute, [\n  ['from', StringSerializer],\n  ['to', StringSerializer],\n  ['agent', StringSerializer],\n  ['who', StringSerializer],\n  ['escrow_id', UInt32Serializer]\n])\n\nOperationSerializers.escrow_release = OperationDataSerializer(OPERATION_IDS.escrow_release, [\n  ['from', StringSerializer],\n  ['to', StringSerializer],\n  ['agent', StringSerializer],\n  ['who', StringSerializer],\n  ['receiver', StringSerializer],\n  ['escrow_id', UInt32Serializer],\n  ['hbd_amount', AssetSerializer],\n  ['hive_amount', AssetSerializer]\n])\n\nOperationSerializers.escrow_transfer = OperationDataSerializer(OPERATION_IDS.escrow_transfer, [\n  ['from', StringSerializer],\n  ['to', StringSerializer],\n  ['hbd_amount', AssetSerializer],\n  ['hive_amount', AssetSerializer],\n  ['escrow_id', UInt32Serializer],\n  ['agent', StringSerializer],\n  ['fee', AssetSerializer],\n  ['json_meta', StringSerializer],\n  ['ratification_deadline', DateSerializer],\n  ['escrow_expiration', DateSerializer]\n])\n\nOperationSerializers.feed_publish = OperationDataSerializer(OPERATION_IDS.feed_publish, [\n  ['publisher', StringSerializer],\n  ['exchange_rate', PriceSerializer]\n])\n\nOperationSerializers.limit_order_cancel = OperationDataSerializer(\n  OPERATION_IDS.limit_order_cancel,\n  [\n    ['owner', StringSerializer],\n    ['orderid', UInt32Serializer]\n  ]\n)\n\nOperationSerializers.limit_order_create = OperationDataSerializer(\n  OPERATION_IDS.limit_order_create,\n  [\n    ['owner', StringSerializer],\n    ['orderid', UInt32Serializer],\n    ['amount_to_sell', AssetSerializer],\n    ['min_to_receive', AssetSerializer],\n    ['fill_or_kill', BooleanSerializer],\n    ['expiration', DateSerializer]\n  ]\n)\n\nOperationSerializers.limit_order_create2 = OperationDataSerializer(\n  OPERATION_IDS.limit_order_create2,\n  [\n    ['owner', StringSerializer],\n    ['orderid', UInt32Serializer],\n    ['amount_to_sell', AssetSerializer],\n    ['exchange_rate', PriceSerializer],\n    ['fill_or_kill', BooleanSerializer],\n    ['expiration', DateSerializer]\n  ]\n)\n\nOperationSerializers.recover_account = OperationDataSerializer(OPERATION_IDS.recover_account, [\n  ['account_to_recover', StringSerializer],\n  ['new_owner_authority', AuthoritySerializer],\n  ['recent_owner_authority', AuthoritySerializer],\n  ['extensions', ArraySerializer(VoidSerializer)]\n])\n\n// Not used on chain\n// OperationSerializers.report_over_production = OperationDataSerializer(\n//   OPERATION_IDS.report_over_production,\n//   [\n//     ['reporter', StringSerializer],\n//     ['first_block', SignedBlockHeaderSerializer],\n//     ['second_block', SignedBlockHeaderSerializer]\n//   ]\n// )\n\nOperationSerializers.request_account_recovery = OperationDataSerializer(\n  OPERATION_IDS.request_account_recovery,\n  [\n    ['recovery_account', StringSerializer],\n    ['account_to_recover', StringSerializer],\n    ['new_owner_authority', AuthoritySerializer],\n    ['extensions', ArraySerializer(VoidSerializer)]\n  ]\n)\n\nOperationSerializers.reset_account = OperationDataSerializer(OPERATION_IDS.reset_account, [\n  ['reset_account', StringSerializer],\n  ['account_to_reset', StringSerializer],\n  ['new_owner_authority', AuthoritySerializer]\n])\n\nOperationSerializers.set_reset_account = OperationDataSerializer(OPERATION_IDS.set_reset_account, [\n  ['account', StringSerializer],\n  ['current_reset_account', StringSerializer],\n  ['reset_account', StringSerializer]\n])\n\nOperationSerializers.set_withdraw_vesting_route = OperationDataSerializer(\n  OPERATION_IDS.set_withdraw_vesting_route,\n  [\n    ['from_account', StringSerializer],\n    ['to_account', StringSerializer],\n    ['percent', UInt16Serializer],\n    ['auto_vest', BooleanSerializer]\n  ]\n)\n\nOperationSerializers.transfer = OperationDataSerializer(OPERATION_IDS.transfer, [\n  ['from', StringSerializer],\n  ['to', StringSerializer],\n  ['amount', AssetSerializer],\n  ['memo', StringSerializer]\n])\n\nOperationSerializers.transfer_from_savings = OperationDataSerializer(\n  OPERATION_IDS.transfer_from_savings,\n  [\n    ['from', StringSerializer],\n    ['request_id', UInt32Serializer],\n    ['to', StringSerializer],\n    ['amount', AssetSerializer],\n    ['memo', StringSerializer]\n  ]\n)\n\nOperationSerializers.transfer_to_savings = OperationDataSerializer(\n  OPERATION_IDS.transfer_to_savings,\n  [\n    ['from', StringSerializer],\n    ['to', StringSerializer],\n    ['amount', AssetSerializer],\n    ['memo', StringSerializer]\n  ]\n)\n\nOperationSerializers.transfer_to_vesting = OperationDataSerializer(\n  OPERATION_IDS.transfer_to_vesting,\n  [\n    ['from', StringSerializer],\n    ['to', StringSerializer],\n    ['amount', AssetSerializer]\n  ]\n)\n\nOperationSerializers.vote = OperationDataSerializer(OPERATION_IDS.vote, [\n  ['voter', StringSerializer],\n  ['author', StringSerializer],\n  ['permlink', StringSerializer],\n  ['weight', Int16Serializer]\n])\n\nOperationSerializers.withdraw_vesting = OperationDataSerializer(OPERATION_IDS.withdraw_vesting, [\n  ['account', StringSerializer],\n  ['vesting_shares', AssetSerializer]\n])\n\nOperationSerializers.witness_update = OperationDataSerializer(OPERATION_IDS.witness_update, [\n  ['owner', StringSerializer],\n  ['url', StringSerializer],\n  ['block_signing_key', PublicKeySerializer],\n  ['props', ChainPropertiesSerializer],\n  ['fee', AssetSerializer]\n])\n\nOperationSerializers.witness_set_properties = OperationDataSerializer(\n  OPERATION_IDS.witness_set_properties,\n  [\n    ['owner', StringSerializer],\n    ['props', FlatMapSerializer(StringSerializer, VariableBinarySerializer)],\n    ['extensions', ArraySerializer(VoidSerializer)]\n  ]\n)\n\nOperationSerializers.account_update2 = OperationDataSerializer(OPERATION_IDS.account_update2, [\n  ['account', StringSerializer],\n  ['owner', OptionalSerializer(AuthoritySerializer)],\n  ['active', OptionalSerializer(AuthoritySerializer)],\n  ['posting', OptionalSerializer(AuthoritySerializer)],\n  ['memo_key', OptionalSerializer(PublicKeySerializer)],\n  ['json_metadata', StringSerializer],\n  ['posting_json_metadata', StringSerializer],\n  ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.create_proposal = OperationDataSerializer(OPERATION_IDS.create_proposal, [\n  ['creator', StringSerializer],\n  ['receiver', StringSerializer],\n  ['start_date', DateSerializer],\n  ['end_date', DateSerializer],\n  ['daily_pay', AssetSerializer],\n  ['subject', StringSerializer],\n  ['permlink', StringSerializer],\n  ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.update_proposal_votes = OperationDataSerializer(\n  OPERATION_IDS.update_proposal_votes,\n  [\n    ['voter', StringSerializer],\n    ['proposal_ids', ArraySerializer(Int64Serializer)],\n    ['approve', BooleanSerializer],\n    ['extensions', ArraySerializer(VoidSerializer)]\n  ]\n)\n\nOperationSerializers.remove_proposal = OperationDataSerializer(OPERATION_IDS.remove_proposal, [\n  ['proposal_owner', StringSerializer],\n  ['proposal_ids', ArraySerializer(Int64Serializer)],\n  ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nconst ProposalUpdateSerializer = ObjectSerializer([['end_date', DateSerializer]])\n\nOperationSerializers.update_proposal = OperationDataSerializer(OPERATION_IDS.update_proposal, [\n  ['proposal_id', UInt64Serializer],\n  ['creator', StringSerializer],\n  ['daily_pay', AssetSerializer],\n  ['subject', StringSerializer],\n  ['permlink', StringSerializer],\n  [\n    'extensions',\n    ArraySerializer(StaticVariantSerializer([VoidSerializer, ProposalUpdateSerializer]))\n  ]\n])\n\nOperationSerializers.collateralized_convert = OperationDataSerializer(\n  OPERATION_IDS.collateralized_convert,\n  [\n    ['owner', StringSerializer],\n    ['requestid', UInt32Serializer],\n    ['amount', AssetSerializer]\n  ]\n)\n\nOperationSerializers.recurrent_transfer = OperationDataSerializer(\n  OPERATION_IDS.recurrent_transfer,\n  [\n    ['from', StringSerializer],\n    ['to', StringSerializer],\n    ['amount', AssetSerializer],\n    ['memo', StringSerializer],\n    ['recurrence', UInt16Serializer],\n    ['executions', UInt16Serializer],\n    [\n      'extensions',\n      ArraySerializer(\n        ObjectSerializer([\n          ['type', UInt8Serializer],\n          ['value', ObjectSerializer([['pair_id', UInt8Serializer]])]\n        ])\n      )\n    ]\n  ]\n)\n\nconst OperationSerializer = (buffer: ByteBuffer, operation: Operation) => {\n  const serializer = OperationSerializers[operation[0]]\n  if (!serializer) {\n    throw new Error(`No serializer for operation: ${operation[0]}`)\n  }\n  try {\n    serializer(buffer, operation[1])\n  } catch (error: any) {\n    error.message = `${operation[0]}: ${error.message}`\n    throw error\n  }\n}\n\nconst TransactionSerializer = ObjectSerializer([\n  ['ref_block_num', UInt16Serializer],\n  ['ref_block_prefix', UInt32Serializer],\n  ['expiration', DateSerializer],\n  ['operations', ArraySerializer(OperationSerializer)],\n  ['extensions', ArraySerializer(StringSerializer)]\n])\n\nconst EncryptedMemoSerializer = ObjectSerializer([\n  ['from', PublicKeySerializer],\n  ['to', PublicKeySerializer],\n  ['nonce', UInt64Serializer],\n  ['check', UInt32Serializer],\n  ['encrypted', BinarySerializer()]\n])\n\nexport const Serializer = {\n  // Array: ArraySerializer,\n  Asset: AssetSerializer,\n  // Authority: AuthoritySerializer,\n  // Binary: BinarySerializer,\n  // Boolean: BooleanSerializer,\n  // Date: DateSerializer,\n  // FlatMap: FlatMapSerializer,\n  // Int16: Int16Serializer,\n  // Int32: Int32Serializer,\n  // Int64: Int64Serializer,\n  // Int8: Int8Serializer,\n  Memo: EncryptedMemoSerializer,\n  // Object: ObjectSerializer,\n  // Operation: OperationSerializer,\n  // Optional: OptionalSerializer,\n  Price: PriceSerializer,\n  PublicKey: PublicKeySerializer,\n  // StaticVariant: StaticVariantSerializer,\n  String: StringSerializer,\n  Transaction: TransactionSerializer,\n  UInt16: UInt16Serializer,\n  UInt32: UInt32Serializer\n  // UInt64: UInt64Serializer,\n  // UInt8: UInt8Serializer,\n  // Void: VoidSerializer\n}\n","export const sleep = (ms: number): Promise<void> => {\n  return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import { config, serverRpcProxy, type ServerRpcProxyState } from '../config'\nimport { CallResponse } from '../types'\nimport type { APIMethods } from '../api-types'\nimport { sleep } from './sleep'\n\n// ── Server identity (User-Agent) ────────────────────────────────────────────\n\n/**\n * True only when running under Node.js (SSR / server / CLI). Computed once.\n *\n * We attach a descriptive `User-Agent` exclusively here because that is the only\n * place it (a) takes effect and (b) is wanted:\n *  - Node's undici fetch otherwise sends a bare `User-Agent: node`, which is\n *    indistinguishable from any anonymous script in node/CDN analytics.\n *  - Browsers treat `User-Agent` as a forbidden header and silently drop any\n *    override, so setting it there is pointless (and we avoid the churn).\n *  - React Native sets its own native UA (e.g. the mobile app's own string);\n *    overriding it would relabel real mobile traffic, so we explicitly exclude\n *    it via `navigator.product === 'ReactNative'`.\n */\nconst isNodeRuntime: boolean = (() => {\n  try {\n    const isReactNative =\n      typeof navigator !== 'undefined' && (navigator as any).product === 'ReactNative'\n    return (\n      !isReactNative &&\n      typeof process !== 'undefined' &&\n      process.versions != null &&\n      process.versions.node != null\n    )\n  } catch {\n    return false\n  }\n})()\n\n/**\n * Headers that identify the caller on server-side requests. Returns the\n * configured `User-Agent` only under Node; an empty object everywhere else so\n * browser and React Native requests are left exactly as they were.\n */\nfunction serverIdentityHeaders(): Record<string, string> {\n  return isNodeRuntime ? { 'User-Agent': config.userAgent } : {}\n}\n\n// ── Server-side read-through proxy ──────────────────────────────────────────\n\n/**\n * Counters for the proxy path, readable by a host's diagnostics (the web\n * tier's event-loop monitor prints them). `served` = answered by the proxy,\n * `fallback` = proxy configured and eligible but the read went to the node\n * pool, with the reason.\n */\nexport const rpcProxyStats = {\n  served: 0,\n  fallback: 0,\n  /** Reads that went straight to the nodes because the breaker was open. */\n  skipped: 0,\n  fallbackByReason: { status: 0, rpcerror: 0, timeout: 0, transport: 0, validate: 0, parse: 0 } as Record<string, number>\n}\n\n/**\n * `rpcerror` is a 502 tagged `X-Ssr-Cache: RPCERROR`: the proxy reached a node\n * and relayed the node's own error (a tag or post that does not exist, a bad\n * argument). The read still falls back so the caller sees the node's answer\n * unchanged, but the proxy was healthy, so it does not count toward the\n * breaker; the other reasons do.\n */\ntype ProxyMissReason = 'status' | 'rpcerror' | 'timeout' | 'transport' | 'validate' | 'parse'\n\nclass ProxyMiss extends Error {\n  constructor(\n    public reason: ProxyMissReason,\n    message: string\n  ) {\n    super(message)\n  }\n}\n\nconst errorMessage = (e: unknown): string =>\n  e instanceof Error ? e.message : typeof e === 'string' ? e : String(e)\n\n// Breaker: consecutive misses open it for the configured cooldown, a served\n// call closes it. Module state, like the health tracker: one per process.\nlet proxyConsecutiveMisses = 0\nlet proxyOpenUntil = 0\n\n/** Test seam: forget breaker state. */\nexport function resetRpcProxyBreaker(): void {\n  proxyConsecutiveMisses = 0\n  proxyOpenUntil = 0\n}\n\n/**\n * One proxy call for an eligible read. Resolves with the upstream `result` the\n * proxy served, or throws ProxyMiss; the caller then continues with the node\n * loop exactly as if the proxy did not exist. Never throws anything else,\n * except the caller's own abort.\n */\nasync function proxyRpcCall<T>(\n  proxy: ServerRpcProxyState,\n  method: string,\n  params: unknown,\n  callerTimeoutMs: number,\n  externalSignal: AbortSignal | undefined,\n  validate?: (result: unknown) => boolean\n): Promise<T> {\n  const dot = method.indexOf('.')\n  if (dot <= 0 || dot === method.length - 1) {\n    // Unreachable through setServerRpcProxy (it keeps only dotted names), kept\n    // so a future allowlist change fails as a miss rather than a malformed call.\n    throw new ProxyMiss('transport', `method without an api prefix: ${method}`)\n  }\n  // Never wait longer for the proxy than the caller would for one node.\n  const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n    Math.min(proxy.timeoutMs, callerTimeoutMs)\n  )\n  const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n  try {\n    let res: Response\n    try {\n      res = await fetch(proxy.url, {\n        method: 'POST',\n        body: JSON.stringify({ api: method.slice(0, dot), method: method.slice(dot + 1), params }),\n        headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders(), ...proxy.headers },\n        signal\n      })\n    } catch (e: unknown) {\n      if (externalSignal?.aborted) throw e\n      throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'transport', errorMessage(e))\n    }\n    if (res.status !== 200) {\n      // Release the connection: an unconsumed body pins a pooled socket.\n      try {\n        await res.body?.cancel()\n      } catch {\n        // nothing to release\n      }\n      const relayed = res.status === 502 && (res.headers.get('x-ssr-cache') ?? '').toUpperCase() === 'RPCERROR'\n      throw new ProxyMiss(relayed ? 'rpcerror' : 'status', relayed ? 'proxy relayed a node error' : `proxy answered ${res.status}`)\n    }\n    let result: unknown\n    try {\n      result = await res.json()\n    } catch (e: unknown) {\n      if (externalSignal?.aborted) throw e\n      throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'parse', errorMessage(e))\n    }\n    if (validate && !validate(result)) {\n      throw new ProxyMiss('validate', 'proxy result rejected by validator')\n    }\n    return result as T\n  } finally {\n    cleanupTimeout()\n    cleanupMerge()\n  }\n}\n\n// ── Error Types ─────────────────────────────────────────────────────────────\n\nexport class RPCError extends Error {\n  name = 'RPCError'\n  data?: any\n  code: number\n  stack: undefined = undefined\n  constructor(rpcError: { message: string; code: number; data?: any }) {\n    super(rpcError.message)\n    this.code = rpcError.code\n    if ('data' in rpcError) {\n      this.data = rpcError.data\n    }\n  }\n}\n\n/**\n * Transport-level error thrown by jsonRPCCall for HTTP status errors (429, 503).\n * Carries node identity and rate-limit info so callers can record health\n * exactly once without double-counting.\n */\nclass NodeError extends Error {\n  node: string\n  /** Explicit server `Retry-After` in ms, or 0 when the 429 carried no usable header. */\n  rateLimitMs: number\n  /** True for an HTTP 429 regardless of whether a `Retry-After` header was present, so\n   *  a header-less rate limit is still cooled down (with escalating backoff) rather than\n   *  mis-recorded as a plain transport failure. */\n  isRateLimit: boolean\n  constructor(\n    node: string,\n    message: string,\n    opts: { rateLimitMs?: number; isRateLimit?: boolean } = {}\n  ) {\n    super(message)\n    this.node = node\n    this.rateLimitMs = opts.rateLimitMs ?? 0\n    this.isRateLimit = opts.isRateLimit ?? false\n  }\n}\n\n/**\n * Parse an HTTP `Retry-After` header to milliseconds. Supports both forms in the\n * spec: `<delay-seconds>` (e.g. \"120\") and `<http-date>`. Returns 0 when the header\n * is absent or unparseable (including a non-numeric junk value or a past date) so the\n * caller falls back to escalating backoff instead of a NaN/negative cooldown.\n */\nfunction parseRetryAfterMs(header: string | null): number {\n  if (!header) return 0\n  const secs = Number(header)\n  if (Number.isFinite(secs)) return secs > 0 ? secs * 1000 : 0\n  const dateMs = Date.parse(header)\n  if (Number.isFinite(dateMs)) {\n    const delta = dateMs - Date.now()\n    return delta > 0 ? delta : 0\n  }\n  return 0\n}\n\n/** Errors that indicate the request definitely never reached the server. */\nconst PRE_CONNECTION_ERRORS = ['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'EAI_AGAIN']\n\n/** Browser fetch network-failure messages — emitted by Chromium/Firefox/Safari\n *  when CORS preflight fails, DNS fails, TLS fails, or the response is blocked.\n *  These map to scenarios where retrying the same signed broadcast is safe: the\n *  request either never reached the node, or its response was blocked but a\n *  re-broadcast of the *same* signed tx will be deduped by Hive (same trx_id). */\nconst BROWSER_NETWORK_ERRORS = [\n  'Failed to fetch',                       // Chromium\n  'NetworkError when attempting to fetch', // Firefox\n  'Load failed',                           // Safari\n  'fetch failed'                           // Node 18+ undici / Bun — also covered via cause chain\n]\n\n/**\n * Concatenate the error's surface text + the messages/codes from up to 5\n * levels of nested `cause`. Node.js fetch wraps connection failures as\n * `TypeError('fetch failed')` with the real `code` (ECONNREFUSED, etc.)\n * nested in the cause chain. Browser fetch failures have no cause but\n * carry their identifier in `message`.\n */\nfunction flattenErrorText(e: any): string {\n  if (!e) return ''\n  const parts: string[] = [String(e.name || ''), String(e.message || ''), String(e.code || '')]\n  let cause = e.cause\n  for (let depth = 0; cause && depth < 5; depth++) {\n    parts.push(String(cause.code || ''), String(cause.message || ''))\n    cause = cause.cause\n  }\n  return parts.join(' ')\n}\n\n/**\n * Decide whether a broadcast attempt can safely be retried on another node.\n *\n * Safe to retry (same signed tx → Hive dedupes by trx_id at the mempool layer):\n *  - Pre-connection failures (ECONNREFUSED, ENOTFOUND, etc.) — request never sent.\n *  - Browser fetch network failures (CORS block, TLS error, DNS) — TypeError with\n *    a well-known message string.\n *  - JSON parse failures — node returned an HTML error page (typical for\n *    Cloudflare 1033 tunnel-down / 5xx interstitials), so the request never\n *    reached the Hive RPC layer.\n *  - NodeError (HTTP 429/5xx surfaced from jsonRPCCall) — already known transient.\n *\n * NOT safe to retry:\n *  - RPCError — the node accepted the request and the blockchain rejected it.\n *    Retrying on another node would either get the same rejection or accept\n *    a different one; surface the original error instead.\n */\nfunction isBroadcastSafeToRetry(e: any): boolean {\n  if (!e) return false\n  if (e instanceof NodeError) return true\n  if (e instanceof RPCError) return false\n\n  const text = flattenErrorText(e)\n  if (PRE_CONNECTION_ERRORS.some((code) => text.includes(code))) return true\n  if (BROWSER_NETWORK_ERRORS.some((msg) => text.includes(msg))) return true\n\n  // res.json() against an HTML body (Cloudflare/proxy interstitials) throws\n  // SyntaxError. The Hive RPC layer never saw the tx, so failover is safe.\n  if (e instanceof SyntaxError) return true\n  // Some runtimes surface JSON parse errors as plain Error with this text.\n  if (/Unexpected token|JSON\\.parse|Unexpected end of JSON/i.test(text)) return true\n\n  return false\n}\n\n// ── Node Health Tracker ─────────────────────────────────────────────────────\n\n/** Node-level health state tracked by NodeHealthTracker. */\ninterface NodeHealth {\n  /** Global consecutive-failure counter. Resets on success. */\n  consecutiveFailures: number\n  /** Timestamp of the most recent failure. Used with the 30s cooldown window. */\n  lastFailureTime: number\n  /** Epoch ms after which the node is no longer rate-limited. */\n  rateLimitedUntil: number\n  /** Count of consecutive 429s (no intervening success) with no usable Retry-After.\n   *  Drives escalating backoff; reset by a success or by RATE_LIMIT_STREAK_RESET_MS. */\n  rateLimitStreak: number\n  /** Epoch ms of the most recent 429. Used to expire the escalation streak. */\n  lastRateLimitAt: number\n  /** Per-API failure counters. Some nodes disable specific API plugins; tracking\n   * per-API lets us deprioritize a node only for the APIs that fail, not globally.\n   * `defective` marks a cooldown set by recordDefectiveResponse (payload\n   * validation failure) — unlike ordinary strike cooldowns it survives\n   * recordSuccess and only expires on its own. */\n  apiFailures: Map<\n    string,\n    { count: number; cooldownUntil: number; lastFailureTime: number; defective?: boolean }\n  >\n  /** Most recent head_block_number observed for this node. */\n  headBlock: number\n  /** Epoch ms when the head_block was recorded. Used to expire stale observations. */\n  headBlockUpdatedAt: number\n\n  // ── Latency tracking (adaptive ordering) ────────────────────────────────\n  /** EWMA of observed round-trip ms. Fed by successful calls AND by slow/timeout\n   *  failures (so a node that returns 200 in 15s, or aborts at the timeout, is\n   *  ranked on its real slowness — not treated as merely \"healthy\"). `undefined`\n   *  until the first sample. */\n  ewmaLatencyMs?: number\n  /** Number of latency samples folded into the EWMA. Gates \"warmup\": below\n   *  LATENCY_MIN_SAMPLES the node is unproven and keeps its config-order prior. */\n  latencySampleCount: number\n  /** Epoch ms of the most recent latency sample. Used for usability expiry and to\n   *  decide when a node is overdue for an exploratory re-probe. */\n  latencyUpdatedAt: number\n  /** Epoch ms of the most recent exploratory promotion. Single-flight guard so a\n   *  burst of concurrent orderings doesn't all re-probe the same stale node. */\n  lastProbeAt: number\n\n  /**\n   * Per-profile-key latency (same EWMA/warmup/expiry rules as the global one).\n   * The global EWMA mixes cheap calls (get_accounts ~300ms) with heavy ones\n   * (get_account_history, bridge.get_discussion — legitimately seconds), so it\n   * ranks nodes fine but is the WRONG baseline for per-attempt deadlines: a\n   * profile dominated by cheap calls would abort every legitimately-heavy call.\n   * Deadlines/hedge delays therefore key on the FULL method for RPC\n   * (\"condenser_api.get_account_history\") and api+endpoint template for REST —\n   * an API prefix alone still mixes cheap and heavy methods. Ranking keeps the\n   * global profile. Bounded: #nodes × #distinct methods called (code-defined,\n   * not user input); fully cleared whenever the node's global profile expires\n   * (the global clock advances on every sample, so global-stale ⇒ all stale).\n   */\n  apiLatency: Map<string, { ewmaMs: number; sampleCount: number; updatedAt: number }>\n}\n\n/**\n * JSON-RPC error codes that indicate the node itself is unhealthy, not that the\n * client sent a bad request. These should trigger failover to another node.\n *\n * Background: Hive nodes fronted by HAF/jussi/drone return HTTP 200 with a\n * JSON-RPC error body when a backing service (hivemind, postgrest, etc.) is down.\n * The HTTP layer looks healthy, so failover never triggers — the caller just gets\n * an error and gives up. This function identifies those node-level errors.\n */\nfunction isNodeLevelRPCError(code: number, message: string): boolean {\n  // -32603: Internal error — node is having problems\n  if (code === -32603) return true\n  // -32000 to -32099: Server error range (implementation-defined server errors)\n  if (code <= -32000 && code >= -32099) return true\n  // -32601: Method not found — node may be missing this API plugin\n  if (code === -32601) return true\n  // -32602 with node-sick indicators (vs normal \"invalid params\" from bad client input)\n  // e.g. \"Unable to parse endpoint data\" from HAF when a backing service is down\n  if (code === -32602 && /unable to parse|endpoint data|internal/i.test(message)) return true\n  return false\n}\n\n/** Extract the API prefix from a method name like \"rc_api.find_rc_accounts\" -> \"rc_api\". */\nfunction apiOf(method: string): string {\n  const dot = method.indexOf('.')\n  return dot > 0 ? method.slice(0, dot) : method\n}\n\n// ── Rate-limit (429) backoff constants ───────────────────────────────────────\n/** Base cooldown applied to a 429 with no usable `Retry-After` header. Matches the\n *  previous flat default so first-offence behaviour is unchanged. */\nconst RATE_LIMIT_BASE_MS = 10_000\n/** Ceiling for the escalating header-less cooldown. Prevents a node from being\n *  parked far longer than a real public node's throttle window. */\nconst RATE_LIMIT_MAX_MS = 60_000\n/** No 429 from a node for this long ⇒ its escalation streak resets to 0, so an\n *  occasional throttle hours apart doesn't compound into a long park. */\nconst RATE_LIMIT_STREAK_RESET_MS = 120_000\n\n/** Per-API failure threshold before the node is deprioritized for that API only. */\nconst MAX_API_FAILURES_BEFORE_COOLDOWN = 2\n/** How long a node stays deprioritized for a specific API after repeated failures. */\nconst API_COOLDOWN_MS = 60_000\n/** How long head_block observations remain valid before being treated as unknown. */\nconst HEAD_BLOCK_MAX_AGE_MS = 120_000\n/** Maximum lag (in blocks) before a node is considered stale relative to the best-known head. */\nconst STALE_BLOCK_THRESHOLD = 30\n\n// ── Adaptive latency-ordering constants ──────────────────────────────────────\n/** EWMA smoothing weight for a new latency sample. 0.3 ⇒ ~5–6 samples to converge;\n *  absorbs one-off GC/TLS spikes while still reacting to a real regional shift fast. */\nconst LATENCY_EWMA_ALPHA = 0.3\n/** Samples required before a node's latency is trusted for ranking. Below this the\n *  node is \"warming\" and ranks at a neutral prior (config order via tiebreak), so a\n *  single fluke never reorders the list and cold start == today's behavior. */\nconst LATENCY_MIN_SAMPLES = 3\n/** How long a latency sample stays usable for ranking. Past this a node reverts to\n *  warming. Must be > LATENCY_REPROBE_MS so re-probes keep a busy node's profile fresh. */\nconst LATENCY_MAX_AGE_MS = 5 * 60_000\n/** A healthy node not sampled within this window is overdue for an exploratory\n *  re-probe (promoted to front of ONE ordering). This is what lets a demoted node\n *  climb back when it recovers — and what profiles a node that organic traffic never\n *  reaches. 60s ⇒ ~1 probe/node/min worst case = negligible cost. */\nconst LATENCY_REPROBE_MS = 60_000\n/** Neutral score (ms) for an unproven/warming node: optimistic enough to sit ahead\n *  of a proven-slow node (so we explore an unknown before hammering a known-slow one)\n *  but behind a proven-fast node. Fixed, so a node makes at most ONE rank transition\n *  when it crosses LATENCY_MIN_SAMPLES — no churn. */\nconst LATENCY_UNPROVEN_PRIOR_MS = 1_000\n/** A failed call only feeds a latency penalty if it was actually slow (≥ this). Keeps\n *  a genuine timeout / slow-5xx (a far-region node case) visible to the ranker while an\n *  instant ECONNREFUSED (a *down* node, handled by consecutiveFailures) is NOT mis-read\n *  as \"slow\". The penalty value is the *measured* elapsed, never a static constant. */\nconst LATENCY_SLOW_FAILURE_MS = 2_000\n\n/**\n * Latency-ranking tuning, re-exported as a frozen bag so tests assert behaviour\n * against the real numbers instead of mirroring literals that can silently drift.\n * @internal — not part of the package's public API; for the co-located spec only.\n */\nexport const __LATENCY_TUNING__ = Object.freeze({\n  EWMA_ALPHA: LATENCY_EWMA_ALPHA,\n  MIN_SAMPLES: LATENCY_MIN_SAMPLES,\n  MAX_AGE_MS: LATENCY_MAX_AGE_MS,\n  REPROBE_MS: LATENCY_REPROBE_MS,\n  UNPROVEN_PRIOR_MS: LATENCY_UNPROVEN_PRIOR_MS,\n  SLOW_FAILURE_MS: LATENCY_SLOW_FAILURE_MS\n})\n\n/** @internal Exported for testing only. */\nexport class NodeHealthTracker {\n  private health = new Map<string, NodeHealth>()\n\n  private getOrCreate(node: string): NodeHealth {\n    let h = this.health.get(node)\n    if (!h) {\n      h = {\n        consecutiveFailures: 0,\n        lastFailureTime: 0,\n        rateLimitedUntil: 0,\n        rateLimitStreak: 0,\n        lastRateLimitAt: 0,\n        apiFailures: new Map(),\n        headBlock: 0,\n        headBlockUpdatedAt: 0,\n        ewmaLatencyMs: undefined,\n        latencySampleCount: 0,\n        latencyUpdatedAt: 0,\n        // Stamp the probe clock at creation so a brand-new (never-sampled) node is\n        // NOT treated as \"overdue for re-probe\" on its very first ordering pass.\n        // With lastProbeAt=0 the re-probe gate (touch <= now - LATENCY_REPROBE_MS)\n        // fired immediately, so the 2nd+ ordering on a cold worker promoted unproven\n        // nodes ahead of the configured order for no measured reason. Seeding it to\n        // \"now\" preserves configured order during warmup; a genuinely slow preferred\n        // node is still demoted by its EWMA score (not by epoch-zero exploration),\n        // and idle nodes are still re-probed once LATENCY_REPROBE_MS has truly elapsed.\n        lastProbeAt: Date.now(),\n        apiLatency: new Map()\n      }\n      this.health.set(node, h)\n    }\n    return h\n  }\n\n  recordSuccess(node: string, api?: string, durationMs?: number, profileKey?: string): void {\n    const h = this.getOrCreate(node)\n    h.consecutiveFailures = 0\n    // A success means the node recovered — clear the escalation streak so the next\n    // throttle starts from the base cooldown. We deliberately do NOT clear an active\n    // rateLimitedUntil window here: under concurrency a success from a request that was\n    // already in flight can resolve *after* another request recorded a fresh 429\n    // Retry-After, and erasing the window would put a just-throttled node back into\n    // rotation early. The window expires on its own (short for header-less; the server's\n    // value for an explicit Retry-After).\n    h.rateLimitStreak = 0\n    if (api) {\n      // A successful API call clears that API's failure counter — but never an\n      // ACTIVE defective-response cooldown: the \"success\" may itself be an\n      // unvalidated read from the same lying node (validated calls are the\n      // minority of traffic), and re-admitting it early defeats the decisive\n      // penalty. That window expires on its own, like rateLimitedUntil above.\n      const apiFail = h.apiFailures.get(api)\n      if (!apiFail || !(apiFail.defective && apiFail.cooldownUntil > Date.now())) {\n        h.apiFailures.delete(api)\n      }\n    }\n    if (typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0) {\n      // Latency profiles use the finest key available (full method / endpoint\n      // template); the API prefix is only a fallback so bare callers still\n      // profile SOMETHING. Failure state above stays per-API on purpose.\n      this.recordLatency(h, durationMs, profileKey ?? api)\n    }\n  }\n\n  /**\n   * Record a *slow* failed call as a latency signal. The failure counters are\n   * updated separately (recordFailure/recordError); this only feeds the EWMA so a\n   * node that returns 200-but-too-slow, times out, or returns a slow 5xx is ranked\n   * on its real slowness. Callers pass the MEASURED elapsed ms and only call this\n   * when the call was genuinely slow (≥ LATENCY_SLOW_FAILURE_MS) — an instant\n   * connection failure (a *down* node) must NOT look \"slow\".\n   */\n  recordSlowFailure(node: string, durationMs: number, profileKey?: string): void {\n    if (!Number.isFinite(durationMs) || durationMs < LATENCY_SLOW_FAILURE_MS) return\n    this.recordLatency(this.getOrCreate(node), durationMs, profileKey)\n  }\n\n  /**\n   * Usable latency profile (EWMA ms), or `undefined` while unproven or stale.\n   * With a `profileKey` (full RPC method / REST api+endpoint template),\n   * returns that (node, key) profile ONLY — deliberately no fallback to the\n   * mixed global profile, because an average dominated by cheap calls is the\n   * wrong deadline baseline for a heavy method (that fallback is exactly the\n   * \"2s window starves get_account_history\" failure mode). Without a key,\n   * returns the global ranking profile. Both follow the same \"profiled and\n   * fresh\" gate as the ranker.\n   * @internal\n   */\n  getUsableLatencyMs(node: string, profileKey?: string): number | undefined {\n    const h = this.health.get(node)\n    if (!h) return undefined\n    const now = Date.now()\n    if (profileKey !== undefined) {\n      const p = h.apiLatency.get(profileKey)\n      return p &&\n        p.sampleCount >= LATENCY_MIN_SAMPLES &&\n        now - p.updatedAt <= LATENCY_MAX_AGE_MS\n        ? p.ewmaMs\n        : undefined\n    }\n    return this.isLatencyUsable(h, now) ? h.ewmaLatencyMs : undefined\n  }\n\n  /**\n   * Censored latency sample for a request that was ABORTED because a hedge\n   * completed first while it was still in flight. The elapsed-at-abort is a\n   * *lower bound* on the true latency, so folding it in can only move the\n   * node's EWMA toward the truth, never below it — which is what lets repeated\n   * hedge-wins reorder the pool. Deliberately does NOT touch the failure\n   * counters or rate-limit state: the node returned no error, it was merely\n   * slow, and treating cancellation as failure would flap `isNodeHealthy`.\n   * Callers must NOT record this for a primary that already settled on its own\n   * (its outcome was recorded normally; a second sample would be fabricated).\n   * Bypasses the `recordSlowFailure` 2s floor (a hedge can win well below it).\n   * By construction the elapsed is ≥ the hedge delay, so only a degenerate\n   * near-zero epsilon needs rejecting — anything under one LAN round trip is\n   * noise, not a latency measurement.\n   * @internal\n   */\n  recordCensoredLatency(node: string, elapsedMs: number, profileKey?: string): void {\n    if (!Number.isFinite(elapsedMs) || elapsedMs < 50) return\n    this.recordLatency(this.getOrCreate(node), elapsedMs, profileKey)\n  }\n\n  /**\n   * Fold a latency sample into the node's global EWMA (warmup + usability\n   * bookkeeping) and, when a profile key is given, into that (node, key)\n   * profile — the global one ranks nodes, the keyed one calibrates deadlines.\n   */\n  private recordLatency(h: NodeHealth, durationMs: number, profileKey?: string): void {\n    const now = Date.now()\n    // A profile older than the usable window starts fresh, so an idled process\n    // re-learns from scratch rather than ranking on hour-old data. Every keyed\n    // profile shares this clock (each sample updates both), so global-stale\n    // implies every keyed profile is stale too — clear the map rather than\n    // leave never-again-read tombstone entries for the life of the process.\n    if (h.latencyUpdatedAt > 0 && now - h.latencyUpdatedAt > LATENCY_MAX_AGE_MS) {\n      h.ewmaLatencyMs = undefined\n      h.latencySampleCount = 0\n      h.apiLatency.clear()\n    }\n    h.ewmaLatencyMs =\n      h.ewmaLatencyMs === undefined\n        ? durationMs\n        : LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * h.ewmaLatencyMs\n    h.latencySampleCount++\n    h.latencyUpdatedAt = now\n\n    if (profileKey !== undefined) {\n      const p = h.apiLatency.get(profileKey)\n      if (!p || now - p.updatedAt > LATENCY_MAX_AGE_MS) {\n        h.apiLatency.set(profileKey, { ewmaMs: durationMs, sampleCount: 1, updatedAt: now })\n      } else {\n        p.ewmaMs = LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * p.ewmaMs\n        p.sampleCount++\n        p.updatedAt = now\n      }\n    }\n  }\n\n  recordFailure(node: string, api?: string): void {\n    const h = this.getOrCreate(node)\n    if (api) {\n      // API-specific failure: only update the per-API tracker.\n      // This prevents e.g. 3 rc_api failures from marking the node\n      // globally unhealthy for condenser_api too.\n      const now = Date.now()\n      const existing: {\n        count: number\n        cooldownUntil: number\n        lastFailureTime: number\n        defective?: boolean\n      } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n      // Reset counter if previous cooldown expired OR last failure was >30s ago\n      // (avoids sticky penalties from sparse failures hours apart)\n      if (\n        (existing.cooldownUntil > 0 && existing.cooldownUntil <= now) ||\n        (existing.lastFailureTime > 0 && now - existing.lastFailureTime > 30_000)\n      ) {\n        existing.count = 0\n        existing.cooldownUntil = 0\n      }\n      existing.count++\n      existing.lastFailureTime = now\n      if (existing.count >= MAX_API_FAILURES_BEFORE_COOLDOWN) {\n        existing.cooldownUntil = now + API_COOLDOWN_MS\n      }\n      h.apiFailures.set(api, existing)\n    } else {\n      // Transport-level failure (no specific API): update global counter\n      h.consecutiveFailures++\n      h.lastFailureTime = Date.now()\n    }\n  }\n\n  /**\n   * A response that failed the caller's payload validation is a decisive,\n   * reproducible node fault — the node answered 200 with data the caller KNOWS\n   * to be impossible — so it trips the per-API cooldown immediately instead of\n   * accruing ordinary strikes. Deliberately its own method rather than\n   * recordFailure × N: ordinary strikes are cleared by any success, and a\n   * top-ranked lying node keeps recording successes on the unvalidated calls\n   * between probes, which would reset its strikes forever and keep it in\n   * rotation (observed live). Scope stays per-API: the node may be perfectly\n   * healthy for its other API families.\n   */\n  recordDefectiveResponse(node: string, api: string): void {\n    const h = this.getOrCreate(node)\n    const now = Date.now()\n    const existing: {\n      count: number\n      cooldownUntil: number\n      lastFailureTime: number\n      defective?: boolean\n    } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n    existing.count = Math.max(existing.count + 1, MAX_API_FAILURES_BEFORE_COOLDOWN)\n    existing.lastFailureTime = now\n    existing.cooldownUntil = now + API_COOLDOWN_MS\n    existing.defective = true\n    h.apiFailures.set(api, existing)\n  }\n\n  /**\n   * Cool down a rate-limited node. Honors an explicit server `Retry-After`\n   * (`retryAfterMs`) exactly — the server told us when to return. With no usable\n   * header, applies escalating backoff: BASE, 2×BASE, 4×BASE … capped at\n   * RATE_LIMIT_MAX_MS, indexed by the node's consecutive-429 streak (reset by a\n   * success or after RATE_LIMIT_STREAK_RESET_MS of quiet). This stops a throttled\n   * public node from being re-admitted every 10s and re-hammered under sustained\n   * load, which matters most when the fleet's own unlimited node is removed.\n   */\n  recordRateLimit(node: string, retryAfterMs?: number): void {\n    const h = this.getOrCreate(node)\n    const now = Date.now()\n    // Expire a stale streak so an occasional throttle hours apart doesn't compound.\n    if (h.rateLimitStreak > 0 && now - h.lastRateLimitAt > RATE_LIMIT_STREAK_RESET_MS) {\n      h.rateLimitStreak = 0\n    }\n    const hasHeader = typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0\n    const cooldown = hasHeader\n      ? retryAfterMs!\n      : Math.min(RATE_LIMIT_BASE_MS * 2 ** h.rateLimitStreak, RATE_LIMIT_MAX_MS)\n    // Only a header-less 429 advances the escalation streak — an explicit Retry-After is\n    // honored exactly and must not compound the header-less backoff (else several\n    // Retry-After 429s would push a later header-less 429 straight to the 60s cap).\n    if (!hasHeader) h.rateLimitStreak++\n    h.lastRateLimitAt = now\n    // Explicit Retry-After is honored exactly (the server's current instruction). A\n    // header-less cooldown may only move the window FORWARD — it must never truncate a\n    // longer window already set, e.g. a node parked for an hour by an explicit\n    // Retry-After that is later retried as a last resort and returns a header-less 429\n    // must not have its 1h window cut down to the 10s base.\n    h.rateLimitedUntil = hasHeader\n      ? now + cooldown\n      : Math.max(h.rateLimitedUntil, now + cooldown)\n    h.consecutiveFailures++\n    h.lastFailureTime = now\n  }\n\n  /** Record an observed head_block_number for this node. */\n  recordHeadBlock(node: string, blockNum: number): void {\n    if (!blockNum || !Number.isFinite(blockNum)) return\n    const h = this.getOrCreate(node)\n    h.headBlock = blockNum\n    h.headBlockUpdatedAt = Date.now()\n  }\n\n  /**\n   * Consensus head block from recent observations. Uses the median rather than the\n   * max to prevent a single bad/misconfigured node from poisoning the reference.\n   * A node reporting an inflated head_block won't affect the median unless the\n   * majority of nodes agree on that range.\n   */\n  private consensusHeadBlock(): number {\n    const now = Date.now()\n    const recent: number[] = []\n    for (const h of this.health.values()) {\n      if (h.headBlock > 0 && now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS) {\n        recent.push(h.headBlock)\n      }\n    }\n    if (recent.length < 2) return 0 // Need at least 2 observations to compare\n    recent.sort((a, b) => a - b)\n    // Median: for even length, use the lower-middle value (conservative)\n    return recent[Math.floor((recent.length - 1) / 2)]\n  }\n\n  /** True if this node is healthy (globally and for the given API if provided). */\n  isNodeHealthy(node: string, api?: string): boolean {\n    const h = this.health.get(node)\n    if (!h) return true // unknown nodes assumed healthy\n    const now = Date.now()\n\n    // Rate-limited and cooldown hasn't expired\n    if (h.rateLimitedUntil > now) return false\n\n    // Too many consecutive failures within the last 30 seconds\n    if (h.consecutiveFailures >= 3 && now - h.lastFailureTime < 30_000) return false\n\n    // Per-API cooldown: node may be healthy overall but missing this API plugin\n    if (api) {\n      const apiFail = h.apiFailures.get(api)\n      if (apiFail && apiFail.cooldownUntil > now) return false\n    }\n\n    // Head-block staleness: deprioritize nodes lagging behind the consensus head\n    const best = this.consensusHeadBlock()\n    if (\n      best > 0 &&\n      h.headBlock > 0 &&\n      now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS &&\n      best - h.headBlock > STALE_BLOCK_THRESHOLD\n    ) {\n      return false\n    }\n\n    return true\n  }\n\n  /**\n   * Order nodes best-first: healthy nodes sorted by adaptive latency score, then\n   * unhealthy nodes appended. Capability / staleness / rate-limit filtering stays in\n   * `isNodeHealthy` and is unchanged — latency only reorders WITHIN the healthy set,\n   * and only WITHIN the array it is handed (so it never leaves the configured list).\n   *\n   * One ordering per pass MAY promote a healthy node overdue for a re-probe (never\n   * sampled, or not sampled within LATENCY_REPROBE_MS) to the front — single-flight\n   * via `lastProbeAt`. This is what lets a demoted node climb back when it recovers,\n   * and profiles a node that organic traffic (always served by a faster peer) never\n   * reaches. Cold start: with no profiles, every node scores the neutral prior and the\n   * stable config-index tiebreak yields the original order — i.e. today's behavior.\n   */\n  getOrderedNodes(nodes: string[], api?: string): string[] {\n    const healthy: string[] = []\n    const unhealthy: string[] = []\n    for (const node of nodes) {\n      if (this.isNodeHealthy(node, api)) {\n        healthy.push(node)\n      } else {\n        unhealthy.push(node)\n      }\n    }\n    if (healthy.length <= 1) {\n      return [...healthy, ...unhealthy]\n    }\n    const now = Date.now()\n    // Every score in THIS pass falls back to config index on ties → a total,\n    // transitive order with no memo (so no stale-denominator inversions).\n    const ordered = healthy\n      .map((node, i) => ({ node, i, score: this.scoreNode(node, now) }))\n      .sort((a, b) => a.score - b.score || a.i - b.i)\n      .map((d) => d.node)\n    const probe = this.pickReprobeCandidate(healthy, now)\n    if (probe && ordered[0] !== probe) {\n      return [probe, ...ordered.filter((n) => n !== probe), ...unhealthy]\n    }\n    return [...ordered, ...unhealthy]\n  }\n\n  /** A node's latency is usable for ranking only if profiled (≥ MIN_SAMPLES) and fresh. */\n  private isLatencyUsable(h: NodeHealth | undefined, now: number): boolean {\n    return (\n      !!h &&\n      h.ewmaLatencyMs !== undefined &&\n      h.latencySampleCount >= LATENCY_MIN_SAMPLES &&\n      now - h.latencyUpdatedAt <= LATENCY_MAX_AGE_MS\n    )\n  }\n\n  /**\n   * Ranking score (lower = better). Unproven/warming nodes get a fixed neutral prior\n   * so they sit ahead of a proven-slow node but behind a proven-fast one, and make at\n   * most one rank transition when they cross MIN_SAMPLES (no churn).\n   */\n  private scoreNode(node: string, now: number): number {\n    const h = this.health.get(node)\n    if (!this.isLatencyUsable(h, now)) return LATENCY_UNPROVEN_PRIOR_MS\n    return h!.ewmaLatencyMs!\n  }\n\n  /**\n   * At most one healthy node overdue for an exploratory re-probe: never sampled, or\n   * neither sampled nor re-probed within LATENCY_REPROBE_MS. Returns the stalest such\n   * node and stamps `lastProbeAt` to single-flight it against concurrent orderings.\n   *\n   * Note: `getOrCreate` here materializes a health entry per node in the passed list.\n   * The node list (`config.nodes`/`restNodes`) is treated as effectively static — set\n   * once via `setNodes` — so the map is bounded. If a host is ever removed from the\n   * list at runtime its stale entry is simply ignored (never re-surfaced) and is a\n   * negligible, bounded amount of memory.\n   */\n  private pickReprobeCandidate(healthy: string[], now: number): string | undefined {\n    const threshold = now - LATENCY_REPROBE_MS\n    let cand: string | undefined\n    let candTouch = Infinity\n    for (const n of healthy) {\n      const h = this.getOrCreate(n)\n      const touch = Math.max(h.latencyUpdatedAt, h.lastProbeAt)\n      if (touch <= threshold && touch < candTouch) {\n        cand = n\n        candTouch = touch\n      }\n    }\n    if (cand) this.getOrCreate(cand).lastProbeAt = now\n    return cand\n  }\n}\n\n// Exported for the co-located specs only (asserting the call sites' effect on\n// health). Not re-exported by hive-tx/index.ts, so NOT part of the public API.\n// @internal\nexport const rpcHealthTracker = new NodeHealthTracker()\n// @internal\nexport const restHealthTracker = new NodeHealthTracker()\n\n// ── Hedged-request budget ────────────────────────────────────────────────────\n\n/**\n * Token bucket bounding hedged (duplicated) read requests to a fraction of\n * overall traffic. A hedge spends 1 token; every un-hedged success refills\n * `config.resilience.hedgeRefillPerSuccess` (default 0.1 ⇒ steady-state hedge\n * rate ≤ ~9% of successful traffic, with bursts up to `hedgeBucketCapacity`).\n * The self-limiting property this buys: under pool-wide slowness nearly every\n * request wants to hedge while successes (the refills) stagnate, so the bucket\n * drains and hedging auto-disables instead of doubling load into public-node\n * rate limits — the standard hedged-request guard (cf. gRPC's hedging throttle;\n * Dean & Barroso, \"The Tail at Scale\"). One instance per process shared across\n * concurrent calls; plain synchronous mutation is race-free on the JS event\n * loop. Reads config live so runtime tuning via `setResilience` applies.\n * @internal Exported for testing only.\n */\nexport class HedgeBudget {\n  private tokens = config.resilience.hedgeBucketCapacity\n\n  trySpend(): boolean {\n    this.clamp()\n    // Epsilon guards fractional-refill float accumulation (10 × 0.1 < 1 in FP64).\n    if (this.tokens >= 1 - 1e-9) {\n      this.tokens -= 1\n      return true\n    }\n    return false\n  }\n\n  refill(): void {\n    this.clamp()\n    this.tokens = Math.min(\n      config.resilience.hedgeBucketCapacity,\n      this.tokens + config.resilience.hedgeRefillPerSuccess\n    )\n  }\n\n  /** Capacity may be lowered at runtime; never let stored tokens exceed it. */\n  private clamp(): void {\n    if (this.tokens > config.resilience.hedgeBucketCapacity) {\n      this.tokens = config.resilience.hedgeBucketCapacity\n    }\n  }\n\n  /** @internal test hook */\n  get available(): number {\n    return this.tokens\n  }\n\n  /** @internal test hook */\n  reset(tokens = config.resilience.hedgeBucketCapacity): void {\n    this.tokens = tokens\n  }\n}\n\n// @internal — exported for the co-located spec only, like the trackers above.\nexport const rpcHedgeBudget = new HedgeBudget()\n\n/**\n * Per-attempt timeout for a read call. A node profiled for THIS profile key\n * (full RPC method / REST api+endpoint template) is given `factor × EWMA` —\n * floored (≥2s) so a moderate spike on a fast call is not cut off, and capped\n * at the caller's ceiling so this can only ever *shorten* the wait. The\n * effect: a node running far above its own baseline for this exact kind of\n * call is abandoned early and failover starts in seconds instead of the full\n * fixed window.\n *\n * Two deliberate exclusions:\n * - `explicit` callers (who passed a timeout argument) keep exactly what they\n *   asked for — the documented meaning of the parameter is preserved, and a\n *   consumer who knows their call is heavy is never second-guessed.\n * - The profile is per (node, full method) with NO fallback to the node's\n *   mixed global EWMA or even the API-prefix average: a baseline dominated by\n *   cheap `condenser_api.get_accounts` calls must not set the deadline for a\n *   heavy `condenser_api.get_account_history`. An unprofiled (node, method)\n *   pair keeps the caller's timeout unchanged (cold start == old behavior).\n */\nfunction adaptiveAttemptTimeout(\n  tracker: NodeHealthTracker,\n  node: string,\n  profileKey: string,\n  callerTimeout: number,\n  explicit: boolean\n): number {\n  const r = config.resilience\n  if (!r.adaptiveTimeout || explicit) return callerTimeout\n  const ewma = tracker.getUsableLatencyMs(node, profileKey)\n  if (ewma === undefined) return callerTimeout\n  // EWMAs are fractional, but the result feeds AbortSignal.timeout(), which\n  // Node rejects with ERR_OUT_OF_RANGE for non-integer delays (browsers coerce).\n  return Math.ceil(\n    Math.min(callerTimeout, Math.max(r.adaptiveTimeoutFloorMs, r.adaptiveTimeoutFactor * ewma))\n  )\n}\n\n// ── Internal helpers ────────────────────────────────────────────────────────\n\n/** Record a caught error on the health tracker (handles NodeError to avoid double-counting). */\nfunction recordError(tracker: NodeHealthTracker, node: string, e: any, api?: string): void {\n  if (e instanceof NodeError) {\n    if (e.isRateLimit) {\n      // 0 → no usable Retry-After → let recordRateLimit apply escalating backoff.\n      tracker.recordRateLimit(node, e.rateLimitMs || undefined)\n    } else {\n      tracker.recordFailure(node, api)\n    }\n  } else if (e instanceof RPCError) {\n    // RPC-level errors are API-specific (e.g., disabled API)\n    tracker.recordFailure(node, api)\n  } else {\n    // Transport-level failures (DNS, TLS, timeout) affect the whole node\n    tracker.recordFailure(node)\n  }\n}\n\n/**\n * Passively extract head_block_number from known RPC responses\n * (e.g. `condenser_api.get_dynamic_global_properties`, `database_api.get_dynamic_global_properties`).\n * Silently ignores responses without that shape.\n */\nfunction tryRecordHeadBlock(\n  tracker: NodeHealthTracker,\n  node: string,\n  method: string,\n  result: any\n): void {\n  if (!result || typeof result !== 'object') return\n  if (!method.includes('get_dynamic_global_properties')) return\n  const block = (result as any).head_block_number\n  if (typeof block === 'number') {\n    tracker.recordHeadBlock(node, block)\n  }\n}\n\n// ── AbortSignal helpers (browser fallbacks) ─────────────────────────────────\n\n/**\n * Build a TimeoutError \"reason\" for an aborted signal.\n * Prefers the standard `DOMException` when available. Runtimes that ship\n * `AbortController` without `DOMException` (notably React Native / Hermes,\n * old Node < 17) fall back to a plain Error tagged with `name: 'TimeoutError'`\n * — which is what consumers actually check on `signal.reason`.\n */\nfunction createTimeoutReason(): Error {\n  if (typeof DOMException !== 'undefined') {\n    return new DOMException('The operation was aborted due to timeout', 'TimeoutError')\n  }\n  const err = new Error('The operation was aborted due to timeout')\n  err.name = 'TimeoutError'\n  return err\n}\n\n/** AbortSignal.timeout polyfill for pre-Chrome 103 / pre-Safari 16.4.\n *  Returns { signal, cleanup } — caller must invoke cleanup() on success\n *  to clear the dangling timer. */\nfunction createTimeoutSignal(ms: number): { signal: AbortSignal; cleanup: () => void } {\n  // Node's AbortSignal.timeout throws ERR_OUT_OF_RANGE on fractional delays\n  // (browsers coerce them), so guard every caller here.\n  ms = Math.ceil(ms)\n  if (typeof AbortSignal.timeout === 'function') {\n    return { signal: AbortSignal.timeout(ms), cleanup: () => {} }\n  }\n  const controller = new AbortController()\n  const timer = setTimeout(() => controller.abort(createTimeoutReason()), ms)\n  return { signal: controller.signal, cleanup: () => clearTimeout(timer) }\n}\n\n/** AbortSignal.any polyfill for pre-Chrome 116 / pre-Safari 17.4.\n *  Returns { signal, cleanup } — caller must invoke cleanup() on success\n *  to remove listeners from the input signals (prevents leaks when the\n *  same long-lived signal is reused across many callRPC invocations). */\nfunction mergeSignals(\n  primary: AbortSignal,\n  secondary?: AbortSignal\n): { signal: AbortSignal; cleanup: () => void } {\n  if (!secondary) return { signal: primary, cleanup: () => {} }\n  if (typeof AbortSignal.any === 'function') {\n    return { signal: AbortSignal.any([primary, secondary]), cleanup: () => {} }\n  }\n  // Fallback: controller that aborts with the winning signal's reason\n  const controller = new AbortController()\n  if (primary.aborted) {\n    controller.abort(primary.reason)\n    return { signal: controller.signal, cleanup: () => {} }\n  }\n  if (secondary.aborted) {\n    controller.abort(secondary.reason)\n    return { signal: controller.signal, cleanup: () => {} }\n  }\n\n  const onPrimaryAbort = () => controller.abort(primary.reason)\n  const onSecondaryAbort = () => controller.abort(secondary.reason)\n  primary.addEventListener('abort', onPrimaryAbort, { once: true })\n  secondary.addEventListener('abort', onSecondaryAbort, { once: true })\n\n  const cleanup = () => {\n    primary.removeEventListener('abort', onPrimaryAbort)\n    secondary.removeEventListener('abort', onSecondaryAbort)\n  }\n  return { signal: controller.signal, cleanup }\n}\n\n/**\n * Low-level JSON-RPC call to a single node. No failover.\n * Throws RPCError for blockchain rejections, NodeError for HTTP 429/5xx,\n * and generic Error for other transport failures.\n * @param shouldRetry - If true, retries once on the same node for transient errors.\n */\nconst jsonRPCCall = async (\n  url: string,\n  method: string,\n  params: any,\n  timeout = config.timeout,\n  shouldRetry = false,\n  externalSignal?: AbortSignal\n) => {\n  const id = Math.floor(Math.random() * 100_000_000)\n  const body = {\n    jsonrpc: '2.0',\n    method,\n    params,\n    id\n  }\n  // Merge the per-call timeout with any external abort signal (e.g., SSR\n  // request cancellation). Either one firing cancels the fetch.\n  // Fallbacks for browsers without AbortSignal.timeout (pre-Chrome 103)\n  // or AbortSignal.any (pre-Chrome 116).\n  const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(timeout)\n  const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n  const cleanup = () => {\n    cleanupTimeout()\n    cleanupMerge()\n  }\n\n  try {\n    const res = await fetch(url, {\n      method: 'POST',\n      body: JSON.stringify(body),\n      headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders() },\n      signal\n    })\n\n    // Handle HTTP-level errors before parsing JSON.\n    // Throw NodeError so callers can record health exactly once.\n    if (res.status === 429) {\n      throw new NodeError(url, `HTTP 429 Rate Limited`, {\n        rateLimitMs: parseRetryAfterMs(res.headers.get('Retry-After')),\n        isRateLimit: true\n      })\n    }\n    // Any other 5xx is a node-level failure. Common cases:\n    //   502 Bad Gateway       — upstream HAF/jussi down\n    //   503 Service Unavail   — node draining / maintenance\n    //   504 Gateway Timeout   — slow upstream\n    //   520-530               — Cloudflare interstitials (1033 tunnel error → 530)\n    // Without this branch, the HTML error-page body would fall into res.json()\n    // and throw a generic SyntaxError downstream, making failover guess at\n    // whether the request reached the node.\n    if (res.status >= 500 && res.status < 600) {\n      throw new NodeError(url, `HTTP ${res.status} from ${url}`)\n    }\n\n    const result = (await res.json()) as CallResponse\n    if (\n      !result ||\n      typeof result.id === 'undefined' ||\n      result.id !== id ||\n      result.jsonrpc !== '2.0'\n    ) {\n      throw new Error('JSONRPC id mismatch')\n    }\n    if ('result' in result) {\n      return result.result\n    }\n    if ('error' in result) {\n      const e = result.error\n      if ('message' in e && 'code' in e) {\n        throw new RPCError(e)\n      }\n      throw result.error\n    }\n    // No result and no error?\n    throw result\n  } catch (e) {\n    if (e instanceof RPCError) {\n      throw e\n    }\n    // NodeError should not be retried on the same node - it's an HTTP status issue\n    if (e instanceof NodeError) {\n      throw e\n    }\n    if (externalSignal?.aborted) {\n      throw e\n    }\n    if (shouldRetry) {\n      return jsonRPCCall(url, method, params, timeout, false, externalSignal)\n    }\n    throw e\n  } finally {\n    cleanup()\n  }\n}\n\n/** Small jitter delay between failover attempts to prevent thundering herd. */\nfunction jitterDelay(): Promise<void> {\n  return sleep(50 + Math.random() * 50)\n}\n\n// ── Hedged read attempt ─────────────────────────────────────────────────────\n\n/**\n * One hedged READ attempt: start the primary node, and if it is still pending\n * after `max(hedgeDelayFloorMs, hedgeDelayFactor × primary EWMA)`, race a\n * duplicate against the next healthy untried node. First success wins and the\n * loser is aborted. Resolution rules (mirroring the sequential path exactly):\n *\n * - External abort (caller cancelled): reject immediately, record nothing.\n * - Authoritative RPCError (non-node-level blockchain rejection) from either\n *   leg: an answer, not a fault — abort the other leg, reject immediately.\n * - Failover-class failure: record health for that leg (recordError +\n *   recordSlowFailure — identical to the sequential catch); if the other leg\n *   is still running, keep waiting on it; when both have failed, reject with\n *   the last error so the outer loop continues its normal failover.\n * - Primary fails BEFORE the hedge fires: reject immediately (plain failover —\n *   hedging only ever races slowness, never a node that failed fast).\n *\n * Health/budget bookkeeping on a win: winner records a normal success sample;\n * if the hedge won, the primary gets a censored latency sample (elapsed at\n * abort — a lower bound on its true latency) so repeated hedge-wins reorder\n * the pool; if the primary won without the hedge ever firing, the budget\n * refills. An aborted hedge leg records nothing (it was never given a fair\n * run). Broadcasts NEVER go through this path (double-broadcast risk) — it is\n * wired into `callRPC` only.\n */\nfunction hedgedRpcAttempt<T>(opts: {\n  method: string\n  params: any[] | object\n  api: string\n  primary: string\n  /**\n   * Pre-selected healthy untried peers (up to a few, in rank order). The\n   * actual hedge target is drawn uniformly at random at FIRE time: with many\n   * concurrent callers behind one origin IP, always duplicating to the single\n   * next-ranked node would concentrate the whole hedge stream on it and could\n   * trip its per-IP rate limit — spreading over the top candidates keeps the\n   * same budget bound without a single-target hotspot. Marked tried only if\n   * the hedge actually fires.\n   */\n  hedgePool: string[]\n  callerTimeout: number\n  /** Caller passed an explicit timeout — adaptive shortening is disabled. */\n  explicitTimeout: boolean\n  /** The call's wall-clock deadline: a hedge must not START past it (it would\n   *  be a brand-new request the outer loop itself would refuse to start). */\n  deadlineAt: number\n  externalSignal?: AbortSignal\n  /** Lets the outer loop add the hedge node to its tried-set at fire time. */\n  onHedgeFired: (node: string) => void\n  /** Caller-supplied payload validation — see callRPC's `validate` param. */\n  validate?: (result: unknown) => boolean\n}): Promise<T> {\n  const {\n    method,\n    params,\n    api,\n    primary,\n    hedgePool,\n    callerTimeout,\n    explicitTimeout,\n    deadlineAt,\n    externalSignal,\n    onHedgeFired,\n    validate\n  } = opts\n  return new Promise<T>((resolve, reject) => {\n    let done = false\n    let pendingLegs = 0\n    let hedgeFired = false\n    /** The primary settled on its own (success OR failure). A censored latency\n     *  sample is only valid for a primary that was still in flight when the\n     *  hedge won — recording one after the primary already failed would\n     *  fabricate a second sample for a request whose outcome was recorded. */\n    let primarySettled = false\n    let lastError: any\n    let hedgeTimer: ReturnType<typeof setTimeout> | undefined\n    let primaryStart = 0\n    const controllers: AbortController[] = []\n\n    /** Settle exactly once: clear the timer, abort every other in-flight leg\n     *  (their rejections land behind the `done` guard and are dropped). */\n    const finish = (settle: () => void) => {\n      if (done) return\n      done = true\n      if (hedgeTimer !== undefined) {\n        clearTimeout(hedgeTimer)\n        hedgeTimer = undefined\n      }\n      for (const c of controllers) {\n        if (!c.signal.aborted) c.abort()\n      }\n      settle()\n    }\n\n    const startLeg = (node: string, isHedge: boolean) => {\n      pendingLegs++\n      const controller = new AbortController()\n      controllers.push(controller)\n      // Merge our cancellation handle with the caller's signal; jsonRPCCall\n      // merges the result with its own per-attempt timeout signal.\n      const merged = mergeSignals(controller.signal, externalSignal)\n      const legTimeout = adaptiveAttemptTimeout(\n        rpcHealthTracker,\n        node,\n        method,\n        callerTimeout,\n        explicitTimeout\n      )\n      const start = Date.now()\n      if (!isHedge) primaryStart = start\n      jsonRPCCall(node, method, params, legTimeout, false, merged.signal)\n        .then((res) => {\n          merged.cleanup()\n          pendingLegs--\n          if (!isHedge) primarySettled = true\n          if (done) return\n          if (validate && !validate(res)) {\n            // Well-formed envelope, impossible payload: a node fault the\n            // HTTP/JSON-RPC layers cannot see. Same handling as the catch\n            // path — record the fault against this node's API health, never\n            // record a success for a lie, and let the other leg still win.\n            rpcHealthTracker.recordDefectiveResponse(node, api)\n            lastError = new Error(\n              `[hive-tx] response validation failed for ${method} from ${node}`\n            )\n            if (!isHedge && !hedgeFired) {\n              finish(() => reject(lastError))\n              return\n            }\n            if (pendingLegs === 0) {\n              finish(() => reject(lastError))\n            }\n            return\n          }\n          rpcHealthTracker.recordSuccess(node, api, Date.now() - start, method)\n          tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n          if (isHedge) {\n            if (!primarySettled) {\n              // Primary lost the race while still in flight: censored sample\n              // (lower bound of its true latency) so the ranker learns without\n              // marking it as failed. A primary that already failed was fully\n              // recorded by its own catch — nothing more to record.\n              rpcHealthTracker.recordCensoredLatency(primary, Date.now() - primaryStart, method)\n            }\n          } else if (!hedgeFired) {\n            rpcHedgeBudget.refill()\n          }\n          finish(() => resolve(res as T))\n        })\n        .catch((e) => {\n          merged.cleanup()\n          pendingLegs--\n          if (!isHedge) primarySettled = true\n          if (done) return // aborted loser (or late settle) — already resolved\n          if (externalSignal?.aborted) {\n            // Caller cancelled — bail without recording (mirrors sequential path).\n            finish(() => reject(e))\n            return\n          }\n          if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n            // Authoritative rejection: an answer, not a node fault.\n            finish(() => reject(e))\n            return\n          }\n          // Failover-class failure — record exactly as the sequential catch does.\n          recordError(rpcHealthTracker, node, e, api)\n          rpcHealthTracker.recordSlowFailure(node, Date.now() - start, method)\n          lastError = e\n          if (!isHedge && !hedgeFired) {\n            // Primary failed fast, before the hedge delay: plain failover.\n            finish(() => reject(e))\n            return\n          }\n          if (pendingLegs === 0) {\n            finish(() => reject(lastError))\n          }\n          // else: the other leg is still in flight and may still win.\n        })\n    }\n\n    startLeg(primary, false)\n\n    // Delay from the primary's per-method profile (the eligibility gate\n    // ensured it is usable); a raced expiry just means the floor applies. It is\n    // then clamped BELOW the primary's own attempt window: for a heavy API\n    // (EWMA > window/hedgeDelayFactor) the un-clamped delay would land past\n    // the primary's timeout-abort — which clears this timer — so hedging would\n    // silently never fire for exactly the heavy tail it exists to protect.\n    // Firing at ~80% of the window keeps the duplicate meaningful (it starts\n    // while the primary is still allowed to win) for every profile shape.\n    const ewma = rpcHealthTracker.getUsableLatencyMs(primary, method) ?? 0\n    const primaryWindow = adaptiveAttemptTimeout(\n      rpcHealthTracker,\n      primary,\n      method,\n      callerTimeout,\n      explicitTimeout\n    )\n    const delay = Math.min(\n      Math.max(config.resilience.hedgeDelayFloorMs, config.resilience.hedgeDelayFactor * ewma),\n      0.8 * primaryWindow\n    )\n    hedgeTimer = setTimeout(() => {\n      hedgeTimer = undefined\n      if (done || externalSignal?.aborted) return\n      // Never START a duplicate past the call's wall-clock deadline — it would\n      // extend the hold and spend a token on work the outer loop would refuse.\n      if (Date.now() >= deadlineAt) return\n      // Candidates were selected before the delay elapsed — re-check health at\n      // fire time (one may have been rate-limited meanwhile) BEFORE spending a\n      // token, so a stale pool costs nothing. Random draw spreads concurrent\n      // callers' duplicates across the top candidates (see hedgePool doc).\n      const live = hedgePool.filter((n) => rpcHealthTracker.isNodeHealthy(n, api))\n      if (live.length === 0) return\n      const target = live[Math.floor(Math.random() * live.length)]\n      // Budget check at fire time, not arm time: only actual duplicates spend.\n      if (!rpcHedgeBudget.trySpend()) return\n      hedgeFired = true\n      onHedgeFired(target)\n      startLeg(target, true)\n    }, delay)\n  })\n}\n\n// ── Public API: callRPC ─────────────────────────────────────────────────────\n\n/**\n * Makes API calls to Hive blockchain nodes with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, jitter between retries,\n * and HTTP status awareness (429 rate limiting, 503).\n *\n * If the current node fails, it will automatically try the next healthy node.\n * When all nodes have been tried, wraps around to give earlier nodes another chance\n * until the full retry budget (config.retry) is exhausted.\n * RPCErrors (valid blockchain rejections) are never retried.\n *\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Maximum number of retry attempts (default: config.retry). The\n *   wall-clock budget (`config.resilience.totalBudgetFactor` × timeout) may end\n *   the failover walk before the retry count is exhausted.\n * @param validate - Optional payload validation. Some nodes return a valid\n *   JSON-RPC envelope carrying an impossible payload (e.g. account rows with\n *   metadata fields stripped to \"\"), which no transport-level check can catch.\n *   When the callback returns false the response is treated as a node fault:\n *   recorded against that node's per-API health (repeat offenders get an API\n *   cooldown and are deprioritized) and the failover walk continues to the\n *   next node instead of returning the lie. Keep validators conservative —\n *   reject only payloads the caller KNOWS cannot be correct, or a strict\n *   validator turns every node's honest answer into a failover storm.\n * @returns Promise resolving to the API response\n * @throws {RPCError} On blockchain-level errors (bad params, missing authority, etc.)\n * @throws {Error} If all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callRPC } from 'hive-tx'\n *\n * // Get account information\n * const accounts = await callRPC('condenser_api.get_accounts', [['alice']])\n *\n * // Custom timeout and retry settings\n * const data = await callRPC('condenser_api.get_content', ['alice', 'test-post'], 10_000, 5)\n * ```\n */\nexport const callRPC = async <T = any>(\n  method: string,\n  params: any[] | object = [],\n  timeout?: number,\n  retry = config.retry,\n  signal?: AbortSignal,\n  validate?: (result: unknown) => boolean\n): Promise<T> => {\n  if (!Array.isArray(config.nodes)) {\n    throw new Error('config.nodes is not an array')\n  }\n  if (config.nodes.length === 0) {\n    throw new Error('config.nodes is empty')\n  }\n  // An explicit timeout argument is authoritative: adaptive shortening only\n  // applies to callers who left the window to the SDK (timeout === undefined),\n  // so `callRPC(m, p, 10_000)` still means \"give each attempt 10s\" exactly.\n  const explicitTimeout = timeout !== undefined\n  const ceiling = timeout ?? config.timeout\n  const api = apiOf(method)\n  // Wall-clock budget across ALL failover attempts. Without it the worst case\n  // is (retry+1) × timeout ≈ 30s — exactly the render pile-up this feature\n  // exists to prevent — whenever the WHOLE pool is slow (adaptive timeouts\n  // rise with the EWMAs and hedging self-throttles, both by design). The\n  // deadline is checked before each new attempt AND before a hedge fires; an\n  // in-flight attempt still finishes its own window, so the true ceiling is\n  // deadline + one attempt window (up to ~2× the window if a hedge fired just\n  // before the deadline and the attempt then waits out the hedge leg too).\n  // Note this budget also bounds callers who passed an explicit `retry`: the\n  // wall clock, not the attempt count, is the stronger promise here.\n  // Server-side read-through proxy, when configured and the method is on its\n  // allowlist: one call, and on any miss the node loop below runs unchanged.\n  // It runs BEFORE the node deadline is taken, so a slow proxy costs its own\n  // timeout and nothing of the failover budget the nodes get today.\n  // Snapshot: the binding can be cleared by the host while this call awaits.\n  const proxy = serverRpcProxy\n  if (proxy && isNodeRuntime && proxy.methodSet.has(method)) {\n    if (Date.now() < proxyOpenUntil) {\n      rpcProxyStats.skipped++\n    } else {\n      try {\n        const served = await proxyRpcCall<T>(proxy, method, params, ceiling, signal, validate)\n        rpcProxyStats.served++\n        proxyConsecutiveMisses = 0\n        return served\n      } catch (e: unknown) {\n        if (signal?.aborted) throw e\n        rpcProxyStats.fallback++\n        const reason: string = e instanceof ProxyMiss ? e.reason : 'transport'\n        rpcProxyStats.fallbackByReason[reason] = (rpcProxyStats.fallbackByReason[reason] ?? 0) + 1\n        if (reason === 'rpcerror') {\n          // A relayed node error is a healthy proxy answer: it closes the\n          // count like a served call. Crawler-made feed URLs produce these in\n          // runs, and counting them opened the breaker on a working proxy.\n          proxyConsecutiveMisses = 0\n        } else if (++proxyConsecutiveMisses >= proxy.failureThreshold) {\n          proxyOpenUntil = Date.now() + proxy.cooldownMs\n          proxyConsecutiveMisses = 0\n        }\n      }\n    }\n  }\n\n  const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n\n  // Track nodes tried in the current round. When all nodes have been tried,\n  // clear the set to allow a second round (wrap-around) using the retry budget.\n  const triedInRound = new Set<string>()\n  let lastError: any\n\n  for (let attempt = 0; attempt <= retry; attempt++) {\n    if (attempt > 0 && Date.now() >= deadline) {\n      break\n    }\n    // Re-evaluate node order each attempt so health changes are respected.\n    // Pass api so nodes with an API-specific cooldown are deprioritized.\n    const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n    // Pick the healthiest untried node. If all tried, start a new round.\n    let node = orderedNodes.find((n) => !triedInRound.has(n))\n    if (!node) {\n      triedInRound.clear()\n      node = orderedNodes[0]\n    }\n    triedInRound.add(node)\n\n    // Hedge eligibility for THIS attempt: opted in, the primary has a usable\n    // latency profile for this exact method (so the hedge delay is grounded in\n    // data — cold starts stay sequential), and healthy untried peers exist.\n    let hedgePool: string[] = []\n    if (\n      config.resilience.hedge &&\n      rpcHealthTracker.getUsableLatencyMs(node, method) !== undefined\n    ) {\n      hedgePool = orderedNodes\n        .filter((n) => !triedInRound.has(n) && rpcHealthTracker.isNodeHealthy(n, api))\n        .slice(0, 3)\n    }\n\n    if (hedgePool.length > 0) {\n      try {\n        // All health/budget recording happens inside the hedged attempt —\n        // the catch below must NOT record again (unlike the sequential path).\n        return await hedgedRpcAttempt<T>({\n          method,\n          params,\n          api,\n          primary: node,\n          hedgePool,\n          callerTimeout: ceiling,\n          explicitTimeout,\n          deadlineAt: deadline,\n          externalSignal: signal,\n          onHedgeFired: (n) => triedInRound.add(n),\n          validate\n        })\n      } catch (e: any) {\n        if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n          throw e\n        }\n        if (signal?.aborted) {\n          throw e\n        }\n        lastError = e\n        if (attempt < retry) {\n          await jitterDelay()\n        }\n        continue\n      }\n    }\n\n    const callStart = Date.now()\n    try {\n      const res = await jsonRPCCall(\n        node,\n        method,\n        params,\n        adaptiveAttemptTimeout(rpcHealthTracker, node, method, ceiling, explicitTimeout),\n        false,\n        signal\n      )\n      if (validate && !validate(res)) {\n        // Well-formed envelope, impossible payload: a node fault the\n        // HTTP/JSON-RPC layers cannot see. Count it against this node's API\n        // health (never record a success or refill the hedge budget for a\n        // lie) and fail over to the next node.\n        rpcHealthTracker.recordDefectiveResponse(node, api)\n        lastError = new Error(`[hive-tx] response validation failed for ${method} from ${node}`)\n        if (attempt < retry) {\n          await jitterDelay()\n        }\n        continue\n      }\n      rpcHealthTracker.recordSuccess(node, api, Date.now() - callStart, method)\n      // An un-hedged success is what earns hedge budget back (see HedgeBudget).\n      rpcHedgeBudget.refill()\n      tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n      return res as T\n    } catch (e: any) {\n      // RPCErrors: distinguish node-level failures from genuine blockchain rejections.\n      // Node-level errors (e.g. -32602 \"Unable to parse endpoint data\" from a sick\n      // HAF/jussi backend) should failover; real rejections (bad params, missing\n      // authority, etc.) propagate immediately.\n      if (e instanceof RPCError) {\n        if (!isNodeLevelRPCError(e.code, e.message)) {\n          throw e\n        }\n        // Node-level RPC error — record failure and fall through to failover\n      }\n      // External abort — stop retrying immediately\n      if (signal?.aborted) {\n        throw e\n      }\n      recordError(rpcHealthTracker, node, e, api)\n      // A genuinely slow failure (timeout/abort/slow-5xx) is also a latency signal so\n      // a node that 200s-but-too-slow or aborts at the timeout is demoted by the\n      // ranker, not only by the (transient) failure gate. Measured elapsed, never a\n      // constant; recordSlowFailure ignores instant (down-node) failures.\n      rpcHealthTracker.recordSlowFailure(node, Date.now() - callStart, method)\n      lastError = e\n\n      // Add jitter before trying next node\n      if (attempt < retry) {\n        await jitterDelay()\n      }\n    }\n  }\n\n  throw lastError\n}\n\n// ── Public API: callRPC for broadcasts ──────────────────────────────────────\n\n/**\n * Broadcast-safe RPC call. Only retries on pre-connection errors where the\n * request definitively never reached the server (ECONNREFUSED, ENOTFOUND, etc.).\n * On timeouts, HTTP errors, or any ambiguous failure, throws immediately to\n * prevent double-broadcasting transactions.\n *\n * Tries each node once (no wrap-around) since broadcast retries are dangerous.\n *\n * @internal Used by Transaction.broadcast()\n */\nexport const callRPCBroadcast = async <T = any>(\n  method: string,\n  params: any[] | object = [],\n  timeout = config.broadcastTimeout,\n  signal?: AbortSignal\n): Promise<T> => {\n  if (!Array.isArray(config.nodes)) {\n    throw new Error('config.nodes is not an array')\n  }\n  if (config.nodes.length === 0) {\n    throw new Error('config.nodes is empty')\n  }\n  const api = apiOf(method)\n  // Track which nodes we've already tried - broadcasts must never retry the same node\n  const triedNodes = new Set<string>()\n  let lastError: any\n\n  for (let attempt = 0; attempt < config.nodes.length; attempt++) {\n    // Re-evaluate order each attempt so health changes are respected\n    const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n    const node = orderedNodes.find((n) => !triedNodes.has(n))\n    if (!node) break\n    triedNodes.add(node)\n    if (signal?.aborted) {\n      throw new Error('Aborted')\n    }\n    try {\n      const res = await jsonRPCCall(node, method, params, timeout, false, signal)\n      // Deliberately no latency sample for broadcasts: broadcast_transaction_synchronous\n      // blocks for block inclusion (~1.5–3s+) regardless of the node's read speed, so\n      // feeding it into the shared read EWMA would wrongly demote a fast node for reads.\n      // The same nodes are profiled by callRPC read traffic, so a genuinely slow node is\n      // still demoted there.\n      rpcHealthTracker.recordSuccess(node, api)\n      return res as T\n    } catch (e: any) {\n      // RPCErrors are valid blockchain rejections - never retry\n      if (e instanceof RPCError) {\n        throw e\n      }\n      if (signal?.aborted) {\n        throw e\n      }\n      recordError(rpcHealthTracker, node, e, api)\n      lastError = e\n\n      // Broadcast safety: only fail over when the request is safe to re-send.\n      // `broadcastOperations` signs the tx exactly once and `callRPCBroadcast`\n      // reuses that signed payload across nodes, so any case where the next\n      // node would dedupe by trx_id is fine. RPCErrors (real blockchain\n      // rejections) propagate immediately — see isBroadcastSafeToRetry.\n      if (!isBroadcastSafeToRetry(e)) {\n        throw e\n      }\n    }\n  }\n\n  throw lastError\n}\n\n// ── Public API: callREST ────────────────────────────────────────────────────\n\nconst apiMethods: Record<APIMethods, string> = {\n  balance: '/balance-api',\n  hafah: '/hafah-api',\n  hafbe: '/hafbe-api',\n  hivemind: '/hivemind-api',\n  hivesense: '/hivesense-api',\n  reputation: '/reputation-api',\n  'nft-tracker': '/nft-tracker-api',\n  hafsql: '/hafsql',\n  status: '/status-api'\n}\n\n/**\n * Makes REST API calls to Hive blockchain REST endpoints with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, and timeout support.\n * Wraps around the node list to honor the full retry budget.\n *\n * @template Api - The REST API method type (e.g., 'balance', 'hafah', 'hivemind', etc.)\n * @template P - The endpoint path type for the specified API\n *\n * @param api - The REST API method name to call\n * @param endpoint - The specific endpoint path within the API\n * @param params - Optional parameters for path and query string replacement\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Number of retry attempts before throwing an error (default:\n *   config.retry). The wall-clock budget (`config.resilience.totalBudgetFactor`\n *   × timeout) may end the failover walk before the retry count is exhausted.\n *\n * @returns Promise resolving to the API response data with proper typing\n * @throws Error if all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callREST } from 'hive-tx'\n *\n * // Get account balance\n * const balance = await callREST('balance', '/accounts/{account-name}/balances', { \"account-name\": 'alice' })\n *\n * // Custom timeout and retry settings\n * const data = await callREST('status', '/status', undefined, 10_000, 3)\n * ```\n */\nexport async function callREST(\n  api: APIMethods,\n  endpoint: string,\n  params?: Record<string, any>,\n  timeout?: number,\n  retry = config.retry,\n  signal?: AbortSignal\n): Promise<any> {\n  if (!Array.isArray(config.restNodes)) {\n    throw new Error('config.restNodes is not an array')\n  }\n  if (config.restNodes.length === 0) {\n    throw new Error('config.restNodes is empty')\n  }\n  // Same contract as callRPC: an explicit timeout argument is authoritative\n  // (no adaptive shortening), and a wall-clock deadline bounds the total\n  // failover walk when the whole pool is slow.\n  const explicitTimeout = timeout !== undefined\n  const ceiling = timeout ?? config.timeout\n  const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n  // Latency-profile key: api + endpoint TEMPLATE (pre-substitution, so the\n  // cardinality is code-defined) — a cheap endpoint's baseline must not set\n  // the deadline for a heavy one within the same REST api.\n  const restProfileKey = `${api}:${endpoint}`\n  // Per-API node override: an API served by only a subset of nodes (e.g.\n  // hivesense) uses its own capable-host list so the small retry budget and\n  // cold starts aren't wasted on nodes that 404/503 it. Any API without an\n  // override (or with an empty one) falls back to the generic restNodes.\n  const apiNodes =\n    config.restNodesByApi?.[api]?.length\n      ? config.restNodesByApi[api]!\n      : config.restNodes\n  const triedInRound = new Set<string>()\n  let lastError: any\n  // Track whether the error was already recorded by the HTTP status handler\n  let alreadyRecorded = false\n\n  for (let attempt = 0; attempt <= retry; attempt++) {\n    if (attempt > 0 && Date.now() >= deadline) {\n      break\n    }\n    // Re-evaluate node order each attempt so health changes are respected.\n    // Pass api so per-API cooldowns are respected.\n    const orderedNodes = restHealthTracker.getOrderedNodes(apiNodes, api)\n    let node = orderedNodes.find((n) => !triedInRound.has(n))\n    if (!node) {\n      triedInRound.clear()\n      node = orderedNodes[0]\n    }\n    triedInRound.add(node)\n    const baseUrl = node + apiMethods[api]\n    let path = endpoint as string\n    const paramObj = params || ({} as Record<string, any>)\n    const processedPathParams = new Set<string>()\n\n    // Replace path params ONLY\n    Object.entries(paramObj).forEach(([key, value]) => {\n      if (path.includes(`{${key}}`)) {\n        path = path.replace(`{${key}}`, encodeURIComponent(String(value)))\n        processedPathParams.add(key)\n      }\n    })\n    const url = new URL(baseUrl + path)\n    // Add ONLY remaining params as query (if any)\n    Object.entries(paramObj).forEach(([key, value]) => {\n      if (!processedPathParams.has(key)) {\n        if (Array.isArray(value)) {\n          value.forEach((v) => url.searchParams.append(key, String(v)))\n        } else {\n          url.searchParams.set(key, String(value))\n        }\n      }\n    })\n\n    if (signal?.aborted) {\n      throw new Error('Aborted')\n    }\n    alreadyRecorded = false\n    // Adaptive per-attempt timeout (see adaptiveAttemptTimeout): a profiled\n    // REST node is abandoned at factor×EWMA instead of the full fixed window.\n    const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n      adaptiveAttemptTimeout(restHealthTracker, node, restProfileKey, ceiling, explicitTimeout)\n    )\n    const { signal: restSignal, cleanup: cleanupMerge } = mergeSignals(tSignal, signal)\n    const restCleanup = () => { cleanupTimeout(); cleanupMerge() }\n    const restCallStart = Date.now()\n    try {\n      const response = await fetch(url.toString(), {\n        signal: restSignal,\n        headers: serverIdentityHeaders()\n      })\n      if (response.status === 404) {\n        throw new Error('HTTP 404 - Hint: can happen on wrong params')\n      }\n      if (response.status === 429) {\n        // 0 (no usable Retry-After) → undefined → escalating backoff in recordRateLimit.\n        restHealthTracker.recordRateLimit(\n          node,\n          parseRetryAfterMs(response.headers.get('Retry-After')) || undefined\n        )\n        alreadyRecorded = true\n        throw new Error(`HTTP 429 Rate Limited by ${node}`)\n      }\n      if (response.status === 503) {\n        restHealthTracker.recordFailure(node, api)\n        alreadyRecorded = true\n        throw new Error(`HTTP 503 Service Unavailable from ${node}`)\n      }\n      if (!response.ok) {\n        restHealthTracker.recordFailure(node, api)\n        alreadyRecorded = true\n        throw new Error(`HTTP ${response.status} from ${node}`)\n      }\n      restHealthTracker.recordSuccess(node, api, Date.now() - restCallStart, restProfileKey)\n      return response.json() as any\n    } catch (e: any) {\n      // 404 is not a node issue, don't failover\n      if (e?.message?.includes('HTTP 404')) {\n        throw e\n      }\n      // External abort (caller unmounted / React Query cancelled the request) is the\n      // client's decision, NOT a node fault. Mirror callRPC: bail before recording any\n      // failure or slow-latency sample so a healthy REST node (e.g. an own node) is never\n      // demoted by routine navigation/cancellation.\n      if (signal?.aborted) {\n        throw e\n      }\n      // Only record if not already recorded by 429/503 handler above\n      if (!alreadyRecorded) {\n        restHealthTracker.recordFailure(node, api)\n      }\n      // A slow failure (timeout/abort/slow-5xx — e.g. an own node from a far region) is a\n      // latency signal too, so it is demoted by the ranker, not only the failure gate.\n      // Measured elapsed; recordSlowFailure floors at LATENCY_SLOW_FAILURE_MS so a fast\n      // 404/429 or instant down-node failure is NOT mis-read as \"slow\".\n      restHealthTracker.recordSlowFailure(node, Date.now() - restCallStart, restProfileKey)\n      lastError = e\n\n      if (attempt < retry) {\n        await jitterDelay()\n      }\n    } finally {\n      restCleanup()\n    }\n  }\n\n  throw lastError\n}\n\n// ── Public API: callWithQuorum ───────────────────────────────────────────────\n\n/**\n * Make a JSONRPC call with quorum. The method will cross-check the result\n * with `quorum` number of nodes before returning the result.\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param quorum - Default: 2 (recommended)\n */\nexport const callWithQuorum = async <T = any>(\n  method: string,\n  params: any[] | object = [],\n  quorum = 2,\n  signal?: AbortSignal\n): Promise<T> => {\n  if (!Array.isArray(config.nodes)) {\n    throw new Error('config.nodes is not an Array')\n  }\n  if (quorum > config.nodes.length) {\n    throw new Error('quorum > config.nodes.length')\n  }\n  // We call random nodes for better security (Fisher-Yates shuffle)\n  const shuffleNodes = (arr: string[]) => {\n    const a = [...arr]\n    for (let i = a.length - 1; i > 0; i--) {\n      const j = Math.floor(Math.random() * (i + 1));\n      [a[i], a[j]] = [a[j], a[i]]\n    }\n    return a\n  }\n  let allNodes = shuffleNodes(config.nodes)\n  let currentBatchSize = Math.min(quorum, allNodes.length)\n  let allResults: any[] = []\n  while (currentBatchSize > 0 && allNodes.length > 0) {\n    // Take next batch of nodes\n    const batchNodes = allNodes.splice(0, currentBatchSize)\n    const promises: Promise<any>[] = []\n    const batchResults: any[] = []\n    // Launch batch calls in parallel\n    for (let i = 0; i < batchNodes.length; i++) {\n      promises.push(\n        jsonRPCCall(batchNodes[i], method, params, undefined, true, signal)\n          .then((data) => batchResults.push(data))\n          .catch(() => {})\n      )\n    }\n    await Promise.all(promises)\n    allResults.push(...batchResults)\n    // Check for consensus in successful results\n    const consensusResult = findConsensus(allResults, quorum)\n    if (consensusResult) {\n      return consensusResult\n    }\n    // Prepare next batch\n    currentBatchSize = Math.min(quorum, allNodes.length)\n    if (currentBatchSize === 0) {\n      throw new Error('No more nodes available.')\n    }\n  }\n  throw new Error(\"Couldn't reach quorum.\")\n}\n\nfunction findConsensus(results: any[], quorum: number) {\n  const resultGroups = new Map<string, any[]>()\n  for (const result of results) {\n    const key = JSON.stringify(result)\n    if (!resultGroups.has(key)) {\n      resultGroups.set(key, [])\n    }\n    resultGroups.get(key)!.push(result)\n  }\n  const consensusGroup = Array.from(resultGroups.values()).find((group) => group.length >= quorum)\n  return consensusGroup ? consensusGroup[0] : null\n}\n","import bs58 from 'bs58'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PublicKey } from './PublicKey'\nimport { Signature } from './Signature'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport type KeyRole = 'owner' | 'active' | 'posting' | 'memo'\n\nconst NETWORK_ID = new Uint8Array([0x80])\n\n/**\n * ECDSA (secp256k1) private key for signing and encryption operations.\n * Handles key generation, derivation from seeds/passwords, and cryptographic operations.\n *\n * All private keys are stored internally as Uint8Array and can be converted to/from\n * Wallet Import Format (WIF) strings for storage and transmission.\n *\n * @example\n * ```typescript\n * // From WIF string\n * const key = PrivateKey.from('5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw')\n *\n * // Generate random key\n * const randomKey = PrivateKey.randomKey()\n *\n * // From username and password\n * const loginKey = PrivateKey.fromLogin('username', 'password')\n *\n * // Sign a message\n * const signature = key.sign(someHash)\n *\n * // Get public key\n * const pubKey = key.createPublic()\n * ```\n */\nexport class PrivateKey {\n  key: Uint8Array\n\n  constructor(key: Uint8Array) {\n    this.key = key\n    try {\n      secp256k1.getPublicKey(key)\n    } catch (e) {\n      throw new Error('invalid private key')\n    }\n  }\n\n  /**\n   * Creates a PrivateKey instance from a WIF string or raw Uint8Array.\n   * Automatically detects the input type and uses the appropriate method.\n   *\n   * @param value - WIF formatted string or raw 32-byte key as Uint8Array\n   * @returns New PrivateKey instance\n   * @throws Error if the key format is invalid\n   */\n  static from(value: string | Uint8Array): PrivateKey {\n    if (typeof value === 'string') {\n      return PrivateKey.fromString(value)\n    } else {\n      return new PrivateKey(value)\n    }\n  }\n\n  /**\n   * Creates a PrivateKey from a Wallet Import Format (WIF) encoded string.\n   *\n   * @param wif - WIF encoded private key string\n   * @returns New PrivateKey instance\n   * @throws Error if WIF format is invalid or checksum fails\n   */\n  static fromString(wif: string): PrivateKey {\n    return new PrivateKey(decodePrivate(wif).subarray(1))\n  }\n\n  /**\n   * Creates a PrivateKey from a seed string or Uint8Array.\n   * The seed is hashed with SHA256 to produce the private key.\n   *\n   * @param seed - Seed string (converted to bytes) or raw byte array\n   * @returns New PrivateKey instance derived from seed\n   */\n  static fromSeed(seed: string | Uint8Array): PrivateKey {\n    if (typeof seed === 'string') {\n      const isHex = /^[0-9a-fA-F]+$/.test(seed)\n      if (isHex) {\n        seed = hexToBytes(seed)\n      } else {\n        // Convert non-hex string to Uint8Array using UTF-8 encoding\n        // Avoid top-level TextEncoder — not available on all runtimes (e.g. Hermes)\n        const bytes: number[] = []\n        for (let i = 0; i < seed.length; i++) {\n          let c = seed.charCodeAt(i)\n          if (c < 0x80) {\n            bytes.push(c)\n          } else if (c < 0x800) {\n            bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n          } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < seed.length) {\n            const next = seed.charCodeAt(++i)\n            c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n            bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n          } else {\n            bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n          }\n        }\n        seed = new Uint8Array(bytes)\n      }\n    }\n    return new PrivateKey(sha256(seed))\n  }\n\n  /**\n   * Derives a PrivateKey from username, password, and role using Hive's key derivation scheme.\n   * This generates the same keys that the Hive wallet uses for login-based keys.\n   *\n   * @param username - Hive username\n   * @param password - Master password (or seed phrase)\n   * @param role - Key role ('owner', 'active', 'posting', 'memo')\n   * @returns New PrivateKey instance for the specified role\n   */\n  static fromLogin(username: string, password: string, role: KeyRole = 'active'): PrivateKey {\n    const seed = username + role + password\n    return PrivateKey.fromSeed(seed)\n  }\n\n  /**\n   * Signs a 32-byte message hash using ECDSA and returns a recoverable signature.\n   * The signature includes recovery information to allow public key recovery.\n   *\n   * @param message - 32-byte message hash to sign (Uint8Array)\n   * @returns Signature object containing the signature data\n   */\n  sign(message: Uint8Array): Signature {\n    const rv = secp256k1.sign(message, this.key, {\n      extraEntropy: true,\n      format: 'recovered',\n      prehash: false // prehash does sha256 on the message\n    })\n    const recovery = parseInt(bytesToHex(rv.subarray(0, 1)), 16)\n    return Signature.from((recovery + 31).toString(16) + bytesToHex(rv.subarray(1)))\n  }\n\n  /**\n   * Derives the corresponding public key for this private key.\n   *\n   * @param prefix - Optional address prefix (defaults to config.address_prefix)\n   * @returns PublicKey instance derived from this private key\n   */\n  createPublic(prefix?: string): PublicKey {\n    return new PublicKey(secp256k1.getPublicKey(this.key), prefix)\n  }\n\n  /**\n   * Returns the private key as a Wallet Import Format (WIF) encoded string.\n   * This includes network ID and checksum for safe storage/transmission.\n   *\n   * @returns WIF encoded private key string\n   */\n  toString(): string {\n    return encodePrivate(new Uint8Array([...NETWORK_ID, ...this.key]))\n  }\n\n  /**\n   * Returns a masked representation of the private key for debugging/logging.\n   * Shows only the first and last 6 characters to avoid accidental exposure.\n   * Use toString() to get the full key for export/serialization.\n   *\n   * @returns Masked key representation for safe logging\n   */\n  inspect(): string {\n    const key = this.toString()\n    return `PrivateKey: ${key.slice(0, 6)}...${key.slice(-6)}`\n  }\n\n  /**\n   * Computes a shared secret using ECDH key exchange for memo encryption.\n   * The shared secret is used as a key for AES encryption/decryption.\n   *\n   * @param publicKey - Other party's public key\n   * @returns 64-byte shared secret as Uint8Array\n   */\n  getSharedSecret(publicKey: PublicKey): Uint8Array {\n    const s = secp256k1.getSharedSecret(this.key, publicKey.key)\n    // strip the parity byte\n    return sha512(s.subarray(1))\n  }\n\n  /**\n   * Generates a new cryptographically secure random private key.\n   * Uses the secp256k1 key generation algorithm for security.\n   * This method may take up to 250ms due to entropy collection.\n   *\n   * @returns New randomly generated PrivateKey instance\n   */\n  static randomKey(): PrivateKey {\n    return new PrivateKey(secp256k1.keygen().secretKey)\n  }\n}\n\nconst doubleSha256 = (input: Uint8Array) => {\n  const dbl = sha256(sha256(input))\n  return dbl\n}\n\n/** Encode bs58+doubleSha256-checksum private key. */\nconst encodePrivate = (key: Uint8Array) => {\n  // assert.equal(key.readUInt8(0), 0x80, 'private key network id mismatch')\n  const checksum = doubleSha256(key)\n  return bs58.encode(new Uint8Array([...key, ...checksum.slice(0, 4)]))\n}\n\n/** Decode bs58+doubleSha256-checksum encoded private key. */\nconst decodePrivate = (encodedKey: string) => {\n  const buffer = bs58.decode(encodedKey)\n  if (!isUint8ArrayEqual(buffer.slice(0, 1), NETWORK_ID)) {\n    throw new Error('Private key network id mismatch')\n  }\n  const checksum = buffer.slice(-4)\n  const key = buffer.slice(0, -4)\n  const checksumVerify = doubleSha256(key).slice(0, 4)\n  if (!isUint8ArrayEqual(checksum, checksumVerify)) {\n    throw new Error('Private key checksum mismatch')\n  }\n  return key\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array) => {\n  if (a === b) return true\n  if (a.byteLength !== b.byteLength) return false\n  const len = a.byteLength\n  let i = 0\n  while (i < len && a[i] === b[i]) i++\n  return i === len\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { cbc as AESCBC } from '@noble/ciphers/aes.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PrivateKey } from './PrivateKey'\nimport { PublicKey } from './PublicKey'\n\nexport const encrypt = (\n  privateKey: PrivateKey,\n  publicKey: PublicKey,\n  message: Uint8Array,\n  nonce: bigint = uniqueNonce()\n) => crypt(privateKey, publicKey, nonce, message)\n\nexport const decrypt = (\n  privateKey: PrivateKey,\n  publicKey: PublicKey,\n  nonce: bigint,\n  message: Uint8Array,\n  checksum: number\n): Uint8Array => {\n  const d = crypt(privateKey, publicKey, nonce, message, checksum)\n  return d.message\n}\n\n/**\n * @arg message - Encrypted or plain text message (see checksum)\n * @arg checksum - shared secret checksum (null to encrypt, non-null to decrypt)\n */\nconst crypt = (\n  privateKey: PrivateKey,\n  publicKey: PublicKey,\n  nonce: bigint,\n  message: Uint8Array,\n  checksum?: number\n): { nonce: bigint; message: Uint8Array; checksum: number } => {\n  const nonceL = nonce\n  const S = privateKey.getSharedSecret(publicKey)\n  let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n  ebuf.writeUint64(nonceL)\n  ebuf.append(S)\n  ebuf.flip()\n\n  const encryptionKey = sha512(new Uint8Array(ebuf.toBuffer()))\n  const iv = encryptionKey.subarray(32, 48)\n  const tag = encryptionKey.subarray(0, 32)\n\n  // check if first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.\n  const check = sha256(encryptionKey).subarray(0, 4)\n  const cbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n  cbuf.append(check)\n  cbuf.flip()\n  const check32 = cbuf.readUint32()\n  if (checksum !== undefined) {\n    if (check32 !== checksum) {\n      throw new Error('Invalid key')\n    }\n    message = cryptoJsDecrypt(message, tag, iv)\n  } else {\n    message = cryptoJsEncrypt(message, tag, iv)\n  }\n  return { nonce: nonceL, message, checksum: check32 }\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} ciphertext - binary format\n * @return {Uint8Array} the decrypted message\n */\nconst cryptoJsDecrypt = (message: Uint8Array, tag: Uint8Array, iv: Uint8Array): Uint8Array => {\n  let messageBuffer = message\n  const decipher = AESCBC(tag, iv)\n  messageBuffer = decipher.decrypt(messageBuffer)\n  return messageBuffer\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} plaintext - binary format\n * @return {Uint8Array} binary\n */\nexport const cryptoJsEncrypt = (\n  message: Uint8Array,\n  tag: Uint8Array,\n  iv: Uint8Array\n): Uint8Array => {\n  let messageBuffer = message\n  const cipher = AESCBC(tag, iv)\n  messageBuffer = cipher.encrypt(messageBuffer)\n  return messageBuffer\n}\n\nlet uniqueNonceEntropy: number | null = null\n\nconst uniqueNonce = (): bigint => {\n  if (uniqueNonceEntropy === null) {\n    const randomPrivateKey = secp256k1.utils.randomSecretKey()\n    uniqueNonceEntropy = (randomPrivateKey[0] << 8) | randomPrivateKey[1]\n  }\n  let long = BigInt(Date.now())\n  const entropy = ++uniqueNonceEntropy % 0x10000\n  long = (long << BigInt(16)) | BigInt(entropy)\n  return long\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\n\nconst PublicKeyDeserializer = (buf: ByteBuffer) => {\n  const c = fixedBuf(buf, 33)\n  return new PublicKey(c)\n}\n\nconst UInt64Deserializer = (b: ByteBuffer) => {\n  return b.readUint64()\n}\n\nconst UInt32Deserializer = (b: ByteBuffer) => {\n  return b.readUint32()\n}\n\nconst BinaryDeserializer = (b: ByteBuffer) => {\n  const len = <number>b.readVarint32()\n  const bCopy = b.copy(b.offset, b.offset + len)\n  b.skip(len)\n  return new Uint8Array(bCopy.toBuffer())\n}\n\nconst BufferDeserializer = (keyDeserializers: any) => (buf: Uint8Array) => {\n  const obj: any = {}\n  const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n  buffer.append(buf)\n  buffer.flip()\n  for (const [key, deserializer] of keyDeserializers) {\n    try {\n      obj[key] = deserializer(buffer)\n    } catch (error: any) {\n      error.message = `${key}: ${error.message}`\n      throw error\n    }\n  }\n  return obj\n}\n\nfunction fixedBuf(b: ByteBuffer, len: number) {\n  if (!b) {\n    throw Error('No buffer found on first parameter')\n  } else {\n    const bCopy = b.copy(b.offset, b.offset + len)\n    b.skip(len)\n    return new Uint8Array(bCopy.toBuffer())\n  }\n}\n\nconst EncryptedMemoDeserializer = BufferDeserializer([\n  ['from', PublicKeyDeserializer],\n  ['to', PublicKeyDeserializer],\n  ['nonce', UInt64Deserializer],\n  ['check', UInt32Deserializer],\n  ['encrypted', BinaryDeserializer]\n])\n\nexport const Deserializer = {\n  Memo: EncryptedMemoDeserializer\n}\n","import bs58 from 'bs58'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Serializer } from './serializer'\nimport { PrivateKey } from './PrivateKey'\nimport * as Aes from './aes'\nimport { PublicKey } from './PublicKey'\nimport { Deserializer } from './deserializer'\n\nexport type Memo = {\n  /**\n   * Encrypts a memo for secure private messaging\n   */\n  encode(\n    privateKey: string | PrivateKey,\n    publicKey: string | PublicKey,\n    memo: string,\n    testNonce?: any\n  ): string\n\n  /**\n   * Decrypts a memo message\n   */\n  decode(privateKey: string | PrivateKey, memo: string): string\n}\n\n/**\n * Encodes a memo using AES encryption for secure private messaging on Hive.\n * Messages must start with '#' to be encrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Sender's private memo key (string WIF format or PrivateKey instance)\n * @param publicKey - Recipient's public memo key (string or PublicKey instance)\n * @param memo - Message to encrypt (must start with '#' for encryption)\n * @param testNonce - Optional nonce for testing (advanced usage)\n * @returns Encrypted memo string prefixed with '#'\n * @throws Error if encryption is not supported in current environment\n */\nconst encode = (\n  privateKey: string | PrivateKey,\n  publicKey: string | PublicKey,\n  memo: string,\n  testNonce?: any\n): string => {\n  if (!memo.startsWith('#')) {\n    return memo\n  }\n  memo = memo.substring(1)\n  checkEncryption()\n  privateKey = toPrivateObj(privateKey)\n  publicKey = toPublicObj(publicKey)\n  const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n  mbuf.writeVString(memo)\n  const memoBuffer = new Uint8Array(mbuf.copy(0, mbuf.offset).toBuffer())\n  const { nonce, message, checksum } = Aes.encrypt(privateKey, publicKey, memoBuffer, testNonce)\n  const mbuf2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n  Serializer.Memo(mbuf2, {\n    check: checksum,\n    encrypted: message,\n    from: privateKey.createPublic(),\n    nonce,\n    to: publicKey\n  })\n  mbuf2.flip()\n  const data = new Uint8Array(mbuf2.toBuffer())\n  return '#' + bs58.encode(data)\n}\n\n/**\n * Decrypts an encrypted memo using AES decryption.\n * Messages must start with '#' to be decrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Recipient's private memo key (string WIF format or PrivateKey instance)\n * @param memo - Encrypted memo string (must start with '#' for decryption)\n * @returns Decrypted memo content with '#' prefix\n * @throws Error if decryption fails or encryption not supported in current environment\n */\nconst decode = (privateKey: string | PrivateKey, memo: string): string => {\n  if (!memo.startsWith('#')) {\n    return memo\n  }\n  memo = memo.substring(1)\n  checkEncryption()\n  privateKey = toPrivateObj(privateKey)\n  // memo = bs58.decode(memo)\n  let memoBuffer = Deserializer.Memo(bs58.decode(memo))\n  const { from, to, nonce, check, encrypted } = memoBuffer\n  const pubkey = privateKey.createPublic().toString()\n  const otherpub =\n    pubkey === new PublicKey(from.key).toString() ? new PublicKey(to.key) : new PublicKey(from.key)\n  memoBuffer = Aes.decrypt(privateKey, otherpub, nonce, encrypted, check)\n  const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n  mbuf.append(memoBuffer)\n  mbuf.flip()\n  return '#' + mbuf.readVString()\n}\n\nlet encodeTest: boolean | undefined\nconst checkEncryption = () => {\n  if (encodeTest === undefined) {\n    let plaintext\n    encodeTest = true // prevent infinate looping\n    try {\n      const wif = '5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw'\n      const pubkey = 'STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA'\n      const cyphertext = encode(wif, pubkey, '#memo爱')\n      plaintext = decode(wif, cyphertext)\n    } finally {\n      encodeTest = plaintext === '#memo爱'\n    }\n  }\n  if (encodeTest === false) {\n    throw new Error('This environment does not support encryption.')\n  }\n}\n\nconst toPrivateObj = (o: string | PrivateKey): PrivateKey => {\n  if (typeof o === 'string') {\n    return PrivateKey.fromString(o)\n  } else {\n    return o\n  }\n}\nconst toPublicObj = (o: string | PublicKey): PublicKey => {\n  if (typeof o === 'string') {\n    return PublicKey.fromString(o)\n  } else {\n    return o\n  }\n}\n\n/**\n * Memo utilities for encrypting and decrypting private messages between Hive users.\n * Uses AES encryption with ECDH key exchange for secure communication.\n *\n * Messages must start with '#' to be encrypted/decrypted.\n * Plain text messages (without '#') are returned unchanged.\n *\n * @example\n * ```typescript\n * import { Memo, PrivateKey, PublicKey } from 'hive-tx'\n *\n * // Encrypt a message\n * const encrypted = Memo.encode(senderPrivateKey, recipientPublicKey, '#Hello World')\n *\n * // Decrypt a message\n * const decrypted = Memo.decode(recipientPrivateKey, encrypted)\n * console.log(decrypted) // '#Hello World'\n * ```\n */\nexport const Memo = {\n  decode,\n  encode\n}\n","import { Serializer } from './serializer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\nexport interface WitnessProps {\n  account_creation_fee?: string\n  account_subsidy_budget?: number\n  account_subsidy_decay?: number\n  key: PublicKey | string\n  maximum_block_size?: number\n  new_signing_key?: PublicKey | string | null\n  hbd_exchange_rate?: { base: string; quote: string }\n  hbd_interest_rate?: number\n  url?: string\n}\n\n/** Return null for a valid username */\nexport const validateUsername = (username: string): null | string => {\n  let suffix = 'Account name should '\n  if (!username) {\n    return suffix + 'not be empty.'\n  }\n  const length = username.length\n  if (length < 3) {\n    return suffix + 'be longer.'\n  }\n  if (length > 16) {\n    return suffix + 'be shorter.'\n  }\n  if (/\\./.test(username)) {\n    suffix = 'Each account segment should '\n  }\n  const ref = username.split('.')\n  const len = ref.length\n  for (let i = 0; i < len; i++) {\n    const label = ref[i]\n    if (!/^[a-z]/.test(label)) {\n      return suffix + 'start with a lowercase letter.'\n    }\n    if (!/^[a-z0-9-]*$/.test(label)) {\n      return suffix + 'have only lowercase letters, digits, or dashes.'\n    }\n    if (!/[a-z0-9]$/.test(label)) {\n      return suffix + 'end with a lowercase letter or digit.'\n    }\n    if (label.length < 3) {\n      return suffix + 'be longer.'\n    }\n  }\n  return null\n}\n\nexport const operations = {\n  vote: 0,\n  comment: 1,\n  transfer: 2,\n  transfer_to_vesting: 3,\n  withdraw_vesting: 4,\n  limit_order_create: 5,\n  limit_order_cancel: 6,\n  feed_publish: 7,\n  convert: 8,\n  account_create: 9,\n  account_update: 10,\n  witness_update: 11,\n  account_witness_vote: 12,\n  account_witness_proxy: 13,\n  pow: 14,\n  custom: 15,\n  report_over_production: 16,\n  delete_comment: 17,\n  custom_json: 18,\n  comment_options: 19,\n  set_withdraw_vesting_route: 20,\n  limit_order_create2: 21,\n  claim_account: 22,\n  create_claimed_account: 23,\n  request_account_recovery: 24,\n  recover_account: 25,\n  change_recovery_account: 26,\n  escrow_transfer: 27,\n  escrow_dispute: 28,\n  escrow_release: 29,\n  pow2: 30,\n  escrow_approve: 31,\n  transfer_to_savings: 32,\n  transfer_from_savings: 33,\n  cancel_transfer_from_savings: 34,\n  custom_binary: 35,\n  decline_voting_rights: 36,\n  reset_account: 37,\n  set_reset_account: 38,\n  claim_reward_balance: 39,\n  delegate_vesting_shares: 40,\n  account_create_with_delegation: 41,\n  witness_set_properties: 42,\n  account_update2: 43,\n  create_proposal: 44,\n  update_proposal_votes: 45,\n  remove_proposal: 46,\n  update_proposal: 47,\n  collateralized_convert: 48,\n  recurrent_transfer: 49,\n  // virtual ops\n  fill_convert_request: 50,\n  author_reward: 51,\n  curation_reward: 52,\n  comment_reward: 53,\n  liquidity_reward: 54,\n  interest: 55,\n  fill_vesting_withdraw: 56,\n  fill_order: 57,\n  shutdown_witness: 58,\n  fill_transfer_from_savings: 59,\n  hardfork: 60,\n  comment_payout_update: 61,\n  return_vesting_delegation: 62,\n  comment_benefactor_reward: 63,\n  producer_reward: 64,\n  clear_null_account_balance: 65,\n  proposal_pay: 66,\n  sps_fund: 67,\n  hardfork_hive: 68,\n  hardfork_hive_restore: 69,\n  delayed_voting: 70,\n  consolidate_treasury_balance: 71,\n  effective_comment_vote: 72,\n  ineffective_delete_comment: 73,\n  sps_convert: 74,\n  expired_account_notification: 75,\n  changed_recovery_account: 76,\n  transfer_to_vesting_completed: 77,\n  pow_reward: 78,\n  vesting_shares_split: 79,\n  account_created: 80,\n  fill_collateralized_convert_request: 81,\n  system_warning: 82,\n  fill_recurrent_transfer: 83,\n  failed_recurrent_transfer: 84,\n  limit_order_cancelled: 85,\n  producer_missed: 86,\n  proposal_fee: 87,\n  collateralized_convert_immediate_conversion: 88,\n  escrow_approved: 89,\n  escrow_rejected: 90,\n  proxy_cleared: 91,\n  declined_voting_rights: 92\n}\n\n/**\n * Make bitmask filter to be used with get_account_history call\n */\nexport const makeBitMaskFilter = (allowedOperations: number[]): [string | null, string | null] => {\n  return allowedOperations\n    .reduce(reduceFunction, [BigInt(0), BigInt(0)])\n    .map((value: bigint) => (value !== BigInt(0) ? value.toString() : null)) as [string | null, string | null]\n}\nconst reduceFunction = (\n  [low, high]: [bigint, bigint],\n  allowedOperation: number\n): [bigint, bigint] => {\n  if (allowedOperation < 64) {\n    return [low | (BigInt(1) << BigInt(allowedOperation)), high]\n  } else {\n    return [low, high | (BigInt(1) << BigInt(allowedOperation - 64))]\n  }\n}\n\nexport const buildWitnessSetProperties = (\n  owner: string,\n  props: WitnessProps\n): ['witness_set_properties', { extensions: never[]; owner: string; props: any }] => {\n  const data = {\n    extensions: [],\n    owner,\n    props: <any>[]\n  }\n  for (const key of Object.keys(props)) {\n    if ((props as any)[key] === undefined) continue\n    let type\n    switch (key) {\n      case 'key':\n      case 'new_signing_key':\n        type = Serializer.PublicKey\n        break\n      case 'account_subsidy_budget':\n      case 'account_subsidy_decay':\n      case 'maximum_block_size':\n        type = Serializer.UInt32\n        break\n      case 'hbd_interest_rate':\n        type = Serializer.UInt16\n        break\n      case 'url':\n        type = Serializer.String\n        break\n      case 'hbd_exchange_rate':\n        type = Serializer.Price\n        break\n      case 'account_creation_fee':\n        type = Serializer.Asset\n        break\n      default:\n        throw new Error(`Unknown witness prop: ${key}`)\n    }\n    data.props.push([key, serialize(type, props[key])])\n  }\n  data.props.sort((a: any, b: any) => a[0].localeCompare(b[0]))\n  return ['witness_set_properties', data]\n}\n\nconst serialize = (serializer: any, data: any) => {\n  const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n  serializer(buffer, data)\n  buffer.flip()\n  // `props` values must be hex\n  return bytesToHex(new Uint8Array(buffer.toBuffer()))\n}\n"]}