@icp-sdk/core 5.4.0 → 6.1.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 +71 -10
  6. package/lib/cjs/agent/agent/api.d.ts.map +1 -1
  7. package/lib/cjs/agent/agent/api.js +6 -1
  8. package/lib/cjs/agent/agent/api.js.map +1 -1
  9. package/lib/cjs/agent/agent/http/index.d.ts +9 -12
  10. package/lib/cjs/agent/agent/http/index.d.ts.map +1 -1
  11. package/lib/cjs/agent/agent/http/index.js +224 -176
  12. package/lib/cjs/agent/agent/http/index.js.map +1 -1
  13. package/lib/cjs/agent/auth.d.ts +6 -5
  14. package/lib/cjs/agent/auth.d.ts.map +1 -1
  15. package/lib/cjs/agent/auth.js +3 -3
  16. package/lib/cjs/agent/auth.js.map +1 -1
  17. package/lib/cjs/agent/canisterStatus/index.d.ts +2 -3
  18. package/lib/cjs/agent/canisterStatus/index.d.ts.map +1 -1
  19. package/lib/cjs/agent/canisterStatus/index.js +65 -122
  20. package/lib/cjs/agent/canisterStatus/index.js.map +1 -1
  21. package/lib/cjs/agent/cbor.d.ts +2 -1
  22. package/lib/cjs/agent/cbor.d.ts.map +1 -1
  23. package/lib/cjs/agent/cbor.js +4 -1
  24. package/lib/cjs/agent/cbor.js.map +1 -1
  25. package/lib/cjs/agent/certificate.d.ts +6 -5
  26. package/lib/cjs/agent/certificate.d.ts.map +1 -1
  27. package/lib/cjs/agent/certificate.js +14 -18
  28. package/lib/cjs/agent/certificate.js.map +1 -1
  29. package/lib/cjs/agent/der.d.ts +3 -2
  30. package/lib/cjs/agent/der.d.ts.map +1 -1
  31. package/lib/cjs/agent/der.js.map +1 -1
  32. package/lib/cjs/agent/errors.d.ts +7 -1
  33. package/lib/cjs/agent/errors.d.ts.map +1 -1
  34. package/lib/cjs/agent/errors.js +34 -16
  35. package/lib/cjs/agent/errors.js.map +1 -1
  36. package/lib/cjs/agent/polling/index.d.ts +7 -7
  37. package/lib/cjs/agent/polling/index.d.ts.map +1 -1
  38. package/lib/cjs/agent/polling/index.js +19 -20
  39. package/lib/cjs/agent/polling/index.js.map +1 -1
  40. package/lib/cjs/agent/polling/strategy.d.ts.map +1 -1
  41. package/lib/cjs/agent/polling/strategy.js +6 -6
  42. package/lib/cjs/agent/polling/strategy.js.map +1 -1
  43. package/lib/cjs/agent/polling/types.d.ts +3 -4
  44. package/lib/cjs/agent/polling/types.d.ts.map +1 -1
  45. package/lib/cjs/agent/public_key.d.ts +3 -2
  46. package/lib/cjs/agent/public_key.d.ts.map +1 -1
  47. package/lib/cjs/agent/public_key.js +2 -2
  48. package/lib/cjs/agent/public_key.js.map +1 -1
  49. package/lib/cjs/agent/request_id.js +10 -10
  50. package/lib/cjs/agent/request_id.js.map +1 -1
  51. package/lib/cjs/agent/subnetStatus/index.d.ts +3 -2
  52. package/lib/cjs/agent/subnetStatus/index.d.ts.map +1 -1
  53. package/lib/cjs/agent/subnetStatus/index.js +65 -88
  54. package/lib/cjs/agent/subnetStatus/index.js.map +1 -1
  55. package/lib/cjs/agent/utils/bls.d.ts.map +1 -1
  56. package/lib/cjs/agent/utils/bls.js +7 -6
  57. package/lib/cjs/agent/utils/bls.js.map +1 -1
  58. package/lib/cjs/agent/utils/readState.d.ts +104 -15
  59. package/lib/cjs/agent/utils/readState.d.ts.map +1 -1
  60. package/lib/cjs/agent/utils/readState.js +106 -17
  61. package/lib/cjs/agent/utils/readState.js.map +1 -1
  62. package/lib/cjs/agent/utils/target.d.ts +15 -0
  63. package/lib/cjs/agent/utils/target.d.ts.map +1 -0
  64. package/lib/cjs/agent/utils/target.js +27 -0
  65. package/lib/cjs/agent/utils/target.js.map +1 -0
  66. package/lib/cjs/candid/utils/buffer.d.ts +2 -1
  67. package/lib/cjs/candid/utils/buffer.d.ts.map +1 -1
  68. package/lib/cjs/candid/utils/buffer.js +5 -2
  69. package/lib/cjs/candid/utils/buffer.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 +71 -10
  104. package/lib/esm/agent/agent/api.d.ts.map +1 -1
  105. package/lib/esm/agent/agent/api.js +1 -0
  106. package/lib/esm/agent/agent/api.js.map +1 -1
  107. package/lib/esm/agent/agent/http/index.d.ts +9 -12
  108. package/lib/esm/agent/agent/http/index.d.ts.map +1 -1
  109. package/lib/esm/agent/agent/http/index.js +218 -170
  110. package/lib/esm/agent/agent/http/index.js.map +1 -1
  111. package/lib/esm/agent/auth.d.ts +6 -5
  112. package/lib/esm/agent/auth.d.ts.map +1 -1
  113. package/lib/esm/agent/auth.js +1 -1
  114. package/lib/esm/agent/auth.js.map +1 -1
  115. package/lib/esm/agent/canister-env/index.js +1 -1
  116. package/lib/esm/agent/canister-env/index.js.map +1 -1
  117. package/lib/esm/agent/canisterStatus/index.d.ts +2 -3
  118. package/lib/esm/agent/canisterStatus/index.d.ts.map +1 -1
  119. package/lib/esm/agent/canisterStatus/index.js +66 -122
  120. package/lib/esm/agent/canisterStatus/index.js.map +1 -1
  121. package/lib/esm/agent/cbor.d.ts +2 -1
  122. package/lib/esm/agent/cbor.d.ts.map +1 -1
  123. package/lib/esm/agent/cbor.js +4 -1
  124. package/lib/esm/agent/cbor.js.map +1 -1
  125. package/lib/esm/agent/certificate.d.ts +6 -5
  126. package/lib/esm/agent/certificate.d.ts.map +1 -1
  127. package/lib/esm/agent/certificate.js +5 -9
  128. package/lib/esm/agent/certificate.js.map +1 -1
  129. package/lib/esm/agent/der.d.ts +3 -2
  130. package/lib/esm/agent/der.d.ts.map +1 -1
  131. package/lib/esm/agent/der.js.map +1 -1
  132. package/lib/esm/agent/errors.d.ts +7 -1
  133. package/lib/esm/agent/errors.d.ts.map +1 -1
  134. package/lib/esm/agent/errors.js +18 -1
  135. package/lib/esm/agent/errors.js.map +1 -1
  136. package/lib/esm/agent/polling/index.d.ts +7 -7
  137. package/lib/esm/agent/polling/index.d.ts.map +1 -1
  138. package/lib/esm/agent/polling/index.js +19 -20
  139. package/lib/esm/agent/polling/index.js.map +1 -1
  140. package/lib/esm/agent/polling/strategy.d.ts.map +1 -1
  141. package/lib/esm/agent/polling/strategy.js +6 -6
  142. package/lib/esm/agent/polling/strategy.js.map +1 -1
  143. package/lib/esm/agent/polling/types.d.ts +3 -4
  144. package/lib/esm/agent/polling/types.d.ts.map +1 -1
  145. package/lib/esm/agent/public_key.d.ts +3 -2
  146. package/lib/esm/agent/public_key.d.ts.map +1 -1
  147. package/lib/esm/agent/public_key.js +2 -2
  148. package/lib/esm/agent/public_key.js.map +1 -1
  149. package/lib/esm/agent/request_id.js +2 -2
  150. package/lib/esm/agent/request_id.js.map +1 -1
  151. package/lib/esm/agent/subnetStatus/index.d.ts +3 -2
  152. package/lib/esm/agent/subnetStatus/index.d.ts.map +1 -1
  153. package/lib/esm/agent/subnetStatus/index.js +63 -86
  154. package/lib/esm/agent/subnetStatus/index.js.map +1 -1
  155. package/lib/esm/agent/utils/bls.d.ts.map +1 -1
  156. package/lib/esm/agent/utils/bls.js +7 -6
  157. package/lib/esm/agent/utils/bls.js.map +1 -1
  158. package/lib/esm/agent/utils/readState.d.ts +104 -15
  159. package/lib/esm/agent/utils/readState.d.ts.map +1 -1
  160. package/lib/esm/agent/utils/readState.js +103 -16
  161. package/lib/esm/agent/utils/readState.js.map +1 -1
  162. package/lib/esm/agent/utils/target.d.ts +15 -0
  163. package/lib/esm/agent/utils/target.d.ts.map +1 -0
  164. package/lib/esm/agent/utils/target.js +23 -0
  165. package/lib/esm/agent/utils/target.js.map +1 -0
  166. package/lib/esm/candid/utils/buffer.d.ts +2 -1
  167. package/lib/esm/candid/utils/buffer.d.ts.map +1 -1
  168. package/lib/esm/candid/utils/buffer.js +5 -2
  169. package/lib/esm/candid/utils/buffer.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 -310
  202. package/src/agent/agent/http/expiry.ts +0 -107
  203. package/src/agent/agent/http/index.ts +0 -1724
  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 -91
  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";
