@icp-sdk/core 5.3.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/lib/cjs/agent/actor.d.ts +7 -3
  2. package/lib/cjs/agent/actor.d.ts.map +1 -1
  3. package/lib/cjs/agent/actor.js +18 -5
  4. package/lib/cjs/agent/actor.js.map +1 -1
  5. package/lib/cjs/agent/agent/api.d.ts +35 -6
  6. package/lib/cjs/agent/agent/api.d.ts.map +1 -1
  7. package/lib/cjs/agent/agent/api.js.map +1 -1
  8. package/lib/cjs/agent/agent/http/index.d.ts +11 -25
  9. package/lib/cjs/agent/agent/http/index.d.ts.map +1 -1
  10. package/lib/cjs/agent/agent/http/index.js +198 -173
  11. package/lib/cjs/agent/agent/http/index.js.map +1 -1
  12. package/lib/cjs/agent/auth.d.ts +6 -5
  13. package/lib/cjs/agent/auth.d.ts.map +1 -1
  14. package/lib/cjs/agent/auth.js +3 -3
  15. package/lib/cjs/agent/auth.js.map +1 -1
  16. package/lib/cjs/agent/canisterStatus/index.d.ts.map +1 -1
  17. package/lib/cjs/agent/canisterStatus/index.js +10 -10
  18. package/lib/cjs/agent/canisterStatus/index.js.map +1 -1
  19. package/lib/cjs/agent/cbor.d.ts +2 -1
  20. package/lib/cjs/agent/cbor.d.ts.map +1 -1
  21. package/lib/cjs/agent/cbor.js +4 -1
  22. package/lib/cjs/agent/cbor.js.map +1 -1
  23. package/lib/cjs/agent/certificate.d.ts +5 -4
  24. package/lib/cjs/agent/certificate.d.ts.map +1 -1
  25. package/lib/cjs/agent/certificate.js +14 -18
  26. package/lib/cjs/agent/certificate.js.map +1 -1
  27. package/lib/cjs/agent/der.d.ts +3 -2
  28. package/lib/cjs/agent/der.d.ts.map +1 -1
  29. package/lib/cjs/agent/der.js.map +1 -1
  30. package/lib/cjs/agent/errors.d.ts +7 -1
  31. package/lib/cjs/agent/errors.d.ts.map +1 -1
  32. package/lib/cjs/agent/errors.js +34 -16
  33. package/lib/cjs/agent/errors.js.map +1 -1
  34. package/lib/cjs/agent/polling/index.d.ts +3 -4
  35. package/lib/cjs/agent/polling/index.d.ts.map +1 -1
  36. package/lib/cjs/agent/polling/index.js +17 -10
  37. package/lib/cjs/agent/polling/index.js.map +1 -1
  38. package/lib/cjs/agent/polling/strategy.d.ts.map +1 -1
  39. package/lib/cjs/agent/polling/strategy.js +6 -6
  40. package/lib/cjs/agent/polling/strategy.js.map +1 -1
  41. package/lib/cjs/agent/polling/types.d.ts +3 -4
  42. package/lib/cjs/agent/polling/types.d.ts.map +1 -1
  43. package/lib/cjs/agent/public_key.d.ts +3 -2
  44. package/lib/cjs/agent/public_key.d.ts.map +1 -1
  45. package/lib/cjs/agent/public_key.js +2 -2
  46. package/lib/cjs/agent/public_key.js.map +1 -1
  47. package/lib/cjs/agent/request_id.js +10 -10
  48. package/lib/cjs/agent/request_id.js.map +1 -1
  49. package/lib/cjs/agent/subnetStatus/index.js +7 -7
  50. package/lib/cjs/agent/subnetStatus/index.js.map +1 -1
  51. package/lib/cjs/agent/utils/bls.d.ts.map +1 -1
  52. package/lib/cjs/agent/utils/bls.js +7 -6
  53. package/lib/cjs/agent/utils/bls.js.map +1 -1
  54. package/lib/cjs/agent/utils/readState.d.ts +2 -2
  55. package/lib/cjs/agent/utils/readState.d.ts.map +1 -1
  56. package/lib/cjs/agent/utils/readState.js +4 -4
  57. package/lib/cjs/agent/utils/readState.js.map +1 -1
  58. package/lib/cjs/agent/utils/target.d.ts +15 -0
  59. package/lib/cjs/agent/utils/target.d.ts.map +1 -0
  60. package/lib/cjs/agent/utils/target.js +27 -0
  61. package/lib/cjs/agent/utils/target.js.map +1 -0
  62. package/lib/cjs/candid/utils/buffer.d.ts +2 -1
  63. package/lib/cjs/candid/utils/buffer.d.ts.map +1 -1
  64. package/lib/cjs/candid/utils/buffer.js +5 -2
  65. package/lib/cjs/candid/utils/buffer.js.map +1 -1
  66. package/lib/cjs/identity/identity/attributes.d.ts +6 -2
  67. package/lib/cjs/identity/identity/attributes.d.ts.map +1 -1
  68. package/lib/cjs/identity/identity/attributes.js +9 -1
  69. package/lib/cjs/identity/identity/attributes.js.map +1 -1
  70. package/lib/cjs/identity/identity/delegation.d.ts +10 -3
  71. package/lib/cjs/identity/identity/delegation.d.ts.map +1 -1
  72. package/lib/cjs/identity/identity/delegation.js +25 -12
  73. package/lib/cjs/identity/identity/delegation.js.map +1 -1
  74. package/lib/cjs/identity/identity/ecdsa.d.ts +2 -2
  75. package/lib/cjs/identity/identity/ecdsa.d.ts.map +1 -1
  76. package/lib/cjs/identity/identity/ecdsa.js +3 -2
  77. package/lib/cjs/identity/identity/ecdsa.js.map +1 -1
  78. package/lib/cjs/identity/identity/ed25519.d.ts +3 -2
  79. package/lib/cjs/identity/identity/ed25519.d.ts.map +1 -1
  80. package/lib/cjs/identity/identity/ed25519.js +18 -15
  81. package/lib/cjs/identity/identity/ed25519.js.map +1 -1
  82. package/lib/cjs/identity/identity/webauthn.d.ts +4 -3
  83. package/lib/cjs/identity/identity/webauthn.d.ts.map +1 -1
  84. package/lib/cjs/identity/identity/webauthn.js +12 -11
  85. package/lib/cjs/identity/identity/webauthn.js.map +1 -1
  86. package/lib/cjs/identity/secp256k1/der.d.ts +2 -1
  87. package/lib/cjs/identity/secp256k1/der.d.ts.map +1 -1
  88. package/lib/cjs/identity/secp256k1/der.js.map +1 -1
  89. package/lib/cjs/identity/secp256k1/pem.d.ts +4 -3
  90. package/lib/cjs/identity/secp256k1/pem.d.ts.map +1 -1
  91. package/lib/cjs/identity/secp256k1/pem.js +2 -2
  92. package/lib/cjs/identity/secp256k1/pem.js.map +1 -1
  93. package/lib/cjs/identity/secp256k1/secp256k1.d.ts +5 -4
  94. package/lib/cjs/identity/secp256k1/secp256k1.d.ts.map +1 -1
  95. package/lib/cjs/identity/secp256k1/secp256k1.js +17 -20
  96. package/lib/cjs/identity/secp256k1/secp256k1.js.map +1 -1
  97. package/lib/cjs/principal/principal.js +5 -5
  98. package/lib/cjs/principal/principal.js.map +1 -1
  99. package/lib/esm/agent/actor.d.ts +7 -3
  100. package/lib/esm/agent/actor.d.ts.map +1 -1
  101. package/lib/esm/agent/actor.js +18 -5
  102. package/lib/esm/agent/actor.js.map +1 -1
  103. package/lib/esm/agent/agent/api.d.ts +35 -6
  104. package/lib/esm/agent/agent/api.d.ts.map +1 -1
  105. package/lib/esm/agent/agent/api.js.map +1 -1
  106. package/lib/esm/agent/agent/http/index.d.ts +11 -25
  107. package/lib/esm/agent/agent/http/index.d.ts.map +1 -1
  108. package/lib/esm/agent/agent/http/index.js +191 -166
  109. package/lib/esm/agent/agent/http/index.js.map +1 -1
  110. package/lib/esm/agent/auth.d.ts +6 -5
  111. package/lib/esm/agent/auth.d.ts.map +1 -1
  112. package/lib/esm/agent/auth.js +1 -1
  113. package/lib/esm/agent/auth.js.map +1 -1
  114. package/lib/esm/agent/canister-env/index.js +1 -1
  115. package/lib/esm/agent/canister-env/index.js.map +1 -1
  116. package/lib/esm/agent/canisterStatus/index.d.ts.map +1 -1
  117. package/lib/esm/agent/canisterStatus/index.js +2 -2
  118. package/lib/esm/agent/canisterStatus/index.js.map +1 -1
  119. package/lib/esm/agent/cbor.d.ts +2 -1
  120. package/lib/esm/agent/cbor.d.ts.map +1 -1
  121. package/lib/esm/agent/cbor.js +4 -1
  122. package/lib/esm/agent/cbor.js.map +1 -1
  123. package/lib/esm/agent/certificate.d.ts +5 -4
  124. package/lib/esm/agent/certificate.d.ts.map +1 -1
  125. package/lib/esm/agent/certificate.js +5 -9
  126. package/lib/esm/agent/certificate.js.map +1 -1
  127. package/lib/esm/agent/der.d.ts +3 -2
  128. package/lib/esm/agent/der.d.ts.map +1 -1
  129. package/lib/esm/agent/der.js.map +1 -1
  130. package/lib/esm/agent/errors.d.ts +7 -1
  131. package/lib/esm/agent/errors.d.ts.map +1 -1
  132. package/lib/esm/agent/errors.js +18 -1
  133. package/lib/esm/agent/errors.js.map +1 -1
  134. package/lib/esm/agent/polling/index.d.ts +3 -4
  135. package/lib/esm/agent/polling/index.d.ts.map +1 -1
  136. package/lib/esm/agent/polling/index.js +15 -8
  137. package/lib/esm/agent/polling/index.js.map +1 -1
  138. package/lib/esm/agent/polling/strategy.d.ts.map +1 -1
  139. package/lib/esm/agent/polling/strategy.js +6 -6
  140. package/lib/esm/agent/polling/strategy.js.map +1 -1
  141. package/lib/esm/agent/polling/types.d.ts +3 -4
  142. package/lib/esm/agent/polling/types.d.ts.map +1 -1
  143. package/lib/esm/agent/public_key.d.ts +3 -2
  144. package/lib/esm/agent/public_key.d.ts.map +1 -1
  145. package/lib/esm/agent/public_key.js +2 -2
  146. package/lib/esm/agent/public_key.js.map +1 -1
  147. package/lib/esm/agent/request_id.js +2 -2
  148. package/lib/esm/agent/request_id.js.map +1 -1
  149. package/lib/esm/agent/subnetStatus/index.js +1 -1
  150. package/lib/esm/agent/subnetStatus/index.js.map +1 -1
  151. package/lib/esm/agent/utils/bls.d.ts.map +1 -1
  152. package/lib/esm/agent/utils/bls.js +7 -6
  153. package/lib/esm/agent/utils/bls.js.map +1 -1
  154. package/lib/esm/agent/utils/readState.d.ts +2 -2
  155. package/lib/esm/agent/utils/readState.d.ts.map +1 -1
  156. package/lib/esm/agent/utils/readState.js +1 -1
  157. package/lib/esm/agent/utils/readState.js.map +1 -1
  158. package/lib/esm/agent/utils/target.d.ts +15 -0
  159. package/lib/esm/agent/utils/target.d.ts.map +1 -0
  160. package/lib/esm/agent/utils/target.js +23 -0
  161. package/lib/esm/agent/utils/target.js.map +1 -0
  162. package/lib/esm/candid/utils/buffer.d.ts +2 -1
  163. package/lib/esm/candid/utils/buffer.d.ts.map +1 -1
  164. package/lib/esm/candid/utils/buffer.js +5 -2
  165. package/lib/esm/candid/utils/buffer.js.map +1 -1
  166. package/lib/esm/identity/identity/attributes.d.ts +6 -2
  167. package/lib/esm/identity/identity/attributes.d.ts.map +1 -1
  168. package/lib/esm/identity/identity/attributes.js +9 -1
  169. package/lib/esm/identity/identity/attributes.js.map +1 -1
  170. package/lib/esm/identity/identity/delegation.d.ts +10 -3
  171. package/lib/esm/identity/identity/delegation.d.ts.map +1 -1
  172. package/lib/esm/identity/identity/delegation.js +22 -9
  173. package/lib/esm/identity/identity/delegation.js.map +1 -1
  174. package/lib/esm/identity/identity/ecdsa.d.ts +2 -2
  175. package/lib/esm/identity/identity/ecdsa.d.ts.map +1 -1
  176. package/lib/esm/identity/identity/ecdsa.js +3 -2
  177. package/lib/esm/identity/identity/ecdsa.js.map +1 -1
  178. package/lib/esm/identity/identity/ed25519.d.ts +3 -2
  179. package/lib/esm/identity/identity/ed25519.d.ts.map +1 -1
  180. package/lib/esm/identity/identity/ed25519.js +10 -7
  181. package/lib/esm/identity/identity/ed25519.js.map +1 -1
  182. package/lib/esm/identity/identity/webauthn.d.ts +4 -3
  183. package/lib/esm/identity/identity/webauthn.d.ts.map +1 -1
  184. package/lib/esm/identity/identity/webauthn.js +8 -7
  185. package/lib/esm/identity/identity/webauthn.js.map +1 -1
  186. package/lib/esm/identity/secp256k1/der.d.ts +2 -1
  187. package/lib/esm/identity/secp256k1/der.d.ts.map +1 -1
  188. package/lib/esm/identity/secp256k1/der.js.map +1 -1
  189. package/lib/esm/identity/secp256k1/pem.d.ts +4 -3
  190. package/lib/esm/identity/secp256k1/pem.d.ts.map +1 -1
  191. package/lib/esm/identity/secp256k1/pem.js +2 -2
  192. package/lib/esm/identity/secp256k1/pem.js.map +1 -1
  193. package/lib/esm/identity/secp256k1/secp256k1.d.ts +5 -4
  194. package/lib/esm/identity/secp256k1/secp256k1.d.ts.map +1 -1
  195. package/lib/esm/identity/secp256k1/secp256k1.js +10 -13
  196. package/lib/esm/identity/secp256k1/secp256k1.js.map +1 -1
  197. package/lib/esm/principal/principal.js +2 -2
  198. package/lib/esm/principal/principal.js.map +1 -1
  199. package/package.json +20 -10
  200. package/src/agent/actor.ts +0 -524
  201. package/src/agent/agent/api.ts +0 -292
  202. package/src/agent/agent/http/expiry.ts +0 -107
  203. package/src/agent/agent/http/index.ts +0 -1727
  204. package/src/agent/agent/http/transforms.ts +0 -54
  205. package/src/agent/agent/http/types.ts +0 -145
  206. package/src/agent/agent/index.ts +0 -4
  207. package/src/agent/auth.ts +0 -147
  208. package/src/agent/canister-env/index.ts +0 -192
  209. package/src/agent/canisterStatus/index.ts +0 -260
  210. package/src/agent/cbor.ts +0 -63
  211. package/src/agent/certificate.ts +0 -1058
  212. package/src/agent/constants.ts +0 -24
  213. package/src/agent/der.ts +0 -191
  214. package/src/agent/errors.ts +0 -962
  215. package/src/agent/fetch_candid.ts +0 -37
  216. package/src/agent/index.ts +0 -130
  217. package/src/agent/observable.ts +0 -49
  218. package/src/agent/polling/backoff.ts +0 -129
  219. package/src/agent/polling/index.ts +0 -238
  220. package/src/agent/polling/strategy.ts +0 -140
  221. package/src/agent/polling/types.ts +0 -28
  222. package/src/agent/public_key.ts +0 -65
  223. package/src/agent/request_id.ts +0 -99
  224. package/src/agent/subnetStatus/index.ts +0 -263
  225. package/src/agent/utils/bls.ts +0 -18
  226. package/src/agent/utils/buffer.ts +0 -64
  227. package/src/agent/utils/certificateReject.ts +0 -25
  228. package/src/agent/utils/createExpirableStore.ts +0 -31
  229. package/src/agent/utils/expirableStore.ts +0 -47
  230. package/src/agent/utils/inMemoryExpirableStore.ts +0 -49
  231. package/src/agent/utils/indexedDBExpirableStore.ts +0 -191
  232. package/src/agent/utils/leb.ts +0 -14
  233. package/src/agent/utils/random.ts +0 -30
  234. package/src/agent/utils/readState.ts +0 -180
  235. package/src/candid/candid-core.ts +0 -274
  236. package/src/candid/candid-ui.ts +0 -281
  237. package/src/candid/idl.ts +0 -2654
  238. package/src/candid/index.ts +0 -35
  239. package/src/candid/types.ts +0 -7
  240. package/src/candid/utils/bigint-math.ts +0 -26
  241. package/src/candid/utils/buffer.ts +0 -221
  242. package/src/candid/utils/hash.ts +0 -31
  243. package/src/candid/utils/leb128.ts +0 -233
  244. package/src/identity/identity/attributes.ts +0 -84
  245. package/src/identity/identity/delegation.ts +0 -411
  246. package/src/identity/identity/ecdsa.ts +0 -162
  247. package/src/identity/identity/ed25519.ts +0 -246
  248. package/src/identity/identity/partial.ts +0 -60
  249. package/src/identity/identity/webauthn.ts +0 -265
  250. package/src/identity/index.ts +0 -44
  251. package/src/identity/secp256k1/der.ts +0 -177
  252. package/src/identity/secp256k1/index.ts +0 -52
  253. package/src/identity/secp256k1/pem.ts +0 -39
  254. package/src/identity/secp256k1/secp256k1.ts +0 -276
  255. package/src/index.ts +0 -3
  256. package/src/principal/index.ts +0 -19
  257. package/src/principal/principal.ts +0 -181
  258. package/src/principal/utils/base32.ts +0 -101
  259. package/src/principal/utils/getCrc.ts +0 -52
