@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
@@ -48,17 +48,18 @@ const index_ts_2 = require("../../subnetStatus/index.js");
48
48
  const readState_ts_1 = require("../../utils/readState.js");
49
49
  const certificate_ts_1 = require("../../certificate.js");
50
50
  const certificateReject_ts_1 = require("../../utils/certificateReject.js");
51
- const ed25519_1 = require("@noble/curves/ed25519");
51
+ const ed25519_js_1 = require("@noble/curves/ed25519.js");
52
52
  const createExpirableStore_ts_1 = require("../../utils/createExpirableStore.js");
53
53
  const public_key_ts_1 = require("../../public_key.js");
54
54
  const observable_ts_1 = require("../../observable.js");
55
55
  const backoff_ts_1 = require("../../polling/backoff.js");
56
56
  const leb_ts_1 = require("../../utils/leb.js");
57
57
  const index_ts_3 = require("../../polling/index.js");
58
- const utils_1 = require("@noble/hashes/utils");
58
+ const utils_js_1 = require("@noble/hashes/utils.js");
59
59
  const buffer_ts_1 = require("../../utils/buffer.js");
60
60
  const constants_ts_1 = require("../../constants.js");
61
61
  const types_ts_2 = require("./types.js");
62
+ const target_ts_1 = require("../../utils/target.js");
62
63
  var types_ts_3 = require("./types.js");
63
64
  Object.defineProperty(exports, "RequestStatusResponseStatus", { enumerable: true, get: function () { return types_ts_3.RequestStatusResponseStatus; } });
64
65
  const MINUTE_TO_MSECS = 60 * 1_000;
@@ -215,13 +216,13 @@ class HttpAgent {
215
216
  else {
216
217
  throw errors_ts_1.UnknownError.fromCode(new errors_ts_1.UnexpectedErrorCode(`Unknown status: ${status}`));
217
218
  }
218
- const separatorWithHash = (0, utils_1.concatBytes)(constants_ts_1.IC_RESPONSE_DOMAIN_SEPARATOR, hash);
219
+ const separatorWithHash = (0, utils_js_1.concatBytes)(constants_ts_1.IC_RESPONSE_DOMAIN_SEPARATOR, hash);
219
220
  const pubKey = subnetNodeKeys.get(nodeId);
220
221
  if (!pubKey) {
221
222
  throw errors_ts_1.ProtocolError.fromCode(new errors_ts_1.MalformedPublicKeyErrorCode());
222
223
  }
223
224
  const rawKey = public_key_ts_1.Ed25519PublicKey.fromDer(pubKey).rawKey;
224
- const valid = ed25519_1.ed25519.verify(sig.signature, separatorWithHash, rawKey);
225
+ const valid = ed25519_js_1.ed25519.verify(sig.signature, separatorWithHash, rawKey);
225
226
  if (!valid) {
226
227
  throw errors_ts_1.TrustError.fromCode(new errors_ts_1.QuerySignatureVerificationFailedErrorCode(nodeId));
227
228
  }
@@ -251,10 +252,14 @@ class HttpAgent {
251
252
  this.rootKey = null;
252
253
  }
253
254
  else {
254
- this.rootKey = (0, utils_1.hexToBytes)(exports.IC_ROOT_KEY);
255
+ this.rootKey = (0, utils_js_1.hexToBytes)(exports.IC_ROOT_KEY);
255
256
  }
256
257
  const host = determineHost(options.host);
257
258
  this.host = new URL(host);
259
+ // Ensure trailing slash so relative API path construction preserves any base path prefix
260
+ if (!this.host.pathname.endsWith('/')) {
261
+ this.host.pathname += '/';
262
+ }
258
263
  // Rewrite to avoid redirects and normalize the host before using it for namespacing caches
259
264
  if (this.host.hostname.endsWith(IC0_SUB_DOMAIN)) {
260
265
  this.host.hostname = IC0_DOMAIN;
@@ -375,10 +380,12 @@ class HttpAgent {
375
380
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.IdentityInvalidErrorCode());
376
381
  }
377
382
  const canister = _principal_1.Principal.from(canisterId);
378
- const ecid = options.effectiveCanisterId
379
- ? _principal_1.Principal.from(options.effectiveCanisterId)
380
- : canister;
381
- await this.#asyncGuard(ecid);
383
+ const target = options.effectiveTarget
384
+ ? (0, target_ts_1.inputToTarget)(options.effectiveTarget)
385
+ : options.effectiveCanisterId
386
+ ? { canisterId: _principal_1.Principal.from(options.effectiveCanisterId) }
387
+ : { canisterId: canister };
388
+ await this.#asyncGuard(target);
382
389
  const sender = id.getPrincipal();
383
390
  const ingress_expiry = calculateIngressExpiry(this.#maxIngressExpiryInMinutes, this.#timeDiffMsecs);
384
391
  const submit = {
@@ -433,26 +440,43 @@ class HttpAgent {
433
440
  const body = cbor.encode(transformedRequest.body);
434
441
  const backoff = this.#backoffStrategy();
435
442
  try {
436
- // Attempt v4 sync call
437
- const requestSync = () => {
438
- const url = new URL(`/api/v4/canister/${ecid.toText()}/call`, this.host);
439
- this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
440
- return this.#fetch(url, {
441
- ...this.#callOptions,
442
- ...transformedRequest.request,
443
- body,
444
- });
445
- };
446
- const requestAsync = () => {
447
- const url = new URL(`/api/v2/canister/${ecid.toText()}/call`, this.host);
448
- this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
449
- return this.#fetch(url, {
450
- ...this.#callOptions,
451
- ...transformedRequest.request,
452
- body,
453
- });
454
- };
455
- const requestFn = callSync ? requestSync : requestAsync;
443
+ let requestFn;
444
+ if ('canisterId' in target) {
445
+ // Attempt v4 sync call
446
+ const requestSync = () => {
447
+ const url = new URL(`api/v4/canister/${target.canisterId.toText()}/call`, this.host);
448
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
449
+ return this.#fetch(url, {
450
+ ...this.#callOptions,
451
+ ...transformedRequest.request,
452
+ body,
453
+ });
454
+ };
455
+ const requestAsync = () => {
456
+ const url = new URL(`api/v2/canister/${target.canisterId.toText()}/call`, this.host);
457
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
458
+ return this.#fetch(url, {
459
+ ...this.#callOptions,
460
+ ...transformedRequest.request,
461
+ body,
462
+ });
463
+ };
464
+ requestFn = callSync ? requestSync : requestAsync;
465
+ }
466
+ else {
467
+ if (!callSync) {
468
+ throw errors_ts_1.InputError.fromCode(new errors_ts_1.EffectiveSubnetIdAsyncErrorCode());
469
+ }
470
+ requestFn = () => {
471
+ const url = new URL(`api/v4/subnet/${target.subnetId.toText()}/call`, this.host);
472
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
473
+ return this.#fetch(url, {
474
+ ...this.#callOptions,
475
+ ...transformedRequest.request,
476
+ body,
477
+ });
478
+ };
479
+ }
456
480
  const { responseBodyBytes, ...response } = await this.#requestAndRetry({