@@ -8,20 +8,21 @@ import { Expiry, httpHeadersTransform, makeNonceTransform } from "./transforms.j
8
8
  import { Endpoint, makeNonce, ReadRequestType, SubmitRequestType, } from "./types.js";
9
9
  import { request as canisterStatusRequest } from "../../canisterStatus/index.js";
10
10
  import { request as subnetStatusRequest } from "../../subnetStatus/index.js";
11
- import { lookupNodeKeysFromCertificate } from "../../utils/readState.js";
11
+ import { StateValues, encodePath, 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,39 @@ 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) {
895
+ if (typeof effectiveTarget === 'string' || effectiveTarget instanceof Principal) {
896
+ // compatibility with v5
897
+ effectiveTarget = { canisterId: Principal.from(effectiveTarget) };
898
+ }
843
899
  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
- }
900
+ const target = inputToTarget(effectiveTarget);
901
+ if (!fields.disableTimeVerification) {
902
+ await this.#syncTimeGuard(target);
903
+ }
904
+ // Encode paths into their raw form. Raw (pre-encoded) paths pass through unchanged; each
905
+ // KnownPath is retained alongside its encoded form so its value can be decoded below.
906
+ const encodedPaths = [];
907
+ const knownPaths = [];
908
+ for (const path of fields.paths) {
909
+ const encoded = encodePath(path);
910
+ encodedPaths.push(encoded);
911
+ if (!Array.isArray(path)) {
912
+ knownPaths.push({ path, encoded });
852
913
  }
853
914
  }