@@ -1,5 +1,5 @@
1
1
  import { Principal } from '../../../principal/index.js';
2
- import { HashTreeDecodeErrorCode, CreateHttpAgentErrorCode, MissingFetchErrorCode, ExcessiveSignaturesErrorCode, ExternalError, IdentityInvalidErrorCode, IngressExpiryInvalidErrorCode, InputError, LookupErrorCode, MalformedPublicKeyErrorCode, MalformedSignatureErrorCode, MissingRootKeyErrorCode, ProtocolError, QuerySignatureVerificationFailedErrorCode, RejectError, TimeoutWaitingForResponseErrorCode, TrustError, UncertifiedRejectUpdateErrorCode, UnexpectedErrorCode, UnexpectedV4StatusErrorCode, UnknownError, HttpErrorCode, HttpV4ApiNotSupportedErrorCode, TransportError, HttpFetchErrorCode, AgentError, MalformedLookupFoundValueErrorCode, CertificateOutdatedErrorCode, CertificateNotAuthorizedErrorCode, UNREACHABLE_ERROR, } from "../../errors.js";
2
+ import { HashTreeDecodeErrorCode, CreateHttpAgentErrorCode, MissingFetchErrorCode, ExcessiveSignaturesErrorCode, ExternalError, IdentityInvalidErrorCode, IngressExpiryInvalidErrorCode, InputError, LookupErrorCode, MalformedPublicKeyErrorCode, MalformedSignatureErrorCode, MissingRootKeyErrorCode, ProtocolError, QuerySignatureVerificationFailedErrorCode, RejectError, TimeoutWaitingForResponseErrorCode, TrustError, UncertifiedRejectUpdateErrorCode, UnexpectedErrorCode, UnexpectedV4StatusErrorCode, UnknownError, HttpErrorCode, HttpV4ApiNotSupportedErrorCode, TransportError, HttpFetchErrorCode, AgentError, MalformedLookupFoundValueErrorCode, CertificateOutdatedErrorCode, CertificateNotAuthorizedErrorCode, EffectiveSubnetIdAsyncErrorCode, } from "../../errors.js";
3
3
  import { AnonymousIdentity } from "../../auth.js";
