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