915
+ const resolvedFields = { ...fields, paths: encodedPaths };
854
916
  let transformedRequest;
855
917
  let requestId;
856
918
  // If a pre-signed request is provided, use it
@@ -860,31 +922,48 @@ export class HttpAgent {
860
922
  }
861
923
  else {
862
924
  // This is fields, we need to create a request
863
- requestId = getRequestId(fields);
925
+ requestId = this.#getRequestId(resolvedFields);
864
926
  // Always create a fresh request with the current identity
865
927
  const identity = await this.#identity;
866
928
  if (!identity) {
867
929
  throw ExternalError.fromCode(new IdentityInvalidErrorCode());
868
930
  }
869
- transformedRequest = await this.createReadStateRequest(fields, identity);
931
+ transformedRequest = await this.createReadStateRequest(resolvedFields, identity);
870
932
  }
871
- const url = new URL(`/api/v3/canister/${canister.toString()}/read_state`, this.host);
872
- return await this.#readStateInner(url, { canisterId: canister }, transformedRequest, requestId);
933
+ const url = 'canisterId' in target
934
+ ? new URL(`api/v3/canister/${target.canisterId.toString()}/read_state`, this.host)
935
+ : new URL(`api/v3/subnet/${target.subnetId.toString()}/read_state`, this.host);
936
+ if (this.rootKey === null) {
937
+ throw ExternalError.fromCode(new MissingRootKeyErrorCode(this.#shouldFetchRootKey));
938
+ }
939
+ const rootKey = this.rootKey;
940
+ const { certificate } = await this.#readStateInner(url, target, transformedRequest, requestId);
941
+ const verifiedCertificate = await Certificate.create({
942
+ certificate,
943
+ rootKey,
944
+ principal: target,
945
+ blsVerify: fields.blsVerify,
946
+ maxAgeInMinutes: fields.maxAgeInMinutes,
947
+ disableTimeVerification: fields.disableTimeVerification,
948
+ agent: this,
949
+ });
950
+ // Decode the value at each KnownPath with its own decoder, keyed by the path. A value absent
951
+ // from the certificate maps to null.
952
+ const decoded = new Map();
953
+ for (const { path, encoded } of knownPaths) {
954
+ const buffer = lookupResultToBuffer(verifiedCertificate.lookup_path(encoded));
955
+ decoded.set(path.key, buffer === undefined ? null : path.decode(buffer));
956
+ }
957
+ return { certificate, verifiedCertificate, values: new StateValues(decoded) };
873
958
  }
959
+ // eslint-disable-next-line
874
960
  /**
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.
961
+ * @deprecated Use `readState`
879
962
  */
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);
963
+ readSubnetState(subnetId, options) {
964
+ return this.readState({ subnetId: Principal.from(subnetId) }, options);
886
965
  }