4
4
  import * as cbor from "../../cbor.js";
5
5
  import { hashOfMap, requestIdOf } from "../../request_id.js";
@@ -11,17 +11,18 @@ import { request as subnetStatusRequest } from "../../subnetStatus/index.js";
11
11
  import { lookupNodeKeysFromCertificate } from "../../utils/readState.js";
12
12
  import { Certificate, check_canister_ranges, getSubnetIdFromCertificate, lookup_path, lookupResultToBuffer, LookupPathStatus, } from "../../certificate.js";
13
13
  import { readCertifiedReject } from "../../utils/certificateReject.js";
14
- import { ed25519 } from '@noble/curves/ed25519';
14
+ import { ed25519 } from '@noble/curves/ed25519.js';
15
15
  import { createExpirableStore } from "../../utils/createExpirableStore.js";
16
16
  import { Ed25519PublicKey } from "../../public_key.js";
17
17
  import { ObservableLog } from "../../observable.js";
18
18
  import { ExponentialBackoff, } from "../../polling/backoff.js";
19
19
  import { decodeTime } from "../../utils/leb.js";
20
20
  import { pollForResponse } from "../../polling/index.js";
21
- import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';
21
+ import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js';
22
22
  import { uint8Equals, uint8FromBufLike } from "../../utils/buffer.js";
