@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
@@ -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,39 @@ 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) {
933
+ if (typeof effectiveTarget === 'string' || effectiveTarget instanceof _principal_1.Principal) {
934
+ // compatibility with v5
935
+ effectiveTarget = { canisterId: _principal_1.Principal.from(effectiveTarget) };
936
+ }
881
937
  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
- }
938
+ const target = (0, target_ts_1.inputToTarget)(effectiveTarget);
939
+ if (!fields.disableTimeVerification) {
940
+ await this.#syncTimeGuard(target);
941
+ }
942
+ // Encode paths into their raw form. Raw (pre-encoded) paths pass through unchanged; each
943
+ // KnownPath is retained alongside its encoded form so its value can be decoded below.
944
+ const encodedPaths = [];
945
+ const knownPaths = [];
946
+ for (const path of fields.paths) {
947
+ const encoded = (0, readState_ts_1.encodePath)(path);
948
+ encodedPaths.push(encoded);
949
+ if (!Array.isArray(path)) {
950
+ knownPaths.push({ path, encoded });
890
951
  }
891
952
  }
953
+ const resolvedFields = { ...fields, paths: encodedPaths };
892
954
  let transformedRequest;
893
955
  let requestId;
894
956
  // If a pre-signed request is provided, use it
@@ -898,31 +960,48 @@ class HttpAgent {
898
960
  }
899
961
  else {
900
962
  // This is fields, we need to create a request
901
- requestId = getRequestId(fields);
963
+ requestId = this.#getRequestId(resolvedFields);
902
964
  // Always create a fresh request with the current identity
903
965
  const identity = await this.#identity;
904
966
  if (!identity) {
905
967
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.IdentityInvalidErrorCode());
906
968
  }
907
- transformedRequest = await this.createReadStateRequest(fields, identity);
969
+ transformedRequest = await this.createReadStateRequest(resolvedFields, identity);
908
970
  }
909
- const url = new URL(`/api/v3/canister/${canister.toString()}/read_state`, this.host);
910
- return await this.#readStateInner(url, { canisterId: canister }, transformedRequest, requestId);
971
+ const url = 'canisterId' in target
972
+ ? new URL(`api/v3/canister/${target.canisterId.toString()}/read_state`, this.host)
973
+ : new URL(`api/v3/subnet/${target.subnetId.toString()}/read_state`, this.host);
974
+ if (this.rootKey === null) {
975
+ throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.MissingRootKeyErrorCode(this.#shouldFetchRootKey));
976
+ }
977
+ const rootKey = this.rootKey;
978
+ const { certificate } = await this.#readStateInner(url, target, transformedRequest, requestId);
979
+ const verifiedCertificate = await certificate_ts_1.Certificate.create({
980
+ certificate,
981
+ rootKey,
982
+ principal: target,
983
+ blsVerify: fields.blsVerify,
984
+ maxAgeInMinutes: fields.maxAgeInMinutes,
985
+ disableTimeVerification: fields.disableTimeVerification,
986
+ agent: this,
987
+ });
988
+ // Decode the value at each KnownPath with its own decoder, keyed by the path. A value absent
989
+ // from the certificate maps to null.
990
+ const decoded = new Map();
991
+ for (const { path, encoded } of knownPaths) {
992
+ const buffer = (0, certificate_ts_1.lookupResultToBuffer)(verifiedCertificate.lookup_path(encoded));
993
+ decoded.set(path.key, buffer === undefined ? null : path.decode(buffer));
994
+ }
995
+ return { certificate, verifiedCertificate, values: new readState_ts_1.StateValues(decoded) };
911
996
  }
997
+ // eslint-disable-next-line
912
998
  /**
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.
999
+ * @deprecated Use `readState`
917
1000
  */
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);
1001
+ readSubnetState(subnetId, options) {
1002
+ return this.readState({ subnetId: _principal_1.Principal.from(subnetId) }, options);
924
1003
  }
925
- async #readStateInner(url, principal, transformedRequest, requestId) {
1004
+ async #readStateInner(url, target, transformedRequest, requestId) {
926
1005
  const backoff = this.#backoffStrategy();
