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,GAAuB,UAAAC,GAAU,qBAAAC,GAAqB,uBAAAC,GAAuB,YAAAC,GAAY,4BAAAC,GAA4B,kBAAAC,GAAkB,sBAAAC,GAAsB,+BAAAC,GAA+B,MAAAC,GAAM,wBAAAC,GAAwB,uBAAAC,GAAuB,eAAAC,EAAe,EAAInE,GAAYoE,GAAa,YAAWpE","names":["ReplicaRejectCode","exports","AgentError","_AgentError","message","exports","concat","buffers","result","acc","curr","index","b","exports","toHex","buffer","x","hexRe","fromHex","hex","compare","b1","b2","u1","u2","bufEquals","uint8ToBuf","arr","bufFromBufLike","bufLike","candid_1","borc_1","__importDefault","sha256_1","buffer_1","hash","data","exports","hashValue","value","hashString","vals","hashOfMap","encoded","requestIdOf","request","map","sorted","key","hashedKey","hashedValue","k1","k2","concatenated","x","principal_1","request_id_1","buffer_1","domainSeparator","SignIdentity","request","body","fields","__rest","requestId","exports","AnonymousIdentity","createIdentityDescriptor","identity","borc_1","__importDefault","cbor","__importStar","simple_cbor_1","buffer_1","PrincipalEncoder","value","v","BufferEncoder","BigIntEncoder","serializer","CborTag","exports","encode","decodePositiveBigInt","buf","len","res","i","Uint8ArrayDecoder","raw","start","end","decode","input","buffer","decoder","val","e","randomNumber","array","exports","random_1","SubmitRequestType","exports","makeNonce","buffer","view","rand1","rand2","rand3","rand4","candid_1","cbor","__importStar","types_1","NANOSECONDS_PER_MILLISECONDS","REPLICA_PERMITTED_DRIFT_MILLISECONDS","Expiry","deltaInMSec","rounded_down_nanos","exports","makeNonceTransform","nonceFn","request","headers","makeExpiryTransform","delayInMilliseconds","httpHeadersTransform","headerFields","value","key","errors_1","AgentHTTPResponseError","message","response","exports","bls12_381_1","buffer_1","blsVerify","pk","sig","msg","primaryKey","signature","message","exports","candid_1","decodeLeb128","buf","exports","decodeTime","decoded","cbor","__importStar","errors_1","request_id_1","buffer_1","principal_1","bls","leb_1","CertificateVerificationError","reason","exports","NodeType","hashTreeToString","tree","indent","s","x","labelToString","label","decoder","left","right","sub","isBufferGreaterThan","a","b","a8","b8","Certificate","_Certificate","certificate","_rootKey","_canisterId","_blsVerify","_maxAgeInMinutes","options","cert","blsVerify","path","lookup_path","rootHash","reconstruct","derKey","sig","key","extractDER","msg","domain_sep","sigVer","lookupTime","lookupResultToBuffer","FIVE_MINUTES_IN_MSEC","MAX_AGE_IN_MSEC","now","earliestCertificateTime","fiveMinutesFromNow","certTime","d","check_canister_ranges","publicKeyLookup","DER_PREFIX","KEY_LENGTH","buf","expectedLength","prefix","result","LookupStatus","t","len","str","LabelLookupStatus","lookupResult","find_label","flatten_forks","leftLookupResult","rightLookupResult","params","canisterId","subnetId","rangeLookup","v","r","principal_1","errors_1","certificate_1","buffer_1","Cbor","__importStar","leb_1","CustomPath","key","path","decodeStrategy","exports","request","options","agent","paths","canisterId","uniquePaths","encodedPaths","status","promises","index","response","cert","lookup","data","decodeControllers","decodeHex","decodeCbor","decodeUtf8","error","_a","fetchNodeKeys","certificate","root_key","tree","delegation","subnetId","subnetLookupResult","nodeForks","nodeKeys","fork","node_id","publicKeyLookupResult","derEncodedPublicKey","encodePath","encoder","encode","arg","canisterBuffer","metaPath","encoded","buf","ExpirableMap","options","_ExpirableMap_inner","_ExpirableMap_expirationTime","_a","_b","source","expirationTime","currentTime","__classPrivateFieldSet","key","value","entry","__classPrivateFieldGet","iterator","callbackfn","thisArg","exports","buffer_1","encodeLenBytes","len","exports","encodeLen","buf","offset","decodeLenBytes","decodeLen","lenBytes","wrapDER","payload","oid","bitStringHeaderLength","unwrapDER","derEncoded","expect","n","msg","payloadLen","result","der_1","Ed25519PublicKey","_Ed25519PublicKey","key","_Ed25519PublicKey_rawKey","_Ed25519PublicKey_derKey","__classPrivateFieldSet","rawKey","derKey","publicKey","unwrapped","__classPrivateFieldGet","exports","Observable","func","observer","data","rest","exports","ObservableLog","message","error","RANDOMIZATION_FACTOR","MULTIPLIER","INITIAL_INTERVAL_MSEC","MAX_INTERVAL_MSEC","MAX_ELAPSED_TIME_MSEC","MAX_ITERATIONS","ExponentialBackoff","_ExponentialBackoff","options","_ExponentialBackoff_currentInterval","_ExponentialBackoff_randomizationFactor","_ExponentialBackoff_multiplier","_ExponentialBackoff_maxInterval","_ExponentialBackoff_startTime","_ExponentialBackoff_maxElapsedTime","_ExponentialBackoff_maxIterations","_ExponentialBackoff_date","_ExponentialBackoff_count","initialInterval","randomizationFactor","multiplier","maxInterval","maxElapsedTime","maxIterations","date","__classPrivateFieldSet","__classPrivateFieldGet","delta","min","max","_a","exports","exponentialBackoff","backoff","next","principal_1","errors_1","auth_1","cbor","__importStar","request_id_1","buffer_1","transforms_1","types_1","errors_2","canisterStatus_1","certificate_1","ed25519_1","expirableMap_1","public_key_1","leb_1","observable_1","backoff_1","__exportStar","exports","types_2","RequestStatusResponseStatus","DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS","IC0_DOMAIN","IC0_SUB_DOMAIN","ICP0_DOMAIN","ICP0_SUB_DOMAIN","ICP_API_DOMAIN","ICP_API_SUB_DOMAIN","HttpDefaultFetchError","message","IdentityInvalidError","getDefaultFetch","defaultFetch","HttpAgent","_HttpAgent","options","_HttpAgent_retryTimes","_HttpAgent_backoffStrategy","_HttpAgent_waterMark","_HttpAgent_queryPipeline","_HttpAgent_updatePipeline","_HttpAgent_subnetKeys","_HttpAgent_verifyQuerySignatures","_HttpAgent_verifyQueryResponse","queryResponse","subnetStatus","__classPrivateFieldGet","status","signatures","requestId","domainSeparator","sig","timestamp","identity","nodeId","hash","reply","reject_code","reject_message","error_code","separatorWithHash","pubKey","rawKey","location","knownHosts","remoteHosts","hostname","knownHost","host","__classPrivateFieldSet","_a","defaultBackoffFactory","name","password","log","type","fn","priority","x","canisterId","id","canister","ecid","sender","ingress_expiry","submit","transformedRequest","body","backoff","request","_HttpAgent_instances","_HttpAgent_requestAndRetry","response","responseBuffer","responseBody","fields","makeQuery","args","_HttpAgent_requestAndRetryQuery","getSubnetStatus","query","updatedSubnetStatus","decodedResponse","parsedTime","tree","decoded","timeLookup","date","CanisterStatus","callTime","replicaTime","error","headers","effectiveCanisterId","subnetResponse","p","r","r2","tries","delay","resolve","fetchResponse","_b","timeStampInMs","responseText","errorMessage","principal_1","ProxyMessageKind","exports","ProxyStubAgent","_frontend","_agent","msg","response","ProxyAgent","_backend","id","maybePromise","resolve","reject","principal","canisterId","fields","rootKey","__exportStar","exports","getDefaultAgent","agent","buffer_1","FIVE_MINUTES_IN_MSEC","defaultStrategy","chain","conditionalDelay","once","backoff","timeout","exports","first","condition","timeInMsec","canisterId","requestId","status","resolve","maxAttempts","count","attempts","throttle","throttleInMsec","end","startingThrottleInMsec","backoffFactor","currentThrottling","strategies","a","agent_1","certificate_1","buffer_1","exports","__importStar","strategy_1","pollForResponse","agent","canisterId","requestId","strategy","request","blsVerify","path","currentRequest","_a","state","cert","maybeBuf","status","rejectCode","rejectMessage","exports","IDL","bitcoin_network","bitcoin_address","bitcoin_get_balance_args","satoshi","bitcoin_get_balance_result","bitcoin_get_current_fee_percentiles_args","millisatoshi_per_byte","bitcoin_get_current_fee_percentiles_result","bitcoin_get_utxos_args","block_hash","outpoint","utxo","bitcoin_get_utxos_result","bitcoin_send_transaction_args","canister_id","canister_info_args","change_origin","change_details","change","canister_info_result","canister_status_args","log_visibility","definite_canister_settings","canister_status_result","clear_chunk_store_args","canister_settings","create_canister_args","create_canister_result","delete_canister_args","deposit_cycles_args","ecdsa_curve","ecdsa_public_key_args","ecdsa_public_key_result","fetch_canister_logs_args","canister_log_record","fetch_canister_logs_result","http_header","http_request_result","http_request_args","canister_install_mode","chunk_hash","install_chunked_code_args","wasm_module","install_code_args","node_metrics_history_args","node_metrics","node_metrics_history_result","provisional_create_canister_with_cycles_args","provisional_create_canister_with_cycles_result","provisional_top_up_canister_args","raw_rand_result","sign_with_ecdsa_args","sign_with_ecdsa_result","start_canister_args","stop_canister_args","stored_chunks_args","stored_chunks_result","uninstall_code_args","update_settings_args","upload_chunk_args","upload_chunk_result","buffer_1","agent_1","errors_1","candid_1","polling_1","principal_1","buffer_2","management_idl_1","__importDefault","ActorCallError","canisterId","methodName","type","props","n","exports","QueryCallRejectedError","result","_a","UpdateCallRejectedError","requestId","response","metadataSymbol","Actor","_Actor","metadata","actor","fields","config","mode","arg","wasmModule","getManagementCanister","settings","settingsToCanisterSettings","interfaceFactory","options","service","CanisterActor","DEFAULT_ACTOR_CONFIG","func","_createActorMethod","configuration","decodeReturnValue","types","msg","returnValues","blsVerify","caller","args","_b","agent","cid","effectiveCanisterId","pollingStrategyFactory","ecid","pollStrategy","responseBytes","shouldIncludeHttpDetails","handler","transform","_methodName","first","exports","IDL","actor_1","asset_idl_1","__importDefault","createAssetCanisterActor","config","exports","principal_1","CanisterStatus","__importStar","http_1","actor_1","fetchCandid","canisterId","agent","candid","tmpHackInterface","IDL","exports","__exportStar","exports","__importStar","cjsm","__esModule","Cbor","CanisterStatus","polling","randomNumber","bufFromBufLike","uint8ToBuf","bufEquals","compare","fromHex","toHex","concat","blsVerify","verify","hashOfMap","requestIdOf","hashValue","hash","Ed25519PublicKey","fetchCandid","unwrapDER","wrapDER","SECP256K1_OID","ED25519_OID","DER_COSE_OID","decodeLen","decodeLenBytes","encodeLen","encodeLenBytes","check_canister_ranges","find_label","flatten_forks","lookup_path","LookupStatus","reconstruct","lookupResultToBuffer","Certificate","hashTreeToString","NodeType","CertificateVerificationError","createAssetCanisterActor","createIdentityDescriptor","AnonymousIdentity","SignIdentity","makeNonce","SubmitRequestType","httpHeadersTransform","makeExpiryTransform","makeNonceTransform","Expiry","getDefaultAgent","ProxyAgent","ProxyStubAgent","ProxyMessageKind","AgentHTTPResponseError","HttpAgent","IdentityInvalidError","MANAGEMENT_CANISTER_ID","IC_ROOT_KEY","RequestStatusResponseStatus","ReplicaRejectCode","getManagementCanister","ACTOR_METHOD_WITH_HTTP_DETAILS","Actor","UpdateCallRejectedError","QueryCallRejectedError","ActorCallError","endpoint_default"],"sources":["../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/agent/api.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/errors.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/utils/buffer.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/request_id.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/auth.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/cbor.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/utils/random.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/agent/http/types.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/agent/http/transforms.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/agent/http/errors.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/utils/bls.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/utils/leb.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/certificate.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/canisterStatus/index.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/utils/expirableMap.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/der.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/public_key.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/observable.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/polling/backoff.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/agent/http/index.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/agent/proxy.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/agent/index.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/polling/strategy.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/polling/index.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/canisters/management_idl.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/actor.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/canisters/asset_idl.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/canisters/asset.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/fetch_candid.ts","../esm/npm/@dfinity/agent@1.4.0/node_modules/@dfinity/agent/src/index.ts","endpoint.js"],"sourcesContent":["import { Principal } from '@dfinity/principal';\nimport { RequestId } from '../request_id';\nimport { JsonObject } from '@dfinity/candid';\nimport { Identity } from '../auth';\nimport { HttpHeaderField } from './http/types';\n\n/**\n * Codes used by the replica for rejecting a message.\n * See {@link https://sdk.dfinity.org/docs/interface-spec/#reject-codes | the interface spec}.\n */\nexport enum ReplicaRejectCode {\n  SysFatal = 1,\n  SysTransient = 2,\n  DestinationInvalid = 3,\n  CanisterReject = 4,\n  CanisterError = 5,\n}\n\n/**\n * Options when doing a {@link Agent.readState} call.\n */\nexport interface ReadStateOptions {\n  /**\n   * A list of paths to read the state of.\n   */\n  paths: ArrayBuffer[][];\n}\n\n/**\n *\n */\nexport type QueryResponse = QueryResponseReplied | QueryResponseRejected;\n\nexport const enum QueryResponseStatus {\n  Replied = 'replied',\n  Rejected = 'rejected',\n}\n\nexport interface HttpDetailsResponse {\n  ok: boolean;\n  status: number;\n  statusText: string;\n  headers: HttpHeaderField[];\n}\n\nexport type ApiQueryResponse = QueryResponse \u0026 {\n  httpDetails: HttpDetailsResponse;\n  requestId: RequestId;\n};\n\nexport interface QueryResponseBase {\n  status: QueryResponseStatus;\n}\n\nexport type NodeSignature = {\n  // the batch time\n  timestamp: bigint;\n  // the signature\n  signature: Uint8Array;\n  // the ID of the node that created the signature\n  identity: Uint8Array;\n};\n\nexport interface QueryResponseReplied extends QueryResponseBase {\n  status: QueryResponseStatus.Replied;\n  reply: { arg: ArrayBuffer };\n  signatures?: NodeSignature[];\n}\n\nexport interface QueryResponseRejected extends QueryResponseBase {\n  status: QueryResponseStatus.Rejected;\n  reject_code: ReplicaRejectCode;\n  reject_message: string;\n  error_code: string;\n  signatures?: NodeSignature[];\n}\n\n/**\n * Options when doing a {@link Agent.query} call.\n */\nexport interface QueryFields {\n  /**\n   * The method name to call.\n   */\n  methodName: string;\n\n  /**\n   * A binary encoded argument. This is already encoded and will be sent as is.\n   */\n  arg: ArrayBuffer;\n\n  /**\n   * Overrides canister id for path to fetch. This is used for management canister calls.\n   */\n  effectiveCanisterId?: Principal;\n}\n\n/**\n * Options when doing a {@link Agent.call} call.\n */\nexport interface CallOptions {\n  /**\n   * The method name to call.\n   */\n  methodName: string;\n\n  /**\n   * A binary encoded argument. This is already encoded and will be sent as is.\n   */\n  arg: ArrayBuffer;\n\n  /**\n   * An effective canister ID, used for routing. This should only be mentioned if\n   * it's different from the canister ID.\n   */\n  effectiveCanisterId: Principal | string;\n}\n\nexport interface ReadStateResponse {\n  certificate: ArrayBuffer;\n}\n\nexport interface SubmitResponse {\n  requestId: RequestId;\n  response: {\n    ok: boolean;\n    status: number;\n    statusText: string;\n    body: {\n      error_code?: string;\n      reject_code: number;\n      reject_message: string;\n    } | null;\n    headers: HttpHeaderField[];\n  };\n}\n\n/**\n * An Agent able to make calls and queries to a Replica.\n */\nexport interface Agent {\n  readonly rootKey: ArrayBuffer | null;\n  /**\n   * Returns the principal ID associated with this agent (by default). It only shows\n   * the principal of the default identity in the agent, which is the principal used\n   * when calls don't specify it.\n   */\n  getPrincipal(): Promise\u003cPrincipal\u003e;\n\n  /**\n   * Create the request for the read state call.\n   * `readState` uses this internally.\n   * Useful to avoid signing the same request multiple times.\n   */\n  createReadStateRequest?(\n    options: ReadStateOptions,\n    identity?: Identity,\n    // eslint-disable-next-line  @typescript-eslint/no-explicit-any\n  ): Promise\u003cany\u003e;\n\n  /**\n   * Send a read state query to the replica. This includes a list of paths to return,\n   * and will return a Certificate. This will only reject on communication errors,\n   * but the certificate might contain less information than requested.\n   * @param effectiveCanisterId A Canister ID related to this call.\n   * @param options The options for this call.\n   * @param identity Identity for the call. If not specified, uses the instance identity.\n   * @param request The request to send in case it has already been created.\n   */\n  readState(\n    effectiveCanisterId: Principal | string,\n    options: ReadStateOptions,\n    identity?: Identity,\n    // eslint-disable-next-line  @typescript-eslint/no-explicit-any\n    request?: any,\n  ): Promise\u003cReadStateResponse\u003e;\n\n  call(canisterId: Principal | string, fields: CallOptions): Promise\u003cSubmitResponse\u003e;\n\n  /**\n   * Query the status endpoint of the replica. This normally has a few fields that\n   * corresponds to the version of the replica, its root public key, and any other\n   * information made public.\n   * @returns A JsonObject that is essentially a record of fields from the status\n   *     endpoint.\n   */\n  status(): Promise\u003cJsonObject\u003e;\n\n  /**\n   * Send a query call to a canister. See\n   * {@link https://sdk.dfinity.org/docs/interface-spec/#http-query | the interface spec}.\n   * @param canisterId The Principal of the Canister to send the query to. Sending a query to\n   *     the management canister is not supported (as it has no meaning from an agent).\n   * @param options Options to use to create and send the query.\n   * @param identity Sender principal to use when sending the query.\n   * @returns The response from the replica. The Promise will only reject when the communication\n   *     failed. If the query itself failed but no protocol errors happened, the response will\n   *     be of type QueryResponseRejected.\n   */\n  query(\n    canisterId: Principal | string,\n    options: QueryFields,\n    identity?: Identity | Promise\u003cIdentity\u003e,\n  ): Promise\u003cApiQueryResponse\u003e;\n\n  /**\n   * By default, the agent is configured to talk to the main Internet Computer,\n   * and verifies responses using a hard-coded public key.\n   *\n   * This function will instruct the agent to ask the endpoint for its public\n   * key, and use that instead. This is required when talking to a local test\n   * instance, for example.\n   *\n   * Only use this when you are  _not_ talking to the main Internet Computer,\n   * otherwise you are prone to man-in-the-middle attacks! Do not call this\n   * function by default.\n   */\n  fetchRootKey(): Promise\u003cArrayBuffer\u003e;\n  /**\n   * If an application needs to invalidate an identity under certain conditions, an `Agent` may expose an `invalidateIdentity` method.\n   * Invoking this method will set the inner identity used by the `Agent` to `null`.\n   *\n   * A use case for this would be - after a certain period of inactivity, a secure application chooses to invalidate the identity of any `HttpAgent` instances. An invalid identity can be replaced by `Agent.replaceIdentity`\n   */\n  invalidateIdentity?(): void;\n  /**\n   * If an application needs to replace an identity under certain conditions, an `Agent` may expose a `replaceIdentity` method.\n   * Invoking this method will set the inner identity used by the `Agent` to a newly provided identity.\n   *\n   * A use case for this would be - after authenticating using `@dfinity/auth-client`, you can replace the `AnonymousIdentity` of your `Actor` with a `DelegationIdentity`.\n   *\n   * ```Actor.agentOf(defaultActor).replaceIdentity(await authClient.getIdentity());```\n   */\n  replaceIdentity?(identity: Identity): void;\n}\n","/**\n * An error that happens in the Agent. This is the root of all errors and should be used\n * everywhere in the Agent code (this package).\n *\n * @todo https://github.com/dfinity/agent-js/issues/420\n */\nexport class AgentError extends Error {\n  constructor(public readonly message: string) {\n    super(message);\n    Object.setPrototypeOf(this, AgentError.prototype);\n  }\n}\n","/**\n * Concatenate multiple array buffers.\n * @param buffers The buffers to concatenate.\n */\nexport function concat(...buffers: ArrayBuffer[]): ArrayBuffer {\n  const result = new Uint8Array(buffers.reduce((acc, curr) =\u003e acc + curr.byteLength, 0));\n  let index = 0;\n  for (const b of buffers) {\n    result.set(new Uint8Array(b), index);\n    index += b.byteLength;\n  }\n  return result.buffer;\n}\n\n/**\n * Transforms a buffer to an hexadecimal string. This will use the buffer as an Uint8Array.\n * @param buffer The buffer to return the hexadecimal string of.\n */\nexport function toHex(buffer: ArrayBuffer): string {\n  return [...new Uint8Array(buffer)].map(x =\u003e x.toString(16).padStart(2, '0')).join('');\n}\n\nconst hexRe = new RegExp(/^[0-9a-fA-F]+$/);\n\n/**\n * Transforms a hexadecimal string into an array buffer.\n * @param hex The hexadecimal string to use.\n */\nexport function fromHex(hex: string): ArrayBuffer {\n  if (!hexRe.test(hex)) {\n    throw new Error('Invalid hexadecimal string.');\n  }\n  const buffer = [...hex]\n    .reduce((acc, curr, i) =\u003e {\n      acc[(i / 2) | 0] = (acc[(i / 2) | 0] || '') + curr;\n      return acc;\n    }, [] as string[])\n    .map(x =\u003e Number.parseInt(x, 16));\n\n  return new Uint8Array(buffer).buffer;\n}\n\n/**\n *\n * @param b1 array buffer 1\n * @param b2 array buffer 2\n * @returns number - negative if b1 \u003c b2, positive if b1 \u003e b2, 0 if b1 === b2\n */\nexport function compare(b1: ArrayBuffer, b2: ArrayBuffer): number {\n  if (b1.byteLength !== b2.byteLength) {\n    return b1.byteLength - b2.byteLength;\n  }\n\n  const u1 = new Uint8Array(b1);\n  const u2 = new Uint8Array(b2);\n  for (let i = 0; i \u003c u1.length; i++) {\n    if (u1[i] !== u2[i]) {\n      return u1[i] - u2[i];\n    }\n  }\n  return 0;\n}\n\n/**\n * Checks two array buffers for equality.\n * @param b1 array buffer 1\n * @param b2 array buffer 2\n * @returns boolean\n */\nexport function bufEquals(b1: ArrayBuffer, b2: ArrayBuffer): boolean {\n  return compare(b1, b2) === 0;\n}\n\n/**\n * Returns a true ArrayBuffer from a Uint8Array, as Uint8Array.buffer is unsafe.\n * @param {Uint8Array} arr Uint8Array to convert\n * @returns ArrayBuffer\n */\nexport function uint8ToBuf(arr: Uint8Array): ArrayBuffer {\n  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).buffer;\n}\n\n/**\n * Returns a true ArrayBuffer from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns ArrayBuffer\n */\nexport function bufFromBufLike(\n  bufLike:\n    | ArrayBuffer\n    | Uint8Array\n    | DataView\n    | ArrayBufferView\n    | ArrayBufferLike\n    | [number]\n    | number[]\n    | { buffer: ArrayBuffer },\n): ArrayBuffer {\n  if (bufLike instanceof Uint8Array) {\n    return uint8ToBuf(bufLike);\n  }\n  if (bufLike instanceof ArrayBuffer) {\n    return bufLike;\n  }\n  if (Array.isArray(bufLike)) {\n    return uint8ToBuf(new Uint8Array(bufLike));\n  }\n  if ('buffer' in bufLike) {\n    return bufFromBufLike(bufLike.buffer);\n  }\n  return uint8ToBuf(new Uint8Array(bufLike));\n}\n","import { lebEncode } from '@dfinity/candid';\nimport { Principal } from '@dfinity/principal';\nimport borc from 'borc';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { compare, concat, uint8ToBuf } from './utils/buffer';\n\nexport type RequestId = ArrayBuffer \u0026 { __requestId__: void };\n\n/**\n * sha256 hash the provided Buffer\n * @param data - input to hash function\n */\nexport function hash(data: ArrayBuffer): ArrayBuffer {\n  return uint8ToBuf(sha256.create().update(new Uint8Array(data)).digest());\n}\n\ninterface ToHashable {\n  toHash(): unknown;\n}\n\n/**\n *\n * @param value unknown value\n * @returns ArrayBuffer\n */\nexport function hashValue(value: unknown): ArrayBuffer {\n  if (value instanceof borc.Tagged) {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return hashValue((value as any).value);\n  } else if (typeof value === 'string') {\n    return hashString(value);\n  } else if (typeof value === 'number') {\n    return hash(lebEncode(value));\n  } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n    return hash(value as ArrayBuffer);\n  } else if (Array.isArray(value)) {\n    const vals = value.map(hashValue);\n    return hash(concat(...vals));\n  } else if (value \u0026\u0026 typeof value === 'object' \u0026\u0026 (value as Principal)._isPrincipal) {\n    return hash((value as Principal).toUint8Array());\n  } else if (\n    typeof value === 'object' \u0026\u0026\n    value !== null \u0026\u0026\n    typeof (value as ToHashable).toHash === 'function'\n  ) {\n    return hashValue((value as ToHashable).toHash());\n    // TODO This should be move to a specific async method as the webauthn flow required\n    // the flow to be synchronous to ensure Safari touch id works.\n    // } else if (value instanceof Promise) {\n    //   return value.then(x =\u003e hashValue(x));\n  } else if (typeof value === 'object') {\n    return hashOfMap(value as Record\u003cstring, unknown\u003e);\n  } else if (typeof value === 'bigint') {\n    // Do this check much later than the other bigint check because this one is much less\n    // type-safe.\n    // So we want to try all the high-assurance type guards before this 'probable' one.\n    return hash(lebEncode(value));\n  }\n  throw Object.assign(new Error(`Attempt to hash a value of unsupported type: ${value}`), {\n    // include so logs/callers can understand the confusing value.\n    // (when stringified in error message, prototype info is lost)\n    value,\n  });\n}\n\nconst hashString = (value: string): ArrayBuffer =\u003e {\n  const encoded = new TextEncoder().encode(value);\n  return hash(encoded);\n};\n\n/**\n * Get the RequestId of the provided ic-ref request.\n * RequestId is the result of the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param request - ic-ref request to hash into RequestId\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function requestIdOf(request: Record\u003cstring, any\u003e): RequestId {\n  return hashOfMap(request) as RequestId;\n}\n\n/**\n * Hash a map into an ArrayBuffer using the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param map - Any non-nested object\n * @returns ArrayBuffer\n */\nexport function hashOfMap(map: Record\u003cstring, unknown\u003e): ArrayBuffer {\n  const hashed: Array\u003c[ArrayBuffer, ArrayBuffer]\u003e = Object.entries(map)\n    .filter(([, value]) =\u003e value !== undefined)\n    .map(([key, value]: [string, unknown]) =\u003e {\n      const hashedKey = hashString(key);\n      const hashedValue = hashValue(value);\n\n      return [hashedKey, hashedValue] as [ArrayBuffer, ArrayBuffer];\n    });\n\n  const traversed: Array\u003c[ArrayBuffer, ArrayBuffer]\u003e = hashed;\n\n  const sorted: Array\u003c[ArrayBuffer, ArrayBuffer]\u003e = traversed.sort(([k1], [k2]) =\u003e {\n    return compare(k1, k2);\n  });\n\n  const concatenated: ArrayBuffer = concat(...sorted.map(x =\u003e concat(...x)));\n  const result = hash(concatenated);\n  return result;\n}\n","import { Principal } from '@dfinity/principal';\nimport { HttpAgentRequest } from './agent/http/types';\nimport { requestIdOf } from './request_id';\nimport { concat, toHex } from './utils/buffer';\n\nconst domainSeparator = new TextEncoder().encode('\\x0Aic-request');\n\n/**\n * A Key Pair, containing a secret and public key.\n */\nexport interface KeyPair {\n  secretKey: ArrayBuffer;\n  publicKey: PublicKey;\n}\n\n/**\n * A public key that is DER encoded. This is a branded ArrayBuffer.\n */\nexport type DerEncodedPublicKey = ArrayBuffer \u0026 { __derEncodedPublicKey__?: void };\n\n/**\n * A signature array buffer.\n */\nexport type Signature = ArrayBuffer \u0026 { __signature__: void };\n\n/**\n * A Public Key implementation.\n */\nexport interface PublicKey {\n  toDer(): DerEncodedPublicKey;\n  // rawKey, toRaw, and derKey are optional for backwards compatibility.\n  toRaw?(): ArrayBuffer;\n  rawKey?: ArrayBuffer;\n  derKey?: DerEncodedPublicKey;\n}\n\n/**\n * A General Identity object. This does not have to be a private key (for example,\n * the Anonymous identity), but it must be able to transform request.\n */\nexport interface Identity {\n  /**\n   * Get the principal represented by this identity. Normally should be a\n   * `Principal.selfAuthenticating()`.\n   */\n  getPrincipal(): Principal;\n\n  /**\n   * Transform a request into a signed version of the request. This is done last\n   * after the transforms on the body of a request. The returned object can be\n   * anything, but must be serializable to CBOR.\n   */\n  transformRequest(request: HttpAgentRequest): Promise\u003cunknown\u003e;\n}\n\n/**\n * An Identity that can sign blobs.\n */\nexport abstract class SignIdentity implements Identity {\n  protected _principal: Principal | undefined;\n\n  /**\n   * Returns the public key that would match this identity's signature.\n   */\n  public abstract getPublicKey(): PublicKey;\n\n  /**\n   * Signs a blob of data, with this identity's private key.\n   */\n  public abstract sign(blob: ArrayBuffer): Promise\u003cSignature\u003e;\n\n  /**\n   * Get the principal represented by this identity. Normally should be a\n   * `Principal.selfAuthenticating()`.\n   */\n  public getPrincipal(): Principal {\n    if (!this._principal) {\n      this._principal = Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()));\n    }\n    return this._principal;\n  }\n\n  /**\n   * Transform a request into a signed version of the request. This is done last\n   * after the transforms on the body of a request. The returned object can be\n   * anything, but must be serializable to CBOR.\n   * @param request - internet computer request to transform\n   */\n  public async transformRequest(request: HttpAgentRequest): Promise\u003cunknown\u003e {\n    const { body, ...fields } = request;\n    const requestId = await requestIdOf(body);\n    return {\n      ...fields,\n      body: {\n        content: body,\n        sender_pubkey: this.getPublicKey().toDer(),\n        sender_sig: await this.sign(concat(domainSeparator, requestId)),\n      },\n    };\n  }\n}\n\nexport class AnonymousIdentity implements Identity {\n  public getPrincipal(): Principal {\n    return Principal.anonymous();\n  }\n\n  public async transformRequest(request: HttpAgentRequest): Promise\u003cunknown\u003e {\n    return {\n      ...request,\n      body: { content: request.body },\n    };\n  }\n}\n\n/*\n * We need to communicate with other agents on the page about identities,\n * but those messages may need to go across boundaries where it's not possible to\n * serialize/deserialize object prototypes easily.\n * So these are lightweight, serializable objects that contain enough information to recreate\n * SignIdentities, but don't commit to having all methods of SignIdentity.\n *\n * Use Case:\n * * DOM Events that let differently-versioned components communicate to one another about\n *   Identities, even if they're using slightly different versions of agent packages to\n *   create/interpret them.\n */\nexport interface AnonymousIdentityDescriptor {\n  type: 'AnonymousIdentity';\n}\nexport interface PublicKeyIdentityDescriptor {\n  type: 'PublicKeyIdentity';\n  publicKey: string;\n}\nexport type IdentityDescriptor = AnonymousIdentityDescriptor | PublicKeyIdentityDescriptor;\n\n/**\n * Create an IdentityDescriptor from a @dfinity/identity Identity\n * @param identity - identity describe in returned descriptor\n */\nexport function createIdentityDescriptor(\n  identity: SignIdentity | AnonymousIdentity,\n): IdentityDescriptor {\n  const identityIndicator: IdentityDescriptor =\n    'getPublicKey' in identity\n      ? { type: 'PublicKeyIdentity', publicKey: toHex(identity.getPublicKey().toDer()) }\n      : { type: 'AnonymousIdentity' };\n  return identityIndicator;\n}\n","// This file is based on:\n// https://github.com/dfinity-lab/dfinity/blob/9bca65f8edd65701ea6bdb00e0752f9186bbc893/docs/spec/public/index.adoc#cbor-encoding-of-requests-and-responses\nimport borc from 'borc';\nimport * as cbor from 'simple-cbor';\nimport { CborEncoder, SelfDescribeCborSerializer } from 'simple-cbor';\nimport { Principal } from '@dfinity/principal';\nimport { concat, fromHex, toHex } from './utils/buffer';\n\n// We are using hansl/simple-cbor for CBOR serialization, to avoid issues with\n// encoding the uint64 values that the HTTP handler of the client expects for\n// canister IDs. However, simple-cbor does not yet provide deserialization so\n// we are using `Uint8Array` so that we can use the dignifiedquire/borc CBOR\n// decoder.\n\nclass PrincipalEncoder implements CborEncoder\u003cPrincipal\u003e {\n  public get name() {\n    return 'Principal';\n  }\n\n  public get priority() {\n    return 0;\n  }\n\n  public match(value: any): boolean {\n    return value \u0026\u0026 value._isPrincipal === true;\n  }\n\n  public encode(v: Principal): cbor.CborValue {\n    return cbor.value.bytes(v.toUint8Array());\n  }\n}\n\nclass BufferEncoder implements CborEncoder\u003cArrayBuffer\u003e {\n  public get name() {\n    return 'Buffer';\n  }\n\n  public get priority() {\n    return 1;\n  }\n\n  public match(value: any): boolean {\n    return value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n  }\n\n  public encode(v: ArrayBuffer): cbor.CborValue {\n    return cbor.value.bytes(new Uint8Array(v));\n  }\n}\n\nclass BigIntEncoder implements CborEncoder\u003cBigInt\u003e {\n  public get name() {\n    return 'BigInt';\n  }\n\n  public get priority() {\n    return 1;\n  }\n\n  public match(value: any): boolean {\n    return typeof value === `bigint`;\n  }\n\n  public encode(v: bigint): cbor.CborValue {\n    // Always use a bigint encoding.\n    if (v \u003e BigInt(0)) {\n      return cbor.value.tagged(2, cbor.value.bytes(fromHex(v.toString(16))));\n    } else {\n      return cbor.value.tagged(3, cbor.value.bytes(fromHex((BigInt('-1') * v).toString(16))));\n    }\n  }\n}\n\nconst serializer = SelfDescribeCborSerializer.withDefaultEncoders(true);\nserializer.addEncoder(new PrincipalEncoder());\nserializer.addEncoder(new BufferEncoder());\nserializer.addEncoder(new BigIntEncoder());\n\nexport enum CborTag {\n  Uint64LittleEndian = 71,\n  Semantic = 55799,\n}\n\n/**\n * Encode a JavaScript value into CBOR.\n */\nexport function encode(value: any): ArrayBuffer {\n  return serializer.serialize(value);\n}\n\nfunction decodePositiveBigInt(buf: Uint8Array): bigint {\n  const len = buf.byteLength;\n  let res = BigInt(0);\n  for (let i = 0; i \u003c len; i++) {\n    res = res * BigInt(0x100) + BigInt(buf[i]);\n  }\n\n  return res;\n}\n\n// A BORC subclass that decodes byte strings to ArrayBuffer instead of the Buffer class.\nclass Uint8ArrayDecoder extends borc.Decoder {\n  public createByteString(raw: ArrayBuffer[]): ArrayBuffer {\n    return concat(...raw);\n  }\n\n  public createByteStringFromHeap(start: number, end: number): ArrayBuffer {\n    if (start === end) {\n      return new ArrayBuffer(0);\n    }\n\n    return new Uint8Array((this as any)._heap.slice(start, end));\n  }\n}\n\nexport function decode\u003cT\u003e(input: ArrayBuffer): T {\n  const buffer = new Uint8Array(input);\n  const decoder = new Uint8ArrayDecoder({\n    size: buffer.byteLength,\n    tags: {\n      // Override tags 2 and 3 for BigInt support (borc supports only BigNumber).\n      2: val =\u003e decodePositiveBigInt(val),\n      3: val =\u003e -decodePositiveBigInt(val),\n      [CborTag.Semantic]: (value: T): T =\u003e value,\n    },\n  });\n\n  try {\n    return decoder.decodeFirst(buffer);\n  } catch(e: unknown) {\n    throw new Error(`Failed to decode CBOR: ${e}, input: ${toHex(buffer)}`);\n  }\n}\n","/**\n * Generates a random unsigned 32-bit integer between 0 and 0xffffffff\n * @returns {number} a random number\n */\nexport const randomNumber = (): number =\u003e {\n  // determine whether browser crypto is available\n  if (typeof window !== 'undefined' \u0026\u0026 !!window.crypto \u0026\u0026 !!window.crypto.getRandomValues) {\n    const array = new Uint32Array(1);\n    window.crypto.getRandomValues(array);\n    return array[0];\n  }\n  // A second check for webcrypto, in case it is loaded under global instead of window\n  if (typeof crypto !== 'undefined' \u0026\u0026 crypto.getRandomValues) {\n    const array = new Uint32Array(1);\n    crypto.getRandomValues(array);\n    return array[0];\n  }\n\n  type nodeCrypto = {\n    randomInt: (min: number, max: number) =\u003e number;\n  };\n\n  // determine whether node crypto is available\n  if (typeof crypto !== 'undefined' \u0026\u0026 (crypto as unknown as nodeCrypto).randomInt) {\n    return (crypto as unknown as nodeCrypto).randomInt(0, 0xffffffff);\n  }\n\n  // fall back to Math.random\n  return Math.floor(Math.random() * 0xffffffff);\n};\n","import type { Principal } from '@dfinity/principal';\nimport { Expiry } from './transforms';\nimport { randomNumber } from '../../utils/random';\n\n/**\n * @internal\n */\nexport const enum Endpoint {\n  Query = 'read',\n  ReadState = 'read_state',\n  Call = 'call',\n}\n\n// An HttpAgent request, before it gets encoded and sent to the server.\n// We create an empty request that we will fill later.\nexport type HttpAgentRequest =\n  | HttpAgentQueryRequest\n  | HttpAgentSubmitRequest\n  | HttpAgentReadStateRequest;\n\nexport interface HttpAgentBaseRequest {\n  readonly endpoint: Endpoint;\n  request: RequestInit;\n}\n\nexport type HttpHeaderField = [string, string];\n\nexport interface HttpAgentSubmitRequest extends HttpAgentBaseRequest {\n  readonly endpoint: Endpoint.Call;\n  body: CallRequest;\n}\n\nexport interface HttpAgentQueryRequest extends HttpAgentBaseRequest {\n  readonly endpoint: Endpoint.Query;\n  body: ReadRequest;\n}\n\nexport interface HttpAgentReadStateRequest extends HttpAgentBaseRequest {\n  readonly endpoint: Endpoint.ReadState;\n  body: ReadRequest;\n}\n\nexport interface Signed\u003cT\u003e {\n  content: T;\n  sender_pubkey: ArrayBuffer;\n  sender_sig: ArrayBuffer;\n}\n\nexport interface UnSigned\u003cT\u003e {\n  content: T;\n}\n\nexport type Envelope\u003cT\u003e = Signed\u003cT\u003e | UnSigned\u003cT\u003e;\n\nexport interface HttpAgentRequestTransformFn {\n  (args: HttpAgentRequest): Promise\u003cHttpAgentRequest | undefined | void\u003e;\n  priority?: number;\n}\n\n// The fields in a \"call\" submit request.\nexport interface CallRequest extends Record\u003cstring, any\u003e {\n  request_type: SubmitRequestType.Call;\n  canister_id: Principal;\n  method_name: string;\n  arg: ArrayBuffer;\n  sender: Uint8Array | Principal;\n  ingress_expiry: Expiry;\n}\n\n// The types of values allowed in the `request_type` field for submit requests.\nexport enum SubmitRequestType {\n  Call = 'call',\n}\n\n// The types of values allowed in the `request_type` field for read requests.\nexport const enum ReadRequestType {\n  Query = 'query',\n  ReadState = 'read_state',\n}\n\n// The fields in a \"query\" read request.\nexport interface QueryRequest extends Record\u003cstring, any\u003e {\n  request_type: ReadRequestType.Query;\n  canister_id: Principal;\n  method_name: string;\n  arg: ArrayBuffer;\n  sender: Uint8Array | Principal;\n  ingress_expiry: Expiry;\n}\n\nexport interface ReadStateRequest extends Record\u003cstring, any\u003e {\n  request_type: ReadRequestType.ReadState;\n  paths: ArrayBuffer[][];\n  ingress_expiry: Expiry;\n  sender: Uint8Array | Principal;\n}\n\nexport type ReadRequest = QueryRequest | ReadStateRequest;\n\n// A Nonce that can be used for calls.\nexport type Nonce = Uint8Array \u0026 { __nonce__: void };\n\n/**\n * Create a random Nonce, based on random values\n */\nexport function makeNonce(): Nonce {\n  // Encode 128 bits.\n  const buffer = new ArrayBuffer(16);\n  const view = new DataView(buffer);\n  const rand1 = randomNumber();\n  const rand2 = randomNumber();\n  const rand3 = randomNumber();\n  const rand4 = randomNumber();\n\n  view.setUint32(0, rand1);\n  view.setUint32(4, rand2);\n  view.setUint32(8, rand3);\n  view.setUint32(12, rand4);\n\n  return buffer as Nonce;\n}\n","import { lebEncode } from '@dfinity/candid';\nimport * as cbor from 'simple-cbor';\nimport {\n  Endpoint,\n  HttpAgentRequest,\n  HttpAgentRequestTransformFn,\n  HttpHeaderField,\n  makeNonce,\n  Nonce,\n} from './types';\n\nconst NANOSECONDS_PER_MILLISECONDS = BigInt(1_000_000);\n\nconst REPLICA_PERMITTED_DRIFT_MILLISECONDS = 60 * 1000;\n\nexport class Expiry {\n  private readonly _value: bigint;\n\n  constructor(deltaInMSec: number) {\n    // Use bigint because it can overflow the maximum number allowed in a double float.\n    const raw_value =\n      BigInt(Math.floor(Date.now() + deltaInMSec - REPLICA_PERMITTED_DRIFT_MILLISECONDS)) *\n      NANOSECONDS_PER_MILLISECONDS;\n\n    // round down to the nearest second\n    const ingress_as_seconds = raw_value / BigInt(1_000_000_000);\n\n    // round down to nearest minute\n    const ingress_as_minutes = ingress_as_seconds / BigInt(60);\n\n    const rounded_down_nanos = ingress_as_minutes * BigInt(60) * BigInt(1_000_000_000);\n\n    this._value = rounded_down_nanos;\n  }\n\n  public toCBOR(): cbor.CborValue {\n    // TODO: change this to take the minimum amount of space (it always takes 8 bytes now).\n    return cbor.value.u64(this._value.toString(16), 16);\n  }\n\n  public toHash(): ArrayBuffer {\n    return lebEncode(this._value);\n  }\n}\n\n/**\n * Create a Nonce transform, which takes a function that returns a Buffer, and adds it\n * as the nonce to every call requests.\n * @param nonceFn A function that returns a buffer. By default uses a semi-random method.\n */\nexport function makeNonceTransform(nonceFn: () =\u003e Nonce = makeNonce): HttpAgentRequestTransformFn {\n  return async (request: HttpAgentRequest) =\u003e {\n    // Nonce needs to be inserted into the header for all requests, to enable logs to be correlated with requests.\n    const headers = request.request.headers;\n    // TODO: uncomment this when the http proxy supports it.\n    // headers.set('X-IC-Request-ID', toHex(new Uint8Array(nonce)));\n    request.request.headers = headers;\n\n    // Nonce only needs to be inserted into the body for async calls, to prevent replay attacks.\n    if (request.endpoint === Endpoint.Call) {\n      request.body.nonce = nonceFn();\n    }\n  };\n}\n\n/**\n * Create a transform that adds a delay (by default 5 minutes) to the expiry.\n *\n * @param delayInMilliseconds The delay to add to the call time, in milliseconds.\n */\nexport function makeExpiryTransform(delayInMilliseconds: number): HttpAgentRequestTransformFn {\n  return async (request: HttpAgentRequest) =\u003e {\n    request.body.ingress_expiry = new Expiry(delayInMilliseconds);\n  };\n}\n\n/**\n * Maps the default fetch headers field to the serializable HttpHeaderField.\n *\n * @param headers Fetch definition of the headers type\n * @returns array of header fields\n */\nexport function httpHeadersTransform(headers: Headers): HttpHeaderField[] {\n  const headerFields: HttpHeaderField[] = [];\n  headers.forEach((value, key) =\u003e {\n    headerFields.push([key, value]);\n  });\n  return headerFields;\n}\n","import { AgentError } from '../../errors';\nimport { HttpDetailsResponse } from '../api';\n\nexport class AgentHTTPResponseError extends AgentError {\n  constructor(message: string, public readonly response: HttpDetailsResponse) {\n    super(message);\n    this.name = this.constructor.name;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import { bls12_381 } from '@noble/curves/bls12-381';\nimport { toHex } from './buffer';\n\nexport let verify: (pk: Uint8Array, sig: Uint8Array, msg: Uint8Array) =\u003e boolean;\n\n/**\n *\n * @param pk primary key: Uint8Array\n * @param sig signature: Uint8Array\n * @param msg message: Uint8Array\n * @returns boolean\n */\nexport function blsVerify(pk: Uint8Array, sig: Uint8Array, msg: Uint8Array): boolean {\n  const primaryKey = typeof pk === 'string' ? pk : toHex(pk);\n  const signature = typeof sig === 'string' ? sig : toHex(sig);\n  const message = typeof msg === 'string' ? msg : toHex(msg);\n  return bls12_381.verifyShortSignature(signature, message, primaryKey);\n}\n","import { PipeArrayBuffer, lebDecode } from '@dfinity/candid';\n\nexport const decodeLeb128 = (buf: ArrayBuffer): bigint =\u003e {\n  return lebDecode(new PipeArrayBuffer(buf));\n};\n\n// time is a LEB128-encoded Nat\nexport const decodeTime = (buf: ArrayBuffer): Date =\u003e {\n  const decoded = decodeLeb128(buf);\n\n  // nanoseconds to milliseconds\n  return new Date(Number(decoded) / 1_000_000);\n};\n","import * as cbor from './cbor';\nimport { AgentError } from './errors';\nimport { hash } from './request_id';\nimport { bufEquals, concat, fromHex, toHex } from './utils/buffer';\nimport { Principal } from '@dfinity/principal';\nimport * as bls from './utils/bls';\nimport { decodeTime } from './utils/leb';\n\n/**\n * A certificate may fail verification with respect to the provided public key\n */\nexport class CertificateVerificationError extends AgentError {\n  constructor(reason: string) {\n    super(`Invalid certificate: ${reason}`);\n  }\n}\n\nexport interface Cert {\n  tree: HashTree;\n  signature: ArrayBuffer;\n  delegation?: Delegation;\n}\n\nexport enum NodeType {\n  Empty = 0,\n  Fork = 1,\n  Labeled = 2,\n  Leaf = 3,\n  Pruned = 4,\n}\n\nexport type NodeLabel = ArrayBuffer | Uint8Array;\n\nexport type HashTree =\n  | [NodeType.Empty]\n  | [NodeType.Fork, HashTree, HashTree]\n  | [NodeType.Labeled, NodeLabel, HashTree]\n  | [NodeType.Leaf, NodeLabel]\n  | [NodeType.Pruned, NodeLabel];\n\n/**\n * Make a human readable string out of a hash tree.\n * @param tree\n */\nexport function hashTreeToString(tree: HashTree): string {\n  const indent = (s: string) =\u003e\n    s\n      .split('\\n')\n      .map(x =\u003e '  ' + x)\n      .join('\\n');\n  function labelToString(label: ArrayBuffer): string {\n    const decoder = new TextDecoder(undefined, { fatal: true });\n    try {\n      return JSON.stringify(decoder.decode(label));\n    } catch (e) {\n      return `data(...${label.byteLength} bytes)`;\n    }\n  }\n\n  switch (tree[0]) {\n    case NodeType.Empty:\n      return '()';\n    case NodeType.Fork: {\n      if (tree[1] instanceof Array \u0026\u0026 tree[2] instanceof ArrayBuffer) {\n        const left = hashTreeToString(tree[1]);\n        const right = hashTreeToString(tree[2]);\n        return `sub(\\n left:\\n${indent(left)}\\n---\\n right:\\n${indent(right)}\\n)`;\n      } else {\n        throw new Error('Invalid tree structure for fork');\n      }\n    }\n    case NodeType.Labeled: {\n      if (tree[1] instanceof ArrayBuffer \u0026\u0026 tree[2] instanceof ArrayBuffer) {\n        const label = labelToString(tree[1]);\n        const sub = hashTreeToString(tree[2]);\n        return `label(\\n label:\\n${indent(label)}\\n sub:\\n${indent(sub)}\\n)`;\n      } else {\n        throw new Error('Invalid tree structure for labeled');\n      }\n    }\n    case NodeType.Leaf: {\n      if (!tree[1]) {\n        throw new Error('Invalid tree structure for leaf');\n      } else if (Array.isArray(tree[1])) {\n        return JSON.stringify(tree[1]);\n      }\n      return `leaf(...${tree[1].byteLength} bytes)`;\n    }\n    case NodeType.Pruned: {\n      if (!tree[1]) {\n        throw new Error('Invalid tree structure for pruned');\n      } else if (Array.isArray(tree[1])) {\n        return JSON.stringify(tree[1]);\n      }\n\n      return `pruned(${toHex(new Uint8Array(tree[1]))}`;\n    }\n    default: {\n      return `unknown(${JSON.stringify(tree[0])})`;\n    }\n  }\n}\n\ninterface Delegation extends Record\u003cstring, unknown\u003e {\n  subnet_id: ArrayBuffer;\n  certificate: ArrayBuffer;\n}\n\nfunction isBufferGreaterThan(a: ArrayBuffer, b: ArrayBuffer): boolean {\n  const a8 = new Uint8Array(a);\n  const b8 = new Uint8Array(b);\n  for (let i = 0; i \u003c a8.length; i++) {\n    if (a8[i] \u003e b8[i]) {\n      return true;\n    }\n  }\n  return false;\n}\n\ntype VerifyFunc = (pk: Uint8Array, sig: Uint8Array, msg: Uint8Array) =\u003e Promise\u003cboolean\u003e | boolean;\n\nexport interface CreateCertificateOptions {\n  /**\n   * The bytes encoding the certificate to be verified\n   */\n  certificate: ArrayBuffer;\n  /**\n   * The root key against which to verify the certificate\n   * (normally, the root key of the IC main network)\n   */\n  rootKey: ArrayBuffer;\n  /**\n   * The effective canister ID of the request when verifying a response, or\n   * the signing canister ID when verifying a certified variable.\n   */\n  canisterId: Principal;\n  /**\n   * BLS Verification strategy. Default strategy uses wasm for performance, but that may not be available in all contexts.\n   */\n  blsVerify?: VerifyFunc;\n\n  /**\n   * The maximum age of the certificate in minutes. Default is 5 minutes.\n   * @default 5\n   * This is used to verify the time the certificate was signed, particularly for validating Delegation certificates, which can live for longer than the default window of +/- 5 minutes. If the certificate is\n   * older than the specified age, it will fail verification.\n   */\n  maxAgeInMinutes?: number;\n}\n\nexport class Certificate {\n  private readonly cert: Cert;\n\n  /**\n   * Create a new instance of a certificate, automatically verifying it. Throws a\n   * CertificateVerificationError if the certificate cannot be verified.\n   * @constructs  Certificate\n   * @param {CreateCertificateOptions} options {@link CreateCertificateOptions}\n   * @param {ArrayBuffer} options.certificate The bytes of the certificate\n   * @param {ArrayBuffer} options.rootKey The root key to verify against\n   * @param {Principal} options.canisterId The effective or signing canister ID\n   * @param {number} options.maxAgeInMinutes The maximum age of the certificate in minutes. Default is 5 minutes.\n   * @throws {CertificateVerificationError}\n   */\n  public static async create(options: CreateCertificateOptions): Promise\u003cCertificate\u003e {\n    const cert = Certificate.createUnverified(options);\n\n    await cert.verify();\n    return cert;\n  }\n\n  private static createUnverified(options: CreateCertificateOptions): Certificate {\n    let blsVerify = options.blsVerify;\n    if (!blsVerify) {\n      blsVerify = bls.blsVerify;\n    }\n    return new Certificate(\n      options.certificate,\n      options.rootKey,\n      options.canisterId,\n      blsVerify,\n      options.maxAgeInMinutes,\n    );\n  }\n\n  private constructor(\n    certificate: ArrayBuffer,\n    private _rootKey: ArrayBuffer,\n    private _canisterId: Principal,\n    private _blsVerify: VerifyFunc,\n    // Default to 5 minutes\n    private _maxAgeInMinutes: number = 5,\n  ) {\n    this.cert = cbor.decode(new Uint8Array(certificate));\n  }\n\n  public lookup(path: Array\u003cArrayBuffer | string\u003e): LookupResult {\n    // constrain the type of the result, so that empty HashTree is undefined\n    return lookup_path(path, this.cert.tree);\n  }\n\n  public lookup_label(label: ArrayBuffer): LookupResult {\n    return this.lookup([label]);\n  }\n\n  private async verify(): Promise\u003cvoid\u003e {\n    const rootHash = await reconstruct(this.cert.tree);\n    const derKey = await this._checkDelegationAndGetKey(this.cert.delegation);\n    const sig = this.cert.signature;\n    const key = extractDER(derKey);\n    const msg = concat(domain_sep('ic-state-root'), rootHash);\n    let sigVer = false;\n\n    const lookupTime = lookupResultToBuffer(this.lookup(['time']));\n    if (!lookupTime) {\n      // Should never happen - time is always present in IC certificates\n      throw new CertificateVerificationError('Certificate does not contain a time');\n    }\n\n    const FIVE_MINUTES_IN_MSEC = 5 * 60 * 1000;\n    const MAX_AGE_IN_MSEC = this._maxAgeInMinutes * 60 * 1000;\n    const now = Date.now();\n    const earliestCertificateTime = now - MAX_AGE_IN_MSEC;\n    const fiveMinutesFromNow = now + FIVE_MINUTES_IN_MSEC;\n\n    const certTime = decodeTime(lookupTime);\n\n    if (certTime.getTime() \u003c earliestCertificateTime) {\n      throw new CertificateVerificationError(\n        `Certificate is signed more than ${this._maxAgeInMinutes} minutes in the past. Certificate time: ` +\n          certTime.toISOString() +\n          ' Current time: ' +\n          new Date(now).toISOString(),\n      );\n    } else if (certTime.getTime() \u003e fiveMinutesFromNow) {\n      throw new CertificateVerificationError(\n        'Certificate is signed more than 5 minutes in the future. Certificate time: ' +\n          certTime.toISOString() +\n          ' Current time: ' +\n          new Date(now).toISOString(),\n      );\n    }\n\n    try {\n      sigVer = await this._blsVerify(new Uint8Array(key), new Uint8Array(sig), new Uint8Array(msg));\n    } catch (err) {\n      sigVer = false;\n    }\n    if (!sigVer) {\n      throw new CertificateVerificationError('Signature verification failed');\n    }\n  }\n\n  private async _checkDelegationAndGetKey(d?: Delegation): Promise\u003cArrayBuffer\u003e {\n    if (!d) {\n      return this._rootKey;\n    }\n\n    const cert: Certificate = await Certificate.createUnverified({\n      certificate: d.certificate,\n      rootKey: this._rootKey,\n      canisterId: this._canisterId,\n      blsVerify: this._blsVerify,\n      // Do not check max age for delegation certificates\n      maxAgeInMinutes: Infinity,\n    });\n\n    if (cert.cert.delegation) {\n      throw new CertificateVerificationError('Delegation certificates cannot be nested');\n    }\n\n    await cert.verify();\n\n    const canisterInRange = check_canister_ranges({\n      canisterId: this._canisterId,\n      subnetId: Principal.fromUint8Array(new Uint8Array(d.subnet_id)),\n      tree: cert.cert.tree,\n    });\n    if (!canisterInRange) {\n      throw new CertificateVerificationError(\n        `Canister ${this._canisterId} not in range of delegations for subnet 0x${toHex(\n          d.subnet_id,\n        )}`,\n      );\n    }\n    const publicKeyLookup = lookupResultToBuffer(\n      cert.lookup(['subnet', d.subnet_id, 'public_key']),\n    );\n    if (!publicKeyLookup) {\n      throw new Error(`Could not find subnet key for subnet 0x${toHex(d.subnet_id)}`);\n    }\n    return publicKeyLookup;\n  }\n}\n\nconst DER_PREFIX = fromHex(\n  '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100',\n);\nconst KEY_LENGTH = 96;\n\nfunction extractDER(buf: ArrayBuffer): ArrayBuffer {\n  const expectedLength = DER_PREFIX.byteLength + KEY_LENGTH;\n  if (buf.byteLength !== expectedLength) {\n    throw new TypeError(`BLS DER-encoded public key must be ${expectedLength} bytes long`);\n  }\n  const prefix = buf.slice(0, DER_PREFIX.byteLength);\n  if (!bufEquals(prefix, DER_PREFIX)) {\n    throw new TypeError(\n      `BLS DER-encoded public key is invalid. Expect the following prefix: ${DER_PREFIX}, but get ${prefix}`,\n    );\n  }\n\n  return buf.slice(DER_PREFIX.byteLength);\n}\n\n/**\n * utility function to constrain the type of a path\n * @param {ArrayBuffer | HashTree | undefined} result - the result of a lookup\n * @returns ArrayBuffer or Undefined\n */\nexport function lookupResultToBuffer(result: LookupResult): ArrayBuffer | undefined {\n  if (result.status !== LookupStatus.Found) {\n    return undefined;\n  }\n\n  if (result.value instanceof ArrayBuffer) {\n    return result.value;\n  }\n\n  if (result.value instanceof Uint8Array) {\n    return result.value.buffer;\n  }\n\n  return undefined;\n}\n\n/**\n * @param t\n */\nexport async function reconstruct(t: HashTree): Promise\u003cArrayBuffer\u003e {\n  switch (t[0]) {\n    case NodeType.Empty:\n      return hash(domain_sep('ic-hashtree-empty'));\n    case NodeType.Pruned:\n      return t[1] as ArrayBuffer;\n    case NodeType.Leaf:\n      return hash(concat(domain_sep('ic-hashtree-leaf'), t[1] as ArrayBuffer));\n    case NodeType.Labeled:\n      return hash(\n        concat(\n          domain_sep('ic-hashtree-labeled'),\n          t[1] as ArrayBuffer,\n          await reconstruct(t[2] as HashTree),\n        ),\n      );\n    case NodeType.Fork:\n      return hash(\n        concat(\n          domain_sep('ic-hashtree-fork'),\n          await reconstruct(t[1] as HashTree),\n          await reconstruct(t[2] as HashTree),\n        ),\n      );\n    default:\n      throw new Error('unreachable');\n  }\n}\n\nfunction domain_sep(s: string): ArrayBuffer {\n  const len = new Uint8Array([s.length]);\n  const str = new TextEncoder().encode(s);\n  return concat(len, str);\n}\n\nexport enum LookupStatus {\n  Unknown = 'unknown',\n  Absent = 'absent',\n  Found = 'found',\n}\n\nexport interface LookupResultAbsent {\n  status: LookupStatus.Absent;\n}\n\nexport interface LookupResultUnknown {\n  status: LookupStatus.Unknown;\n}\n\nexport interface LookupResultFound {\n  status: LookupStatus.Found;\n  value: ArrayBuffer | HashTree;\n}\n\nexport type LookupResult = LookupResultAbsent | LookupResultUnknown | LookupResultFound;\n\nenum LabelLookupStatus {\n  Less = 'less',\n  Greater = 'greater',\n}\n\ninterface LookupResultGreater {\n  status: LabelLookupStatus.Greater;\n}\n\ninterface LookupResultLess {\n  status: LabelLookupStatus.Less;\n}\n\ntype LabelLookupResult = LookupResult | LookupResultGreater | LookupResultLess;\n\nexport function lookup_path(path: Array\u003cArrayBuffer | string\u003e, tree: HashTree): LookupResult {\n  if (path.length === 0) {\n    switch (tree[0]) {\n      case NodeType.Leaf: {\n        if (!tree[1]) {\n          throw new Error('Invalid tree structure for leaf');\n        }\n\n        if (tree[1] instanceof ArrayBuffer) {\n          return {\n            status: LookupStatus.Found,\n            value: tree[1],\n          };\n        }\n\n        if (tree[1] instanceof Uint8Array) {\n          return {\n            status: LookupStatus.Found,\n            value: tree[1].buffer,\n          };\n        }\n\n        return {\n          status: LookupStatus.Found,\n          value: tree[1],\n        };\n      }\n\n      default: {\n        return {\n          status: LookupStatus.Found,\n          value: tree,\n        };\n      }\n    }\n  }\n\n  const label = typeof path[0] === 'string' ? new TextEncoder().encode(path[0]) : path[0];\n  const lookupResult = find_label(label, tree);\n\n  switch (lookupResult.status) {\n    case LookupStatus.Found: {\n      return lookup_path(path.slice(1), lookupResult.value as HashTree);\n    }\n\n    case LabelLookupStatus.Greater:\n    case LabelLookupStatus.Less: {\n      return {\n        status: LookupStatus.Absent,\n      };\n    }\n\n    default: {\n      return lookupResult;\n    }\n  }\n}\n\n/**\n * If the tree is a fork, flatten it into an array of trees\n * @param t - the tree to flatten\n * @returns HashTree[] - the flattened tree\n */\nexport function flatten_forks(t: HashTree): HashTree[] {\n  switch (t[0]) {\n    case NodeType.Empty:\n      return [];\n    case NodeType.Fork:\n      return flatten_forks(t[1] as HashTree).concat(flatten_forks(t[2] as HashTree));\n    default:\n      return [t];\n  }\n}\n\nexport function find_label(label: ArrayBuffer, tree: HashTree): LabelLookupResult {\n  switch (tree[0]) {\n    // if we have a labelled node, compare the node's label to the one we are\n    // looking for\n    case NodeType.Labeled:\n      // if the label we're searching for is greater than this node's label,\n      // we need to keep searching\n      if (isBufferGreaterThan(label, tree[1])) {\n        return {\n          status: LabelLookupStatus.Greater,\n        };\n      }\n\n      // if the label we're searching for is equal this node's label, we can\n      // stop searching and return the found node\n      if (bufEquals(label, tree[1])) {\n        return {\n          status: LookupStatus.Found,\n          value: tree[2],\n        };\n      }\n\n      // if the label we're searching for is not greater than or equal to this\n      // node's label, then it's less than this node's label, and we can stop\n      // searching because we've looked too far\n      return {\n        status: LabelLookupStatus.Less,\n      };\n\n    // if we have a fork node, we need to search both sides, starting with the left\n    case NodeType.Fork:\n      // search in the left node\n      const leftLookupResult = find_label(label, tree[1]);\n\n      switch (leftLookupResult.status) {\n        // if the label we're searching for is greater than the left node lookup,\n        // we need to search the right node\n        case LabelLookupStatus.Greater: {\n          const rightLookupResult = find_label(label, tree[2]);\n\n          // if the label we're searching for is less than the right node lookup,\n          // then we can stop searching and say that the label is provably Absent\n          if (rightLookupResult.status === LabelLookupStatus.Less) {\n            return {\n              status: LookupStatus.Absent,\n            };\n          }\n\n          // if the label we're searching for is less than or equal to the right\n          // node lookup, then we let the caller handle it\n          return rightLookupResult;\n        }\n\n        // if the left node returns an uncertain result, we need to search the\n        // right node\n        case LookupStatus.Unknown: {\n          let rightLookupResult = find_label(label, tree[2]);\n\n          // if the label we're searching for is less than the right node lookup,\n          // then we also need to return an uncertain result\n          if (rightLookupResult.status === LabelLookupStatus.Less) {\n            return {\n              status: LookupStatus.Unknown,\n            };\n          }\n\n          // if the label we're searching for is less than or equal to the right\n          // node lookup, then we let the caller handle it\n          return rightLookupResult;\n        }\n\n        // if the label we're searching for is not greater than the left node\n        // lookup, or the result is not uncertain, we stop searching and return\n        // whatever the result of the left node lookup was, which can be either\n        // Found or Absent\n        default: {\n          return leftLookupResult;\n        }\n      }\n\n    // if we encounter a Pruned node, we can't know for certain if the label\n    // we're searching for is present or not\n    case NodeType.Pruned:\n      return {\n        status: LookupStatus.Unknown,\n      };\n\n    // if the current node is Empty, or a Leaf, we can stop searching because\n    // we know for sure that the label we're searching for is not present\n    default:\n      return {\n        status: LookupStatus.Absent,\n      };\n  }\n}\n\n/**\n * Check if a canister falls within a range of canisters\n * @param canisterId Principal\n * @param ranges [Principal, Principal][]\n * @returns\n */\nexport function check_canister_ranges(params: {\n  canisterId: Principal;\n  subnetId: Principal;\n  tree: HashTree;\n}): boolean {\n  const { canisterId, subnetId, tree } = params;\n  const rangeLookup = lookup_path(['subnet', subnetId.toUint8Array(), 'canister_ranges'], tree);\n\n  if (rangeLookup.status !== LookupStatus.Found || !(rangeLookup.value instanceof ArrayBuffer)) {\n    throw new Error(`Could not find canister ranges for subnet ${subnetId}`);\n  }\n\n  const ranges_arr: Array\u003c[Uint8Array, Uint8Array]\u003e = cbor.decode(rangeLookup.value);\n  const ranges: Array\u003c[Principal, Principal]\u003e = ranges_arr.map(v =\u003e [\n    Principal.fromUint8Array(v[0]),\n    Principal.fromUint8Array(v[1]),\n  ]);\n\n  const canisterInRange = ranges.some(r =\u003e r[0].ltEq(canisterId) \u0026\u0026 r[1].gtEq(canisterId));\n\n  return canisterInRange;\n}\n","/** @module CanisterStatus */\nimport { Principal } from '@dfinity/principal';\nimport { AgentError } from '../errors';\nimport { HttpAgent } from '../agent/http';\nimport {\n  Cert,\n  Certificate,\n  CreateCertificateOptions,\n  HashTree,\n  flatten_forks,\n  check_canister_ranges,\n  LookupStatus,\n  lookup_path,\n  lookupResultToBuffer,\n} from '../certificate';\nimport { toHex } from '../utils/buffer';\nimport * as Cbor from '../cbor';\nimport { decodeLeb128, decodeTime } from '../utils/leb';\nimport { DerEncodedPublicKey } from '..';\n\n/**\n * Represents the useful information about a subnet\n * @param {string} subnetId the principal id of the canister's subnet\n * @param {string[]} nodeKeys the keys of the individual nodes in the subnet\n */\nexport type SubnetStatus = {\n  // Principal as a string\n  subnetId: string;\n  nodeKeys: Map\u003cstring, DerEncodedPublicKey\u003e;\n  metrics?: {\n    num_canisters: bigint;\n    canister_state_bytes: bigint;\n    consumed_cycles_total: {\n      current: bigint;\n      deleted: bigint;\n    };\n    update_transactions_total: bigint;\n  };\n};\n\n/**\n * Types of an entry on the canisterStatus map.\n * An entry of null indicates that the request failed, due to lack of permissions or the result being missing.\n */\nexport type Status =\n  | string\n  | ArrayBuffer\n  | Date\n  | ArrayBuffer[]\n  | Principal[]\n  | SubnetStatus\n  | bigint\n  | null;\n\n/**\n * Interface to define a custom path. Nested paths will be represented as individual buffers, and can be created from text using TextEncoder.\n * @param {string} key the key to use to access the returned value in the canisterStatus map\n * @param {ArrayBuffer[]} path the path to the desired value, represented as an array of buffers\n * @param {string} decodeStrategy the strategy to use to decode the returned value\n */\nexport class CustomPath implements CustomPath {\n  public key: string;\n  public path: ArrayBuffer[] | string;\n  public decodeStrategy: 'cbor' | 'hex' | 'leb128' | 'utf-8' | 'raw';\n  constructor(\n    key: string,\n    path: ArrayBuffer[] | string,\n    decodeStrategy: 'cbor' | 'hex' | 'leb128' | 'utf-8' | 'raw',\n  ) {\n    this.key = key;\n    this.path = path;\n    this.decodeStrategy = decodeStrategy;\n  }\n}\n\n/**\n * @deprecated Use {@link CustomPath} instead\n * @param {string} key the key to use to access the returned value in the canisterStatus map\n * @param {string} path the path to the desired value, represented as a string\n * @param {string} decodeStrategy the strategy to use to decode the returned value\n */\nexport interface MetaData {\n  kind: 'metadata';\n  key: string;\n  path: string | ArrayBuffer;\n  decodeStrategy: 'cbor' | 'hex' | 'leb128' | 'utf-8' | 'raw';\n}\n\n/**\n * Pre-configured fields for canister status paths\n */\nexport type Path =\n  | 'time'\n  | 'controllers'\n  | 'subnet'\n  | 'module_hash'\n  | 'candid'\n  | MetaData\n  | CustomPath;\n\nexport type StatusMap = Map\u003cPath | string, Status\u003e;\n\nexport type CanisterStatusOptions = {\n  canisterId: Principal;\n  agent: HttpAgent;\n  paths?: Path[] | Set\u003cPath\u003e;\n  blsVerify?: CreateCertificateOptions['blsVerify'];\n};\n\n/**\n * Request information in the request_status state tree for a given canister.\n * Can be used to request information about the canister's controllers, time, module hash, candid interface, and more.\n * @param {CanisterStatusOptions} options {@link CanisterStatusOptions}\n * @param {CanisterStatusOptions['canisterId']} options.canisterId {@link Principal}\n * @param {CanisterStatusOptions['agent']} options.agent {@link HttpAgent} optional authenticated agent to use to make the canister request. Useful for accessing private metadata under icp:private\n * @param {CanisterStatusOptions['paths']} options.paths {@link Path[]}\n * @returns {Status} object populated with data from the requested paths\n * @example\n * const status = await canisterStatus({\n *   paths: ['controllers', 'candid'],\n *   ...options\n * });\n *\n * const controllers = status.get('controllers');\n */\nexport const request = async (options: {\n  canisterId: Principal;\n  agent: HttpAgent;\n  paths?: Path[] | Set\u003cPath\u003e;\n}): Promise\u003cStatusMap\u003e =\u003e {\n  const { agent, paths } = options;\n  const canisterId = Principal.from(options.canisterId);\n\n  const uniquePaths = [...new Set(paths)];\n\n  // Map path options to their correct formats\n  const encodedPaths = uniquePaths.map(path =\u003e {\n    return encodePath(path, canisterId);\n  });\n  const status = new Map\u003cstring | Path, Status\u003e();\n\n  const promises = uniquePaths.map((path, index) =\u003e {\n    return (async () =\u003e {\n      try {\n        const response = await agent.readState(canisterId, {\n          paths: [encodedPaths[index]],\n        });\n        const cert = await Certificate.create({\n          certificate: response.certificate,\n          rootKey: agent.rootKey,\n          canisterId: canisterId,\n        });\n\n        const lookup = (cert: Certificate, path: Path) =\u003e {\n          if (path === 'subnet') {\n            const data = fetchNodeKeys(response.certificate, canisterId, agent.rootKey);\n            return {\n              path: path,\n              data,\n            };\n          } else {\n            return {\n              path: path,\n              data: lookupResultToBuffer(cert.lookup(encodePath(path, canisterId))),\n            };\n          }\n        };\n\n        // must pass in the rootKey if we have no delegation\n        const { path, data } = lookup(cert, uniquePaths[index]);\n        if (!data) {\n          // Typically, the cert lookup will throw\n          console.warn(`Expected to find result for path ${path}, but instead found nothing.`);\n          if (typeof path === 'string') {\n            status.set(path, null);\n          } else {\n            status.set(path.key, null);\n          }\n        } else {\n          switch (path) {\n            case 'time': {\n              status.set(path, decodeTime(data));\n              break;\n            }\n            case 'controllers': {\n              status.set(path, decodeControllers(data));\n              break;\n            }\n            case 'module_hash': {\n              status.set(path, decodeHex(data));\n              break;\n            }\n            case 'subnet': {\n              status.set(path, data);\n              break;\n            }\n            case 'candid': {\n              status.set(path, new TextDecoder().decode(data));\n              break;\n            }\n            default: {\n              // Check for CustomPath signature\n              if (typeof path !== 'string' \u0026\u0026 'key' in path \u0026\u0026 'path' in path) {\n                switch (path.decodeStrategy) {\n                  case 'raw':\n                    status.set(path.key, data);\n                    break;\n                  case 'leb128': {\n                    status.set(path.key, decodeLeb128(data));\n                    break;\n                  }\n                  case 'cbor': {\n                    status.set(path.key, decodeCbor(data));\n                    break;\n                  }\n                  case 'hex': {\n                    status.set(path.key, decodeHex(data));\n                    break;\n                  }\n                  case 'utf-8': {\n                    status.set(path.key, decodeUtf8(data));\n                  }\n                }\n              }\n            }\n          }\n        }\n      } catch (error) {\n        // Break on signature verification errors\n        if ((error as AgentError)?.message?.includes('Invalid certificate')) {\n          throw new AgentError((error as AgentError).message);\n        }\n        if (typeof path !== 'string' \u0026\u0026 'key' in path \u0026\u0026 'path' in path) {\n          status.set(path.key, null);\n        } else {\n          status.set(path, null);\n        }\n        console.group();\n        console.warn(`Expected to find result for path ${path}, but instead found nothing.`);\n        console.warn(error);\n        console.groupEnd();\n      }\n    })();\n  });\n\n  // Fetch all values separately, as each option can fail\n  await Promise.all(promises);\n\n  return status;\n};\n\nexport const fetchNodeKeys = (\n  certificate: ArrayBuffer,\n  canisterId: Principal,\n  root_key?: ArrayBuffer | Uint8Array,\n): SubnetStatus =\u003e {\n  if (!canisterId._isPrincipal) {\n    throw new Error('Invalid canisterId');\n  }\n  const cert = Cbor.decode(new Uint8Array(certificate)) as Cert;\n  const tree = cert.tree;\n  let delegation = cert.delegation;\n  let subnetId: Principal;\n  if (delegation \u0026\u0026 delegation.subnet_id) {\n    subnetId = Principal.fromUint8Array(new Uint8Array(delegation.subnet_id));\n  }\n\n  // On local replica, with System type subnet, there is no delegation\n  else if (!delegation \u0026\u0026 typeof root_key !== 'undefined') {\n    subnetId = Principal.selfAuthenticating(new Uint8Array(root_key));\n    delegation = {\n      subnet_id: subnetId.toUint8Array(),\n      certificate: new ArrayBuffer(0),\n    };\n  }\n  // otherwise use default NNS subnet id\n  else {\n    subnetId = Principal.selfAuthenticating(\n      Principal.fromText(\n        'tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe',\n      ).toUint8Array(),\n    );\n    delegation = {\n      subnet_id: subnetId.toUint8Array(),\n      certificate: new ArrayBuffer(0),\n    };\n  }\n\n  const canisterInRange = check_canister_ranges({ canisterId, subnetId, tree });\n  if (!canisterInRange) {\n    throw new Error('Canister not in range');\n  }\n\n  const subnetLookupResult = lookup_path(['subnet', delegation.subnet_id, 'node'], tree);\n  if (subnetLookupResult.status !== LookupStatus.Found) {\n    throw new Error('Node not found');\n  }\n  if (subnetLookupResult.value instanceof ArrayBuffer) {\n    throw new Error('Invalid node tree');\n  }\n\n  const nodeForks = flatten_forks(subnetLookupResult.value);\n  const nodeKeys = new Map\u003cstring, DerEncodedPublicKey\u003e();\n\n  nodeForks.forEach(fork =\u003e {\n    const node_id = Principal.from(new Uint8Array(fork[1] as ArrayBuffer)).toText();\n    const publicKeyLookupResult = lookup_path(['public_key'], fork[2] as HashTree);\n    if (publicKeyLookupResult.status !== LookupStatus.Found) {\n      throw new Error('Public key not found');\n    }\n\n    const derEncodedPublicKey = publicKeyLookupResult.value as ArrayBuffer;\n    if (derEncodedPublicKey.byteLength !== 44) {\n      throw new Error('Invalid public key length');\n    } else {\n      nodeKeys.set(node_id, derEncodedPublicKey as DerEncodedPublicKey);\n    }\n  });\n\n  return {\n    subnetId: Principal.fromUint8Array(new Uint8Array(delegation.subnet_id)).toText(),\n    nodeKeys,\n  };\n};\n\nexport const encodePath = (path: Path, canisterId: Principal): ArrayBuffer[] =\u003e {\n  const encoder = new TextEncoder();\n\n  const encode = (arg: string): ArrayBuffer =\u003e {\n    return new DataView(encoder.encode(arg).buffer).buffer;\n  };\n  const canisterBuffer = new DataView(canisterId.toUint8Array().buffer).buffer;\n  switch (path) {\n    case 'time':\n      return [encode('time')];\n    case 'controllers':\n      return [encode('canister'), canisterBuffer, encode('controllers')];\n    case 'module_hash':\n      return [encode('canister'), canisterBuffer, encode('module_hash')];\n    case 'subnet':\n      return [encode('subnet')];\n    case 'candid':\n      return [encode('canister'), canisterBuffer, encode('metadata'), encode('candid:service')];\n    default: {\n      // Check for CustomPath signature\n      if ('key' in path \u0026\u0026 'path' in path) {\n        // For simplified metadata queries\n        if (typeof path['path'] === 'string' || path['path'] instanceof ArrayBuffer) {\n          const metaPath = path.path;\n          const encoded = typeof metaPath === 'string' ? encode(metaPath) : metaPath;\n\n          return [encode('canister'), canisterBuffer, encode('metadata'), encoded];\n\n          // For non-metadata, return the provided custompath\n        } else {\n          return path['path'];\n        }\n      }\n    }\n  }\n  throw new Error(\n    `An unexpeected error was encountered while encoding your path for canister status. Please ensure that your path, ${path} was formatted correctly.`,\n  );\n};\n\nconst decodeHex = (buf: ArrayBuffer): string =\u003e {\n  return toHex(buf);\n};\n\nconst decodeCbor = (buf: ArrayBuffer): ArrayBuffer[] =\u003e {\n  return Cbor.decode(buf);\n};\n\nconst decodeUtf8 = (buf: ArrayBuffer): string =\u003e {\n  return new TextDecoder().decode(buf);\n};\n\n// Controllers are CBOR-encoded buffers\nconst decodeControllers = (buf: ArrayBuffer): Principal[] =\u003e {\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  const controllersRaw = decodeCbor(buf);\n  return controllersRaw.map((buf: ArrayBuffer) =\u003e {\n    return Principal.fromUint8Array(new Uint8Array(buf));\n  });\n};\n","export type ExpirableMapOptions\u003cK, V\u003e = {\n  source?: Iterable\u003c[K, V]\u003e;\n  expirationTime?: number;\n};\n\n/**\n * A map that expires entries after a given time.\n * Defaults to 10 minutes.\n */\nexport class ExpirableMap\u003cK, V\u003e implements Map\u003cK, V\u003e {\n  // Internals\n  #inner: Map\u003cK, { value: V; timestamp: number }\u003e;\n  #expirationTime: number;\n\n  [Symbol.iterator]: () =\u003e IterableIterator\u003c[K, V]\u003e = this.entries.bind(this);\n  [Symbol.toStringTag] = 'ExpirableMap';\n\n  /**\n   * Create a new ExpirableMap.\n   * @param {ExpirableMapOptions\u003cany, any\u003e} options - options for the map.\n   * @param {Iterable\u003c[any, any]\u003e} options.source - an optional source of entries to initialize the map with.\n   * @param {number} options.expirationTime - the time in milliseconds after which entries will expire.\n   */\n  constructor(options: ExpirableMapOptions\u003cK, V\u003e = {}) {\n    const { source = [], expirationTime = 10 * 60 * 1000 } = options;\n    const currentTime = Date.now();\n    this.#inner = new Map(\n      [...source].map(([key, value]) =\u003e [key, { value, timestamp: currentTime }]),\n    );\n    this.#expirationTime = expirationTime;\n  }\n\n  /**\n   * Prune removes all expired entries.\n   */\n  prune() {\n    const currentTime = Date.now();\n    for (const [key, entry] of this.#inner.entries()) {\n      if (currentTime - entry.timestamp \u003e this.#expirationTime) {\n        this.#inner.delete(key);\n      }\n    }\n    return this;\n  }\n\n  // Implementing the Map interface\n\n  /**\n   * Set the value for the given key. Prunes expired entries.\n   * @param key for the entry\n   * @param value of the entry\n   * @returns this\n   */\n  set(key: K, value: V) {\n    this.prune();\n    const entry = {\n      value,\n      timestamp: Date.now(),\n    };\n    this.#inner.set(key, entry);\n\n    return this;\n  }\n\n  /**\n   * Get the value associated with the key, if it exists and has not expired.\n   * @param key K\n   * @returns the value associated with the key, or undefined if the key is not present or has expired.\n   */\n  get(key: K) {\n    const entry = this.#inner.get(key);\n    if (entry === undefined) {\n      return undefined;\n    }\n    if (Date.now() - entry.timestamp \u003e this.#expirationTime) {\n      this.#inner.delete(key);\n      return undefined;\n    }\n    return entry.value;\n  }\n\n  /**\n   * Clear all entries.\n   */\n  clear() {\n    this.#inner.clear();\n  }\n\n  /**\n   * Entries returns the entries of the map, without the expiration time.\n   * @returns an iterator over the entries of the map.\n   */\n  entries(): IterableIterator\u003c[K, V]\u003e {\n    const iterator = this.#inner.entries();\n    const generator = function* () {\n      for (const [key, value] of iterator) {\n        yield [key, value.value] as [K, V];\n      }\n    };\n    return generator();\n  }\n\n  /**\n   * Values returns the values of the map, without the expiration time.\n   * @returns an iterator over the values of the map.\n   */\n  values(): IterableIterator\u003cV\u003e {\n    const iterator = this.#inner.values();\n    const generator = function* () {\n      for (const value of iterator) {\n        yield value.value;\n      }\n    };\n    return generator();\n  }\n\n  /**\n   * Keys returns the keys of the map\n   * @returns an iterator over the keys of the map.\n   */\n  keys(): IterableIterator\u003cK\u003e {\n    return this.#inner.keys();\n  }\n\n  /**\n   * forEach calls the callbackfn on each entry of the map.\n   * @param callbackfn to call on each entry\n   * @param thisArg to use as this when calling the callbackfn\n   */\n  forEach(callbackfn: (value: V, key: K, map: Map\u003cK, V\u003e) =\u003e void, thisArg?: ExpirableMap\u003cK, V\u003e) {\n    for (const [key, value] of this.#inner.entries()) {\n      callbackfn.call(thisArg, value.value, key, this);\n    }\n  }\n\n  /**\n   * has returns true if the key exists and has not expired.\n   * @param key K\n   * @returns true if the key exists and has not expired.\n   */\n  has(key: K): boolean {\n    return this.#inner.has(key);\n  }\n\n  /**\n   * delete the entry for the given key.\n   * @param key K\n   * @returns true if the key existed and has been deleted.\n   */\n  delete(key: K) {\n    return this.#inner.delete(key);\n  }\n\n  /**\n   * get size of the map.\n   * @returns the size of the map.\n   */\n  get size() {\n    return this.#inner.size;\n  }\n}\n","import { bufEquals } from './utils/buffer';\n\nexport const encodeLenBytes = (len: number): number =\u003e {\n  if (len \u003c= 0x7f) {\n    return 1;\n  } else if (len \u003c= 0xff) {\n    return 2;\n  } else if (len \u003c= 0xffff) {\n    return 3;\n  } else if (len \u003c= 0xffffff) {\n    return 4;\n  } else {\n    throw new Error('Length too long (\u003e 4 bytes)');\n  }\n};\n\nexport const encodeLen = (buf: Uint8Array, offset: number, len: number): number =\u003e {\n  if (len \u003c= 0x7f) {\n    buf[offset] = len;\n    return 1;\n  } else if (len \u003c= 0xff) {\n    buf[offset] = 0x81;\n    buf[offset + 1] = len;\n    return 2;\n  } else if (len \u003c= 0xffff) {\n    buf[offset] = 0x82;\n    buf[offset + 1] = len \u003e\u003e 8;\n    buf[offset + 2] = len;\n    return 3;\n  } else if (len \u003c= 0xffffff) {\n    buf[offset] = 0x83;\n    buf[offset + 1] = len \u003e\u003e 16;\n    buf[offset + 2] = len \u003e\u003e 8;\n    buf[offset + 3] = len;\n    return 4;\n  } else {\n    throw new Error('Length too long (\u003e 4 bytes)');\n  }\n};\n\nexport const decodeLenBytes = (buf: Uint8Array, offset: number): number =\u003e {\n  if (buf[offset] \u003c 0x80) return 1;\n  if (buf[offset] === 0x80) throw new Error('Invalid length 0');\n  if (buf[offset] === 0x81) return 2;\n  if (buf[offset] === 0x82) return 3;\n  if (buf[offset] === 0x83) return 4;\n  throw new Error('Length too long (\u003e 4 bytes)');\n};\n\nexport const decodeLen = (buf: Uint8Array, offset: number): number =\u003e {\n  const lenBytes = decodeLenBytes(buf, offset);\n  if (lenBytes === 1) return buf[offset];\n  else if (lenBytes === 2) return buf[offset + 1];\n  else if (lenBytes === 3) return (buf[offset + 1] \u003c\u003c 8) + buf[offset + 2];\n  else if (lenBytes === 4)\n    return (buf[offset + 1] \u003c\u003c 16) + (buf[offset + 2] \u003c\u003c 8) + buf[offset + 3];\n  throw new Error('Length too long (\u003e 4 bytes)');\n};\n\n/**\n * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE\n */\nexport const DER_COSE_OID = Uint8Array.from([\n  ...[0x30, 0x0c], // SEQUENCE\n  ...[0x06, 0x0a], // OID with 10 bytes\n  ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xb8, 0x43, 0x01, 0x01], // DER encoded COSE\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm\n */\nexport const ED25519_OID = Uint8Array.from([\n  ...[0x30, 0x05], // SEQUENCE\n  ...[0x06, 0x03], // OID with 3 bytes\n  ...[0x2b, 0x65, 0x70], // id-Ed25519 OID\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm\n */\nexport const SECP256K1_OID = Uint8Array.from([\n  ...[0x30, 0x10], // SEQUENCE\n  ...[0x06, 0x07], // OID with 7 bytes\n  ...[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01], // OID ECDSA\n  ...[0x06, 0x05], // OID with 5 bytes\n  ...[0x2b, 0x81, 0x04, 0x00, 0x0a], // OID secp256k1\n]);\n\n/**\n * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:\n * `SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param payload The payload to encode as the bit string\n * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with\n */\nexport function wrapDER(payload: ArrayBuffer, oid: Uint8Array): Uint8Array {\n  // The Bit String header needs to include the unused bit count byte in its length\n  const bitStringHeaderLength = 2 + encodeLenBytes(payload.byteLength + 1);\n  const len = oid.byteLength + bitStringHeaderLength + payload.byteLength;\n  let offset = 0;\n  const buf = new Uint8Array(1 + encodeLenBytes(len) + len);\n  // Sequence\n  buf[offset++] = 0x30;\n  // Sequence Length\n  offset += encodeLen(buf, offset, len);\n\n  // OID\n  buf.set(oid, offset);\n  offset += oid.byteLength;\n\n  // Bit String Header\n  buf[offset++] = 0x03;\n  offset += encodeLen(buf, offset, payload.byteLength + 1);\n  // 0 padding\n  buf[offset++] = 0x00;\n  buf.set(new Uint8Array(payload), offset);\n\n  return buf;\n}\n\n/**\n * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.\n *\n * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param derEncoded The DER encoded and tagged data\n * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID\n * @returns The unwrapped payload\n */\nexport const unwrapDER = (derEncoded: ArrayBuffer, oid: Uint8Array): Uint8Array =\u003e {\n  let offset = 0;\n  const expect = (n: number, msg: string) =\u003e {\n    if (buf[offset++] !== n) {\n      throw new Error('Expected: ' + msg);\n    }\n  };\n\n  const buf = new Uint8Array(derEncoded);\n  expect(0x30, 'sequence');\n  offset += decodeLenBytes(buf, offset);\n\n  if (!bufEquals(buf.slice(offset, offset + oid.byteLength), oid)) {\n    throw new Error('Not the expected OID.');\n  }\n  offset += oid.byteLength;\n\n  expect(0x03, 'bit string');\n  const payloadLen = decodeLen(buf, offset) - 1; // Subtracting 1 to account for the 0 padding\n  offset += decodeLenBytes(buf, offset);\n  expect(0x00, '0 padding');\n  const result = buf.slice(offset);\n  if (payloadLen !== result.length) {\n    throw new Error(\n      `DER payload mismatch: Expected length ${payloadLen} actual length ${result.length}`,\n    );\n  }\n  return result;\n};\n","import { DerEncodedPublicKey, PublicKey } from './auth';\nimport { ED25519_OID, unwrapDER, wrapDER } from './der';\n\nexport class Ed25519PublicKey implements PublicKey {\n  public static from(key: PublicKey): Ed25519PublicKey {\n    return this.fromDer(key.toDer());\n  }\n\n  public static fromRaw(rawKey: ArrayBuffer): Ed25519PublicKey {\n    return new Ed25519PublicKey(rawKey);\n  }\n\n  public static fromDer(derKey: DerEncodedPublicKey): Ed25519PublicKey {\n    return new Ed25519PublicKey(this.derDecode(derKey));\n  }\n\n  // The length of Ed25519 public keys is always 32 bytes.\n  private static RAW_KEY_LENGTH = 32;\n\n  private static derEncode(publicKey: ArrayBuffer): DerEncodedPublicKey {\n    return wrapDER(publicKey, ED25519_OID).buffer as DerEncodedPublicKey;\n  }\n\n  private static derDecode(key: DerEncodedPublicKey): ArrayBuffer {\n    const unwrapped = unwrapDER(key, ED25519_OID);\n    if (unwrapped.length !== this.RAW_KEY_LENGTH) {\n      throw new Error('An Ed25519 public key must be exactly 32bytes long');\n    }\n    return unwrapped;\n  }\n\n  #rawKey: ArrayBuffer;\n\n  public get rawKey(): ArrayBuffer {\n    return this.#rawKey;\n  }\n\n  #derKey: DerEncodedPublicKey;\n\n  public get derKey(): DerEncodedPublicKey {\n    return this.#derKey;\n  }\n\n  // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n  private constructor(key: ArrayBuffer) {\n    if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n      throw new Error('An Ed25519 public key must be exactly 32bytes long');\n    }\n    this.#rawKey = key;\n    this.#derKey = Ed25519PublicKey.derEncode(key);\n  }\n\n  public toDer(): DerEncodedPublicKey {\n    return this.derKey;\n  }\n\n  public toRaw(): ArrayBuffer {\n    return this.rawKey;\n  }\n}\n","import { AgentError } from './errors';\n\nexport type ObserveFunction\u003cT\u003e = (data: T, ...rest: unknown[]) =\u003e void;\n\nexport class Observable\u003cT\u003e {\n  observers: ObserveFunction\u003cT\u003e[];\n\n  constructor() {\n    this.observers = [];\n  }\n\n  subscribe(func: ObserveFunction\u003cT\u003e) {\n    this.observers.push(func);\n  }\n\n  unsubscribe(func: ObserveFunction\u003cT\u003e) {\n    this.observers = this.observers.filter(observer =\u003e observer !== func);\n  }\n\n  notify(data: T, ...rest: unknown[]) {\n    this.observers.forEach(observer =\u003e observer(data, ...rest));\n  }\n}\n\nexport type AgentLog =\n  | {\n      message: string;\n      level: 'warn' | 'info';\n    }\n  | {\n      message: string;\n      level: 'error';\n      error: AgentError;\n    };\n\nexport class ObservableLog extends Observable\u003cAgentLog\u003e {\n  constructor() {\n    super();\n  }\n  print(message: string, ...rest: unknown[]) {\n    this.notify({ message, level: 'info' }, ...rest);\n  }\n  warn(message: string, ...rest: unknown[]) {\n    this.notify({ message, level: 'warn' }, ...rest);\n  }\n  error(message: string, error: AgentError, ...rest: unknown[]) {\n    this.notify({ message, level: 'error', error }, ...rest);\n  }\n}\n","const RANDOMIZATION_FACTOR = 0.5;\nconst MULTIPLIER = 1.5;\nconst INITIAL_INTERVAL_MSEC = 500;\nconst MAX_INTERVAL_MSEC = 60_000;\nconst MAX_ELAPSED_TIME_MSEC = 900_000;\nconst MAX_ITERATIONS = 10;\n\nexport type BackoffStrategy = {\n  next: () =\u003e number | null;\n  currentInterval?: number;\n  count?: number;\n  ellapsedTimeInMsec?: number;\n};\n\nexport type BackoffStrategyArgs = {\n  maxIterations?: number;\n  maxElapsedTime?: number;\n};\n\nexport type BackoffStrategyFactory = (args?: BackoffStrategyArgs) =\u003e BackoffStrategy;\n\n// export type BackoffStrategyGenerator = Generator\u003cnumber, void, unknown\u003e;\n\nexport type ExponentialBackoffOptions = {\n  initialInterval?: number;\n  randomizationFactor?: number;\n  multiplier?: number;\n  maxInterval?: number;\n  maxElapsedTime?: number;\n  maxIterations?: number;\n  date?: DateConstructor;\n};\n\n/**\n * Exponential backoff strategy.\n */\nexport class ExponentialBackoff {\n  #currentInterval: number;\n  #randomizationFactor: number;\n  #multiplier: number;\n  #maxInterval: number;\n  #startTime: number;\n  #maxElapsedTime: number;\n  #maxIterations: number;\n  #date: DateConstructor;\n  #count = 0;\n\n  static default = {\n    initialInterval: INITIAL_INTERVAL_MSEC,\n    randomizationFactor: RANDOMIZATION_FACTOR,\n    multiplier: MULTIPLIER,\n    maxInterval: MAX_INTERVAL_MSEC,\n    // 1 minute\n    maxElapsedTime: MAX_ELAPSED_TIME_MSEC,\n    maxIterations: MAX_ITERATIONS,\n    date: Date,\n  };\n\n  constructor(options: ExponentialBackoffOptions = ExponentialBackoff.default) {\n    const {\n      initialInterval = INITIAL_INTERVAL_MSEC,\n      randomizationFactor = RANDOMIZATION_FACTOR,\n      multiplier = MULTIPLIER,\n      maxInterval = MAX_INTERVAL_MSEC,\n      maxElapsedTime = MAX_ELAPSED_TIME_MSEC,\n      maxIterations = MAX_ITERATIONS,\n      date = Date,\n    } = options;\n    this.#currentInterval = initialInterval;\n    this.#randomizationFactor = randomizationFactor;\n    this.#multiplier = multiplier;\n    this.#maxInterval = maxInterval;\n    this.#date = date;\n    this.#startTime = date.now();\n    this.#maxElapsedTime = maxElapsedTime;\n    this.#maxIterations = maxIterations;\n  }\n\n  get ellapsedTimeInMsec() {\n    return this.#date.now() - this.#startTime;\n  }\n\n  get currentInterval() {\n    return this.#currentInterval;\n  }\n\n  get count() {\n    return this.#count;\n  }\n\n  get randomValueFromInterval() {\n    const delta = this.#randomizationFactor * this.#currentInterval;\n    const min = this.#currentInterval - delta;\n    const max = this.#currentInterval + delta;\n    return Math.random() * (max - min) + min;\n  }\n\n  public incrementCurrentInterval() {\n    this.#currentInterval = Math.min(this.#currentInterval * this.#multiplier, this.#maxInterval);\n    this.#count++;\n\n    return this.#currentInterval;\n  }\n\n  public next() {\n    if (this.ellapsedTimeInMsec \u003e= this.#maxElapsedTime || this.#count \u003e= this.#maxIterations) {\n      return null;\n    } else {\n      this.incrementCurrentInterval();\n      return this.randomValueFromInterval;\n    }\n  }\n}\n/**\n * Utility function to create an exponential backoff iterator.\n * @param options - for the exponential backoff\n * @returns an iterator that yields the next delay in the exponential backoff\n * @yields the next delay in the exponential backoff\n */\nexport function* exponentialBackoff(\n  options: ExponentialBackoffOptions = ExponentialBackoff.default,\n) {\n  const backoff = new ExponentialBackoff(options);\n\n  let next = backoff.next();\n  while (next) {\n    yield next;\n    next = backoff.next();\n  }\n}\n","import { JsonObject } from '@dfinity/candid';\nimport { Principal } from '@dfinity/principal';\nimport { AgentError } from '../../errors';\nimport { AnonymousIdentity, Identity } from '../../auth';\nimport * as cbor from '../../cbor';\nimport { RequestId, hashOfMap, requestIdOf } from '../../request_id';\nimport { bufFromBufLike, concat, fromHex } from '../../utils/buffer';\nimport {\n  Agent,\n  ApiQueryResponse,\n  QueryFields,\n  QueryResponse,\n  ReadStateOptions,\n  ReadStateResponse,\n  SubmitResponse,\n} from '../api';\nimport { Expiry, httpHeadersTransform, makeNonceTransform } from './transforms';\nimport {\n  CallRequest,\n  Endpoint,\n  HttpAgentRequest,\n  HttpAgentRequestTransformFn,\n  HttpAgentSubmitRequest,\n  makeNonce,\n  Nonce,\n  QueryRequest,\n  ReadRequestType,\n  SubmitRequestType,\n} from './types';\nimport { AgentHTTPResponseError } from './errors';\nimport { SubnetStatus, request } from '../../canisterStatus';\nimport {\n  CertificateVerificationError,\n  HashTree,\n  LookupStatus,\n  lookup_path,\n} from '../../certificate';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { ExpirableMap } from '../../utils/expirableMap';\nimport { Ed25519PublicKey } from '../../public_key';\nimport { decodeTime } from '../../utils/leb';\nimport { ObservableLog } from '../../observable';\nimport { BackoffStrategy, BackoffStrategyFactory, ExponentialBackoff } from '../../polling/backoff';\nexport * from './transforms';\nexport { Nonce, makeNonce } from './types';\n\nexport enum RequestStatusResponseStatus {\n  Received = 'received',\n  Processing = 'processing',\n  Replied = 'replied',\n  Rejected = 'rejected',\n  Unknown = 'unknown',\n  Done = 'done',\n}\n\n// Default delta for ingress expiry is 5 minutes.\nconst DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;\n\n// Root public key for the IC, encoded as hex\nexport const IC_ROOT_KEY =\n  '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +\n  'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +\n  '5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +\n  'b01291091c5f87b98883463f98091a0baaae';\n\nexport const MANAGEMENT_CANISTER_ID = 'aaaaa-aa';\n\n// IC0 domain info\nconst IC0_DOMAIN = 'ic0.app';\nconst IC0_SUB_DOMAIN = '.ic0.app';\n\nconst ICP0_DOMAIN = 'icp0.io';\nconst ICP0_SUB_DOMAIN = '.icp0.io';\n\nconst ICP_API_DOMAIN = 'icp-api.io';\nconst ICP_API_SUB_DOMAIN = '.icp-api.io';\n\nclass HttpDefaultFetchError extends AgentError {\n  constructor(public readonly message: string) {\n    super(message);\n  }\n}\nexport class IdentityInvalidError extends AgentError {\n  constructor(public readonly message: string) {\n    super(message);\n  }\n}\n\n// HttpAgent options that can be used at construction.\nexport interface HttpAgentOptions {\n  // Another HttpAgent to inherit configuration (pipeline and fetch) of. This\n  // is only used at construction.\n  source?: HttpAgent;\n\n  // A surrogate to the global fetch function. Useful for testing.\n  fetch?: typeof fetch;\n\n  // Additional options to pass along to fetch. Will not override fields that\n  // the agent already needs to set\n  // Should follow the RequestInit interface, but we intentially support non-standard fields\n  fetchOptions?: Record\u003cstring, unknown\u003e;\n\n  // Additional options to pass along to fetch for the call API.\n  callOptions?: Record\u003cstring, unknown\u003e;\n\n  // The host to use for the client. By default, uses the same host as\n  // the current page.\n  host?: string;\n\n  // The principal used to send messages. This cannot be empty at the request\n  // time (will throw).\n  identity?: Identity | Promise\u003cIdentity\u003e;\n\n  credentials?: {\n    name: string;\n    password?: string;\n  };\n  /**\n   * Adds a unique {@link Nonce} with each query.\n   * Enabling will prevent queries from being answered with a cached response.\n   * @example\n   * const agent = new HttpAgent({ useQueryNonces: true });\n   * agent.addTransform(makeNonceTransform(makeNonce);\n   * @default false\n   */\n  useQueryNonces?: boolean;\n  /**\n   * Number of times to retry requests before throwing an error\n   * @default 3\n   */\n  retryTimes?: number;\n  /**\n   * The strategy to use for backoff when retrying requests\n   */\n  backoffStrategy?: BackoffStrategyFactory;\n  /**\n   * Whether the agent should verify signatures signed by node keys on query responses. Increases security, but adds overhead and must make a separate request to cache the node keys for the canister's subnet.\n   * @default true\n   */\n  verifyQuerySignatures?: boolean;\n  /**\n   * Whether to log to the console. Defaults to false.\n   */\n  logToConsole?: boolean;\n}\n\nfunction getDefaultFetch(): typeof fetch {\n  let defaultFetch;\n\n  if (typeof window !== 'undefined') {\n    // Browser context\n    if (window.fetch) {\n      defaultFetch = window.fetch.bind(window);\n    } else {\n      throw new HttpDefaultFetchError(\n        'Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.',\n      );\n    }\n  } else if (typeof global !== 'undefined') {\n    // Node context\n    if (global.fetch) {\n      defaultFetch = global.fetch.bind(global);\n    } else {\n      throw new HttpDefaultFetchError(\n        'Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.',\n      );\n    }\n  } else if (typeof self !== 'undefined') {\n    if (self.fetch) {\n      defaultFetch = self.fetch.bind(self);\n    }\n  }\n\n  if (defaultFetch) {\n    return defaultFetch;\n  }\n  throw new HttpDefaultFetchError(\n    'Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.',\n  );\n}\n\n// A HTTP agent allows users to interact with a client of the internet computer\n// using the available methods. It exposes an API that closely follows the\n// public view of the internet computer, and is not intended to be exposed\n// directly to the majority of users due to its low-level interface.\n//\n// There is a pipeline to apply transformations to the request before sending\n// it to the client. This is to decouple signature, nonce generation and\n// other computations so that this class can stay as simple as possible while\n// allowing extensions.\nexport class HttpAgent implements Agent {\n  public rootKey = fromHex(IC_ROOT_KEY);\n  private _identity: Promise\u003cIdentity\u003e | null;\n  private readonly _fetch: typeof fetch;\n  private readonly _fetchOptions?: Record\u003cstring, unknown\u003e;\n  private readonly _callOptions?: Record\u003cstring, unknown\u003e;\n  private _timeDiffMsecs = 0;\n  private readonly _host: URL;\n  private readonly _credentials: string | undefined;\n  private _rootKeyFetched = false;\n  #retryTimes; // Retry requests N times before erroring by default\n  #backoffStrategy: BackoffStrategyFactory;\n  public readonly _isAgent = true;\n\n  // The UTC time in milliseconds when the latest request was made\n  #waterMark = 0;\n\n  get waterMark(): number {\n    return this.#waterMark;\n  }\n\n  public log: ObservableLog = new ObservableLog();\n\n  #queryPipeline: HttpAgentRequestTransformFn[] = [];\n  #updatePipeline: HttpAgentRequestTransformFn[] = [];\n\n  #subnetKeys: ExpirableMap\u003cstring, SubnetStatus\u003e = new ExpirableMap({\n    expirationTime: 5 * 60 * 1000, // 5 minutes\n  });\n  #verifyQuerySignatures = true;\n\n  constructor(options: HttpAgentOptions = {}) {\n    if (options.source) {\n      if (!(options.source instanceof HttpAgent)) {\n        throw new Error(\"An Agent's source can only be another HttpAgent\");\n      }\n      this._identity = options.source._identity;\n      this._fetch = options.source._fetch;\n      this._host = options.source._host;\n      this._credentials = options.source._credentials;\n    } else {\n      this._fetch = options.fetch || getDefaultFetch() || fetch.bind(global);\n      this._fetchOptions = options.fetchOptions;\n      this._callOptions = options.callOptions;\n    }\n    if (options.host !== undefined) {\n      if (!options.host.match(/^[a-z]+:/) \u0026\u0026 typeof window !== 'undefined') {\n        this._host = new URL(window.location.protocol + '//' + options.host);\n      } else {\n        this._host = new URL(options.host);\n      }\n    } else if (options.source !== undefined) {\n      // Safe to ignore here.\n      this._host = options.source._host;\n    } else {\n      const location = typeof window !== 'undefined' ? window.location : undefined;\n      if (!location) {\n        this._host = new URL('https://icp-api.io');\n        this.log.warn(\n          'Could not infer host from window.location, defaulting to mainnet gateway of https://icp-api.io. Please provide a host to the HttpAgent constructor to avoid this warning.',\n        );\n      }\n      // Mainnet, local, and remote environments will have the api route available\n      const knownHosts = ['ic0.app', 'icp0.io', '127.0.0.1', 'localhost'];\n      const remoteHosts = ['.github.dev', '.gitpod.io'];\n      const hostname = location?.hostname;\n      let knownHost;\n      if (hostname \u0026\u0026 typeof hostname === 'string') {\n        if (remoteHosts.some(host =\u003e hostname.endsWith(host))) {\n          knownHost = hostname;\n        } else {\n          knownHost = knownHosts.find(host =\u003e hostname.endsWith(host));\n        }\n      }\n\n      if (location \u0026\u0026 knownHost) {\n        // If the user is on a boundary-node provided host, we can use the same host for the agent\n        this._host = new URL(\n          `${location.protocol}//${knownHost}${location.port ? ':' + location.port : ''}`,\n        );\n      } else {\n        this._host = new URL('https://icp-api.io');\n        this.log.warn(\n          'Could not infer host from window.location, defaulting to mainnet gateway of https://icp-api.io. Please provide a host to the HttpAgent constructor to avoid this warning.',\n        );\n      }\n    }\n    if (options.verifyQuerySignatures !== undefined) {\n      this.#verifyQuerySignatures = options.verifyQuerySignatures;\n    }\n    // Default is 3\n    this.#retryTimes = options.retryTimes ?? 3;\n    // Delay strategy for retries. Default is exponential backoff\n    const defaultBackoffFactory = () =\u003e\n      new ExponentialBackoff({\n        maxIterations: this.#retryTimes,\n      });\n    this.#backoffStrategy = options.backoffStrategy || defaultBackoffFactory;\n    // Rewrite to avoid redirects\n    if (this._host.hostname.endsWith(IC0_SUB_DOMAIN)) {\n      this._host.hostname = IC0_DOMAIN;\n    } else if (this._host.hostname.endsWith(ICP0_SUB_DOMAIN)) {\n      this._host.hostname = ICP0_DOMAIN;\n    } else if (this._host.hostname.endsWith(ICP_API_SUB_DOMAIN)) {\n      this._host.hostname = ICP_API_DOMAIN;\n    }\n\n    if (options.credentials) {\n      const { name, password } = options.credentials;\n      this._credentials = `${name}${password ? ':' + password : ''}`;\n    }\n    this._identity = Promise.resolve(options.identity || new AnonymousIdentity());\n\n    // Add a nonce transform to ensure calls are unique\n    this.addTransform('update', makeNonceTransform(makeNonce));\n    if (options.useQueryNonces) {\n      this.addTransform('query', makeNonceTransform(makeNonce));\n    }\n    if (options.logToConsole) {\n      this.log.subscribe(log =\u003e {\n        if (log.level === 'error') {\n          console.error(log.message);\n        } else if (log.level === 'warn') {\n          console.warn(log.message);\n        } else {\n          console.log(log.message);\n        }\n      });\n    }\n  }\n\n  public isLocal(): boolean {\n    const hostname = this._host.hostname;\n    return hostname === '127.0.0.1' || hostname.endsWith('127.0.0.1');\n  }\n\n  public addTransform(\n    type: 'update' | 'query',\n    fn: HttpAgentRequestTransformFn,\n    priority = fn.priority || 0,\n  ): void {\n    if (type === 'update') {\n      // Keep the pipeline sorted at all time, by priority.\n      const i = this.#updatePipeline.findIndex(x =\u003e (x.priority || 0) \u003c priority);\n      this.#updatePipeline.splice(\n        i \u003e= 0 ? i : this.#updatePipeline.length,\n        0,\n        Object.assign(fn, { priority }),\n      );\n    } else if (type === 'query') {\n      // Keep the pipeline sorted at all time, by priority.\n      const i = this.#queryPipeline.findIndex(x =\u003e (x.priority || 0) \u003c priority);\n      this.#queryPipeline.splice(\n        i \u003e= 0 ? i : this.#queryPipeline.length,\n        0,\n        Object.assign(fn, { priority }),\n      );\n    }\n  }\n\n  public async getPrincipal(): Promise\u003cPrincipal\u003e {\n    if (!this._identity) {\n      throw new IdentityInvalidError(\n        \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n      );\n    }\n    return (await this._identity).getPrincipal();\n  }\n\n  public async call(\n    canisterId: Principal | string,\n    options: {\n      methodName: string;\n      arg: ArrayBuffer;\n      effectiveCanisterId?: Principal | string;\n    },\n    identity?: Identity | Promise\u003cIdentity\u003e,\n  ): Promise\u003cSubmitResponse\u003e {\n    const id = await (identity !== undefined ? await identity : await this._identity);\n    if (!id) {\n      throw new IdentityInvalidError(\n        \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n      );\n    }\n    const canister = Principal.from(canisterId);\n    const ecid = options.effectiveCanisterId\n      ? Principal.from(options.effectiveCanisterId)\n      : canister;\n\n    const sender: Principal = id.getPrincipal() || Principal.anonymous();\n\n    let ingress_expiry = new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS);\n\n    // If the value is off by more than 30 seconds, reconcile system time with the network\n    if (Math.abs(this._timeDiffMsecs) \u003e 1_000 * 30) {\n      ingress_expiry = new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS + this._timeDiffMsecs);\n    }\n\n    const submit: CallRequest = {\n      request_type: SubmitRequestType.Call,\n      canister_id: canister,\n      method_name: options.methodName,\n      arg: options.arg,\n      sender,\n      ingress_expiry,\n    };\n\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    let transformedRequest: any = (await this._transform({\n      request: {\n        body: null,\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/cbor',\n          ...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),\n        },\n      },\n      endpoint: Endpoint.Call,\n      body: submit,\n    })) as HttpAgentSubmitRequest;\n\n    // Apply transform for identity.\n    transformedRequest = await id.transformRequest(transformedRequest);\n\n    const body = cbor.encode(transformedRequest.body);\n\n    this.log.print(\n      `fetching \"/api/v2/canister/${ecid.toText()}/call\" with request:`,\n      transformedRequest,\n    );\n\n    // Run both in parallel. The fetch is quite expensive, so we have plenty of time to\n    // calculate the requestId locally.\n    const backoff = this.#backoffStrategy();\n    const request = this.#requestAndRetry({\n      request: () =\u003e\n        this._fetch('' + new URL(`/api/v2/canister/${ecid.toText()}/call`, this._host), {\n          ...this._callOptions,\n          ...transformedRequest.request,\n          body,\n        }),\n      backoff,\n      tries: 0,\n    });\n\n    const [response, requestId] = await Promise.all([request, requestIdOf(submit)]);\n\n    const responseBuffer = await response.arrayBuffer();\n    const responseBody = (\n      response.status === 200 \u0026\u0026 responseBuffer.byteLength \u003e 0 ? cbor.decode(responseBuffer) : null\n    ) as SubmitResponse['response']['body'];\n\n    return {\n      requestId,\n      response: {\n        ok: response.ok,\n        status: response.status,\n        statusText: response.statusText,\n        body: responseBody,\n        headers: httpHeadersTransform(response.headers),\n      },\n    };\n  }\n\n  async #requestAndRetryQuery(args: {\n    ecid: Principal;\n    transformedRequest: HttpAgentRequest;\n    body: ArrayBuffer;\n    requestId: RequestId;\n    backoff: BackoffStrategy;\n    tries: number;\n  }): Promise\u003cApiQueryResponse\u003e {\n    const { ecid, transformedRequest, body, requestId, backoff, tries } = args;\n\n    const delay = tries === 0 ? 0 : backoff.next();\n    this.log.print(`fetching \"/api/v2/canister/${ecid.toString()}/query\" with tries:`, {\n      tries,\n      backoff,\n      delay,\n    });\n\n    // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n    if (delay === null) {\n      throw new AgentError(\n        `Timestamp failed to pass the watermark after retrying the configured ${\n          this.#retryTimes\n        } times. We cannot guarantee the integrity of the response since it could be a replay attack.`,\n      );\n    }\n\n    if (delay \u003e 0) {\n      await new Promise(resolve =\u003e setTimeout(resolve, delay));\n    }\n    let response: ApiQueryResponse;\n    // Make the request and retry if it throws an error\n    try {\n      this.log.print(\n        `fetching \"/api/v2/canister/${ecid.toString()}/query\" with request:`,\n        transformedRequest,\n      );\n      const fetchResponse = await this._fetch(\n        '' + new URL(`/api/v2/canister/${ecid.toString()}/query`, this._host),\n        {\n          ...this._fetchOptions,\n          ...transformedRequest.request,\n          body,\n        },\n      );\n      if (fetchResponse.status === 200) {\n        const queryResponse: QueryResponse = cbor.decode(await fetchResponse.arrayBuffer());\n        response = {\n          ...queryResponse,\n          httpDetails: {\n            ok: fetchResponse.ok,\n            status: fetchResponse.status,\n            statusText: fetchResponse.statusText,\n            headers: httpHeadersTransform(fetchResponse.headers),\n          },\n          requestId,\n        };\n      } else {\n        throw new AgentHTTPResponseError(\n          `Gateway returned an error:\\n` +\n            `  Code: ${fetchResponse.status} (${fetchResponse.statusText})\\n` +\n            `  Body: ${await fetchResponse.text()}\\n`,\n          {\n            ok: fetchResponse.ok,\n            status: fetchResponse.status,\n            statusText: fetchResponse.statusText,\n            headers: httpHeadersTransform(fetchResponse.headers),\n          },\n        );\n      }\n    } catch (error) {\n      if (tries \u003c this.#retryTimes) {\n        this.log.warn(\n          `Caught exception while attempting to make query:\\n` +\n            `  ${error}\\n` +\n            `  Retrying query.`,\n        );\n        return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });\n      }\n      throw error;\n    }\n\n    const timestamp = response.signatures?.[0]?.timestamp;\n\n    // Skip watermark verification if the user has set verifyQuerySignatures to false\n    if (!this.#verifyQuerySignatures) {\n      return response;\n    }\n\n    if (!timestamp) {\n      throw new Error(\n        'Timestamp not found in query response. This suggests a malformed or malicious response.',\n      );\n    }\n\n    // Convert the timestamp to milliseconds\n    const timeStampInMs = Number(BigInt(timestamp) / BigInt(1_000_000));\n\n    this.log.print('watermark and timestamp', {\n      waterMark: this.waterMark,\n      timestamp: timeStampInMs,\n    });\n\n    // If the timestamp is less than the watermark, retry the request up to the retry limit\n    if (Number(this.waterMark) \u003e timeStampInMs) {\n      const error = new AgentError('Timestamp is below the watermark. Retrying query.');\n      this.log.error('Timestamp is below', error, {\n        timestamp,\n        waterMark: this.waterMark,\n      });\n      if (tries \u003c this.#retryTimes) {\n        return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });\n      }\n      {\n        throw new AgentError(\n          `Timestamp failed to pass the watermark after retrying the configured ${\n            this.#retryTimes\n          } times. We cannot guarantee the integrity of the response since it could be a replay attack.`,\n        );\n      }\n    }\n\n    return response;\n  }\n\n  async #requestAndRetry(args: {\n    request: () =\u003e Promise\u003cResponse\u003e;\n    backoff: BackoffStrategy;\n    tries: number;\n  }): Promise\u003cResponse\u003e {\n    const { request, backoff, tries } = args;\n    const delay = tries === 0 ? 0 : backoff.next();\n\n    // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n    if (delay === null) {\n      throw new AgentError(\n        `Timestamp failed to pass the watermark after retrying the configured ${\n          this.#retryTimes\n        } times. We cannot guarantee the integrity of the response since it could be a replay attack.`,\n      );\n    }\n\n    if (delay \u003e 0) {\n      await new Promise(resolve =\u003e setTimeout(resolve, delay));\n    }\n\n    let response: Response;\n    try {\n      response = await request();\n    } catch (error) {\n      if (this.#retryTimes \u003e tries) {\n        this.log.warn(\n          `Caught exception while attempting to make request:\\n` +\n            `  ${error}\\n` +\n            `  Retrying request.`,\n        );\n        // Delay the request by the configured backoff strategy\n        return await this.#requestAndRetry({ request, backoff, tries: tries + 1 });\n      }\n      throw error;\n    }\n    if (response.ok) {\n      return response;\n    }\n\n    const responseText = await response.clone().text();\n    const errorMessage =\n      `Server returned an error:\\n` +\n      `  Code: ${response.status} (${response.statusText})\\n` +\n      `  Body: ${responseText}\\n`;\n\n    if (tries \u003c this.#retryTimes) {\n      return await this.#requestAndRetry({ request, backoff, tries: tries + 1 });\n    }\n    throw new AgentHTTPResponseError(errorMessage, {\n      ok: response.ok,\n      status: response.status,\n      statusText: response.statusText,\n      headers: httpHeadersTransform(response.headers),\n    });\n  }\n\n  public async query(\n    canisterId: Principal | string,\n    fields: QueryFields,\n    identity?: Identity | Promise\u003cIdentity\u003e,\n  ): Promise\u003cApiQueryResponse\u003e {\n    const backoff = this.#backoffStrategy();\n    const ecid = fields.effectiveCanisterId\n      ? Principal.from(fields.effectiveCanisterId)\n      : Principal.from(canisterId);\n\n    this.log.print(`ecid ${ecid.toString()}`);\n    this.log.print(`canisterId ${canisterId.toString()}`);\n    const makeQuery = async () =\u003e {\n      const id = await (identity !== undefined ? await identity : await this._identity);\n      if (!id) {\n        throw new IdentityInvalidError(\n          \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n        );\n      }\n\n      const canister = Principal.from(canisterId);\n      const sender = id?.getPrincipal() || Principal.anonymous();\n\n      const request: QueryRequest = {\n        request_type: ReadRequestType.Query,\n        canister_id: canister,\n        method_name: fields.methodName,\n        arg: fields.arg,\n        sender,\n        ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),\n      };\n\n      const requestId = await requestIdOf(request);\n\n      // TODO: remove this any. This can be a Signed or UnSigned request.\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      let transformedRequest: HttpAgentRequest = await this._transform({\n        request: {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application/cbor',\n            ...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),\n          },\n        },\n        endpoint: Endpoint.Query,\n        body: request,\n      });\n\n      // Apply transform for identity.\n      transformedRequest = (await id?.transformRequest(transformedRequest)) as HttpAgentRequest;\n\n      const body = cbor.encode(transformedRequest.body);\n\n      const args = {\n        canister: canister.toText(),\n        ecid,\n        transformedRequest,\n        body,\n        requestId,\n        backoff,\n        tries: 0,\n      };\n\n      return await this.#requestAndRetryQuery(args);\n    };\n\n    const getSubnetStatus = async (): Promise\u003cSubnetStatus | void\u003e =\u003e {\n      if (!this.#verifyQuerySignatures) {\n        return undefined;\n      }\n      const subnetStatus = this.#subnetKeys.get(ecid.toString());\n      if (subnetStatus) {\n        return subnetStatus;\n      }\n      await this.fetchSubnetKeys(ecid.toString());\n      return this.#subnetKeys.get(ecid.toString());\n    };\n    // Attempt to make the query i=retryTimes times\n    // Make query and fetch subnet keys in parallel\n    const [query, subnetStatus] = await Promise.all([makeQuery(), getSubnetStatus()]);\n\n    this.log.print('Query response:', query);\n    // Skip verification if the user has disabled it\n    if (!this.#verifyQuerySignatures) {\n      return query;\n    }\n\n    try {\n      return this.#verifyQueryResponse(query, subnetStatus);\n    } catch (_) {\n      // In case the node signatures have changed, refresh the subnet keys and try again\n      this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');\n      this.#subnetKeys.delete(canisterId.toString());\n      await this.fetchSubnetKeys(ecid.toString());\n\n      const updatedSubnetStatus = this.#subnetKeys.get(canisterId.toString());\n      if (!updatedSubnetStatus) {\n        throw new CertificateVerificationError(\n          'Invalid signature from replica signed query: no matching node key found.',\n        );\n      }\n      return this.#verifyQueryResponse(query, updatedSubnetStatus);\n    }\n  }\n\n  /**\n   * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation\n   * @param queryResponse - The response from the query\n   * @param subnetStatus - The subnet status, including all node keys\n   * @returns ApiQueryResponse\n   */\n  #verifyQueryResponse = (\n    queryResponse: ApiQueryResponse,\n    subnetStatus: SubnetStatus | void,\n  ): ApiQueryResponse =\u003e {\n    if (this.#verifyQuerySignatures === false) {\n      // This should not be called if the user has disabled verification\n      return queryResponse;\n    }\n    if (!subnetStatus) {\n      throw new CertificateVerificationError(\n        'Invalid signature from replica signed query: no matching node key found.',\n      );\n    }\n    const { status, signatures = [], requestId } = queryResponse;\n\n    const domainSeparator = new TextEncoder().encode('\\x0Bic-response');\n    for (const sig of signatures) {\n      const { timestamp, identity } = sig;\n      const nodeId = Principal.fromUint8Array(identity).toText();\n      let hash: ArrayBuffer;\n\n      // Hash is constructed differently depending on the status\n      if (status === 'replied') {\n        const { reply } = queryResponse;\n        hash = hashOfMap({\n          status: status,\n          reply: reply,\n          timestamp: BigInt(timestamp),\n          request_id: requestId,\n        });\n      } else if (status === 'rejected') {\n        const { reject_code, reject_message, error_code } = queryResponse;\n        hash = hashOfMap({\n          status: status,\n          reject_code: reject_code,\n          reject_message: reject_message,\n          error_code: error_code,\n          timestamp: BigInt(timestamp),\n          request_id: requestId,\n        });\n      } else {\n        throw new Error(`Unknown status: ${status}`);\n      }\n\n      const separatorWithHash = concat(domainSeparator, new Uint8Array(hash));\n\n      // FIX: check for match without verifying N times\n      const pubKey = subnetStatus?.nodeKeys.get(nodeId);\n      if (!pubKey) {\n        throw new CertificateVerificationError(\n          'Invalid signature from replica signed query: no matching node key found.',\n        );\n      }\n      const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;\n      const valid = ed25519.verify(\n        sig.signature,\n        new Uint8Array(separatorWithHash),\n        new Uint8Array(rawKey),\n      );\n      if (valid) return queryResponse;\n\n      throw new CertificateVerificationError(\n        `Invalid signature from replica ${nodeId} signed query.`,\n      );\n    }\n    return queryResponse;\n  };\n\n  public async createReadStateRequest(\n    fields: ReadStateOptions,\n    identity?: Identity | Promise\u003cIdentity\u003e,\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  ): Promise\u003cany\u003e {\n    const id = await (identity !== undefined ? await identity : await this._identity);\n    if (!id) {\n      throw new IdentityInvalidError(\n        \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n      );\n    }\n    const sender = id?.getPrincipal() || Principal.anonymous();\n\n    // TODO: remove this any. This can be a Signed or UnSigned request.\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    const transformedRequest: any = await this._transform({\n      request: {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/cbor',\n          ...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),\n        },\n      },\n      endpoint: Endpoint.ReadState,\n      body: {\n        request_type: ReadRequestType.ReadState,\n        paths: fields.paths,\n        sender,\n        ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),\n      },\n    });\n\n    // Apply transform for identity.\n    return id?.transformRequest(transformedRequest);\n  }\n\n  public async readState(\n    canisterId: Principal | string,\n    fields: ReadStateOptions,\n    identity?: Identity | Promise\u003cIdentity\u003e,\n    // eslint-disable-next-line\n    request?: any,\n  ): Promise\u003cReadStateResponse\u003e {\n    const canister = typeof canisterId === 'string' ? Principal.fromText(canisterId) : canisterId;\n\n    const transformedRequest = request ?? (await this.createReadStateRequest(fields, identity));\n    const body = cbor.encode(transformedRequest.body);\n\n    this.log.print(\n      `fetching \"/api/v2/canister/${canister}/read_state\" with request:`,\n      transformedRequest,\n    );\n    // TODO - https://dfinity.atlassian.net/browse/SDK-1092\n    const backoff = this.#backoffStrategy();\n\n    const response = await this.#requestAndRetry({\n      request: () =\u003e\n        this._fetch(\n          '' + new URL(`/api/v2/canister/${canister.toString()}/read_state`, this._host),\n          {\n            ...this._fetchOptions,\n            ...transformedRequest.request,\n            body,\n          },\n        ),\n      backoff,\n      tries: 0,\n    });\n\n    if (!response.ok) {\n      throw new Error(\n        `Server returned an error:\\n` +\n          `  Code: ${response.status} (${response.statusText})\\n` +\n          `  Body: ${await response.text()}\\n`,\n      );\n    }\n    const decodedResponse: ReadStateResponse = cbor.decode(await response.arrayBuffer());\n\n    this.log.print('Read state response:', decodedResponse);\n    const parsedTime = await this.parseTimeFromResponse(decodedResponse);\n    if (parsedTime \u003e 0) {\n      this.log.print('Read state response time:', parsedTime);\n      this.#waterMark = parsedTime;\n    }\n\n    return decodedResponse;\n  }\n\n  public async parseTimeFromResponse(response: ReadStateResponse): Promise\u003cnumber\u003e {\n    let tree: HashTree;\n    if (response.certificate) {\n      const decoded: { tree: HashTree } | undefined = cbor.decode(response.certificate);\n      if (decoded \u0026\u0026 'tree' in decoded) {\n        tree = decoded.tree;\n      } else {\n        throw new Error('Could not decode time from response');\n      }\n      const timeLookup = lookup_path(['time'], tree);\n      if (timeLookup.status !== LookupStatus.Found) {\n        throw new Error('Time was not found in the response or was not in its expected format.');\n      }\n\n      if (!(timeLookup.value instanceof ArrayBuffer) \u0026\u0026 !ArrayBuffer.isView(timeLookup)) {\n        throw new Error('Time was not found in the response or was not in its expected format.');\n      }\n      const date = decodeTime(bufFromBufLike(timeLookup.value as ArrayBuffer));\n      this.log.print('Time from response:', date);\n      this.log.print('Time from response in milliseconds:', Number(date));\n      return Number(date);\n    } else {\n      this.log.warn('No certificate found in response');\n    }\n    return 0;\n  }\n\n  /**\n   * Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request\n   * @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default\n   */\n  public async syncTime(canisterId?: Principal): Promise\u003cvoid\u003e {\n    const CanisterStatus = await import('../../canisterStatus');\n    const callTime = Date.now();\n    try {\n      if (!canisterId) {\n        this.log.print(\n          'Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai',\n        );\n      }\n      const status = await CanisterStatus.request({\n        // Fall back with canisterId of the ICP Ledger\n        canisterId: canisterId ?? Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),\n        agent: this,\n        paths: ['time'],\n      });\n\n      const replicaTime = status.get('time');\n      if (replicaTime) {\n        this._timeDiffMsecs = Number(replicaTime as bigint) - Number(callTime);\n      }\n    } catch (error) {\n      this.log.error('Caught exception while attempting to sync time', error as AgentError);\n    }\n  }\n\n  public async status(): Promise\u003cJsonObject\u003e {\n    const headers: Record\u003cstring, string\u003e = this._credentials\n      ? {\n          Authorization: 'Basic ' + btoa(this._credentials),\n        }\n      : {};\n\n    this.log.print(`fetching \"/api/v2/status\"`);\n    const backoff = this.#backoffStrategy();\n    const response = await this.#requestAndRetry({\n      backoff,\n      request: () =\u003e\n        this._fetch('' + new URL(`/api/v2/status`, this._host), { headers, ...this._fetchOptions }),\n      tries: 0,\n    });\n    return cbor.decode(await response.arrayBuffer());\n  }\n\n  public async fetchRootKey(): Promise\u003cArrayBuffer\u003e {\n    if (!this._rootKeyFetched) {\n      // Hex-encoded version of the replica root key\n      this.rootKey = ((await this.status()) as JsonObject \u0026 { root_key: ArrayBuffer }).root_key;\n      this._rootKeyFetched = true;\n    }\n    return this.rootKey;\n  }\n\n  public invalidateIdentity(): void {\n    this._identity = null;\n  }\n\n  public replaceIdentity(identity: Identity): void {\n    this._identity = Promise.resolve(identity);\n  }\n\n  public async fetchSubnetKeys(canisterId: Principal | string) {\n    const effectiveCanisterId: Principal = Principal.from(canisterId);\n    const response = await request({\n      canisterId: effectiveCanisterId,\n      paths: ['subnet'],\n      agent: this,\n    });\n\n    const subnetResponse = response.get('subnet');\n    if (subnetResponse \u0026\u0026 typeof subnetResponse === 'object' \u0026\u0026 'nodeKeys' in subnetResponse) {\n      this.#subnetKeys.set(effectiveCanisterId.toText(), subnetResponse as SubnetStatus);\n      return subnetResponse as SubnetStatus;\n    }\n    // If the subnet status is not returned, return undefined\n    return undefined;\n  }\n\n  protected _transform(request: HttpAgentRequest): Promise\u003cHttpAgentRequest\u003e {\n    let p = Promise.resolve(request);\n    if (request.endpoint === Endpoint.Call) {\n      for (const fn of this.#updatePipeline) {\n        p = p.then(r =\u003e fn(r).then(r2 =\u003e r2 || r));\n      }\n    } else {\n      for (const fn of this.#queryPipeline) {\n        p = p.then(r =\u003e fn(r).then(r2 =\u003e r2 || r));\n      }\n    }\n\n    return p;\n  }\n}\n","import { JsonObject } from '@dfinity/candid';\nimport {\n  Agent,\n  ApiQueryResponse,\n  CallOptions,\n  QueryFields,\n  QueryResponse,\n  ReadStateOptions,\n  ReadStateResponse,\n  SubmitResponse,\n} from './api';\nimport { Principal } from '@dfinity/principal';\n\nexport enum ProxyMessageKind {\n  Error = 'err',\n  GetPrincipal = 'gp',\n  GetPrincipalResponse = 'gpr',\n  Query = 'q',\n  QueryResponse = 'qr',\n  Call = 'c',\n  CallResponse = 'cr',\n  ReadState = 'rs',\n  ReadStateResponse = 'rsr',\n  Status = 's',\n  StatusResponse = 'sr',\n}\n\nexport interface ProxyMessageBase {\n  id: number;\n  type: ProxyMessageKind;\n}\n\nexport interface ProxyMessageError extends ProxyMessageBase {\n  type: ProxyMessageKind.Error;\n  error: any;\n}\n\nexport interface ProxyMessageGetPrincipal extends ProxyMessageBase {\n  type: ProxyMessageKind.GetPrincipal;\n}\n\nexport interface ProxyMessageGetPrincipalResponse extends ProxyMessageBase {\n  type: ProxyMessageKind.GetPrincipalResponse;\n  response: string;\n}\n\nexport interface ProxyMessageQuery extends ProxyMessageBase {\n  type: ProxyMessageKind.Query;\n  args: [string, QueryFields];\n}\n\nexport interface ProxyMessageQueryResponse extends ProxyMessageBase {\n  type: ProxyMessageKind.QueryResponse;\n  response: QueryResponse;\n}\n\nexport interface ProxyMessageCall extends ProxyMessageBase {\n  type: ProxyMessageKind.Call;\n  args: [string, CallOptions];\n}\n\nexport interface ProxyMessageCallResponse extends ProxyMessageBase {\n  type: ProxyMessageKind.CallResponse;\n  response: SubmitResponse;\n}\n\nexport interface ProxyMessageReadState extends ProxyMessageBase {\n  type: ProxyMessageKind.ReadState;\n  args: [string, ReadStateOptions];\n}\n\nexport interface ProxyMessageReadStateResponse extends ProxyMessageBase {\n  type: ProxyMessageKind.ReadStateResponse;\n  response: ReadStateResponse;\n}\n\nexport interface ProxyMessageStatus extends ProxyMessageBase {\n  type: ProxyMessageKind.Status;\n}\n\nexport interface ProxyMessageStatusResponse extends ProxyMessageBase {\n  type: ProxyMessageKind.StatusResponse;\n  response: JsonObject;\n}\n\nexport type ProxyMessage =\n  | ProxyMessageError\n  | ProxyMessageGetPrincipal\n  | ProxyMessageGetPrincipalResponse\n  | ProxyMessageQuery\n  | ProxyMessageQueryResponse\n  | ProxyMessageCall\n  | ProxyMessageReadState\n  | ProxyMessageReadStateResponse\n  | ProxyMessageCallResponse\n  | ProxyMessageStatus\n  | ProxyMessageStatusResponse;\n\n// A Stub Agent that forwards calls to another Agent implementation.\nexport class ProxyStubAgent {\n  constructor(private _frontend: (msg: ProxyMessage) =\u003e void, private _agent: Agent) {}\n\n  public onmessage(msg: ProxyMessage): void {\n    switch (msg.type) {\n      case ProxyMessageKind.GetPrincipal:\n        this._agent.getPrincipal().then(response =\u003e {\n          this._frontend({\n            id: msg.id,\n            type: ProxyMessageKind.GetPrincipalResponse,\n            response: response.toText(),\n          });\n        });\n        break;\n      case ProxyMessageKind.Query:\n        this._agent.query(...msg.args).then(response =\u003e {\n          this._frontend({\n            id: msg.id,\n            type: ProxyMessageKind.QueryResponse,\n            response,\n          });\n        });\n        break;\n      case ProxyMessageKind.Call:\n        this._agent.call(...msg.args).then(response =\u003e {\n          this._frontend({\n            id: msg.id,\n            type: ProxyMessageKind.CallResponse,\n            response,\n          });\n        });\n        break;\n      case ProxyMessageKind.ReadState:\n        this._agent.readState(...msg.args).then(response =\u003e {\n          this._frontend({\n            id: msg.id,\n            type: ProxyMessageKind.ReadStateResponse,\n            response,\n          });\n        });\n        break;\n      case ProxyMessageKind.Status:\n        this._agent.status().then(response =\u003e {\n          this._frontend({\n            id: msg.id,\n            type: ProxyMessageKind.StatusResponse,\n            response,\n          });\n        });\n        break;\n\n      default:\n        throw new Error(`Invalid message received: ${JSON.stringify(msg)}`);\n    }\n  }\n}\n\n// An Agent that forwards calls to a backend. The calls are serialized\nexport class ProxyAgent implements Agent {\n  private _nextId = 0;\n  private _pendingCalls = new Map\u003cnumber, [(resolve: any) =\u003e void, (reject: any) =\u003e void]\u003e();\n  public rootKey = null;\n\n  constructor(private _backend: (msg: ProxyMessage) =\u003e void) {}\n\n  public onmessage(msg: ProxyMessage): void {\n    const id = msg.id;\n\n    const maybePromise = this._pendingCalls.get(id);\n    if (!maybePromise) {\n      throw new Error('A proxy get the same message twice...');\n    }\n\n    this._pendingCalls.delete(id);\n    const [resolve, reject] = maybePromise;\n\n    switch (msg.type) {\n      case ProxyMessageKind.Error:\n        return reject(msg.error);\n      case ProxyMessageKind.GetPrincipalResponse:\n      case ProxyMessageKind.CallResponse:\n      case ProxyMessageKind.QueryResponse:\n      case ProxyMessageKind.ReadStateResponse:\n      case ProxyMessageKind.StatusResponse:\n        return resolve(msg.response);\n      default:\n        throw new Error(`Invalid message being sent to ProxyAgent: ${JSON.stringify(msg)}`);\n    }\n  }\n\n  public async getPrincipal(): Promise\u003cPrincipal\u003e {\n    return this._sendAndWait({\n      id: this._nextId++,\n      type: ProxyMessageKind.GetPrincipal,\n    }).then(principal =\u003e {\n      if (typeof principal !== 'string') {\n        throw new Error('Invalid principal received.');\n      }\n      return Principal.fromText(principal);\n    });\n  }\n\n  public readState(\n    canisterId: Principal | string,\n    fields: ReadStateOptions,\n  ): Promise\u003cReadStateResponse\u003e {\n    return this._sendAndWait({\n      id: this._nextId++,\n      type: ProxyMessageKind.ReadState,\n      args: [canisterId.toString(), fields],\n    }) as Promise\u003cReadStateResponse\u003e;\n  }\n\n  public call(canisterId: Principal | string, fields: CallOptions): Promise\u003cSubmitResponse\u003e {\n    return this._sendAndWait({\n      id: this._nextId++,\n      type: ProxyMessageKind.Call,\n      args: [canisterId.toString(), fields],\n    }) as Promise\u003cSubmitResponse\u003e;\n  }\n\n  public status(): Promise\u003cJsonObject\u003e {\n    return this._sendAndWait({\n      id: this._nextId++,\n      type: ProxyMessageKind.Status,\n    }) as Promise\u003cJsonObject\u003e;\n  }\n\n  public query(canisterId: Principal | string, fields: QueryFields): Promise\u003cApiQueryResponse\u003e {\n    return this._sendAndWait({\n      id: this._nextId++,\n      type: ProxyMessageKind.Query,\n      args: [canisterId.toString(), fields],\n    }) as Promise\u003cApiQueryResponse\u003e;\n  }\n\n  private async _sendAndWait(msg: ProxyMessage): Promise\u003cunknown\u003e {\n    return new Promise((resolve, reject) =\u003e {\n      this._pendingCalls.set(msg.id, [resolve, reject]);\n\n      this._backend(msg);\n    });\n  }\n\n  public async fetchRootKey(): Promise\u003cArrayBuffer\u003e {\n    // Hex-encoded version of the replica root key\n    const rootKey = ((await this.status()) as any).root_key;\n    this.rootKey = rootKey;\n    return rootKey;\n  }\n}\n","import { GlobalInternetComputer } from '../index';\nimport { Agent } from './api';\n\nexport * from './api';\nexport * from './http';\nexport * from './http/errors';\nexport * from './proxy';\n\ndeclare const window: GlobalInternetComputer;\ndeclare const global: GlobalInternetComputer;\ndeclare const self: GlobalInternetComputer;\n\nexport function getDefaultAgent(): Agent {\n  const agent =\n    typeof window === 'undefined'\n      ? typeof global === 'undefined'\n        ? typeof self === 'undefined'\n          ? undefined\n          : self.ic.agent\n        : global.ic.agent\n      : window.ic.agent;\n\n  if (!agent) {\n    throw new Error('No Agent could be found.');\n  }\n\n  return agent;\n}\n","import { Principal } from '@dfinity/principal';\nimport { RequestStatusResponseStatus } from '../agent';\nimport { toHex } from '../utils/buffer';\nimport { PollStrategy } from './index';\nimport { RequestId } from '../request_id';\n\nexport type Predicate\u003cT\u003e = (\n  canisterId: Principal,\n  requestId: RequestId,\n  status: RequestStatusResponseStatus,\n) =\u003e Promise\u003cT\u003e;\n\nconst FIVE_MINUTES_IN_MSEC = 5 * 60 * 1000;\n\n/**\n * A best practices polling strategy: wait 2 seconds before the first poll, then 1 second\n * with an exponential backoff factor of 1.2. Timeout after 5 minutes.\n */\nexport function defaultStrategy(): PollStrategy {\n  return chain(conditionalDelay(once(), 1000), backoff(1000, 1.2), timeout(FIVE_MINUTES_IN_MSEC));\n}\n\n/**\n * Predicate that returns true once.\n */\nexport function once(): Predicate\u003cboolean\u003e {\n  let first = true;\n  return async () =\u003e {\n    if (first) {\n      first = false;\n      return true;\n    }\n    return false;\n  };\n}\n\n/**\n * Delay the polling once.\n * @param condition A predicate that indicates when to delay.\n * @param timeInMsec The amount of time to delay.\n */\nexport function conditionalDelay(condition: Predicate\u003cboolean\u003e, timeInMsec: number): PollStrategy {\n  return async (\n    canisterId: Principal,\n    requestId: RequestId,\n    status: RequestStatusResponseStatus,\n  ) =\u003e {\n    if (await condition(canisterId, requestId, status)) {\n      return new Promise(resolve =\u003e setTimeout(resolve, timeInMsec));\n    }\n  };\n}\n\n/**\n * Error out after a maximum number of polling has been done.\n * @param count The maximum attempts to poll.\n */\nexport function maxAttempts(count: number): PollStrategy {\n  let attempts = count;\n  return async (\n    canisterId: Principal,\n    requestId: RequestId,\n    status: RequestStatusResponseStatus,\n  ) =\u003e {\n    if (--attempts \u003c= 0) {\n      throw new Error(\n        `Failed to retrieve a reply for request after ${count} attempts:\\n` +\n          `  Request ID: ${toHex(requestId)}\\n` +\n          `  Request status: ${status}\\n`,\n      );\n    }\n  };\n}\n\n/**\n * Throttle polling.\n * @param throttleInMsec Amount in millisecond to wait between each polling.\n */\nexport function throttle(throttleInMsec: number): PollStrategy {\n  return () =\u003e new Promise(resolve =\u003e setTimeout(resolve, throttleInMsec));\n}\n\n/**\n * Reject a call after a certain amount of time.\n * @param timeInMsec Time in milliseconds before the polling should be rejected.\n */\nexport function timeout(timeInMsec: number): PollStrategy {\n  const end = Date.now() + timeInMsec;\n  return async (\n    canisterId: Principal,\n    requestId: RequestId,\n    status: RequestStatusResponseStatus,\n  ) =\u003e {\n    if (Date.now() \u003e end) {\n      throw new Error(\n        `Request timed out after ${timeInMsec} msec:\\n` +\n          `  Request ID: ${toHex(requestId)}\\n` +\n          `  Request status: ${status}\\n`,\n      );\n    }\n  };\n}\n\n/**\n * A strategy that throttle, but using an exponential backoff strategy.\n * @param startingThrottleInMsec The throttle in milliseconds to start with.\n * @param backoffFactor The factor to multiple the throttle time between every poll. For\n *   example if using 2, the throttle will double between every run.\n */\nexport function backoff(startingThrottleInMsec: number, backoffFactor: number): PollStrategy {\n  let currentThrottling = startingThrottleInMsec;\n\n  return () =\u003e\n    new Promise(resolve =\u003e\n      setTimeout(() =\u003e {\n        currentThrottling *= backoffFactor;\n        resolve();\n      }, currentThrottling),\n    );\n}\n\n/**\n * Chain multiple polling strategy. This _chains_ the strategies, so if you pass in,\n * say, two throttling strategy of 1 second, it will result in a throttle of 2 seconds.\n * @param strategies A strategy list to chain.\n */\nexport function chain(...strategies: PollStrategy[]): PollStrategy {\n  return async (\n    canisterId: Principal,\n    requestId: RequestId,\n    status: RequestStatusResponseStatus,\n  ) =\u003e {\n    for (const a of strategies) {\n      await a(canisterId, requestId, status);\n    }\n  };\n}\n","import { Principal } from '@dfinity/principal';\nimport { Agent, RequestStatusResponseStatus } from '../agent';\nimport { Certificate, CreateCertificateOptions, lookupResultToBuffer } from '../certificate';\nimport { RequestId } from '../request_id';\nimport { toHex } from '../utils/buffer';\n\nexport * as strategy from './strategy';\nexport { defaultStrategy } from './strategy';\nexport type PollStrategy = (\n  canisterId: Principal,\n  requestId: RequestId,\n  status: RequestStatusResponseStatus,\n) =\u003e Promise\u003cvoid\u003e;\nexport type PollStrategyFactory = () =\u003e PollStrategy;\n\n/**\n * Polls the IC to check the status of the given request then\n * returns the response bytes once the request has been processed.\n * @param agent The agent to use to poll read_state.\n * @param canisterId The effective canister ID.\n * @param requestId The Request ID to poll status for.\n * @param strategy A polling strategy.\n * @param request Request for the readState call.\n * @param blsVerify - optional replacement function that verifies the BLS signature of a certificate.\n */\nexport async function pollForResponse(\n  agent: Agent,\n  canisterId: Principal,\n  requestId: RequestId,\n  strategy: PollStrategy,\n  // eslint-disable-next-line\n  request?: any,\n  blsVerify?: CreateCertificateOptions['blsVerify'],\n): Promise\u003cArrayBuffer\u003e {\n  const path = [new TextEncoder().encode('request_status'), requestId];\n  const currentRequest = request ?? (await agent.createReadStateRequest?.({ paths: [path] }));\n  const state = await agent.readState(canisterId, { paths: [path] }, undefined, currentRequest);\n  if (agent.rootKey == null) throw new Error('Agent root key not initialized before polling');\n  const cert = await Certificate.create({\n    certificate: state.certificate,\n    rootKey: agent.rootKey,\n    canisterId: canisterId,\n    blsVerify,\n  });\n  const maybeBuf = lookupResultToBuffer(cert.lookup([...path, new TextEncoder().encode('status')]));\n  let status;\n  if (typeof maybeBuf === 'undefined') {\n    // Missing requestId means we need to wait\n    status = RequestStatusResponseStatus.Unknown;\n  } else {\n    status = new TextDecoder().decode(maybeBuf);\n  }\n\n  switch (status) {\n    case RequestStatusResponseStatus.Replied: {\n      return lookupResultToBuffer(cert.lookup([...path, 'reply']))!;\n    }\n\n    case RequestStatusResponseStatus.Received:\n    case RequestStatusResponseStatus.Unknown:\n    case RequestStatusResponseStatus.Processing:\n      // Execute the polling strategy, then retry.\n      await strategy(canisterId, requestId, status);\n      return pollForResponse(agent, canisterId, requestId, strategy, currentRequest);\n\n    case RequestStatusResponseStatus.Rejected: {\n      const rejectCode = new Uint8Array(\n        lookupResultToBuffer(cert.lookup([...path, 'reject_code']))!,\n      )[0];\n      const rejectMessage = new TextDecoder().decode(\n        lookupResultToBuffer(cert.lookup([...path, 'reject_message']))!,\n      );\n      throw new Error(\n        `Call was rejected:\\n` +\n          `  Request ID: ${toHex(requestId)}\\n` +\n          `  Reject code: ${rejectCode}\\n` +\n          `  Reject text: ${rejectMessage}\\n`,\n      );\n    }\n\n    case RequestStatusResponseStatus.Done:\n      // This is _technically_ not an error, but we still didn't see the `Replied` status so\n      // we don't know the result and cannot decode it.\n      throw new Error(\n        `Call was marked as done but we never saw the reply:\\n` +\n          `  Request ID: ${toHex(requestId)}\\n`,\n      );\n  }\n  throw new Error('unreachable');\n}\n","/*\n * This file is generated from the candid for asset management.\n * didc version: 0.4.0\n */\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\n\nexport default ({ IDL }) =\u003e {\n  const bitcoin_network = IDL.Variant({\n    mainnet: IDL.Null,\n    testnet: IDL.Null,\n  });\n  const bitcoin_address = IDL.Text;\n  const bitcoin_get_balance_args = IDL.Record({\n    network: bitcoin_network,\n    address: bitcoin_address,\n    min_confirmations: IDL.Opt(IDL.Nat32),\n  });\n  const satoshi = IDL.Nat64;\n  const bitcoin_get_balance_result = satoshi;\n  const bitcoin_get_current_fee_percentiles_args = IDL.Record({\n    network: bitcoin_network,\n  });\n  const millisatoshi_per_byte = IDL.Nat64;\n  const bitcoin_get_current_fee_percentiles_result = IDL.Vec(millisatoshi_per_byte);\n  const bitcoin_get_utxos_args = IDL.Record({\n    network: bitcoin_network,\n    filter: IDL.Opt(\n      IDL.Variant({\n        page: IDL.Vec(IDL.Nat8),\n        min_confirmations: IDL.Nat32,\n      }),\n    ),\n    address: bitcoin_address,\n  });\n  const block_hash = IDL.Vec(IDL.Nat8);\n  const outpoint = IDL.Record({\n    txid: IDL.Vec(IDL.Nat8),\n    vout: IDL.Nat32,\n  });\n  const utxo = IDL.Record({\n    height: IDL.Nat32,\n    value: satoshi,\n    outpoint: outpoint,\n  });\n  const bitcoin_get_utxos_result = IDL.Record({\n    next_page: IDL.Opt(IDL.Vec(IDL.Nat8)),\n    tip_height: IDL.Nat32,\n    tip_block_hash: block_hash,\n    utxos: IDL.Vec(utxo),\n  });\n  const bitcoin_send_transaction_args = IDL.Record({\n    transaction: IDL.Vec(IDL.Nat8),\n    network: bitcoin_network,\n  });\n  const canister_id = IDL.Principal;\n  const canister_info_args = IDL.Record({\n    canister_id: canister_id,\n    num_requested_changes: IDL.Opt(IDL.Nat64),\n  });\n  const change_origin = IDL.Variant({\n    from_user: IDL.Record({ user_id: IDL.Principal }),\n    from_canister: IDL.Record({\n      canister_version: IDL.Opt(IDL.Nat64),\n      canister_id: IDL.Principal,\n    }),\n  });\n  const change_details = IDL.Variant({\n    creation: IDL.Record({ controllers: IDL.Vec(IDL.Principal) }),\n    code_deployment: IDL.Record({\n      mode: IDL.Variant({\n        reinstall: IDL.Null,\n        upgrade: IDL.Null,\n        install: IDL.Null,\n      }),\n      module_hash: IDL.Vec(IDL.Nat8),\n    }),\n    controllers_change: IDL.Record({\n      controllers: IDL.Vec(IDL.Principal),\n    }),\n    code_uninstall: IDL.Null,\n  });\n  const change = IDL.Record({\n    timestamp_nanos: IDL.Nat64,\n    canister_version: IDL.Nat64,\n    origin: change_origin,\n    details: change_details,\n  });\n  const canister_info_result = IDL.Record({\n    controllers: IDL.Vec(IDL.Principal),\n    module_hash: IDL.Opt(IDL.Vec(IDL.Nat8)),\n    recent_changes: IDL.Vec(change),\n    total_num_changes: IDL.Nat64,\n  });\n  const canister_status_args = IDL.Record({ canister_id: canister_id });\n  const log_visibility = IDL.Variant({\n    controllers: IDL.Null,\n    public: IDL.Null,\n  });\n  const definite_canister_settings = IDL.Record({\n    freezing_threshold: IDL.Nat,\n    controllers: IDL.Vec(IDL.Principal),\n    reserved_cycles_limit: IDL.Nat,\n    log_visibility: log_visibility,\n    wasm_memory_limit: IDL.Nat,\n    memory_allocation: IDL.Nat,\n    compute_allocation: IDL.Nat,\n  });\n  const canister_status_result = IDL.Record({\n    status: IDL.Variant({\n      stopped: IDL.Null,\n      stopping: IDL.Null,\n      running: IDL.Null,\n    }),\n    memory_size: IDL.Nat,\n    cycles: IDL.Nat,\n    settings: definite_canister_settings,\n    query_stats: IDL.Record({\n      response_payload_bytes_total: IDL.Nat,\n      num_instructions_total: IDL.Nat,\n      num_calls_total: IDL.Nat,\n      request_payload_bytes_total: IDL.Nat,\n    }),\n    idle_cycles_burned_per_day: IDL.Nat,\n    module_hash: IDL.Opt(IDL.Vec(IDL.Nat8)),\n    reserved_cycles: IDL.Nat,\n  });\n  const clear_chunk_store_args = IDL.Record({ canister_id: canister_id });\n  const canister_settings = IDL.Record({\n    freezing_threshold: IDL.Opt(IDL.Nat),\n    controllers: IDL.Opt(IDL.Vec(IDL.Principal)),\n    reserved_cycles_limit: IDL.Opt(IDL.Nat),\n    log_visibility: IDL.Opt(log_visibility),\n    wasm_memory_limit: IDL.Opt(IDL.Nat),\n    memory_allocation: IDL.Opt(IDL.Nat),\n    compute_allocation: IDL.Opt(IDL.Nat),\n  });\n  const create_canister_args = IDL.Record({\n    settings: IDL.Opt(canister_settings),\n    sender_canister_version: IDL.Opt(IDL.Nat64),\n  });\n  const create_canister_result = IDL.Record({ canister_id: canister_id });\n  const delete_canister_args = IDL.Record({ canister_id: canister_id });\n  const deposit_cycles_args = IDL.Record({ canister_id: canister_id });\n  const ecdsa_curve = IDL.Variant({ secp256k1: IDL.Null });\n  const ecdsa_public_key_args = IDL.Record({\n    key_id: IDL.Record({ name: IDL.Text, curve: ecdsa_curve }),\n    canister_id: IDL.Opt(canister_id),\n    derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n  });\n  const ecdsa_public_key_result = IDL.Record({\n    public_key: IDL.Vec(IDL.Nat8),\n    chain_code: IDL.Vec(IDL.Nat8),\n  });\n  const fetch_canister_logs_args = IDL.Record({ canister_id: canister_id });\n  const canister_log_record = IDL.Record({\n    idx: IDL.Nat64,\n    timestamp_nanos: IDL.Nat64,\n    content: IDL.Vec(IDL.Nat8),\n  });\n  const fetch_canister_logs_result = IDL.Record({\n    canister_log_records: IDL.Vec(canister_log_record),\n  });\n  const http_header = IDL.Record({ value: IDL.Text, name: IDL.Text });\n  const http_request_result = IDL.Record({\n    status: IDL.Nat,\n    body: IDL.Vec(IDL.Nat8),\n    headers: IDL.Vec(http_header),\n  });\n  const http_request_args = IDL.Record({\n    url: IDL.Text,\n    method: IDL.Variant({\n      get: IDL.Null,\n      head: IDL.Null,\n      post: IDL.Null,\n    }),\n    max_response_bytes: IDL.Opt(IDL.Nat64),\n    body: IDL.Opt(IDL.Vec(IDL.Nat8)),\n    transform: IDL.Opt(\n      IDL.Record({\n        function: IDL.Func(\n          [\n            IDL.Record({\n              context: IDL.Vec(IDL.Nat8),\n              response: http_request_result,\n            }),\n          ],\n          [http_request_result],\n          ['query'],\n        ),\n        context: IDL.Vec(IDL.Nat8),\n      }),\n    ),\n    headers: IDL.Vec(http_header),\n  });\n  const canister_install_mode = IDL.Variant({\n    reinstall: IDL.Null,\n    upgrade: IDL.Opt(\n      IDL.Record({\n        wasm_memory_persistence: IDL.Opt(IDL.Variant({ keep: IDL.Null, replace: IDL.Null })),\n        skip_pre_upgrade: IDL.Opt(IDL.Bool),\n      }),\n    ),\n    install: IDL.Null,\n  });\n  const chunk_hash = IDL.Record({ hash: IDL.Vec(IDL.Nat8) });\n  const install_chunked_code_args = IDL.Record({\n    arg: IDL.Vec(IDL.Nat8),\n    wasm_module_hash: IDL.Vec(IDL.Nat8),\n    mode: canister_install_mode,\n    chunk_hashes_list: IDL.Vec(chunk_hash),\n    target_canister: canister_id,\n    store_canister: IDL.Opt(canister_id),\n    sender_canister_version: IDL.Opt(IDL.Nat64),\n  });\n  const wasm_module = IDL.Vec(IDL.Nat8);\n  const install_code_args = IDL.Record({\n    arg: IDL.Vec(IDL.Nat8),\n    wasm_module: wasm_module,\n    mode: canister_install_mode,\n    canister_id: canister_id,\n    sender_canister_version: IDL.Opt(IDL.Nat64),\n  });\n  const node_metrics_history_args = IDL.Record({\n    start_at_timestamp_nanos: IDL.Nat64,\n    subnet_id: IDL.Principal,\n  });\n  const node_metrics = IDL.Record({\n    num_block_failures_total: IDL.Nat64,\n    node_id: IDL.Principal,\n    num_blocks_proposed_total: IDL.Nat64,\n  });\n  const node_metrics_history_result = IDL.Vec(\n    IDL.Record({\n      timestamp_nanos: IDL.Nat64,\n      node_metrics: IDL.Vec(node_metrics),\n    }),\n  );\n  const provisional_create_canister_with_cycles_args = IDL.Record({\n    settings: IDL.Opt(canister_settings),\n    specified_id: IDL.Opt(canister_id),\n    amount: IDL.Opt(IDL.Nat),\n    sender_canister_version: IDL.Opt(IDL.Nat64),\n  });\n  const provisional_create_canister_with_cycles_result = IDL.Record({\n    canister_id: canister_id,\n  });\n  const provisional_top_up_canister_args = IDL.Record({\n    canister_id: canister_id,\n    amount: IDL.Nat,\n  });\n  const raw_rand_result = IDL.Vec(IDL.Nat8);\n  const sign_with_ecdsa_args = IDL.Record({\n    key_id: IDL.Record({ name: IDL.Text, curve: ecdsa_curve }),\n    derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n    message_hash: IDL.Vec(IDL.Nat8),\n  });\n  const sign_with_ecdsa_result = IDL.Record({\n    signature: IDL.Vec(IDL.Nat8),\n  });\n  const start_canister_args = IDL.Record({ canister_id: canister_id });\n  const stop_canister_args = IDL.Record({ canister_id: canister_id });\n  const stored_chunks_args = IDL.Record({ canister_id: canister_id });\n  const stored_chunks_result = IDL.Vec(chunk_hash);\n  const uninstall_code_args = IDL.Record({\n    canister_id: canister_id,\n    sender_canister_version: IDL.Opt(IDL.Nat64),\n  });\n  const update_settings_args = IDL.Record({\n    canister_id: IDL.Principal,\n    settings: canister_settings,\n    sender_canister_version: IDL.Opt(IDL.Nat64),\n  });\n  const upload_chunk_args = IDL.Record({\n    chunk: IDL.Vec(IDL.Nat8),\n    canister_id: IDL.Principal,\n  });\n  const upload_chunk_result = chunk_hash;\n  return IDL.Service({\n    bitcoin_get_balance: IDL.Func([bitcoin_get_balance_args], [bitcoin_get_balance_result], []),\n    bitcoin_get_current_fee_percentiles: IDL.Func(\n      [bitcoin_get_current_fee_percentiles_args],\n      [bitcoin_get_current_fee_percentiles_result],\n      [],\n    ),\n    bitcoin_get_utxos: IDL.Func([bitcoin_get_utxos_args], [bitcoin_get_utxos_result], []),\n    bitcoin_send_transaction: IDL.Func([bitcoin_send_transaction_args], [], []),\n    canister_info: IDL.Func([canister_info_args], [canister_info_result], []),\n    canister_status: IDL.Func([canister_status_args], [canister_status_result], []),\n    clear_chunk_store: IDL.Func([clear_chunk_store_args], [], []),\n    create_canister: IDL.Func([create_canister_args], [create_canister_result], []),\n    delete_canister: IDL.Func([delete_canister_args], [], []),\n    deposit_cycles: IDL.Func([deposit_cycles_args], [], []),\n    ecdsa_public_key: IDL.Func([ecdsa_public_key_args], [ecdsa_public_key_result], []),\n    fetch_canister_logs: IDL.Func(\n      [fetch_canister_logs_args],\n      [fetch_canister_logs_result],\n      ['query'],\n    ),\n    http_request: IDL.Func([http_request_args], [http_request_result], []),\n    install_chunked_code: IDL.Func([install_chunked_code_args], [], []),\n    install_code: IDL.Func([install_code_args], [], []),\n    node_metrics_history: IDL.Func([node_metrics_history_args], [node_metrics_history_result], []),\n    provisional_create_canister_with_cycles: IDL.Func(\n      [provisional_create_canister_with_cycles_args],\n      [provisional_create_canister_with_cycles_result],\n      [],\n    ),\n    provisional_top_up_canister: IDL.Func([provisional_top_up_canister_args], [], []),\n    raw_rand: IDL.Func([], [raw_rand_result], []),\n    sign_with_ecdsa: IDL.Func([sign_with_ecdsa_args], [sign_with_ecdsa_result], []),\n    start_canister: IDL.Func([start_canister_args], [], []),\n    stop_canister: IDL.Func([stop_canister_args], [], []),\n    stored_chunks: IDL.Func([stored_chunks_args], [stored_chunks_result], []),\n    uninstall_code: IDL.Func([uninstall_code_args], [], []),\n    update_settings: IDL.Func([update_settings_args], [], []),\n    upload_chunk: IDL.Func([upload_chunk_args], [upload_chunk_result], []),\n  });\n};\n","import { Buffer } from 'buffer/';\nimport {\n  Agent,\n  getDefaultAgent,\n  HttpDetailsResponse,\n  QueryResponseRejected,\n  QueryResponseStatus,\n  ReplicaRejectCode,\n  SubmitResponse,\n} from './agent';\nimport { AgentError } from './errors';\nimport { IDL } from '@dfinity/candid';\nimport { pollForResponse, PollStrategyFactory, strategy } from './polling';\nimport { Principal } from '@dfinity/principal';\nimport { RequestId } from './request_id';\nimport { toHex } from './utils/buffer';\nimport { CreateCertificateOptions } from './certificate';\nimport managementCanisterIdl from './canisters/management_idl';\nimport _SERVICE, { canister_install_mode, canister_settings } from './canisters/management_service';\n\nexport class ActorCallError extends AgentError {\n  constructor(\n    public readonly canisterId: Principal,\n    public readonly methodName: string,\n    public readonly type: 'query' | 'update',\n    public readonly props: Record\u003cstring, string\u003e,\n  ) {\n    super(\n      [\n        `Call failed:`,\n        `  Canister: ${canisterId.toText()}`,\n        `  Method: ${methodName} (${type})`,\n        ...Object.getOwnPropertyNames(props).map(n =\u003e `  \"${n}\": ${JSON.stringify(props[n])}`),\n      ].join('\\n'),\n    );\n  }\n}\n\nexport class QueryCallRejectedError extends ActorCallError {\n  constructor(\n    canisterId: Principal,\n    methodName: string,\n    public readonly result: QueryResponseRejected,\n  ) {\n    super(canisterId, methodName, 'query', {\n      Status: result.status,\n      Code: ReplicaRejectCode[result.reject_code] ?? `Unknown Code \"${result.reject_code}\"`,\n      Message: result.reject_message,\n    });\n  }\n}\n\nexport class UpdateCallRejectedError extends ActorCallError {\n  constructor(\n    canisterId: Principal,\n    methodName: string,\n    public readonly requestId: RequestId,\n    public readonly response: SubmitResponse['response'],\n  ) {\n    super(canisterId, methodName, 'update', {\n      'Request ID': toHex(requestId),\n      ...(response.body\n        ? {\n            ...(response.body.error_code\n              ? {\n                  'Error code': response.body.error_code,\n                }\n              : {}),\n            'Reject code': String(response.body.reject_code),\n            'Reject message': response.body.reject_message,\n          }\n        : {\n            'HTTP status code': response.status.toString(),\n            'HTTP status text': response.statusText,\n          }),\n    });\n  }\n}\n\n/**\n * Configuration to make calls to the Replica.\n */\nexport interface CallConfig {\n  /**\n   * An agent to use in this call, otherwise the actor or call will try to discover the\n   * agent to use.\n   */\n  agent?: Agent;\n\n  /**\n   * A polling strategy factory that dictates how much and often we should poll the\n   * read_state endpoint to get the result of an update call.\n   */\n  pollingStrategyFactory?: PollStrategyFactory;\n\n  /**\n   * The canister ID of this Actor.\n   */\n  canisterId?: string | Principal;\n\n  /**\n   * The effective canister ID. This should almost always be ignored.\n   */\n  effectiveCanisterId?: Principal;\n}\n\n/**\n * Configuration that can be passed to customize the Actor behaviour.\n */\nexport interface ActorConfig extends CallConfig {\n  /**\n   * The Canister ID of this Actor. This is required for an Actor.\n   */\n  canisterId: string | Principal;\n\n  /**\n   * An override function for update calls' CallConfig. This will be called on every calls.\n   */\n  callTransform?(\n    methodName: string,\n    args: unknown[],\n    callConfig: CallConfig,\n  ): Partial\u003cCallConfig\u003e | void;\n\n  /**\n   * An override function for query calls' CallConfig. This will be called on every query.\n   */\n  queryTransform?(\n    methodName: string,\n    args: unknown[],\n    callConfig: CallConfig,\n  ): Partial\u003cCallConfig\u003e | void;\n\n  /**\n   * Polyfill for BLS Certificate verification in case wasm is not supported\n   */\n  blsVerify?: CreateCertificateOptions['blsVerify'];\n}\n\n// TODO: move this to proper typing when Candid support TypeScript.\n/**\n * A subclass of an actor. Actor class itself is meant to be a based class.\n */\nexport type ActorSubclass\u003cT = Record\u003cstring, ActorMethod\u003e\u003e = Actor \u0026 T;\n\n/**\n * An actor method type, defined for each methods of the actor service.\n */\nexport interface ActorMethod\u003cArgs extends unknown[] = unknown[], Ret = unknown\u003e {\n  (...args: Args): Promise\u003cRet\u003e;\n  withOptions(options: CallConfig): (...args: Args) =\u003e Promise\u003cRet\u003e;\n}\n\n/**\n * An actor method type, defined for each methods of the actor service.\n */\nexport interface ActorMethodWithHttpDetails\u003cArgs extends unknown[] = unknown[], Ret = unknown\u003e\n  extends ActorMethod {\n  (...args: Args): Promise\u003c{ httpDetails: HttpDetailsResponse; result: Ret }\u003e;\n}\n\nexport type FunctionWithArgsAndReturn\u003cArgs extends unknown[] = unknown[], Ret = unknown\u003e = (\n  ...args: Args\n) =\u003e Ret;\n\n// Update all entries of T with the extra information from ActorMethodWithInfo\nexport type ActorMethodMappedWithHttpDetails\u003cT\u003e = {\n  [K in keyof T]: T[K] extends FunctionWithArgsAndReturn\u003cinfer Args, infer Ret\u003e\n    ? ActorMethodWithHttpDetails\u003cArgs, Ret\u003e\n    : never;\n};\n\n/**\n * The mode used when installing a canister.\n */\nexport type CanisterInstallMode =\n  | {\n      reinstall: null;\n    }\n  | {\n      upgrade:\n        | []\n        | [\n            {\n              skip_pre_upgrade: [] | [boolean];\n            },\n          ];\n    }\n  | {\n      install: null;\n    };\n\n/**\n * Internal metadata for actors. It's an enhanced version of ActorConfig with\n * some fields marked as required (as they are defaulted) and canisterId as\n * a Principal type.\n */\ninterface ActorMetadata {\n  service: IDL.ServiceClass;\n  agent?: Agent;\n  config: ActorConfig;\n}\n\nconst metadataSymbol = Symbol.for('ic-agent-metadata');\n\nexport interface CreateActorClassOpts {\n  httpDetails?: boolean;\n}\n\ninterface CreateCanisterSettings {\n  freezing_threshold?: bigint;\n  controllers?: Array\u003cPrincipal\u003e;\n  memory_allocation?: bigint;\n  compute_allocation?: bigint;\n}\n\n/**\n * An actor base class. An actor is an object containing only functions that will\n * return a promise. These functions are derived from the IDL definition.\n */\nexport class Actor {\n  /**\n   * Get the Agent class this Actor would call, or undefined if the Actor would use\n   * the default agent (global.ic.agent).\n   * @param actor The actor to get the agent of.\n   */\n  public static agentOf(actor: Actor): Agent | undefined {\n    return actor[metadataSymbol].config.agent;\n  }\n\n  /**\n   * Get the interface of an actor, in the form of an instance of a Service.\n   * @param actor The actor to get the interface of.\n   */\n  public static interfaceOf(actor: Actor): IDL.ServiceClass {\n    return actor[metadataSymbol].service;\n  }\n\n  public static canisterIdOf(actor: Actor): Principal {\n    return Principal.from(actor[metadataSymbol].config.canisterId);\n  }\n\n  public static async install(\n    fields: {\n      module: ArrayBuffer;\n      mode?: canister_install_mode;\n      arg?: ArrayBuffer;\n    },\n    config: ActorConfig,\n  ): Promise\u003cvoid\u003e {\n    const mode = fields.mode === undefined ? { install: null } : fields.mode;\n    // Need to transform the arg into a number array.\n    const arg = fields.arg ? [...new Uint8Array(fields.arg)] : [];\n    // Same for module.\n    const wasmModule = [...new Uint8Array(fields.module)];\n    const canisterId =\n      typeof config.canisterId === 'string'\n        ? Principal.fromText(config.canisterId)\n        : config.canisterId;\n\n    await getManagementCanister(config).install_code({\n      mode,\n      arg,\n      wasm_module: wasmModule,\n      canister_id: canisterId,\n      sender_canister_version: [],\n    });\n  }\n\n  public static async createCanister(\n    config?: CallConfig,\n    settings?: CreateCanisterSettings,\n  ): Promise\u003cPrincipal\u003e {\n    function settingsToCanisterSettings(settings: CreateCanisterSettings): [canister_settings] {\n      return [\n        {\n          controllers: settings.controllers ? [settings.controllers] : [],\n          compute_allocation: settings.compute_allocation ? [settings.compute_allocation] : [],\n          freezing_threshold: settings.freezing_threshold ? [settings.freezing_threshold] : [],\n          memory_allocation: settings.memory_allocation ? [settings.memory_allocation] : [],\n          reserved_cycles_limit: [],\n          log_visibility: [],\n          wasm_memory_limit: [],\n        },\n      ];\n    }\n\n    const { canister_id: canisterId } = await getManagementCanister(\n      config || {},\n    ).provisional_create_canister_with_cycles({\n      amount: [],\n      settings: settingsToCanisterSettings(settings || {}),\n      specified_id: [],\n      sender_canister_version: [],\n    });\n\n    return canisterId;\n  }\n\n  public static async createAndInstallCanister(\n    interfaceFactory: IDL.InterfaceFactory,\n    fields: {\n      module: ArrayBuffer;\n      arg?: ArrayBuffer;\n    },\n    config?: CallConfig,\n  ): Promise\u003cActorSubclass\u003e {\n    const canisterId = await this.createCanister(config);\n    await this.install(\n      {\n        ...fields,\n      },\n      { ...config, canisterId },\n    );\n\n    return this.createActor(interfaceFactory, { ...config, canisterId });\n  }\n\n  public static createActorClass(\n    interfaceFactory: IDL.InterfaceFactory,\n    options?: CreateActorClassOpts,\n  ): ActorConstructor {\n    const service = interfaceFactory({ IDL });\n\n    class CanisterActor extends Actor {\n      [x: string]: ActorMethod;\n\n      constructor(config: ActorConfig) {\n        if (!config.canisterId)\n          throw new AgentError(\n            `Canister ID is required, but received ${typeof config.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`,\n          );\n        const canisterId =\n          typeof config.canisterId === 'string'\n            ? Principal.fromText(config.canisterId)\n            : config.canisterId;\n\n        super({\n          config: {\n            ...DEFAULT_ACTOR_CONFIG,\n            ...config,\n            canisterId,\n          },\n          service,\n        });\n\n        for (const [methodName, func] of service._fields) {\n          if (options?.httpDetails) {\n            func.annotations.push(ACTOR_METHOD_WITH_HTTP_DETAILS);\n          }\n\n          this[methodName] = _createActorMethod(this, methodName, func, config.blsVerify);\n        }\n      }\n    }\n\n    return CanisterActor;\n  }\n\n  public static createActor\u003cT = Record\u003cstring, ActorMethod\u003e\u003e(\n    interfaceFactory: IDL.InterfaceFactory,\n    configuration: ActorConfig,\n  ): ActorSubclass\u003cT\u003e {\n    if (!configuration.canisterId) {\n      throw new AgentError(\n        `Canister ID is required, but received ${typeof configuration.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`,\n      );\n    }\n    return new (this.createActorClass(interfaceFactory))(\n      configuration,\n    ) as unknown as ActorSubclass\u003cT\u003e;\n  }\n\n  public static createActorWithHttpDetails\u003cT = Record\u003cstring, ActorMethod\u003e\u003e(\n    interfaceFactory: IDL.InterfaceFactory,\n    configuration: ActorConfig,\n  ): ActorSubclass\u003cActorMethodMappedWithHttpDetails\u003cT\u003e\u003e {\n    return new (this.createActorClass(interfaceFactory, { httpDetails: true }))(\n      configuration,\n    ) as unknown as ActorSubclass\u003cActorMethodMappedWithHttpDetails\u003cT\u003e\u003e;\n  }\n\n  private [metadataSymbol]: ActorMetadata;\n\n  protected constructor(metadata: ActorMetadata) {\n    this[metadataSymbol] = Object.freeze(metadata);\n  }\n}\n\n// IDL functions can have multiple return values, so decoding always\n// produces an array. Ensure that functions with single or zero return\n// values behave as expected.\nfunction decodeReturnValue(types: IDL.Type[], msg: ArrayBuffer) {\n  const returnValues = IDL.decode(types, Buffer.from(msg));\n  switch (returnValues.length) {\n    case 0:\n      return undefined;\n    case 1:\n      return returnValues[0];\n    default:\n      return returnValues;\n  }\n}\n\nconst DEFAULT_ACTOR_CONFIG = {\n  pollingStrategyFactory: strategy.defaultStrategy,\n};\n\nexport type ActorConstructor = new (config: ActorConfig) =\u003e ActorSubclass;\n\nexport const ACTOR_METHOD_WITH_HTTP_DETAILS = 'http-details';\n\nfunction _createActorMethod(\n  actor: Actor,\n  methodName: string,\n  func: IDL.FuncClass,\n  blsVerify?: CreateCertificateOptions['blsVerify'],\n): ActorMethod {\n  let caller: (options: CallConfig, ...args: unknown[]) =\u003e Promise\u003cunknown\u003e;\n  if (func.annotations.includes('query') || func.annotations.includes('composite_query')) {\n    caller = async (options, ...args) =\u003e {\n      // First, if there's a config transformation, call it.\n      options = {\n        ...options,\n        ...actor[metadataSymbol].config.queryTransform?.(methodName, args, {\n          ...actor[metadataSymbol].config,\n          ...options,\n        }),\n      };\n\n      const agent = options.agent || actor[metadataSymbol].config.agent || getDefaultAgent();\n      const cid = Principal.from(options.canisterId || actor[metadataSymbol].config.canisterId);\n      const arg = IDL.encode(func.argTypes, args);\n\n      const result = await agent.query(cid, {\n        methodName,\n        arg,\n        effectiveCanisterId: options.effectiveCanisterId,\n      });\n\n      switch (result.status) {\n        case QueryResponseStatus.Rejected:\n          throw new QueryCallRejectedError(cid, methodName, result);\n\n        case QueryResponseStatus.Replied:\n          return func.annotations.includes(ACTOR_METHOD_WITH_HTTP_DETAILS)\n            ? {\n                httpDetails: result.httpDetails,\n                result: decodeReturnValue(func.retTypes, result.reply.arg),\n              }\n            : decodeReturnValue(func.retTypes, result.reply.arg);\n      }\n    };\n  } else {\n    caller = async (options, ...args) =\u003e {\n      // First, if there's a config transformation, call it.\n      options = {\n        ...options,\n        ...actor[metadataSymbol].config.callTransform?.(methodName, args, {\n          ...actor[metadataSymbol].config,\n          ...options,\n        }),\n      };\n\n      const agent = options.agent || actor[metadataSymbol].config.agent || getDefaultAgent();\n      const { canisterId, effectiveCanisterId, pollingStrategyFactory } = {\n        ...DEFAULT_ACTOR_CONFIG,\n        ...actor[metadataSymbol].config,\n        ...options,\n      };\n      const cid = Principal.from(canisterId);\n      const ecid = effectiveCanisterId !== undefined ? Principal.from(effectiveCanisterId) : cid;\n      const arg = IDL.encode(func.argTypes, args);\n      const { requestId, response } = await agent.call(cid, {\n        methodName,\n        arg,\n        effectiveCanisterId: ecid,\n      });\n\n      if (!response.ok || response.body /* IC-1462 */) {\n        throw new UpdateCallRejectedError(cid, methodName, requestId, response);\n      }\n\n      const pollStrategy = pollingStrategyFactory();\n      const responseBytes = await pollForResponse(agent, ecid, requestId, pollStrategy, blsVerify);\n      const shouldIncludeHttpDetails = func.annotations.includes(ACTOR_METHOD_WITH_HTTP_DETAILS);\n\n      if (responseBytes !== undefined) {\n        return shouldIncludeHttpDetails\n          ? {\n              httpDetails: response,\n              result: decodeReturnValue(func.retTypes, responseBytes),\n            }\n          : decodeReturnValue(func.retTypes, responseBytes);\n      } else if (func.retTypes.length === 0) {\n        return shouldIncludeHttpDetails\n          ? {\n              httpDetails: response,\n              result: undefined,\n            }\n          : undefined;\n      } else {\n        throw new Error(`Call was returned undefined, but type [${func.retTypes.join(',')}].`);\n      }\n    };\n  }\n\n  const handler = (...args: unknown[]) =\u003e caller({}, ...args);\n  handler.withOptions =\n    (options: CallConfig) =\u003e\n    (...args: unknown[]) =\u003e\n      caller(options, ...args);\n  return handler as ActorMethod;\n}\n\nexport type ManagementCanisterRecord = _SERVICE;\n\n/**\n * Create a management canister actor\n * @param config - a CallConfig\n */\nexport function getManagementCanister(config: CallConfig): ActorSubclass\u003cManagementCanisterRecord\u003e {\n  function transform(\n    _methodName: string,\n    args: Record\u003cstring, unknown\u003e \u0026 { canister_id: string }[],\n  ) {\n    if (config.effectiveCanisterId) {\n      return { effectiveCanisterId: Principal.from(config.effectiveCanisterId) };\n    }\n    const first = args[0];\n    let effectiveCanisterId = Principal.fromHex('');\n    if (first \u0026\u0026 typeof first === 'object' \u0026\u0026 first.canister_id) {\n      effectiveCanisterId = Principal.from(first.canister_id as unknown);\n    }\n    return { effectiveCanisterId };\n  }\n\n  return Actor.createActor\u003cManagementCanisterRecord\u003e(managementCanisterIdl, {\n    ...config,\n    canisterId: Principal.fromHex(''),\n    ...{\n      callTransform: transform,\n      queryTransform: transform,\n    },\n  });\n}\n","/**\n * This file is generated from the candid for asset management.\n */\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nexport default ({ IDL }) =\u003e {\n  return IDL.Service({\n    retrieve: IDL.Func([IDL.Text], [IDL.Vec(IDL.Nat8)], ['query']),\n    store: IDL.Func([IDL.Text, IDL.Vec(IDL.Nat8)], [], []),\n  });\n};\n","import { Actor, ActorConfig, ActorSubclass, CallConfig } from '../actor';\nimport assetCanister from './asset_idl';\n\nexport interface AssetCanisterRecord {\n  store(path: string, content: number[]): Promise\u003cvoid\u003e;\n  retrieve(path: string): Promise\u003cnumber[]\u003e;\n}\n\n/**\n * Create a management canister actor.\n * @param config\n */\nexport function createAssetCanisterActor(config: ActorConfig) {\n  return Actor.createActor\u003cAssetCanisterRecord\u003e(assetCanister, config);\n}\n","import { Principal } from '@dfinity/principal';\nimport * as CanisterStatus from './canisterStatus/index';\nimport { IDL } from '@dfinity/candid';\nimport { HttpAgent } from './agent/http';\nimport { Actor, ActorSubclass } from './actor';\n\n/**\n * Retrieves the Candid interface for the specified canister.\n *\n * @param agent The agent to use for the request (usually an `HttpAgent`)\n * @param canisterId A string corresponding to the canister ID\n * @returns Candid source code\n */\nexport async function fetchCandid(canisterId: string, agent?: HttpAgent): Promise\u003cstring\u003e {\n  if (!agent) {\n    // Create an anonymous `HttpAgent` (adapted from Candid UI)\n    agent = new HttpAgent();\n    if (agent.isLocal()) {\n      agent.fetchRootKey();\n    }\n  }\n\n  // Attempt to use canister metadata\n  const status = await CanisterStatus.request({\n    agent,\n    canisterId: Principal.fromText(canisterId),\n    paths: ['candid'],\n  });\n  const candid = status.get('candid') as string | undefined;\n  if (candid) {\n    return candid;\n  }\n\n  // Use `__get_candid_interface_tmp_hack` for canisters without Candid metadata\n  const tmpHackInterface: IDL.InterfaceFactory = ({ IDL }) =\u003e\n    IDL.Service({\n      __get_candid_interface_tmp_hack: IDL.Func([], [IDL.Text], ['query']),\n    });\n  const actor: ActorSubclass = Actor.createActor(tmpHackInterface, { agent, canisterId });\n  return (await actor.__get_candid_interface_tmp_hack()) as string;\n}\n","import { ActorSubclass } from './actor';\n\nexport * from './actor';\nexport * from './agent';\nexport * from './agent/http/transforms';\nexport * from './agent/http/types';\nexport * from './auth';\nexport * from './canisters/asset';\nexport * from './certificate';\nexport * from './der';\nexport * from './fetch_candid';\nexport * from './public_key';\nexport * from './request_id';\nexport * from './utils/bls';\nexport * from './utils/buffer';\nexport * from './utils/random';\nexport * as polling from './polling';\nimport * as CanisterStatus from './canisterStatus';\nexport * as CanisterStatus from './canisterStatus';\n/**\n * The CanisterStatus utility is used to request structured data directly from the IC public API. This data can be accessed using agent.readState, but CanisterStatus provides a helpful abstraction with some known paths.\n *\n * You can request a canisters Controllers, ModuleHash, Candid interface, Subnet, or Time, or provide a custom path {@link CanisterStatus.CustomPath} and pass arbitrary buffers for valid paths identified in https://internetcomputer.org/docs/current/references/ic-interface-spec.\n *\n * The primary method for this namespace is {@link CanisterStatus.request}\n */\n\nimport { Agent, HttpAgent } from './agent';\nimport { IDL } from '@dfinity/candid';\n\nexport * as Cbor from './cbor';\n\nexport interface GlobalInternetComputer {\n  ic: {\n    agent: Agent;\n    HttpAgent: typeof HttpAgent;\n    IDL: typeof IDL;\n    /**\n     * Simple advertisement of features in whoever is managing this `globalThis.ic`.\n     * Use Case\n     * - Scripts that know they need an ic feature can detect using this and, if not present\n     *   (e.g. old bootstrap version), they can dynamically include their own and continue\n     *   operating (e.g. polyfill).\n     *   This is useful when adding features to bootstrap. You can still deploy your canister to\n     *   an ic with old bootstrap, then just dynamically reload your own new-version bootstrap if\n     *   needed.\n     */\n    features?: {\n      /** This is falsy if authn isn't supported at all */\n      authentication?: boolean;\n    };\n    /**\n     * The Actor for the canister being used for the frontend. Normally should correspond to the\n     * canister represented by the canister id in the URL.\n     *\n     * It does not have any functions configured.\n     *\n     * If a canister ID could not be found, no actor were created and this is undefined.\n     */\n    canister: ActorSubclass | undefined;\n  };\n}\n","import * as cjsm from \"@dfinity/agent\";export const { __esModule,Cbor,CanisterStatus,polling,randomNumber,bufFromBufLike,uint8ToBuf,bufEquals,compare,fromHex,toHex,concat,blsVerify,verify,hashOfMap,requestIdOf,hashValue,hash,Ed25519PublicKey,fetchCandid,unwrapDER,wrapDER,SECP256K1_OID,ED25519_OID,DER_COSE_OID,decodeLen,decodeLenBytes,encodeLen,encodeLenBytes,check_canister_ranges,find_label,flatten_forks,lookup_path,LookupStatus,reconstruct,lookupResultToBuffer,Certificate,hashTreeToString,NodeType,CertificateVerificationError,createAssetCanisterActor,createIdentityDescriptor,AnonymousIdentity,SignIdentity,makeNonce,SubmitRequestType,httpHeadersTransform,makeExpiryTransform,makeNonceTransform,Expiry,getDefaultAgent,ProxyAgent,ProxyStubAgent,ProxyMessageKind,AgentHTTPResponseError,HttpAgent,IdentityInvalidError,MANAGEMENT_CANISTER_ID,IC_ROOT_KEY,RequestStatusResponseStatus,ReplicaRejectCode,getManagementCanister,ACTOR_METHOD_WITH_HTTP_DETAILS,Actor,UpdateCallRejectedError,QueryCallRejectedError,ActorCallError } = cjsm;export default cjsm.default ?? cjsm;"],"version":3}