23
23
  import { IC_RESPONSE_DOMAIN_SEPARATOR } from "../../constants.js";
24
24
  import { RequestStatusResponseStatus } from "./types.js";
25
+ import { getTargetKey, inputToTarget } from "../../utils/target.js";
25
26
  export { RequestStatusResponseStatus } from "./types.js";
26
27
  const MINUTE_TO_MSECS = 60 * 1_000;
27
28
  const MSECS_TO_NANOSECONDS = 1_000_000;
@@ -217,6 +218,10 @@ export class HttpAgent {
217
218
  }
218
219
  const host = determineHost(options.host);
219
220
  this.host = new URL(host);
221
+ // Ensure trailing slash so relative API path construction preserves any base path prefix
222
+ if (!this.host.pathname.endsWith('/')) {
223
+ this.host.pathname += '/';
224
+ }
220
225
  // Rewrite to avoid redirects and normalize the host before using it for namespacing caches
221
226
  if (this.host.hostname.endsWith(IC0_SUB_DOMAIN)) {
222
227
  this.host.hostname = IC0_DOMAIN;
@@ -327,11 +332,6 @@ export class HttpAgent {
327
332
  * Makes a call to a canister method.
328
333
  * @param canisterId - The ID of the canister to call. Can be a Principal or a string.
329
334
  * @param options - Options for the call.
330
- * @param options.methodName - The name of the method to call.
331
- * @param options.arg - The argument to pass to the method, as a Uint8Array.
332
- * @param options.effectiveCanisterId - (Optional) The effective canister ID, if different from the target canister ID.
333
- * @param options.callSync - (Optional) Whether to use synchronous call mode. Defaults to true.
334
- * @param options.nonce - (Optional) A unique nonce for the request. If provided, it will override any nonce set by transforms.
335
335
  * @param identity - (Optional) The identity to use for the call. If not provided, the agent's current identity will be used.
336
336
  * @returns A promise that resolves to the response of the call, including the request ID and response details.
337
337
  */
@@ -342,10 +342,12 @@ export class HttpAgent {
342
342
  throw ExternalError.fromCode(new IdentityInvalidErrorCode());
343
343
  }
344
344
  const canister = Principal.from(canisterId);
345
- const ecid = options.effectiveCanisterId
346
- ? Principal.from(options.effectiveCanisterId)
347
- : canister;
348
- await this.#asyncGuard(ecid);
345
+ const target = options.effectiveTarget
346
+ ? inputToTarget(options.effectiveTarget)
347
+ : options.effectiveCanisterId
348
+ ? { canisterId: Principal.from(options.effectiveCanisterId) }
349
+ : { canisterId: canister };
350
+ await this.#asyncGuard(target);
349
351
  const sender = id.getPrincipal();
350
352
  const ingress_expiry = calculateIngressExpiry(this.#maxIngressExpiryInMinutes, this.#timeDiffMsecs);
351
353
  const submit = {
@@ -394,30 +396,49 @@ export class HttpAgent {
394
396
  }
395
397
  // Apply transform for identity.
396
398
  transformedRequest = (await id.transformRequest(transformedRequest));
399
+ // Compute the request ID from the post-transform content so it matches the
400
+ // hash the IC computes (e.g. when an Identity injects `sender_info`).
401
+ const requestId = requestIdOf(transformedRequest.body.content ?? submit);
397
402
  const body = cbor.encode(transformedRequest.body);
398
403
  const backoff = this.#backoffStrategy();
399
- const requestId = requestIdOf(submit);
400
404
  try {
401
- // Attempt v4 sync call
402
- const requestSync = () => {
403
- const url = new URL(`/api/v4/canister/${ecid.toText()}/call`, this.host);
404
- this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
405
- return this.#fetch(url, {
406
- ...this.#callOptions,
407
- ...transformedRequest.request,
408
- body,
409
- });
410
- };
411
- const requestAsync = () => {
412
- const url = new URL(`/api/v2/canister/${ecid.toText()}/call`, this.host);
413
- this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
414
- return this.#fetch(url, {
415
- ...this.#callOptions,
416
- ...transformedRequest.request,
417
- body,
418
- });
419
- };
420
- const requestFn = callSync ? requestSync : requestAsync;
405
+ let requestFn;
406
+ if ('canisterId' in target) {
407
+ // Attempt v4 sync call
408
+ const requestSync = () => {
409
+ const url = new URL(`api/v4/canister/${target.canisterId.toText()}/call`, this.host);
410
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
411
+ return this.#fetch(url, {
412
+ ...this.#callOptions,
413
+ ...transformedRequest.request,
414
+ body,
415
+ });
416
+ };
417
+ const requestAsync = () => {
418
+ const url = new URL(`api/v2/canister/${target.canisterId.toText()}/call`, this.host);
419
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
420
+ return this.#fetch(url, {
421
+ ...this.#callOptions,
422
+ ...transformedRequest.request,
423
+ body,
424
+ });
425
+ };
426
+ requestFn = callSync ? requestSync : requestAsync;
427
+ }
428
+ else {
429
+ if (!callSync) {
430
+ throw InputError.fromCode(new EffectiveSubnetIdAsyncErrorCode());
431
+ }
432
+ requestFn = () => {
433
+ const url = new URL(`api/v4/subnet/${target.subnetId.toText()}/call`, this.host);
434
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
435
+ return this.#fetch(url, {
436
+ ...this.#callOptions,
437
+ ...transformedRequest.request,
438
+ body,
439
+ });
440
+ };
441
+ }
421
442
  const { responseBodyBytes, ...response } = await this.#requestAndRetry({
422
443
  requestFn,
423
444
  backoff,