887
- async #readStateInner(url, principal, transformedRequest, requestId) {
966
+ async #readStateInner(url, target, transformedRequest, requestId) {
888
967
  const backoff = this.#backoffStrategy();
889
968
  try {
890
969
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -905,16 +984,8 @@ export class HttpAgent {
905
984
  if (error.hasCode(IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
906
985
  // if there is an ingress expiry error and the time has not been synced yet,
907
986
  // 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);
987
+ await this.syncTime(target);
988
+ return await this.#readStateInner(url, target, transformedRequest, requestId);
918
989
  }
919
990
  // override the error code to include the request details
920
991
  error.code.requestContext = {
@@ -959,20 +1030,27 @@ export class HttpAgent {
959
1030
  }
960
1031
  /**
961
1032
  * 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.
1033
+ * @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
1034
  */
964
- async syncTime(canisterIdOverride) {
1035
+ async syncTime(targetOverride) {
1036
+ if (targetOverride &&
1037
+ (typeof targetOverride === 'string' || targetOverride instanceof Principal)) {
1038
+ // compatibility with v5
1039
+ targetOverride = { canisterId: Principal.from(targetOverride) };
1040
+ }
965
1041
  this.#syncTimePromise =
966
1042
  this.#syncTimePromise ??
967
1043
  (async () => {
968
1044
  await this.#rootKeyGuard();
969
1045
  const callTime = Date.now();
970
1046
  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');
1047
+ if (!targetOverride) {
1048
+ this.log.print('Syncing time with the IC. No target provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');
973
1049
  }
974
1050
  // Fall back with canisterId of the ICP Ledger
975
- const canisterId = canisterIdOverride ?? Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai');
1051
+ const target = targetOverride ?? {
1052
+ canisterId: Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),
1053
+ };
976
1054
  const anonymousAgent = HttpAgent.createSync({
977
1055
  identity: new AnonymousIdentity(),
978
1056
  host: this.host.toString(),
@@ -984,12 +1062,19 @@ export class HttpAgent {
984
1062
  const replicaTimes = await Promise.all(Array(3)
985
1063
  .fill(null)
986
1064
  .map(async () => {
987
- const status = await canisterStatusRequest({
988
- canisterId,
989
- agent: anonymousAgent,
990
- paths: ['time'],
991
- disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
992
- });
1065
+ const status = 'canisterId' in target
1066
+ ? await canisterStatusRequest({
1067
+ canisterId: target.canisterId,
1068
+ agent: anonymousAgent,
1069
+ paths: ['time'],
1070
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1071
+ })
1072
+ : await subnetStatusRequest({
1073
+ subnetId: target.subnetId,
1074
+ agent: anonymousAgent,
1075
+ paths: ['time'],
1076
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1077
+ });
993
1078
  const date = status.get('time');
994
1079
  if (date instanceof Date) {
995
1080
  return date.getTime();
@@ -1009,43 +1094,12 @@ export class HttpAgent {
1009
1094
  this.#syncTimePromise = null;
1010
1095
  });
1011
1096
  }
1097
+ // eslint-disable-next-line
1012
1098
  /**
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.
1099
+ * @deprecated Use {@link syncTime}
1015
1100
  */
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
- }
1101
+ syncTimeWithSubnet(subnetId) {
1102
+ return this.syncTime({ subnetId });
1049
1103
  }
1050
1104
  #setTimeDiffMsecs(callTime, replicaTimes) {
1051
1105
  const maxReplicaTime = replicaTimes.reduce((max, current) => {
@@ -1066,7 +1120,7 @@ export class HttpAgent {
1066
1120
  Authorization: `Basic ${btoa(this.#credentials)}`,
1067
1121
  }
1068
1122
  : {};
1069
- const url = new URL(`/api/v2/status`, this.host);
1123
+ const url = new URL(`api/v2/status`, this.host);
1070
1124
  this.log.print(`fetching "${url.pathname}"`);
1071
1125
  const backoff = this.#backoffStrategy();
1072
1126
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -1091,8 +1145,8 @@ export class HttpAgent {
1091
1145
  this.#rootKeyPromise = null;
1092
1146
  });
1093
1147
  }
1094
- async #asyncGuard(canisterIdOverride) {
1095
- await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(canisterIdOverride)]);
1148
+ async #asyncGuard(targetOverride) {
1149
+ await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(targetOverride)]);
1096
1150
  }
1097
1151
  async #rootKeyGuard() {
1098
1152
  if (this.rootKey) {
@@ -1107,9 +1161,9 @@ export class HttpAgent {
1107
1161
  throw ExternalError.fromCode(new MissingRootKeyErrorCode(this.#shouldFetchRootKey));
1108
1162
  }
1109
1163
  }
1110
- async #syncTimeGuard(canisterIdOverride) {
1164
+ async #syncTimeGuard(targetOverride) {
1111
1165
  if (this.#shouldSyncTime && !this.hasSyncedTime()) {
1112
- await this.syncTime(canisterIdOverride);
1166
+ await this.syncTime(targetOverride);
1113
1167
  }
1114
1168
  }
1115
1169
  invalidateIdentity() {
@@ -1118,52 +1172,52 @@ export class HttpAgent {
1118
1172
  replaceIdentity(identity) {
1119
1173
  this.#identity = Promise.resolve(identity);
1120
1174
  }
1121
- async fetchSubnetKeys(canisterId) {
1122
- const effectiveCanisterId = Principal.from(canisterId);
1175
+ async fetchSubnetKeys(effectiveTarget) {
1176
+ if (typeof effectiveTarget === 'string' || effectiveTarget instanceof Principal) {
1177
+ // compatibility with v5
1178
+ effectiveTarget = { canisterId: Principal.from(effectiveTarget) };
1179
+ }
1180
+ const target = inputToTarget(effectiveTarget);
1181
+ const targetKey = getTargetKey(target);
1123
1182
  // Return cached result if available within the TTL.
1124
- const cached = await this.#subnetNodeKeyExpirableStore.get(effectiveCanisterId.toText());
1183
+ const cached = await this.#subnetNodeKeyExpirableStore.get(targetKey);
1125
1184
  if (cached) {
1126
1185
  return cached;
1127
1186
  }
1128
1187
  // Deduplicate parallel requests for the same canister so that concurrent
1129
1188
  // query calls share a single read_state round-trip instead of each
1130
1189
  // issuing their own.
1131
- const inflight = this.#subnetKeysFetching.get(effectiveCanisterId.toText());
1190
+ const inflight = this.#subnetKeysFetching.get(targetKey);
1132
1191
  if (inflight) {
1133
1192
  return inflight;
1134
1193
  }
1135
- const fetchPromise = this.#doFetchSubnetKeys(effectiveCanisterId).finally(() => {
1136
- this.#subnetKeysFetching.delete(effectiveCanisterId.toText());
1194
+ const fetchPromise = this.#doFetchSubnetKeys(target).finally(() => {
1195
+ this.#subnetKeysFetching.delete(targetKey);
1137
1196
  });
1138
- this.#subnetKeysFetching.set(effectiveCanisterId.toText(), fetchPromise);
1197
+ this.#subnetKeysFetching.set(targetKey, fetchPromise);
1139
1198
  return fetchPromise;
1140
1199
  }
1141
- async #doFetchSubnetKeys(effectiveCanisterId) {
1142
- await this.#asyncGuard(effectiveCanisterId);
1200
+ async #doFetchSubnetKeys(target) {
1201
+ await this.#asyncGuard(target);
1143
1202
  const rootKey = this.rootKey;
1144
- const canisterReadState = await this.readState(effectiveCanisterId, {
1203
+ const { verifiedCertificate: canisterCertificate } = await this.readState(target, {
1145
1204
  paths: [[utf8ToBytes('subnet')]],
1146
1205
  });
1147
- const canisterCertificate = await Certificate.create({
1148
- certificate: canisterReadState.certificate,
1149
- rootKey,
1150
- principal: { canisterId: effectiveCanisterId },
1151
- agent: this,
1152
- });
1153
- if (!canisterCertificate.cert.delegation) {
1206
+ const targetKey = getTargetKey(target);
1207
+ if ('canisterId' in target && !canisterCertificate.cert.delegation) {
1154
1208
  const subnetId = Principal.selfAuthenticating(rootKey);
1155
1209
  const canisterInRange = check_canister_ranges({
1156
- canisterId: effectiveCanisterId,
1210
+ canisterId: target.canisterId,
1157
1211
  subnetId,
1158
1212
  tree: canisterCertificate.cert.tree,
1159
1213
  });
1160
1214
  if (!canisterInRange) {
1161
- throw TrustError.fromCode(new CertificateNotAuthorizedErrorCode(effectiveCanisterId, subnetId));
1215
+ throw TrustError.fromCode(new CertificateNotAuthorizedErrorCode(target.canisterId, subnetId));
1162
1216
  }
1163
1217
  }
1164
1218
  const subnetId = getSubnetIdFromCertificate(canisterCertificate.cert, rootKey);
1165
1219
  const nodeKeys = lookupNodeKeysFromCertificate(canisterCertificate.cert, subnetId);
1166
- await this.#subnetNodeKeyExpirableStore.set(effectiveCanisterId.toText(), nodeKeys);
1220
+ await this.#subnetNodeKeyExpirableStore.set(targetKey, nodeKeys);
1167
1221
  return nodeKeys;
1168
1222
  }
1169
1223
  /**
@@ -1174,16 +1228,10 @@ export class HttpAgent {
1174
1228
  */
1175
1229
  async getSubnetIdFromCanister(canisterId) {
1176
1230
  const effectiveCanisterId = Principal.from(canisterId);
1177
- await this.#asyncGuard(effectiveCanisterId);
1178
- const canisterReadState = await this.readState(effectiveCanisterId, {
1231
+ await this.#asyncGuard({ canisterId: effectiveCanisterId });
1232
+ const { verifiedCertificate: canisterCertificate } = await this.readState({ canisterId: effectiveCanisterId }, {
1179
1233
  paths: [[utf8ToBytes('time')]],
1180
1234
  });
1181
- const canisterCertificate = await Certificate.create({
1182
- certificate: canisterReadState.certificate,
1183
- rootKey: this.rootKey,
1184
- principal: { canisterId: effectiveCanisterId },
1185
- agent: this,
1186
- });
1187
1235
  return getSubnetIdFromCertificate(canisterCertificate.cert, this.rootKey);
1188
1236
  }
1189
1237
  _transform(request) {