927
1006
  try {
928
1007
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -943,16 +1022,8 @@ class HttpAgent {
943
1022
  if (error.hasCode(errors_ts_1.IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
944
1023
  // if there is an ingress expiry error and the time has not been synced yet,
945
1024
  // 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);
1025
+ await this.syncTime(target);
1026
+ return await this.#readStateInner(url, target, transformedRequest, requestId);
956
1027
  }
957
1028
  // override the error code to include the request details
958
1029
  error.code.requestContext = {
@@ -997,20 +1068,27 @@ class HttpAgent {
997
1068
  }
998
1069
  /**
999
1070
  * 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.
1071
+ * @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
1072
  */
1002
- async syncTime(canisterIdOverride) {
1073
+ async syncTime(targetOverride) {
1074
+ if (targetOverride &&
1075
+ (typeof targetOverride === 'string' || targetOverride instanceof _principal_1.Principal)) {
1076
+ // compatibility with v5
1077
+ targetOverride = { canisterId: _principal_1.Principal.from(targetOverride) };
1078
+ }
1003
1079
  this.#syncTimePromise =
1004
1080
  this.#syncTimePromise ??
1005
1081
  (async () => {
1006
1082
  await this.#rootKeyGuard();
1007
1083
  const callTime = Date.now();
1008
1084
  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');
1085
+ if (!targetOverride) {
1086
+ this.log.print('Syncing time with the IC. No target provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');
1011
1087
  }
1012
1088
  // Fall back with canisterId of the ICP Ledger
1013
- const canisterId = canisterIdOverride ?? _principal_1.Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai');
1089
+ const target = targetOverride ?? {
1090
+ canisterId: _principal_1.Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),
1091
+ };
1014
1092
  const anonymousAgent = HttpAgent.createSync({
1015
1093
  identity: new auth_ts_1.AnonymousIdentity(),
1016
1094
  host: this.host.toString(),
@@ -1022,12 +1100,19 @@ class HttpAgent {
1022
1100
  const replicaTimes = await Promise.all(Array(3)
1023
1101
  .fill(null)
1024
1102
  .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
- });
1103
+ const status = 'canisterId' in target
1104
+ ? await (0, index_ts_1.request)({
1105
+ canisterId: target.canisterId,
1106
+ agent: anonymousAgent,
1107
+ paths: ['time'],
1108
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1109
+ })
1110
+ : await (0, index_ts_2.request)({
1111
+ subnetId: target.subnetId,
1112
+ agent: anonymousAgent,
1113
+ paths: ['time'],
1114
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1115
+ });
1031
1116
  const date = status.get('time');
1032
1117
  if (date instanceof Date) {
1033
1118
  return date.getTime();
@@ -1047,43 +1132,12 @@ class HttpAgent {
1047
1132
  this.#syncTimePromise = null;
1048
1133
  });
1049
1134
  }
1135
+ // eslint-disable-next-line
1050
1136
  /**
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.
1137
+ * @deprecated Use {@link syncTime}
1053
1138
  */
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
- }
1139
+ syncTimeWithSubnet(subnetId) {
1140
+ return this.syncTime({ subnetId });
1087
1141
  }
1088
1142
  #setTimeDiffMsecs(callTime, replicaTimes) {
1089
1143
  const maxReplicaTime = replicaTimes.reduce((max, current) => {
@@ -1104,7 +1158,7 @@ class HttpAgent {
1104
1158
  Authorization: `Basic ${btoa(this.#credentials)}`,
1105
1159
  }
1106
1160
  : {};
1107
- const url = new URL(`/api/v2/status`, this.host);
1161
+ const url = new URL(`api/v2/status`, this.host);
1108
1162
  this.log.print(`fetching "${url.pathname}"`);
1109
1163
  const backoff = this.#backoffStrategy();
1110
1164
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -1129,8 +1183,8 @@ class HttpAgent {
1129
1183
  this.#rootKeyPromise = null;
1130
1184
  });
1131
1185
  }
1132
- async #asyncGuard(canisterIdOverride) {
1133
- await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(canisterIdOverride)]);
1186
+ async #asyncGuard(targetOverride) {
1187
+ await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(targetOverride)]);
1134
1188
  }
1135
1189
  async #rootKeyGuard() {
1136
1190
  if (this.rootKey) {
@@ -1145,9 +1199,9 @@ class HttpAgent {
1145
1199
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.MissingRootKeyErrorCode(this.#shouldFetchRootKey));
1146
1200
  }
1147
1201
  }
1148
- async #syncTimeGuard(canisterIdOverride) {
1202
+ async #syncTimeGuard(targetOverride) {
1149
1203
  if (this.#shouldSyncTime && !this.hasSyncedTime()) {
1150
- await this.syncTime(canisterIdOverride);
1204
+ await this.syncTime(targetOverride);
1151
1205
  }
1152
1206
  }
1153
1207
  invalidateIdentity() {
@@ -1156,52 +1210,52 @@ class HttpAgent {
1156
1210
  replaceIdentity(identity) {
1157
1211
  this.#identity = Promise.resolve(identity);
1158
1212
  }
1159
- async fetchSubnetKeys(canisterId) {
1160
- const effectiveCanisterId = _principal_1.Principal.from(canisterId);
1213
+ async fetchSubnetKeys(effectiveTarget) {
1214
+ if (typeof effectiveTarget === 'string' || effectiveTarget instanceof _principal_1.Principal) {
1215
+ // compatibility with v5
1216
+ effectiveTarget = { canisterId: _principal_1.Principal.from(effectiveTarget) };
1217
+ }
1218
+ const target = (0, target_ts_1.inputToTarget)(effectiveTarget);
1219
+ const targetKey = (0, target_ts_1.getTargetKey)(target);
1161
1220
  // Return cached result if available within the TTL.
1162
- const cached = await this.#subnetNodeKeyExpirableStore.get(effectiveCanisterId.toText());
1221
+ const cached = await this.#subnetNodeKeyExpirableStore.get(targetKey);
1163
1222
  if (cached) {
1164
1223
  return cached;
1165
1224
  }
1166
1225
  // Deduplicate parallel requests for the same canister so that concurrent
1167
1226
  // query calls share a single read_state round-trip instead of each
1168
1227
  // issuing their own.
1169
- const inflight = this.#subnetKeysFetching.get(effectiveCanisterId.toText());
1228
+ const inflight = this.#subnetKeysFetching.get(targetKey);
1170
1229
  if (inflight) {
1171
1230
  return inflight;
1172
1231
  }
1173
- const fetchPromise = this.#doFetchSubnetKeys(effectiveCanisterId).finally(() => {
1174
- this.#subnetKeysFetching.delete(effectiveCanisterId.toText());
1232
+ const fetchPromise = this.#doFetchSubnetKeys(target).finally(() => {
1233
+ this.#subnetKeysFetching.delete(targetKey);
1175
1234
  });
1176
- this.#subnetKeysFetching.set(effectiveCanisterId.toText(), fetchPromise);
1235
+ this.#subnetKeysFetching.set(targetKey, fetchPromise);
1177
1236
  return fetchPromise;
1178
1237
  }
1179
- async #doFetchSubnetKeys(effectiveCanisterId) {
1180
- await this.#asyncGuard(effectiveCanisterId);
1238
+ async #doFetchSubnetKeys(target) {
1239
+ await this.#asyncGuard(target);
1181
1240
  const rootKey = this.rootKey;
1182
- const canisterReadState = await this.readState(effectiveCanisterId, {
1183
- paths: [[(0, utils_1.utf8ToBytes)('subnet')]],
1184
- });
1185
- const canisterCertificate = await certificate_ts_1.Certificate.create({
1186
- certificate: canisterReadState.certificate,
1187
- rootKey,
1188
- principal: { canisterId: effectiveCanisterId },
1189
- agent: this,
1241
+ const { verifiedCertificate: canisterCertificate } = await this.readState(target, {
1242
+ paths: [[(0, utils_js_1.utf8ToBytes)('subnet')]],
1190
1243
  });
1191
- if (!canisterCertificate.cert.delegation) {
1244
+ const targetKey = (0, target_ts_1.getTargetKey)(target);
1245
+ if ('canisterId' in target && !canisterCertificate.cert.delegation) {
1192
1246
  const subnetId = _principal_1.Principal.selfAuthenticating(rootKey);
1193
1247
  const canisterInRange = (0, certificate_ts_1.check_canister_ranges)({
1194
- canisterId: effectiveCanisterId,
1248
+ canisterId: target.canisterId,
1195
1249
  subnetId,
1196
1250
  tree: canisterCertificate.cert.tree,
1197
1251
  });
1198
1252
  if (!canisterInRange) {
1199
- throw errors_ts_1.TrustError.fromCode(new errors_ts_1.CertificateNotAuthorizedErrorCode(effectiveCanisterId, subnetId));
1253
+ throw errors_ts_1.TrustError.fromCode(new errors_ts_1.CertificateNotAuthorizedErrorCode(target.canisterId, subnetId));
1200
1254
  }
1201
1255
  }
1202
1256
  const subnetId = (0, certificate_ts_1.getSubnetIdFromCertificate)(canisterCertificate.cert, rootKey);
1203
1257
  const nodeKeys = (0, readState_ts_1.lookupNodeKeysFromCertificate)(canisterCertificate.cert, subnetId);
1204
- await this.#subnetNodeKeyExpirableStore.set(effectiveCanisterId.toText(), nodeKeys);
1258
+ await this.#subnetNodeKeyExpirableStore.set(targetKey, nodeKeys);
1205
1259
  return nodeKeys;
1206
1260
  }
1207
1261
  /**
@@ -1212,15 +1266,9 @@ class HttpAgent {
1212
1266
  */
1213
1267
  async getSubnetIdFromCanister(canisterId) {
1214
1268
  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')]],
1218
- });
1219
- const canisterCertificate = await certificate_ts_1.Certificate.create({
1220
- certificate: canisterReadState.certificate,
1221
- rootKey: this.rootKey,
1222
- principal: { canisterId: effectiveCanisterId },
1223
- agent: this,
1269
+ await this.#asyncGuard({ canisterId: effectiveCanisterId });
1270
+ const { verifiedCertificate: canisterCertificate } = await this.readState({ canisterId: effectiveCanisterId }, {
1271
+ paths: [[(0, utils_js_1.utf8ToBytes)('time')]],
1224
1272
  });
1225
1273
  return (0, certificate_ts_1.getSubnetIdFromCertificate)(canisterCertificate.cert, this.rootKey);
1226
1274
  }