@@ -437,7 +458,7 @@ export class HttpAgent {
437
458
  let callError;
438
459
  if (error instanceof AgentError) {
439
460
  // If the error is due to the v4 api not being supported, fall back to v2
440
- if (error.hasCode(HttpV4ApiNotSupportedErrorCode)) {
461
+ if ('canisterId' in target && error.hasCode(HttpV4ApiNotSupportedErrorCode)) {
441
462
  this.log.warn('v4 api not supported. Fall back to v2');
442
463
  return this.call(canisterId, {
443
464
  ...options,
@@ -448,7 +469,7 @@ export class HttpAgent {
448
469
  if (error.hasCode(IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
449
470
  // if there is an ingress expiry error and the time has not been synced yet,
450
471
  // sync time with the network and try again
451
- await this.syncTime(canister);
472
+ await this.syncTime(target);
452
473
  return this.call(canister, options, identity);
453
474
  }
454
475
  // override the error code to include the request details
@@ -475,28 +496,35 @@ export class HttpAgent {
475
496
  * @returns The certified result including the certificate, reply bytes, and raw certificate bytes.
476
497
  */
477
498
  async update(canisterId, fields, pollingOptions = {}) {
478
- const effectiveCanisterId = Principal.from(fields.effectiveCanisterId);
499
+ const canister = Principal.from(canisterId);
500
+ const target = fields.effectiveTarget
501
+ ? inputToTarget(fields.effectiveTarget)
502
+ : fields.effectiveCanisterId
503
+ ? { canisterId: Principal.from(fields.effectiveCanisterId) }
504
+ : { canisterId: canister };
479
505
  const { requestId, response, requestDetails } = await this.call(canisterId, fields);
480
506
  const { body, ...httpDetails } = response;
481
507
  if (isV4ResponseBody(body)) {
482
- return this.#handleV4SyncResponse(body, response, requestId, effectiveCanisterId, fields.methodName, httpDetails, requestDetails, pollingOptions);
508
+ return this.#handleV4SyncResponse(body, response, requestId, canister, target, fields.methodName, httpDetails, requestDetails, pollingOptions, fields.onPollingStarted);
483
509
  }
484
510
  if (isV2ResponseBody(body)) {
485
- this.#handleV2Rejection(body, requestId, effectiveCanisterId, fields.methodName, httpDetails);
511
+ this.#handleV2Rejection(body, requestId, canister, target, fields.methodName, httpDetails);
486
512
  }
487
513
  if (response.status === HTTP_STATUS_ACCEPTED) {
488
- const pollResult = await pollForResponse(this, effectiveCanisterId, requestId, pollingOptions);
514
+ fields.onPollingStarted?.();
515
+ const pollResult = await pollForResponse(this, target, requestId, pollingOptions);
489
516
  return { ...pollResult, requestDetails, callResponse: response };
490
517
  }
491
518
  const unexpectedErrorCode = new UnexpectedErrorCode(`Unexpected response from call: status ${response.status} with unrecognized body`);
492
519
  unexpectedErrorCode.callContext = {
493
- canisterId: effectiveCanisterId,
520
+ canisterId: canister,
521
+ effectiveTarget: target,
494
522
  methodName: fields.methodName,
495
523
  httpDetails,
496
524
  };
497
525
  throw UnknownError.fromCode(unexpectedErrorCode);
498
526
  }
499
- async #handleV4SyncResponse(body, response, requestId, effectiveCanisterId, methodName, httpDetails, requestDetails, pollingOptions) {
527
+ async #handleV4SyncResponse(body, response, requestId, canisterId, effectiveTarget, methodName, httpDetails, requestDetails, pollingOptions, onPollingStarted) {
500
528
  if (this.rootKey == null) {
501
529
  throw ExternalError.fromCode(new MissingRootKeyErrorCode());
502
530
  }
@@ -504,7 +532,7 @@ export class HttpAgent {
504
532
  const certificate = await Certificate.create({
505
533
  certificate: rawCertificate,
506
534
  rootKey: this.rootKey,
507
- principal: { canisterId: effectiveCanisterId },
535
+ principal: effectiveTarget,
508
536
  blsVerify: pollingOptions.blsVerify,
509
537
  agent: this,
510
538
  });
@@ -523,7 +551,8 @@ export class HttpAgent {
523
551
  case RequestStatusResponseStatus.Rejected: {
524
552
  const error = readCertifiedReject(certificate, path, requestId);
525
553
  error.callContext = {
526
- canisterId: effectiveCanisterId,
554
+ canisterId,
555
+ effectiveTarget,
527
556
  methodName,
528
557
  httpDetails,
529
558
  };
@@ -533,13 +562,15 @@ export class HttpAgent {
533
562
  // The certificate does not contain an entry for our request ID status.
534
563
  // Fall back to polling via read state requests.
535
564
  this.log.warn(`v4 sync response certificate does not contain request ID ${bytesToHex(requestId)} status. Falling back to polling.`);
536
- const pollResult = await pollForResponse(this, effectiveCanisterId, requestId, pollingOptions);
565
+ onPollingStarted?.();
566
+ const pollResult = await pollForResponse(this, effectiveTarget, requestId, pollingOptions);
537
567
  return { ...pollResult, requestDetails, callResponse: response };
538
568
  }
539
569
  default: {
540
570
  const errorCode = new UnexpectedV4StatusErrorCode(status, requestId, response, rawCertificate);
541
571
  errorCode.callContext = {
542
- canisterId: effectiveCanisterId,
572
+ canisterId,
573
+ effectiveTarget,
543
574
  methodName,
544
575
  httpDetails,
545
576
  };
@@ -547,20 +578,23 @@ export class HttpAgent {
547
578
  }
548
579
  }
549
580
  }
550
- #handleV2Rejection(body, requestId, effectiveCanisterId, methodName, httpDetails) {
581
+ #handleV2Rejection(body, requestId, canisterId, target, methodName, httpDetails) {
551
582
  const { reject_code, reject_message, error_code } = body;
552
583
  const errorCode = new UncertifiedRejectUpdateErrorCode(requestId, reject_code, reject_message, error_code);
553
584
  errorCode.callContext = {
554
- canisterId: effectiveCanisterId,
585
+ canisterId,
555
586
  methodName,
556
587
  httpDetails,
588
+ effectiveTarget: target,
557
589
  };
558
590
  throw RejectError.fromCode(errorCode);
559
591
  }
560
592
  async #requestAndRetryQuery(args) {
561
- const { ecid, transformedRequest, body, requestId, backoff, tries } = args;
593
+ const { target, transformedRequest, body, requestId, backoff, tries } = args;
562
594
  const delay = tries === 0 ? 0 : backoff.next();
563
- const url = new URL(`/api/v3/canister/${ecid.toString()}/query`, this.host);
595
+ const url = 'canisterId' in target
596
+ ? new URL(`api/v3/canister/${target.canisterId.toString()}/query`, this.host)
597
+ : new URL(`api/v3/subnet/${target.subnetId.toString()}/query`, this.host);
564
598
  this.log.print(`fetching "${url.pathname}" with tries:`, {
565
599
  tries,
566
600
  backoff,
@@ -631,7 +665,7 @@ export class HttpAgent {
631
665
  requestId,
632
666
  signatureTimestampMs,
633
667
  });
634
- await this.syncTime(ecid);
668
+ await this.syncTime(target);
635
669
  return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
636
670
  }
637
671
  throw TrustError.fromCode(new CertificateOutdatedErrorCode(this.#maxIngressExpiryInMinutes, requestId, tries));
@@ -690,7 +724,7 @@ export class HttpAgent {
690
724
  };
691
725
  }
692
726
  const responseText = await response.text();
693
- if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/v4')) {
727
+ if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/v4/canister')) {
694
728
  throw ProtocolError.fromCode(new HttpV4ApiNotSupportedErrorCode());
695
729
  }
696
730
  if (isIngressExpiryInvalidResponse(responseText)) {
@@ -703,18 +737,26 @@ export class HttpAgent {
703
737
  }
704
738
  async query(canisterId, fields, identity) {
705
739
  const backoff = this.#backoffStrategy();
706
- const ecid = fields.effectiveCanisterId
707
- ? Principal.from(fields.effectiveCanisterId)
708
- : Principal.from(canisterId);
709
- await this.#asyncGuard(ecid);
710
- this.log.print(`ecid ${ecid.toString()}`);
740
+ const canister = Principal.from(canisterId);
741
+ const target = fields.effectiveTarget
742
+ ? inputToTarget(fields.effectiveTarget)
743
+ : fields.effectiveCanisterId
744
+ ? { canisterId: Principal.from(fields.effectiveCanisterId) }
745
+ : { canisterId: canister };
746
+ const targetKey = getTargetKey(target);
747
+ await this.#asyncGuard(target);
748
+ if ('canisterId' in target) {
749
+ this.log.print(`ecid ${target.canisterId.toString()}`);
750
+ }
751
+ else {
752
+ this.log.print(`esid ${target.subnetId.toString()}`);
753
+ }
711
754
  this.log.print(`canisterId ${canisterId.toString()}`);
712
755
  let transformedRequest;
713
756
  const id = await (identity ?? this.#identity);
714
757
  if (!id) {
715
758
  throw ExternalError.fromCode(new IdentityInvalidErrorCode());
716
759
  }
717
- const canister = Principal.from(canisterId);
718
760
  const sender = id.getPrincipal();
719
761
  const ingressExpiry = calculateIngressExpiry(this.#maxIngressExpiryInMinutes, this.#timeDiffMsecs);
720
762
  const request = {
@@ -725,7 +767,6 @@ export class HttpAgent {
725
767
  sender,
726
768
  ingress_expiry: ingressExpiry,
727
769
  };
728
- const requestId = requestIdOf(request);
729
770
  transformedRequest = await this._transform({
730
771
  request: {
731
772
  method: 'POST',
@@ -739,10 +780,13 @@ export class HttpAgent {
739
780
  });
740
781
  // Apply transform for identity.
741
782
  transformedRequest = (await id.transformRequest(transformedRequest));
783
+ // Compute the request ID from the post-transform content so it matches the
784
+ // hash the IC computes (e.g. when an Identity injects `sender_info`).
785
+ const requestId = requestIdOf(transformedRequest.body.content ?? request);
742
786
  const body = cbor.encode(transformedRequest.body);
743
787
  const args = {
744
788
  canister: canister.toText(),
745
- ecid,
789
+ target,
746
790
  transformedRequest,
747
791
  body,
748
792
  requestId,
@@ -765,7 +809,7 @@ export class HttpAgent {
765
809
  // Make query and fetch subnet keys in parallel
766
810
  const [queryWithDetails, subnetNodeKeys] = await Promise.all([
767
811
  makeQuery(),
768
- this.fetchSubnetKeys(ecid),
812
+ this.fetchSubnetKeys(target),
769
813
  ]);
770
814
  try {
771
815
  return this.#verifyQueryResponse(queryWithDetails, subnetNodeKeys);
@@ -773,8 +817,8 @@ export class HttpAgent {
773
817
  catch {
774
818
  // In case the node signatures have changed, refresh the subnet keys and try again
775
819
  this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');
776
- await this.#subnetNodeKeyExpirableStore.delete(ecid.toString());
777
- const updatedSubnetNodeKeys = await this.fetchSubnetKeys(ecid);
820
+ await this.#subnetNodeKeyExpirableStore.delete(targetKey);
821
+ const updatedSubnetNodeKeys = await this.fetchSubnetKeys(target);
778
822
  return this.#verifyQueryResponse(queryWithDetails, updatedSubnetNodeKeys);
779
823
  }
780
824
  }
@@ -784,7 +828,7 @@ export class HttpAgent {
784
828
  if (error.hasCode(IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
785
829
  // if there is an ingress expiry error and the time has not been synced yet,
786
830
  // sync time with the network and try again
787
- await this.syncTime(ecid);
831
+ await this.syncTime(target);
788
832
  return this.query(canisterId, fields, identity);
789
833
  }
790
834
  // override the error code to include the request details
@@ -836,20 +880,24 @@ export class HttpAgent {
836
880
  // Apply transform for identity.
837
881
  return id.transformRequest(transformedRequest);
838
882
  }
839
- async readState(canisterId, fields, _identity,
883
+ #getRequestId(options) {
884
+ for (const path of options.paths) {
885
+ const [pathName, value] = path;
886
+ const request_status = new TextEncoder().encode('request_status');
887
+ if (uint8Equals(pathName, request_status)) {
888
+ return value;
889
+ }
890
+ }
891
+ }
892
+ async readState(effectiveTarget, fields, _identity,
840
893
  // eslint-disable-next-line
841
894
  request) {
842
- await this.#rootKeyGuard();
843
- const canister = Principal.from(canisterId);
844
- function getRequestId(options) {
845
- for (const path of options.paths) {
846
- const [pathName, value] = path;
847
- const request_status = new TextEncoder().encode('request_status');
848
- if (uint8Equals(pathName, request_status)) {
849
- return value;
850
- }
851
- }
895
+ if (typeof effectiveTarget === 'string' || effectiveTarget instanceof Principal) {
896
+ // compatibility with v5
897
+ effectiveTarget = { canisterId: Principal.from(effectiveTarget) };
852
898
  }
899
+ await this.#rootKeyGuard();
900
+ const target = inputToTarget(effectiveTarget);
853
901
  let transformedRequest;
854
902
  let requestId;
855
903
  // If a pre-signed request is provided, use it
@@ -859,7 +907,7 @@ export class HttpAgent {
859
907
  }
860
908
  else {
861
909
  // This is fields, we need to create a request
862
- requestId = getRequestId(fields);
910
+ requestId = this.#getRequestId(fields);
863
911
  // Always create a fresh request with the current identity
864
912
  const identity = await this.#identity;
865
913
  if (!identity) {
@@ -867,23 +915,19 @@ export class HttpAgent {
867
915
  }
868
916
  transformedRequest = await this.createReadStateRequest(fields, identity);
869
917
  }
870
- const url = new URL(`/api/v3/canister/${canister.toString()}/read_state`, this.host);
871
- return await this.#readStateInner(url, { canisterId: canister }, transformedRequest, requestId);
918
+ const url = 'canisterId' in target
919
+ ? new URL(`api/v3/canister/${target.canisterId.toString()}/read_state`, this.host)
920
+ : new URL(`api/v3/subnet/${target.subnetId.toString()}/read_state`, this.host);
921
+ return await this.#readStateInner(url, target, transformedRequest, requestId);
872
922
  }
923
+ // eslint-disable-next-line
873
924
  /**
874
- * Reads the state of a subnet from the `/api/v3/subnet/{subnetId}/read_state` endpoint.
875
- * @param subnetId The ID of the subnet to read the state of. If you have a canister ID, you can use {@link HttpAgent.getSubnetIdFromCanister | getSubnetIdFromCanister} to get the subnet ID.
876
- * @param options The options for the read state request.
877
- * @returns The response from the read state request.
925
+ * @deprecated Use `readState`
878
926
  */
879
- async readSubnetState(subnetId, options) {
880
- await this.#rootKeyGuard();
881
- const subnet = Principal.from(subnetId);
882
- const url = new URL(`/api/v3/subnet/${subnet.toString()}/read_state`, this.host);
883
- const transformedRequest = await this.createReadStateRequest(options, this.#identity ?? undefined);
884
- return await this.#readStateInner(url, { subnetId: subnet }, transformedRequest);
927
+ readSubnetState(subnetId, options) {
928
+ return this.readState({ subnetId: Principal.from(subnetId) }, options);
885
929
  }
886
- async #readStateInner(url, principal, transformedRequest, requestId) {
930
+ async #readStateInner(url, target, transformedRequest, requestId) {
887
931
  const backoff = this.#backoffStrategy();
888
932
  try {
889
933
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -904,16 +948,8 @@ export class HttpAgent {
904
948
  if (error.hasCode(IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
905
949
  // if there is an ingress expiry error and the time has not been synced yet,
906
950
  // sync time with the network and try again
907
- if ('canisterId' in principal) {
908
- await this.syncTime(principal.canisterId);
909
- }
910
- else if ('subnetId' in principal) {
911
- await this.syncTimeWithSubnet(principal.subnetId);
912
- }
913
- else {
914
- throw UNREACHABLE_ERROR;
915
- }
916
- return await this.#readStateInner(url, principal, transformedRequest, requestId);
951
+ await this.syncTime(target);
952
+ return await this.#readStateInner(url, target, transformedRequest, requestId);
917
953
  }
918
954
  // override the error code to include the request details
919
955
  error.code.requestContext = {
@@ -958,20 +994,27 @@ export class HttpAgent {
958
994
  }
959
995
  /**
960
996
  * Allows agent to sync its time with the network. Can be called during initialization 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
961
- * @param {Principal} canisterIdOverride - Pass a canister ID if you need to sync the time with a particular subnet. Uses the ICP ledger canister by default.
997
+ * @param {TargetPrincipal} targetOverride - Pass a canister or subnet ID if you need to sync the time with a particular subnet. Uses the ICP ledger canister by default.
962
998
  */
963
- async syncTime(canisterIdOverride) {
999
+ async syncTime(targetOverride) {
1000
+ if (targetOverride &&
1001
+ (typeof targetOverride === 'string' || targetOverride instanceof Principal)) {
1002
+ // compatibility with v5
1003
+ targetOverride = { canisterId: Principal.from(targetOverride) };
1004
+ }
964
1005
  this.#syncTimePromise =
965
1006
  this.#syncTimePromise ??
966
1007
  (async () => {
967
1008
  await this.#rootKeyGuard();
968
1009
  const callTime = Date.now();
969
1010
  try {
970
- if (!canisterIdOverride) {
971
- this.log.print('Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');
1011
+ if (!targetOverride) {
1012
+ this.log.print('Syncing time with the IC. No target provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');
972
1013
  }
973
1014
  // Fall back with canisterId of the ICP Ledger
974
- const canisterId = canisterIdOverride ?? Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai');
1015
+ const target = targetOverride ?? {
1016
+ canisterId: Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),
1017
+ };
975
1018
  const anonymousAgent = HttpAgent.createSync({
976
1019
  identity: new AnonymousIdentity(),
977
1020
  host: this.host.toString(),
@@ -983,12 +1026,19 @@ export class HttpAgent {
983
1026
  const replicaTimes = await Promise.all(Array(3)
984
1027
  .fill(null)
985
1028
  .map(async () => {
986
- const status = await canisterStatusRequest({
987
- canisterId,
988
- agent: anonymousAgent,
989
- paths: ['time'],
990
- disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
991
- });
1029
+ const status = 'canisterId' in target
1030
+ ? await canisterStatusRequest({
1031
+ canisterId: target.canisterId,
1032
+ agent: anonymousAgent,
1033
+ paths: ['time'],
1034
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1035
+ })
1036
+ : await subnetStatusRequest({
1037
+ subnetId: target.subnetId,
1038
+ agent: anonymousAgent,
1039
+ paths: ['time'],
1040
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1041
+ });
992
1042
  const date = status.get('time');
993
1043
  if (date instanceof Date) {
994
1044
  return date.getTime();
@@ -1008,43 +1058,12 @@ export class HttpAgent {
1008
1058
  this.#syncTimePromise = null;
1009
1059
  });
1010
1060
  }
1061
+ // eslint-disable-next-line
1011
1062
  /**
1012
- * Allows agent to sync its time with the network.
1013
- * @param {Principal} subnetId - Pass the subnet ID you need to sync the time with.
1063
+ * @deprecated Use {@link syncTime}
1014
1064
  */
1015
- async syncTimeWithSubnet(subnetId) {
1016
- await this.#rootKeyGuard();
1017
- const callTime = Date.now();
1018
- try {
1019
- const anonymousAgent = HttpAgent.createSync({
1020
- identity: new AnonymousIdentity(),
1021
- host: this.host.toString(),
1022
- fetch: this.#fetch,
1023
- retryTimes: 0,
1024
- rootKey: this.rootKey ?? undefined,
1025
- shouldSyncTime: false,
1026
- });
1027
- const replicaTimes = await Promise.all(Array(3)
1028
- .fill(null)
1029
- .map(async () => {
1030
- const status = await subnetStatusRequest({
1031
- subnetId,
1032
- agent: anonymousAgent,
1033
- paths: ['time'],
1034
- disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1035
- });
1036
- const date = status.get('time');
1037
- if (date instanceof Date) {
1038
- return date.getTime();
1039
- }
1040
- }, []));
1041
- this.#setTimeDiffMsecs(callTime, replicaTimes);
1042
- }
1043
- catch (error) {
1044
- const syncTimeError = error instanceof AgentError ? error : UnknownError.fromCode(new UnexpectedErrorCode(error));
1045
- this.log.error('Caught exception while attempting to sync time with subnet', syncTimeError);
1046
- throw syncTimeError;
1047
- }
1065
+ syncTimeWithSubnet(subnetId) {
1066
+ return this.syncTime({ subnetId });
1048
1067
  }
1049
1068
  #setTimeDiffMsecs(callTime, replicaTimes) {
1050
1069
  const maxReplicaTime = replicaTimes.reduce((max, current) => {
@@ -1065,7 +1084,7 @@ export class HttpAgent {
1065
1084
  Authorization: `Basic ${btoa(this.#credentials)}`,
1066
1085
  }
1067
1086
  : {};
1068
- const url = new URL(`/api/v2/status`, this.host);
1087
+ const url = new URL(`api/v2/status`, this.host);
1069
1088
  this.log.print(`fetching "${url.pathname}"`);
1070
1089
  const backoff = this.#backoffStrategy();
1071
1090
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -1090,8 +1109,8 @@ export class HttpAgent {
1090
1109
  this.#rootKeyPromise = null;
1091
1110
  });
1092
1111
  }
1093
- async #asyncGuard(canisterIdOverride) {
1094
- await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(canisterIdOverride)]);
1112
+ async #asyncGuard(targetOverride) {
1113
+ await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(targetOverride)]);
1095
1114
  }
1096
1115
  async #rootKeyGuard() {
1097
1116
  if (this.rootKey) {
@@ -1106,9 +1125,9 @@ export class HttpAgent {
1106
1125
  throw ExternalError.fromCode(new MissingRootKeyErrorCode(this.#shouldFetchRootKey));
1107
1126
  }
1108
1127
  }
1109
- async #syncTimeGuard(canisterIdOverride) {
1128
+ async #syncTimeGuard(targetOverride) {
1110
1129
  if (this.#shouldSyncTime && !this.hasSyncedTime()) {
1111
- await this.syncTime(canisterIdOverride);
1130
+ await this.syncTime(targetOverride);
1112
1131
  }
1113
1132
  }
1114
1133
  invalidateIdentity() {
@@ -1117,52 +1136,58 @@ export class HttpAgent {
1117
1136
  replaceIdentity(identity) {
1118
1137
  this.#identity = Promise.resolve(identity);
1119
1138
  }
1120
- async fetchSubnetKeys(canisterId) {
1121
- const effectiveCanisterId = Principal.from(canisterId);
1139
+ async fetchSubnetKeys(effectiveTarget) {
1140
+ if (typeof effectiveTarget === 'string' || effectiveTarget instanceof Principal) {
1141
+ // compatibility with v5
1142
+ effectiveTarget = { canisterId: Principal.from(effectiveTarget) };
1143
+ }
1144
+ const target = inputToTarget(effectiveTarget);
1145
+ const targetKey = getTargetKey(target);
1122
1146
  // Return cached result if available within the TTL.
1123
- const cached = await this.#subnetNodeKeyExpirableStore.get(effectiveCanisterId.toText());
1147
+ const cached = await this.#subnetNodeKeyExpirableStore.get(targetKey);
1124
1148
  if (cached) {
1125
1149
  return cached;
1126
1150
  }
1127
1151
  // Deduplicate parallel requests for the same canister so that concurrent
1128
1152
  // query calls share a single read_state round-trip instead of each
1129
1153
  // issuing their own.
1130
- const inflight = this.#subnetKeysFetching.get(effectiveCanisterId.toText());
1154
+ const inflight = this.#subnetKeysFetching.get(targetKey);
1131
1155
  if (inflight) {
1132
1156
  return inflight;
1133
1157
  }
1134
- const fetchPromise = this.#doFetchSubnetKeys(effectiveCanisterId).finally(() => {
1135
- this.#subnetKeysFetching.delete(effectiveCanisterId.toText());
1158
+ const fetchPromise = this.#doFetchSubnetKeys(target).finally(() => {
1159
+ this.#subnetKeysFetching.delete(targetKey);
1136
1160
  });
1137
- this.#subnetKeysFetching.set(effectiveCanisterId.toText(), fetchPromise);
1161
+ this.#subnetKeysFetching.set(targetKey, fetchPromise);
1138
1162
  return fetchPromise;
1139
1163
  }
1140
- async #doFetchSubnetKeys(effectiveCanisterId) {
1141
- await this.#asyncGuard(effectiveCanisterId);
1164
+ async #doFetchSubnetKeys(target) {
1165
+ await this.#asyncGuard(target);
1142
1166
  const rootKey = this.rootKey;
1143
- const canisterReadState = await this.readState(effectiveCanisterId, {
1167
+ const canisterReadState = await this.readState(target, {
1144
1168
  paths: [[utf8ToBytes('subnet')]],
1145
1169
  });
1146
1170
  const canisterCertificate = await Certificate.create({
1147
1171
  certificate: canisterReadState.certificate,
1148
1172
  rootKey,
1149
- principal: { canisterId: effectiveCanisterId },
1173
+ principal: target,
1150
1174
  agent: this,
1151
1175
  });
1152
- if (!canisterCertificate.cert.delegation) {
1176
+ const targetKey = getTargetKey(target);
1177
+ if ('canisterId' in target && !canisterCertificate.cert.delegation) {
1153
1178
  const subnetId = Principal.selfAuthenticating(rootKey);
1154
1179
  const canisterInRange = check_canister_ranges({
1155
- canisterId: effectiveCanisterId,
1180
+ canisterId: target.canisterId,
1156
1181
  subnetId,
1157
1182
  tree: canisterCertificate.cert.tree,
1158
1183
  });
1159
1184
  if (!canisterInRange) {
1160
- throw TrustError.fromCode(new CertificateNotAuthorizedErrorCode(effectiveCanisterId, subnetId));
1185
+ throw TrustError.fromCode(new CertificateNotAuthorizedErrorCode(target.canisterId, subnetId));
1161
1186
  }
1162
1187
  }
1163
1188
  const subnetId = getSubnetIdFromCertificate(canisterCertificate.cert, rootKey);
1164
1189
  const nodeKeys = lookupNodeKeysFromCertificate(canisterCertificate.cert, subnetId);
1165
- await this.#subnetNodeKeyExpirableStore.set(effectiveCanisterId.toText(), nodeKeys);
1190
+ await this.#subnetNodeKeyExpirableStore.set(targetKey, nodeKeys);
1166
1191
  return nodeKeys;
1167
1192
  }
1168
1193
  /**
@@ -1173,8 +1198,8 @@ export class HttpAgent {
1173
1198
  */
1174
1199
  async getSubnetIdFromCanister(canisterId) {
1175
1200
  const effectiveCanisterId = Principal.from(canisterId);
1176
- await this.#asyncGuard(effectiveCanisterId);
1177
- const canisterReadState = await this.readState(effectiveCanisterId, {
1201
+ await this.#asyncGuard({ canisterId: effectiveCanisterId });
1202
+ const canisterReadState = await this.readState({ canisterId: effectiveCanisterId }, {
1178
1203
  paths: [[utf8ToBytes('time')]],
1179
1204
  });
1180
1205
  const canisterCertificate = await Certificate.create({