457
481
  requestFn,
458
482
  backoff,
@@ -472,7 +496,7 @@ class HttpAgent {
472
496
  let callError;
473
497
  if (error instanceof errors_ts_1.AgentError) {
474
498
  // If the error is due to the v4 api not being supported, fall back to v2
475
- if (error.hasCode(errors_ts_1.HttpV4ApiNotSupportedErrorCode)) {
499
+ if ('canisterId' in target && error.hasCode(errors_ts_1.HttpV4ApiNotSupportedErrorCode)) {
476
500
  this.log.warn('v4 api not supported. Fall back to v2');
477
501
  return this.call(canisterId, {
478
502
  ...options,
@@ -483,7 +507,7 @@ class HttpAgent {
483
507
  if (error.hasCode(errors_ts_1.IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
484
508
  // if there is an ingress expiry error and the time has not been synced yet,
485
509
  // sync time with the network and try again
486
- await this.syncTime(canister);
510
+ await this.syncTime(target);
487
511
  return this.call(canister, options, identity);
488
512
  }
489
513
  // override the error code to include the request details
@@ -510,29 +534,35 @@ class HttpAgent {
510
534
  * @returns The certified result including the certificate, reply bytes, and raw certificate bytes.
511
535
  */
512
536
  async update(canisterId, fields, pollingOptions = {}) {
513
- const effectiveCanisterId = _principal_1.Principal.from(fields.effectiveCanisterId);
537
+ const canister = _principal_1.Principal.from(canisterId);
538
+ const target = fields.effectiveTarget
539
+ ? (0, target_ts_1.inputToTarget)(fields.effectiveTarget)
540
+ : fields.effectiveCanisterId
541
+ ? { canisterId: _principal_1.Principal.from(fields.effectiveCanisterId) }
542
+ : { canisterId: canister };
514
543
  const { requestId, response, requestDetails } = await this.call(canisterId, fields);
515
544
  const { body, ...httpDetails } = response;
516
545
  if ((0, api_ts_1.isV4ResponseBody)(body)) {
517
- return this.#handleV4SyncResponse(body, response, requestId, effectiveCanisterId, fields.methodName, httpDetails, requestDetails, pollingOptions, fields.onPollingStarted);
546
+ return this.#handleV4SyncResponse(body, response, requestId, canister, target, fields.methodName, httpDetails, requestDetails, pollingOptions, fields.onPollingStarted);
518
547
  }
519
548
  if ((0, api_ts_1.isV2ResponseBody)(body)) {
520
- this.#handleV2Rejection(body, requestId, effectiveCanisterId, fields.methodName, httpDetails);
549
+ this.#handleV2Rejection(body, requestId, canister, target, fields.methodName, httpDetails);
521
550
  }
522
551
  if (response.status === HTTP_STATUS_ACCEPTED) {
523
552
  fields.onPollingStarted?.();
524
- const pollResult = await (0, index_ts_3.pollForResponse)(this, effectiveCanisterId, requestId, pollingOptions);
553
+ const pollResult = await (0, index_ts_3.pollForResponse)(this, target, requestId, pollingOptions);
525
554
  return { ...pollResult, requestDetails, callResponse: response };
526
555
  }
527
556
  const unexpectedErrorCode = new errors_ts_1.UnexpectedErrorCode(`Unexpected response from call: status ${response.status} with unrecognized body`);
528
557
  unexpectedErrorCode.callContext = {
529
- canisterId: effectiveCanisterId,
558
+ canisterId: canister,
559
+ effectiveTarget: target,
530
560
  methodName: fields.methodName,
531
561
  httpDetails,
532
562
  };
533
563
  throw errors_ts_1.UnknownError.fromCode(unexpectedErrorCode);
534
564
  }
535
- async #handleV4SyncResponse(body, response, requestId, effectiveCanisterId, methodName, httpDetails, requestDetails, pollingOptions, onPollingStarted) {
565
+ async #handleV4SyncResponse(body, response, requestId, canisterId, effectiveTarget, methodName, httpDetails, requestDetails, pollingOptions, onPollingStarted) {
536
566
  if (this.rootKey == null) {
537
567
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.MissingRootKeyErrorCode());
538
568
  }
@@ -540,12 +570,12 @@ class HttpAgent {
540
570
  const certificate = await certificate_ts_1.Certificate.create({
541
571
  certificate: rawCertificate,
542
572
  rootKey: this.rootKey,
543
- principal: { canisterId: effectiveCanisterId },
573
+ principal: effectiveTarget,
544
574
  blsVerify: pollingOptions.blsVerify,
545
575
  agent: this,
546
576
  });
547
- const path = [(0, utils_1.utf8ToBytes)('request_status'), requestId];
548
- const maybeBuf = (0, certificate_ts_1.lookupResultToBuffer)(certificate.lookup_path([...path, (0, utils_1.utf8ToBytes)('status')]));
577
+ const path = [(0, utils_js_1.utf8ToBytes)('request_status'), requestId];
578
+ const maybeBuf = (0, certificate_ts_1.lookupResultToBuffer)(certificate.lookup_path([...path, (0, utils_js_1.utf8ToBytes)('status')]));
549
579
  const status = maybeBuf ? new TextDecoder().decode(maybeBuf) : undefined;
550
580
  switch (status) {
551
581
  case types_ts_2.RequestStatusResponseStatus.Replied:
@@ -559,7 +589,8 @@ class HttpAgent {
559
589
  case types_ts_2.RequestStatusResponseStatus.Rejected: {
560
590
  const error = (0, certificateReject_ts_1.readCertifiedReject)(certificate, path, requestId);
561
591
  error.callContext = {
562
- canisterId: effectiveCanisterId,
592
+ canisterId,
593
+ effectiveTarget,
563
594
  methodName,
564
595
  httpDetails,
565
596
  };
@@ -568,15 +599,16 @@ class HttpAgent {
568
599
  case undefined: {
569
600
  // The certificate does not contain an entry for our request ID status.
570
601
  // Fall back to polling via read state requests.
571
- this.log.warn(`v4 sync response certificate does not contain request ID ${(0, utils_1.bytesToHex)(requestId)} status. Falling back to polling.`);
602
+ this.log.warn(`v4 sync response certificate does not contain request ID ${(0, utils_js_1.bytesToHex)(requestId)} status. Falling back to polling.`);
572
603
  onPollingStarted?.();
573
- const pollResult = await (0, index_ts_3.pollForResponse)(this, effectiveCanisterId, requestId, pollingOptions);
604
+ const pollResult = await (0, index_ts_3.pollForResponse)(this, effectiveTarget, requestId, pollingOptions);
574
605
  return { ...pollResult, requestDetails, callResponse: response };
575
606
  }
576
607
  default: {
577
608
  const errorCode = new errors_ts_1.UnexpectedV4StatusErrorCode(status, requestId, response, rawCertificate);
578
609
  errorCode.callContext = {
579
- canisterId: effectiveCanisterId,
610
+ canisterId,
611
+ effectiveTarget,
580
612
  methodName,
581
613
  httpDetails,
582
614
  };
@@ -584,20 +616,23 @@ class HttpAgent {
584
616
  }
585
617
  }
586
618
  }
587
- #handleV2Rejection(body, requestId, effectiveCanisterId, methodName, httpDetails) {
619
+ #handleV2Rejection(body, requestId, canisterId, target, methodName, httpDetails) {
588
620
  const { reject_code, reject_message, error_code } = body;
589
621
  const errorCode = new errors_ts_1.UncertifiedRejectUpdateErrorCode(requestId, reject_code, reject_message, error_code);
590
622
  errorCode.callContext = {
591
- canisterId: effectiveCanisterId,
623
+ canisterId,
592
624
  methodName,
593
625
  httpDetails,
626
+ effectiveTarget: target,
594
627
  };
595
628
  throw errors_ts_1.RejectError.fromCode(errorCode);
596
629
  }
597
630
  async #requestAndRetryQuery(args) {
598
- const { ecid, transformedRequest, body, requestId, backoff, tries } = args;
631
+ const { target, transformedRequest, body, requestId, backoff, tries } = args;
599
632
  const delay = tries === 0 ? 0 : backoff.next();
600
- const url = new URL(`/api/v3/canister/${ecid.toString()}/query`, this.host);
633
+ const url = 'canisterId' in target
634
+ ? new URL(`api/v3/canister/${target.canisterId.toString()}/query`, this.host)
635
+ : new URL(`api/v3/subnet/${target.subnetId.toString()}/query`, this.host);
601
636
  this.log.print(`fetching "${url.pathname}" with tries:`, {
602
637
  tries,
603
638
  backoff,
@@ -668,7 +703,7 @@ class HttpAgent {
668
703
  requestId,
669
704
  signatureTimestampMs,
670
705
  });
671
- await this.syncTime(ecid);
706
+ await this.syncTime(target);
672
707
  return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
673
708
  }
674
709
  throw errors_ts_1.TrustError.fromCode(new errors_ts_1.CertificateOutdatedErrorCode(this.#maxIngressExpiryInMinutes, requestId, tries));
@@ -727,7 +762,7 @@ class HttpAgent {
727
762
  };
728
763
  }
729
764
  const responseText = await response.text();
730
- if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/v4')) {
765
+ if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/v4/canister')) {
731
766
  throw errors_ts_1.ProtocolError.fromCode(new errors_ts_1.HttpV4ApiNotSupportedErrorCode());
732
767
  }
733
768
  if (isIngressExpiryInvalidResponse(responseText)) {
@@ -740,18 +775,26 @@ class HttpAgent {
740
775
  }
741
776
  async query(canisterId, fields, identity) {
742
777
  const backoff = this.#backoffStrategy();
743
- const ecid = fields.effectiveCanisterId
744
- ? _principal_1.Principal.from(fields.effectiveCanisterId)
745
- : _principal_1.Principal.from(canisterId);
746
- await this.#asyncGuard(ecid);
747
- this.log.print(`ecid ${ecid.toString()}`);
778
+ const canister = _principal_1.Principal.from(canisterId);
779
+ const target = fields.effectiveTarget
780
+ ? (0, target_ts_1.inputToTarget)(fields.effectiveTarget)
781
+ : fields.effectiveCanisterId
782
+ ? { canisterId: _principal_1.Principal.from(fields.effectiveCanisterId) }
783
+ : { canisterId: canister };
784
+ const targetKey = (0, target_ts_1.getTargetKey)(target);
785
+ await this.#asyncGuard(target);
786
+ if ('canisterId' in target) {
787
+ this.log.print(`ecid ${target.canisterId.toString()}`);
788
+ }
789
+ else {
790
+ this.log.print(`esid ${target.subnetId.toString()}`);
791
+ }
748
792
  this.log.print(`canisterId ${canisterId.toString()}`);
749
793
  let transformedRequest;
750
794
  const id = await (identity ?? this.#identity);
751
795
  if (!id) {
752
796
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.IdentityInvalidErrorCode());
753
797
  }
754
- const canister = _principal_1.Principal.from(canisterId);
755
798
  const sender = id.getPrincipal();
756
799
  const ingressExpiry = calculateIngressExpiry(this.#maxIngressExpiryInMinutes, this.#timeDiffMsecs);
757
800
  const request = {
@@ -781,7 +824,7 @@ class HttpAgent {
781
824
  const body = cbor.encode(transformedRequest.body);
782
825
  const args = {
783
826
  canister: canister.toText(),
784
- ecid,
827
+ target,
785
828
  transformedRequest,
786
829
  body,
787
830
  requestId,
@@ -804,7 +847,7 @@ class HttpAgent {
804
847
  // Make query and fetch subnet keys in parallel
805
848
  const [queryWithDetails, subnetNodeKeys] = await Promise.all([
806
849
  makeQuery(),
807
- this.fetchSubnetKeys(ecid),
850
+ this.fetchSubnetKeys(target),
808
851
  ]);
809
852
  try {
810
853
  return this.#verifyQueryResponse(queryWithDetails, subnetNodeKeys);
@@ -812,8 +855,8 @@ class HttpAgent {
812
855
  catch {
813
856
  // In case the node signatures have changed, refresh the subnet keys and try again
814
857
  this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');
815
- await this.#subnetNodeKeyExpirableStore.delete(ecid.toString());
816
- const updatedSubnetNodeKeys = await this.fetchSubnetKeys(ecid);
858
+ await this.#subnetNodeKeyExpirableStore.delete(targetKey);
859
+ const updatedSubnetNodeKeys = await this.fetchSubnetKeys(target);
817
860
  return this.#verifyQueryResponse(queryWithDetails, updatedSubnetNodeKeys);
818
861
  }
819
862
  }
@@ -823,7 +866,7 @@ class HttpAgent {
823
866
  if (error.hasCode(errors_ts_1.IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
824
867
  // if there is an ingress expiry error and the time has not been synced yet,
825
868
  // sync time with the network and try again
826
- await this.syncTime(ecid);
869
+ await this.syncTime(target);
827
870
  return this.query(canisterId, fields, identity);
828
871
  }
829
872
  // override the error code to include the request details
@@ -875,20 +918,24 @@ class HttpAgent {
875
918
  // Apply transform for identity.
876
919
  return id.transformRequest(transformedRequest);
877
920
  }
878
- async readState(canisterId, fields, _identity,
921
+ #getRequestId(options) {
922
+ for (const path of options.paths) {
923
+ const [pathName, value] = path;
924
+ const request_status = new TextEncoder().encode('request_status');
925
+ if ((0, buffer_ts_1.uint8Equals)(pathName, request_status)) {
926
+ return value;
927
+ }
928
+ }
929
+ }
930
+ async readState(effectiveTarget, fields, _identity,
879
931
  // eslint-disable-next-line
880
932
  request) {
881
- await this.#rootKeyGuard();
882
- const canister = _principal_1.Principal.from(canisterId);
883
- function 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 ((0, buffer_ts_1.uint8Equals)(pathName, request_status)) {
888
- return value;
889
- }
890
- }
933
+ if (typeof effectiveTarget === 'string' || effectiveTarget instanceof _principal_1.Principal) {
934
+ // compatibility with v5
935
+ effectiveTarget = { canisterId: _principal_1.Principal.from(effectiveTarget) };
891
936
  }
937
+ await this.#rootKeyGuard();
938
+ const target = (0, target_ts_1.inputToTarget)(effectiveTarget);
892
939
  let transformedRequest;
893
940
  let requestId;
894
941
  // If a pre-signed request is provided, use it
@@ -898,7 +945,7 @@ class HttpAgent {
898
945
  }
899
946
  else {
900
947
  // This is fields, we need to create a request
901
- requestId = getRequestId(fields);
948
+ requestId = this.#getRequestId(fields);
902
949
  // Always create a fresh request with the current identity
903
950
  const identity = await this.#identity;
904
951
  if (!identity) {
@@ -906,23 +953,19 @@ class HttpAgent {
906
953
  }
907
954
  transformedRequest = await this.createReadStateRequest(fields, identity);
908
955
  }
909
- const url = new URL(`/api/v3/canister/${canister.toString()}/read_state`, this.host);
910
- return await this.#readStateInner(url, { canisterId: canister }, transformedRequest, requestId);
956
+ const url = 'canisterId' in target
957
+ ? new URL(`api/v3/canister/${target.canisterId.toString()}/read_state`, this.host)
958
+ : new URL(`api/v3/subnet/${target.subnetId.toString()}/read_state`, this.host);
959
+ return await this.#readStateInner(url, target, transformedRequest, requestId);
911
960
  }
961
+ // eslint-disable-next-line
912
962
  /**
913
- * Reads the state of a subnet from the `/api/v3/subnet/{subnetId}/read_state` endpoint.
914
- * @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.
915
- * @param options The options for the read state request.
916
- * @returns The response from the read state request.
963
+ * @deprecated Use `readState`
917
964
  */
918
- async readSubnetState(subnetId, options) {
919
- await this.#rootKeyGuard();
920
- const subnet = _principal_1.Principal.from(subnetId);
921
- const url = new URL(`/api/v3/subnet/${subnet.toString()}/read_state`, this.host);
922
- const transformedRequest = await this.createReadStateRequest(options, this.#identity ?? undefined);
923
- return await this.#readStateInner(url, { subnetId: subnet }, transformedRequest);
965
+ readSubnetState(subnetId, options) {
966
+ return this.readState({ subnetId: _principal_1.Principal.from(subnetId) }, options);
924
967
  }
925
- async #readStateInner(url, principal, transformedRequest, requestId) {
968
+ async #readStateInner(url, target, transformedRequest, requestId) {
926
969
  const backoff = this.#backoffStrategy();
927
970
  try {
928
971
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -943,16 +986,8 @@ class HttpAgent {
943
986
  if (error.hasCode(errors_ts_1.IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
944
987
  // if there is an ingress expiry error and the time has not been synced yet,
945
988
  // sync time with the network and try again
946
- if ('canisterId' in principal) {
947
- await this.syncTime(principal.canisterId);
948
- }
949
- else if ('subnetId' in principal) {
950
- await this.syncTimeWithSubnet(principal.subnetId);
951
- }
952
- else {
953
- throw errors_ts_1.UNREACHABLE_ERROR;
954
- }
955
- return await this.#readStateInner(url, principal, transformedRequest, requestId);
989
+ await this.syncTime(target);
990
+ return await this.#readStateInner(url, target, transformedRequest, requestId);
956
991
  }
957
992
  // override the error code to include the request details
958
993
  error.code.requestContext = {
@@ -997,20 +1032,27 @@ class HttpAgent {
997
1032
  }
998
1033
  /**
999
1034
  * 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
1000
- * @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.
1035
+ * @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.
1001
1036
  */
1002
- async syncTime(canisterIdOverride) {
1037
+ async syncTime(targetOverride) {
1038
+ if (targetOverride &&
1039
+ (typeof targetOverride === 'string' || targetOverride instanceof _principal_1.Principal)) {
1040
+ // compatibility with v5
1041
+ targetOverride = { canisterId: _principal_1.Principal.from(targetOverride) };
1042
+ }
1003
1043
  this.#syncTimePromise =
1004
1044
  this.#syncTimePromise ??
1005
1045
  (async () => {
1006
1046
  await this.#rootKeyGuard();
1007
1047
  const callTime = Date.now();
1008
1048
  try {
1009
- if (!canisterIdOverride) {
1010
- this.log.print('Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');
1049
+ if (!targetOverride) {
1050
+ this.log.print('Syncing time with the IC. No target provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');
1011
1051
  }
1012
1052
  // Fall back with canisterId of the ICP Ledger
1013
- const canisterId = canisterIdOverride ?? _principal_1.Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai');
1053
+ const target = targetOverride ?? {
1054
+ canisterId: _principal_1.Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),
1055
+ };
1014
1056
  const anonymousAgent = HttpAgent.createSync({
1015
1057
  identity: new auth_ts_1.AnonymousIdentity(),
1016
1058
  host: this.host.toString(),
@@ -1022,12 +1064,19 @@ class HttpAgent {
1022
1064
  const replicaTimes = await Promise.all(Array(3)
1023
1065
  .fill(null)
1024
1066
  .map(async () => {
1025
- const status = await (0, index_ts_1.request)({
1026
- canisterId,
1027
- agent: anonymousAgent,
1028
- paths: ['time'],
1029
- disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1030
- });
1067
+ const status = 'canisterId' in target
1068
+ ? await (0, index_ts_1.request)({
1069
+ canisterId: target.canisterId,
1070
+ agent: anonymousAgent,
1071
+ paths: ['time'],
1072
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1073
+ })
1074
+ : await (0, index_ts_2.request)({
1075
+ subnetId: target.subnetId,
1076
+ agent: anonymousAgent,
1077
+ paths: ['time'],
1078
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1079
+ });
1031
1080
  const date = status.get('time');
1032
1081
  if (date instanceof Date) {
1033
1082
  return date.getTime();
@@ -1047,43 +1096,12 @@ class HttpAgent {
1047
1096
  this.#syncTimePromise = null;
1048
1097
  });
1049
1098
  }
1099
+ // eslint-disable-next-line
1050
1100
  /**
1051
- * Allows agent to sync its time with the network.
1052
- * @param {Principal} subnetId - Pass the subnet ID you need to sync the time with.
1101
+ * @deprecated Use {@link syncTime}
1053
1102
  */
1054
- async syncTimeWithSubnet(subnetId) {
1055
- await this.#rootKeyGuard();
1056
- const callTime = Date.now();
1057
- try {
1058
- const anonymousAgent = HttpAgent.createSync({
1059
- identity: new auth_ts_1.AnonymousIdentity(),
1060
- host: this.host.toString(),
1061
- fetch: this.#fetch,
1062
- retryTimes: 0,
1063
- rootKey: this.rootKey ?? undefined,
1064
- shouldSyncTime: false,
1065
- });
1066
- const replicaTimes = await Promise.all(Array(3)
1067
- .fill(null)
1068
- .map(async () => {
1069
- const status = await (0, index_ts_2.request)({
1070
- subnetId,
1071
- agent: anonymousAgent,
1072
- paths: ['time'],
1073
- disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1074
- });
1075
- const date = status.get('time');
1076
- if (date instanceof Date) {
1077
- return date.getTime();
1078
- }
1079
- }, []));
1080
- this.#setTimeDiffMsecs(callTime, replicaTimes);
1081
- }
1082
- catch (error) {
1083
- const syncTimeError = error instanceof errors_ts_1.AgentError ? error : errors_ts_1.UnknownError.fromCode(new errors_ts_1.UnexpectedErrorCode(error));
1084
- this.log.error('Caught exception while attempting to sync time with subnet', syncTimeError);
1085
- throw syncTimeError;
1086
- }
1103
+ syncTimeWithSubnet(subnetId) {
1104
+ return this.syncTime({ subnetId });
1087
1105
  }
1088
1106
  #setTimeDiffMsecs(callTime, replicaTimes) {
1089
1107
  const maxReplicaTime = replicaTimes.reduce((max, current) => {
@@ -1104,7 +1122,7 @@ class HttpAgent {
1104
1122
  Authorization: `Basic ${btoa(this.#credentials)}`,
1105
1123
  }
1106
1124
  : {};
1107
- const url = new URL(`/api/v2/status`, this.host);
1125
+ const url = new URL(`api/v2/status`, this.host);
1108
1126
  this.log.print(`fetching "${url.pathname}"`);
1109
1127
  const backoff = this.#backoffStrategy();
1110
1128
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -1129,8 +1147,8 @@ class HttpAgent {
1129
1147
  this.#rootKeyPromise = null;
1130
1148
  });
1131
1149
  }
1132
- async #asyncGuard(canisterIdOverride) {
1133
- await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(canisterIdOverride)]);
1150
+ async #asyncGuard(targetOverride) {
1151
+ await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(targetOverride)]);
1134
1152
  }
1135
1153
  async #rootKeyGuard() {
1136
1154
  if (this.rootKey) {
@@ -1145,9 +1163,9 @@ class HttpAgent {
1145
1163
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.MissingRootKeyErrorCode(this.#shouldFetchRootKey));
1146
1164
  }
1147
1165
  }
1148
- async #syncTimeGuard(canisterIdOverride) {
1166
+ async #syncTimeGuard(targetOverride) {
1149
1167
  if (this.#shouldSyncTime && !this.hasSyncedTime()) {
1150
- await this.syncTime(canisterIdOverride);
1168
+ await this.syncTime(targetOverride);
1151
1169
  }
1152
1170
  }
1153
1171
  invalidateIdentity() {
@@ -1156,52 +1174,58 @@ class HttpAgent {
1156
1174
  replaceIdentity(identity) {
1157
1175
  this.#identity = Promise.resolve(identity);
1158
1176
  }
1159
- async fetchSubnetKeys(canisterId) {
1160
- const effectiveCanisterId = _principal_1.Principal.from(canisterId);
1177
+ async fetchSubnetKeys(effectiveTarget) {
1178
+ if (typeof effectiveTarget === 'string' || effectiveTarget instanceof _principal_1.Principal) {
1179
+ // compatibility with v5
1180
+ effectiveTarget = { canisterId: _principal_1.Principal.from(effectiveTarget) };
1181
+ }
1182
+ const target = (0, target_ts_1.inputToTarget)(effectiveTarget);
1183
+ const targetKey = (0, target_ts_1.getTargetKey)(target);
1161
1184
  // Return cached result if available within the TTL.
1162
- const cached = await this.#subnetNodeKeyExpirableStore.get(effectiveCanisterId.toText());
1185
+ const cached = await this.#subnetNodeKeyExpirableStore.get(targetKey);
1163
1186
  if (cached) {
1164
1187
  return cached;
1165
1188
  }
1166
1189
  // Deduplicate parallel requests for the same canister so that concurrent
1167
1190
  // query calls share a single read_state round-trip instead of each
1168
1191
  // issuing their own.
1169
- const inflight = this.#subnetKeysFetching.get(effectiveCanisterId.toText());
1192
+ const inflight = this.#subnetKeysFetching.get(targetKey);
1170
1193
  if (inflight) {
1171
1194
  return inflight;
1172
1195
  }
1173
- const fetchPromise = this.#doFetchSubnetKeys(effectiveCanisterId).finally(() => {
1174
- this.#subnetKeysFetching.delete(effectiveCanisterId.toText());
1196
+ const fetchPromise = this.#doFetchSubnetKeys(target).finally(() => {
1197
+ this.#subnetKeysFetching.delete(targetKey);
1175
1198
  });
1176
- this.#subnetKeysFetching.set(effectiveCanisterId.toText(), fetchPromise);
1199
+ this.#subnetKeysFetching.set(targetKey, fetchPromise);
1177
1200
  return fetchPromise;
1178
1201
  }
1179
- async #doFetchSubnetKeys(effectiveCanisterId) {
1180
- await this.#asyncGuard(effectiveCanisterId);
1202
+ async #doFetchSubnetKeys(target) {
1203
+ await this.#asyncGuard(target);
1181
1204
  const rootKey = this.rootKey;
1182
- const canisterReadState = await this.readState(effectiveCanisterId, {
1183
- paths: [[(0, utils_1.utf8ToBytes)('subnet')]],
1205
+ const canisterReadState = await this.readState(target, {
1206
+ paths: [[(0, utils_js_1.utf8ToBytes)('subnet')]],
1184
1207
  });
1185
1208
  const canisterCertificate = await certificate_ts_1.Certificate.create({
1186
1209
  certificate: canisterReadState.certificate,
1187
1210
  rootKey,
1188
- principal: { canisterId: effectiveCanisterId },
1211
+ principal: target,
1189
1212
  agent: this,
1190
1213
  });
1191
- if (!canisterCertificate.cert.delegation) {
1214
+ const targetKey = (0, target_ts_1.getTargetKey)(target);
1215
+ if ('canisterId' in target && !canisterCertificate.cert.delegation) {
1192
1216
  const subnetId = _principal_1.Principal.selfAuthenticating(rootKey);
1193
1217
  const canisterInRange = (0, certificate_ts_1.check_canister_ranges)({
1194
- canisterId: effectiveCanisterId,
1218
+ canisterId: target.canisterId,
1195
1219
  subnetId,
1196
1220
  tree: canisterCertificate.cert.tree,
1197
1221
  });
1198
1222
  if (!canisterInRange) {
1199
- throw errors_ts_1.TrustError.fromCode(new errors_ts_1.CertificateNotAuthorizedErrorCode(effectiveCanisterId, subnetId));
1223
+ throw errors_ts_1.TrustError.fromCode(new errors_ts_1.CertificateNotAuthorizedErrorCode(target.canisterId, subnetId));
1200
1224
  }
1201
1225
  }
1202
1226
  const subnetId = (0, certificate_ts_1.getSubnetIdFromCertificate)(canisterCertificate.cert, rootKey);
1203
1227
  const nodeKeys = (0, readState_ts_1.lookupNodeKeysFromCertificate)(canisterCertificate.cert, subnetId);
1204
- await this.#subnetNodeKeyExpirableStore.set(effectiveCanisterId.toText(), nodeKeys);
1228
+ await this.#subnetNodeKeyExpirableStore.set(targetKey, nodeKeys);
1205
1229
  return nodeKeys;
1206
1230
  }
1207
1231
  /**
@@ -1212,9 +1236,9 @@ class HttpAgent {
1212
1236
  */
1213
1237
  async getSubnetIdFromCanister(canisterId) {
1214
1238
  const effectiveCanisterId = _principal_1.Principal.from(canisterId);
1215
- await this.#asyncGuard(effectiveCanisterId);
1216
- const canisterReadState = await this.readState(effectiveCanisterId, {
1217
- paths: [[(0, utils_1.utf8ToBytes)('time')]],
1239
+ await this.#asyncGuard({ canisterId: effectiveCanisterId });
1240
+ const canisterReadState = await this.readState({ canisterId: effectiveCanisterId }, {
1241
+ paths: [[(0, utils_js_1.utf8ToBytes)('time')]],
1218
1242
  });
1219
1243
  const canisterCertificate = await certificate_ts_1.Certificate.create({
1220
1244
  certificate: canisterReadState.certificate,