@icp-sdk/core 5.3.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/lib/cjs/agent/actor.d.ts +7 -3
  2. package/lib/cjs/agent/actor.d.ts.map +1 -1
  3. package/lib/cjs/agent/actor.js +18 -5
  4. package/lib/cjs/agent/actor.js.map +1 -1
  5. package/lib/cjs/agent/agent/api.d.ts +35 -6
  6. package/lib/cjs/agent/agent/api.d.ts.map +1 -1
  7. package/lib/cjs/agent/agent/api.js.map +1 -1
  8. package/lib/cjs/agent/agent/http/index.d.ts +11 -25
  9. package/lib/cjs/agent/agent/http/index.d.ts.map +1 -1
  10. package/lib/cjs/agent/agent/http/index.js +198 -173
  11. package/lib/cjs/agent/agent/http/index.js.map +1 -1
  12. package/lib/cjs/agent/auth.d.ts +6 -5
  13. package/lib/cjs/agent/auth.d.ts.map +1 -1
  14. package/lib/cjs/agent/auth.js +3 -3
  15. package/lib/cjs/agent/auth.js.map +1 -1
  16. package/lib/cjs/agent/canisterStatus/index.d.ts.map +1 -1
  17. package/lib/cjs/agent/canisterStatus/index.js +10 -10
  18. package/lib/cjs/agent/canisterStatus/index.js.map +1 -1
  19. package/lib/cjs/agent/cbor.d.ts +2 -1
  20. package/lib/cjs/agent/cbor.d.ts.map +1 -1
  21. package/lib/cjs/agent/cbor.js +4 -1
  22. package/lib/cjs/agent/cbor.js.map +1 -1
  23. package/lib/cjs/agent/certificate.d.ts +5 -4
  24. package/lib/cjs/agent/certificate.d.ts.map +1 -1
  25. package/lib/cjs/agent/certificate.js +14 -18
  26. package/lib/cjs/agent/certificate.js.map +1 -1
  27. package/lib/cjs/agent/der.d.ts +3 -2
  28. package/lib/cjs/agent/der.d.ts.map +1 -1
  29. package/lib/cjs/agent/der.js.map +1 -1
  30. package/lib/cjs/agent/errors.d.ts +7 -1
  31. package/lib/cjs/agent/errors.d.ts.map +1 -1
  32. package/lib/cjs/agent/errors.js +34 -16
  33. package/lib/cjs/agent/errors.js.map +1 -1
  34. package/lib/cjs/agent/polling/index.d.ts +3 -4
  35. package/lib/cjs/agent/polling/index.d.ts.map +1 -1
  36. package/lib/cjs/agent/polling/index.js +17 -10
  37. package/lib/cjs/agent/polling/index.js.map +1 -1
  38. package/lib/cjs/agent/polling/strategy.d.ts.map +1 -1
  39. package/lib/cjs/agent/polling/strategy.js +6 -6
  40. package/lib/cjs/agent/polling/strategy.js.map +1 -1
  41. package/lib/cjs/agent/polling/types.d.ts +3 -4
  42. package/lib/cjs/agent/polling/types.d.ts.map +1 -1
  43. package/lib/cjs/agent/public_key.d.ts +3 -2
  44. package/lib/cjs/agent/public_key.d.ts.map +1 -1
  45. package/lib/cjs/agent/public_key.js +2 -2
  46. package/lib/cjs/agent/public_key.js.map +1 -1
  47. package/lib/cjs/agent/request_id.js +10 -10
  48. package/lib/cjs/agent/request_id.js.map +1 -1
  49. package/lib/cjs/agent/subnetStatus/index.js +7 -7
  50. package/lib/cjs/agent/subnetStatus/index.js.map +1 -1
  51. package/lib/cjs/agent/utils/bls.d.ts.map +1 -1
  52. package/lib/cjs/agent/utils/bls.js +7 -6
  53. package/lib/cjs/agent/utils/bls.js.map +1 -1
  54. package/lib/cjs/agent/utils/readState.d.ts +2 -2
  55. package/lib/cjs/agent/utils/readState.d.ts.map +1 -1
  56. package/lib/cjs/agent/utils/readState.js +4 -4
  57. package/lib/cjs/agent/utils/readState.js.map +1 -1
  58. package/lib/cjs/agent/utils/target.d.ts +15 -0
  59. package/lib/cjs/agent/utils/target.d.ts.map +1 -0
  60. package/lib/cjs/agent/utils/target.js +27 -0
  61. package/lib/cjs/agent/utils/target.js.map +1 -0
  62. package/lib/cjs/candid/utils/buffer.d.ts +2 -1
  63. package/lib/cjs/candid/utils/buffer.d.ts.map +1 -1
  64. package/lib/cjs/candid/utils/buffer.js +5 -2
  65. package/lib/cjs/candid/utils/buffer.js.map +1 -1
  66. package/lib/cjs/identity/identity/attributes.d.ts +6 -2
  67. package/lib/cjs/identity/identity/attributes.d.ts.map +1 -1
  68. package/lib/cjs/identity/identity/attributes.js +9 -1
  69. package/lib/cjs/identity/identity/attributes.js.map +1 -1
  70. package/lib/cjs/identity/identity/delegation.d.ts +10 -3
  71. package/lib/cjs/identity/identity/delegation.d.ts.map +1 -1
  72. package/lib/cjs/identity/identity/delegation.js +25 -12
  73. package/lib/cjs/identity/identity/delegation.js.map +1 -1
  74. package/lib/cjs/identity/identity/ecdsa.d.ts +2 -2
  75. package/lib/cjs/identity/identity/ecdsa.d.ts.map +1 -1
  76. package/lib/cjs/identity/identity/ecdsa.js +3 -2
  77. package/lib/cjs/identity/identity/ecdsa.js.map +1 -1
  78. package/lib/cjs/identity/identity/ed25519.d.ts +3 -2
  79. package/lib/cjs/identity/identity/ed25519.d.ts.map +1 -1
  80. package/lib/cjs/identity/identity/ed25519.js +18 -15
  81. package/lib/cjs/identity/identity/ed25519.js.map +1 -1
  82. package/lib/cjs/identity/identity/webauthn.d.ts +4 -3
  83. package/lib/cjs/identity/identity/webauthn.d.ts.map +1 -1
  84. package/lib/cjs/identity/identity/webauthn.js +12 -11
  85. package/lib/cjs/identity/identity/webauthn.js.map +1 -1
  86. package/lib/cjs/identity/secp256k1/der.d.ts +2 -1
  87. package/lib/cjs/identity/secp256k1/der.d.ts.map +1 -1
  88. package/lib/cjs/identity/secp256k1/der.js.map +1 -1
  89. package/lib/cjs/identity/secp256k1/pem.d.ts +4 -3
  90. package/lib/cjs/identity/secp256k1/pem.d.ts.map +1 -1
  91. package/lib/cjs/identity/secp256k1/pem.js +2 -2
  92. package/lib/cjs/identity/secp256k1/pem.js.map +1 -1
  93. package/lib/cjs/identity/secp256k1/secp256k1.d.ts +5 -4
  94. package/lib/cjs/identity/secp256k1/secp256k1.d.ts.map +1 -1
  95. package/lib/cjs/identity/secp256k1/secp256k1.js +17 -20
  96. package/lib/cjs/identity/secp256k1/secp256k1.js.map +1 -1
  97. package/lib/cjs/principal/principal.js +5 -5
  98. package/lib/cjs/principal/principal.js.map +1 -1
  99. package/lib/esm/agent/actor.d.ts +7 -3
  100. package/lib/esm/agent/actor.d.ts.map +1 -1
  101. package/lib/esm/agent/actor.js +18 -5
  102. package/lib/esm/agent/actor.js.map +1 -1
  103. package/lib/esm/agent/agent/api.d.ts +35 -6
  104. package/lib/esm/agent/agent/api.d.ts.map +1 -1
  105. package/lib/esm/agent/agent/api.js.map +1 -1
  106. package/lib/esm/agent/agent/http/index.d.ts +11 -25
  107. package/lib/esm/agent/agent/http/index.d.ts.map +1 -1
  108. package/lib/esm/agent/agent/http/index.js +191 -166
  109. package/lib/esm/agent/agent/http/index.js.map +1 -1
  110. package/lib/esm/agent/auth.d.ts +6 -5
  111. package/lib/esm/agent/auth.d.ts.map +1 -1
  112. package/lib/esm/agent/auth.js +1 -1
  113. package/lib/esm/agent/auth.js.map +1 -1
  114. package/lib/esm/agent/canister-env/index.js +1 -1
  115. package/lib/esm/agent/canister-env/index.js.map +1 -1
  116. package/lib/esm/agent/canisterStatus/index.d.ts.map +1 -1
  117. package/lib/esm/agent/canisterStatus/index.js +2 -2
  118. package/lib/esm/agent/canisterStatus/index.js.map +1 -1
  119. package/lib/esm/agent/cbor.d.ts +2 -1
  120. package/lib/esm/agent/cbor.d.ts.map +1 -1
  121. package/lib/esm/agent/cbor.js +4 -1
  122. package/lib/esm/agent/cbor.js.map +1 -1
  123. package/lib/esm/agent/certificate.d.ts +5 -4
  124. package/lib/esm/agent/certificate.d.ts.map +1 -1
  125. package/lib/esm/agent/certificate.js +5 -9
  126. package/lib/esm/agent/certificate.js.map +1 -1
  127. package/lib/esm/agent/der.d.ts +3 -2
  128. package/lib/esm/agent/der.d.ts.map +1 -1
  129. package/lib/esm/agent/der.js.map +1 -1
  130. package/lib/esm/agent/errors.d.ts +7 -1
  131. package/lib/esm/agent/errors.d.ts.map +1 -1
  132. package/lib/esm/agent/errors.js +18 -1
  133. package/lib/esm/agent/errors.js.map +1 -1
  134. package/lib/esm/agent/polling/index.d.ts +3 -4
  135. package/lib/esm/agent/polling/index.d.ts.map +1 -1
  136. package/lib/esm/agent/polling/index.js +15 -8
  137. package/lib/esm/agent/polling/index.js.map +1 -1
  138. package/lib/esm/agent/polling/strategy.d.ts.map +1 -1
  139. package/lib/esm/agent/polling/strategy.js +6 -6
  140. package/lib/esm/agent/polling/strategy.js.map +1 -1
  141. package/lib/esm/agent/polling/types.d.ts +3 -4
  142. package/lib/esm/agent/polling/types.d.ts.map +1 -1
  143. package/lib/esm/agent/public_key.d.ts +3 -2
  144. package/lib/esm/agent/public_key.d.ts.map +1 -1
  145. package/lib/esm/agent/public_key.js +2 -2
  146. package/lib/esm/agent/public_key.js.map +1 -1
  147. package/lib/esm/agent/request_id.js +2 -2
  148. package/lib/esm/agent/request_id.js.map +1 -1
  149. package/lib/esm/agent/subnetStatus/index.js +1 -1
  150. package/lib/esm/agent/subnetStatus/index.js.map +1 -1
  151. package/lib/esm/agent/utils/bls.d.ts.map +1 -1
  152. package/lib/esm/agent/utils/bls.js +7 -6
  153. package/lib/esm/agent/utils/bls.js.map +1 -1
  154. package/lib/esm/agent/utils/readState.d.ts +2 -2
  155. package/lib/esm/agent/utils/readState.d.ts.map +1 -1
  156. package/lib/esm/agent/utils/readState.js +1 -1
  157. package/lib/esm/agent/utils/readState.js.map +1 -1
  158. package/lib/esm/agent/utils/target.d.ts +15 -0
  159. package/lib/esm/agent/utils/target.d.ts.map +1 -0
  160. package/lib/esm/agent/utils/target.js +23 -0
  161. package/lib/esm/agent/utils/target.js.map +1 -0
  162. package/lib/esm/candid/utils/buffer.d.ts +2 -1
  163. package/lib/esm/candid/utils/buffer.d.ts.map +1 -1
  164. package/lib/esm/candid/utils/buffer.js +5 -2
  165. package/lib/esm/candid/utils/buffer.js.map +1 -1
  166. package/lib/esm/identity/identity/attributes.d.ts +6 -2
  167. package/lib/esm/identity/identity/attributes.d.ts.map +1 -1
  168. package/lib/esm/identity/identity/attributes.js +9 -1
  169. package/lib/esm/identity/identity/attributes.js.map +1 -1
  170. package/lib/esm/identity/identity/delegation.d.ts +10 -3
  171. package/lib/esm/identity/identity/delegation.d.ts.map +1 -1
  172. package/lib/esm/identity/identity/delegation.js +22 -9
  173. package/lib/esm/identity/identity/delegation.js.map +1 -1
  174. package/lib/esm/identity/identity/ecdsa.d.ts +2 -2
  175. package/lib/esm/identity/identity/ecdsa.d.ts.map +1 -1
  176. package/lib/esm/identity/identity/ecdsa.js +3 -2
  177. package/lib/esm/identity/identity/ecdsa.js.map +1 -1
  178. package/lib/esm/identity/identity/ed25519.d.ts +3 -2
  179. package/lib/esm/identity/identity/ed25519.d.ts.map +1 -1
  180. package/lib/esm/identity/identity/ed25519.js +10 -7
  181. package/lib/esm/identity/identity/ed25519.js.map +1 -1
  182. package/lib/esm/identity/identity/webauthn.d.ts +4 -3
  183. package/lib/esm/identity/identity/webauthn.d.ts.map +1 -1
  184. package/lib/esm/identity/identity/webauthn.js +8 -7
  185. package/lib/esm/identity/identity/webauthn.js.map +1 -1
  186. package/lib/esm/identity/secp256k1/der.d.ts +2 -1
  187. package/lib/esm/identity/secp256k1/der.d.ts.map +1 -1
  188. package/lib/esm/identity/secp256k1/der.js.map +1 -1
  189. package/lib/esm/identity/secp256k1/pem.d.ts +4 -3
  190. package/lib/esm/identity/secp256k1/pem.d.ts.map +1 -1
  191. package/lib/esm/identity/secp256k1/pem.js +2 -2
  192. package/lib/esm/identity/secp256k1/pem.js.map +1 -1
  193. package/lib/esm/identity/secp256k1/secp256k1.d.ts +5 -4
  194. package/lib/esm/identity/secp256k1/secp256k1.d.ts.map +1 -1
  195. package/lib/esm/identity/secp256k1/secp256k1.js +10 -13
  196. package/lib/esm/identity/secp256k1/secp256k1.js.map +1 -1
  197. package/lib/esm/principal/principal.js +2 -2
  198. package/lib/esm/principal/principal.js.map +1 -1
  199. package/package.json +20 -10
  200. package/src/agent/actor.ts +0 -524
  201. package/src/agent/agent/api.ts +0 -292
  202. package/src/agent/agent/http/expiry.ts +0 -107
  203. package/src/agent/agent/http/index.ts +0 -1727
  204. package/src/agent/agent/http/transforms.ts +0 -54
  205. package/src/agent/agent/http/types.ts +0 -145
  206. package/src/agent/agent/index.ts +0 -4
  207. package/src/agent/auth.ts +0 -147
  208. package/src/agent/canister-env/index.ts +0 -192
  209. package/src/agent/canisterStatus/index.ts +0 -260
  210. package/src/agent/cbor.ts +0 -63
  211. package/src/agent/certificate.ts +0 -1058
  212. package/src/agent/constants.ts +0 -24
  213. package/src/agent/der.ts +0 -191
  214. package/src/agent/errors.ts +0 -962
  215. package/src/agent/fetch_candid.ts +0 -37
  216. package/src/agent/index.ts +0 -130
  217. package/src/agent/observable.ts +0 -49
  218. package/src/agent/polling/backoff.ts +0 -129
  219. package/src/agent/polling/index.ts +0 -238
  220. package/src/agent/polling/strategy.ts +0 -140
  221. package/src/agent/polling/types.ts +0 -28
  222. package/src/agent/public_key.ts +0 -65
  223. package/src/agent/request_id.ts +0 -99
  224. package/src/agent/subnetStatus/index.ts +0 -263
  225. package/src/agent/utils/bls.ts +0 -18
  226. package/src/agent/utils/buffer.ts +0 -64
  227. package/src/agent/utils/certificateReject.ts +0 -25
  228. package/src/agent/utils/createExpirableStore.ts +0 -31
  229. package/src/agent/utils/expirableStore.ts +0 -47
  230. package/src/agent/utils/inMemoryExpirableStore.ts +0 -49
  231. package/src/agent/utils/indexedDBExpirableStore.ts +0 -191
  232. package/src/agent/utils/leb.ts +0 -14
  233. package/src/agent/utils/random.ts +0 -30
  234. package/src/agent/utils/readState.ts +0 -180
  235. package/src/candid/candid-core.ts +0 -274
  236. package/src/candid/candid-ui.ts +0 -281
  237. package/src/candid/idl.ts +0 -2654
  238. package/src/candid/index.ts +0 -35
  239. package/src/candid/types.ts +0 -7
  240. package/src/candid/utils/bigint-math.ts +0 -26
  241. package/src/candid/utils/buffer.ts +0 -221
  242. package/src/candid/utils/hash.ts +0 -31
  243. package/src/candid/utils/leb128.ts +0 -233
  244. package/src/identity/identity/attributes.ts +0 -84
  245. package/src/identity/identity/delegation.ts +0 -411
  246. package/src/identity/identity/ecdsa.ts +0 -162
  247. package/src/identity/identity/ed25519.ts +0 -246
  248. package/src/identity/identity/partial.ts +0 -60
  249. package/src/identity/identity/webauthn.ts +0 -265
  250. package/src/identity/index.ts +0 -44
  251. package/src/identity/secp256k1/der.ts +0 -177
  252. package/src/identity/secp256k1/index.ts +0 -52
  253. package/src/identity/secp256k1/pem.ts +0 -39
  254. package/src/identity/secp256k1/secp256k1.ts +0 -276
  255. package/src/index.ts +0 -3
  256. package/src/principal/index.ts +0 -19
  257. package/src/principal/principal.ts +0 -181
  258. package/src/principal/utils/base32.ts +0 -101
  259. package/src/principal/utils/getCrc.ts +0 -52
@@ -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;
@@ -365,11 +370,6 @@ class HttpAgent {
365
370
  * Makes a call to a canister method.
366
371
  * @param canisterId - The ID of the canister to call. Can be a Principal or a string.
367
372
  * @param options - Options for the call.
368
- * @param options.methodName - The name of the method to call.
369
- * @param options.arg - The argument to pass to the method, as a Uint8Array.
370
- * @param options.effectiveCanisterId - (Optional) The effective canister ID, if different from the target canister ID.
371
- * @param options.callSync - (Optional) Whether to use synchronous call mode. Defaults to true.
372
- * @param options.nonce - (Optional) A unique nonce for the request. If provided, it will override any nonce set by transforms.
373
373
  * @param identity - (Optional) The identity to use for the call. If not provided, the agent's current identity will be used.
374
374
  * @returns A promise that resolves to the response of the call, including the request ID and response details.
375
375
  */
@@ -380,10 +380,12 @@ class HttpAgent {
380
380
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.IdentityInvalidErrorCode());
381
381
  }
382
382
  const canister = _principal_1.Principal.from(canisterId);
383
- const ecid = options.effectiveCanisterId
384
- ? _principal_1.Principal.from(options.effectiveCanisterId)
385
- : canister;
386
- 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);
387
389
  const sender = id.getPrincipal();
388
390
  const ingress_expiry = calculateIngressExpiry(this.#maxIngressExpiryInMinutes, this.#timeDiffMsecs);
389
391
  const submit = {
@@ -432,30 +434,49 @@ class HttpAgent {
432
434
  }
433
435
  // Apply transform for identity.
434
436
  transformedRequest = (await id.transformRequest(transformedRequest));
437
+ // Compute the request ID from the post-transform content so it matches the
438
+ // hash the IC computes (e.g. when an Identity injects `sender_info`).
439
+ const requestId = (0, request_id_ts_1.requestIdOf)(transformedRequest.body.content ?? submit);
435
440
  const body = cbor.encode(transformedRequest.body);
436
441
  const backoff = this.#backoffStrategy();
437
- const requestId = (0, request_id_ts_1.requestIdOf)(submit);
438
442
  try {
439
- // Attempt v4 sync call
440
- const requestSync = () => {
441
- const url = new URL(`/api/v4/canister/${ecid.toText()}/call`, this.host);
442
- this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
443
- return this.#fetch(url, {
444
- ...this.#callOptions,
445
- ...transformedRequest.request,
446
- body,
447
- });
448
- };
449
- const requestAsync = () => {
450
- const url = new URL(`/api/v2/canister/${ecid.toText()}/call`, this.host);
451
- this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
452
- return this.#fetch(url, {
453
- ...this.#callOptions,
454
- ...transformedRequest.request,
455
- body,
456
- });
457
- };
458
- 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
+ }
459
480
  const { responseBodyBytes, ...response } = await this.#requestAndRetry({
460
481
  requestFn,
461
482
  backoff,
@@ -475,7 +496,7 @@ class HttpAgent {
475
496
  let callError;
476
497
  if (error instanceof errors_ts_1.AgentError) {
477
498
  // If the error is due to the v4 api not being supported, fall back to v2
478
- if (error.hasCode(errors_ts_1.HttpV4ApiNotSupportedErrorCode)) {
499
+ if ('canisterId' in target && error.hasCode(errors_ts_1.HttpV4ApiNotSupportedErrorCode)) {
479
500
  this.log.warn('v4 api not supported. Fall back to v2');
480
501
  return this.call(canisterId, {
481
502
  ...options,
@@ -486,7 +507,7 @@ class HttpAgent {
486
507
  if (error.hasCode(errors_ts_1.IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
487
508
  // if there is an ingress expiry error and the time has not been synced yet,
488
509
  // sync time with the network and try again
489
- await this.syncTime(canister);
510
+ await this.syncTime(target);
490
511
  return this.call(canister, options, identity);
491
512
  }
492
513
  // override the error code to include the request details
@@ -513,28 +534,35 @@ class HttpAgent {
513
534
  * @returns The certified result including the certificate, reply bytes, and raw certificate bytes.
514
535
  */
515
536
  async update(canisterId, fields, pollingOptions = {}) {
516
- 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 };
517
543
  const { requestId, response, requestDetails } = await this.call(canisterId, fields);
518
544
  const { body, ...httpDetails } = response;
519
545
  if ((0, api_ts_1.isV4ResponseBody)(body)) {
520
- return this.#handleV4SyncResponse(body, response, requestId, effectiveCanisterId, fields.methodName, httpDetails, requestDetails, pollingOptions);
546
+ return this.#handleV4SyncResponse(body, response, requestId, canister, target, fields.methodName, httpDetails, requestDetails, pollingOptions, fields.onPollingStarted);
521
547
  }
522
548
  if ((0, api_ts_1.isV2ResponseBody)(body)) {
523
- this.#handleV2Rejection(body, requestId, effectiveCanisterId, fields.methodName, httpDetails);
549
+ this.#handleV2Rejection(body, requestId, canister, target, fields.methodName, httpDetails);
524
550
  }
525
551
  if (response.status === HTTP_STATUS_ACCEPTED) {
526
- const pollResult = await (0, index_ts_3.pollForResponse)(this, effectiveCanisterId, requestId, pollingOptions);
552
+ fields.onPollingStarted?.();
553
+ const pollResult = await (0, index_ts_3.pollForResponse)(this, target, requestId, pollingOptions);
527
554
  return { ...pollResult, requestDetails, callResponse: response };
528
555
  }
529
556
  const unexpectedErrorCode = new errors_ts_1.UnexpectedErrorCode(`Unexpected response from call: status ${response.status} with unrecognized body`);
530
557
  unexpectedErrorCode.callContext = {
531
- canisterId: effectiveCanisterId,
558
+ canisterId: canister,
559
+ effectiveTarget: target,
532
560
  methodName: fields.methodName,
533
561
  httpDetails,
534
562
  };
535
563
  throw errors_ts_1.UnknownError.fromCode(unexpectedErrorCode);
536
564
  }
537
- async #handleV4SyncResponse(body, response, requestId, effectiveCanisterId, methodName, httpDetails, requestDetails, pollingOptions) {
565
+ async #handleV4SyncResponse(body, response, requestId, canisterId, effectiveTarget, methodName, httpDetails, requestDetails, pollingOptions, onPollingStarted) {
538
566
  if (this.rootKey == null) {
539
567
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.MissingRootKeyErrorCode());
540
568
  }
@@ -542,12 +570,12 @@ class HttpAgent {
542
570
  const certificate = await certificate_ts_1.Certificate.create({
543
571
  certificate: rawCertificate,
544
572
  rootKey: this.rootKey,
545
- principal: { canisterId: effectiveCanisterId },
573
+ principal: effectiveTarget,
546
574
  blsVerify: pollingOptions.blsVerify,
547
575
  agent: this,
548
576
  });
549
- const path = [(0, utils_1.utf8ToBytes)('request_status'), requestId];
550
- 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')]));
551
579
  const status = maybeBuf ? new TextDecoder().decode(maybeBuf) : undefined;
552
580
  switch (status) {
553
581
  case types_ts_2.RequestStatusResponseStatus.Replied:
@@ -561,7 +589,8 @@ class HttpAgent {
561
589
  case types_ts_2.RequestStatusResponseStatus.Rejected: {
562
590
  const error = (0, certificateReject_ts_1.readCertifiedReject)(certificate, path, requestId);
563
591
  error.callContext = {
564
- canisterId: effectiveCanisterId,
592
+ canisterId,
593
+ effectiveTarget,
565
594
  methodName,
566
595
  httpDetails,
567
596
  };
@@ -570,14 +599,16 @@ class HttpAgent {
570
599
  case undefined: {
571
600
  // The certificate does not contain an entry for our request ID status.
572
601
  // Fall back to polling via read state requests.
573
- this.log.warn(`v4 sync response certificate does not contain request ID ${(0, utils_1.bytesToHex)(requestId)} status. Falling back to polling.`);
574
- const pollResult = await (0, index_ts_3.pollForResponse)(this, effectiveCanisterId, requestId, pollingOptions);
602
+ this.log.warn(`v4 sync response certificate does not contain request ID ${(0, utils_js_1.bytesToHex)(requestId)} status. Falling back to polling.`);
603
+ onPollingStarted?.();
604
+ const pollResult = await (0, index_ts_3.pollForResponse)(this, effectiveTarget, requestId, pollingOptions);
575
605
  return { ...pollResult, requestDetails, callResponse: response };
576
606
  }
577
607
  default: {
578
608
  const errorCode = new errors_ts_1.UnexpectedV4StatusErrorCode(status, requestId, response, rawCertificate);
579
609
  errorCode.callContext = {
580
- canisterId: effectiveCanisterId,
610
+ canisterId,
611
+ effectiveTarget,
581
612
  methodName,
582
613
  httpDetails,
583
614
  };
@@ -585,20 +616,23 @@ class HttpAgent {
585
616
  }
586
617
  }
587
618
  }
588
- #handleV2Rejection(body, requestId, effectiveCanisterId, methodName, httpDetails) {
619
+ #handleV2Rejection(body, requestId, canisterId, target, methodName, httpDetails) {
589
620
  const { reject_code, reject_message, error_code } = body;
590
621
  const errorCode = new errors_ts_1.UncertifiedRejectUpdateErrorCode(requestId, reject_code, reject_message, error_code);
591
622
  errorCode.callContext = {
592
- canisterId: effectiveCanisterId,
623
+ canisterId,
593
624
  methodName,
594
625
  httpDetails,
626
+ effectiveTarget: target,
595
627
  };
596
628
  throw errors_ts_1.RejectError.fromCode(errorCode);
597
629
  }
598
630
  async #requestAndRetryQuery(args) {
599
- const { ecid, transformedRequest, body, requestId, backoff, tries } = args;
631
+ const { target, transformedRequest, body, requestId, backoff, tries } = args;
600
632
  const delay = tries === 0 ? 0 : backoff.next();
601
- 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);
602
636
  this.log.print(`fetching "${url.pathname}" with tries:`, {
603
637
  tries,
604
638
  backoff,
@@ -669,7 +703,7 @@ class HttpAgent {
669
703
  requestId,
670
704
  signatureTimestampMs,
671
705
  });
672
- await this.syncTime(ecid);
706
+ await this.syncTime(target);
673
707
  return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
674
708
  }
675
709
  throw errors_ts_1.TrustError.fromCode(new errors_ts_1.CertificateOutdatedErrorCode(this.#maxIngressExpiryInMinutes, requestId, tries));
@@ -728,7 +762,7 @@ class HttpAgent {
728
762
  };
729
763
  }
730
764
  const responseText = await response.text();
731
- 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')) {
732
766
  throw errors_ts_1.ProtocolError.fromCode(new errors_ts_1.HttpV4ApiNotSupportedErrorCode());
733
767
  }
734
768
  if (isIngressExpiryInvalidResponse(responseText)) {
@@ -741,18 +775,26 @@ class HttpAgent {
741
775
  }
742
776
  async query(canisterId, fields, identity) {
743
777
  const backoff = this.#backoffStrategy();
744
- const ecid = fields.effectiveCanisterId
745
- ? _principal_1.Principal.from(fields.effectiveCanisterId)
746
- : _principal_1.Principal.from(canisterId);
747
- await this.#asyncGuard(ecid);
748
- 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
+ }
749
792
  this.log.print(`canisterId ${canisterId.toString()}`);
750
793
  let transformedRequest;
751
794
  const id = await (identity ?? this.#identity);
752
795
  if (!id) {
753
796
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.IdentityInvalidErrorCode());
754
797
  }
755
- const canister = _principal_1.Principal.from(canisterId);
756
798
  const sender = id.getPrincipal();
757
799
  const ingressExpiry = calculateIngressExpiry(this.#maxIngressExpiryInMinutes, this.#timeDiffMsecs);
758
800
  const request = {
@@ -763,7 +805,6 @@ class HttpAgent {
763
805
  sender,
764
806
  ingress_expiry: ingressExpiry,
765
807
  };
766
- const requestId = (0, request_id_ts_1.requestIdOf)(request);
767
808
  transformedRequest = await this._transform({
768
809
  request: {
769
810
  method: 'POST',
@@ -777,10 +818,13 @@ class HttpAgent {
777
818
  });
778
819
  // Apply transform for identity.
779
820
  transformedRequest = (await id.transformRequest(transformedRequest));
821
+ // Compute the request ID from the post-transform content so it matches the
822
+ // hash the IC computes (e.g. when an Identity injects `sender_info`).
823
+ const requestId = (0, request_id_ts_1.requestIdOf)(transformedRequest.body.content ?? request);
780
824
  const body = cbor.encode(transformedRequest.body);
781
825
  const args = {
782
826
  canister: canister.toText(),
783
- ecid,
827
+ target,
784
828
  transformedRequest,
785
829
  body,
786
830
  requestId,
@@ -803,7 +847,7 @@ class HttpAgent {
803
847
  // Make query and fetch subnet keys in parallel
804
848
  const [queryWithDetails, subnetNodeKeys] = await Promise.all([
805
849
  makeQuery(),
806
- this.fetchSubnetKeys(ecid),
850
+ this.fetchSubnetKeys(target),
807
851
  ]);
808
852
  try {
809
853
  return this.#verifyQueryResponse(queryWithDetails, subnetNodeKeys);
@@ -811,8 +855,8 @@ class HttpAgent {
811
855
  catch {
812
856
  // In case the node signatures have changed, refresh the subnet keys and try again
813
857
  this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');
814
- await this.#subnetNodeKeyExpirableStore.delete(ecid.toString());
815
- const updatedSubnetNodeKeys = await this.fetchSubnetKeys(ecid);
858
+ await this.#subnetNodeKeyExpirableStore.delete(targetKey);
859
+ const updatedSubnetNodeKeys = await this.fetchSubnetKeys(target);
816
860
  return this.#verifyQueryResponse(queryWithDetails, updatedSubnetNodeKeys);
817
861
  }
818
862
  }
@@ -822,7 +866,7 @@ class HttpAgent {
822
866
  if (error.hasCode(errors_ts_1.IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
823
867
  // if there is an ingress expiry error and the time has not been synced yet,
824
868
  // sync time with the network and try again
825
- await this.syncTime(ecid);
869
+ await this.syncTime(target);
826
870
  return this.query(canisterId, fields, identity);
827
871
  }
828
872
  // override the error code to include the request details
@@ -874,20 +918,24 @@ class HttpAgent {
874
918
  // Apply transform for identity.
875
919
  return id.transformRequest(transformedRequest);
876
920
  }
877
- 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,
878
931
  // eslint-disable-next-line
879
932
  request) {
880
- await this.#rootKeyGuard();
881
- const canister = _principal_1.Principal.from(canisterId);
882
- function getRequestId(options) {
883
- for (const path of options.paths) {
884
- const [pathName, value] = path;
885
- const request_status = new TextEncoder().encode('request_status');
886
- if ((0, buffer_ts_1.uint8Equals)(pathName, request_status)) {
887
- return value;
888
- }
889
- }
933
+ if (typeof effectiveTarget === 'string' || effectiveTarget instanceof _principal_1.Principal) {
934
+ // compatibility with v5
935
+ effectiveTarget = { canisterId: _principal_1.Principal.from(effectiveTarget) };
890
936
  }
937
+ await this.#rootKeyGuard();
938
+ const target = (0, target_ts_1.inputToTarget)(effectiveTarget);
891
939
  let transformedRequest;
892
940
  let requestId;
893
941
  // If a pre-signed request is provided, use it
@@ -897,7 +945,7 @@ class HttpAgent {
897
945
  }
898
946
  else {
899
947
  // This is fields, we need to create a request
900
- requestId = getRequestId(fields);
948
+ requestId = this.#getRequestId(fields);
901
949
  // Always create a fresh request with the current identity
902
950
  const identity = await this.#identity;
903
951
  if (!identity) {
@@ -905,23 +953,19 @@ class HttpAgent {
905
953
  }
906
954
  transformedRequest = await this.createReadStateRequest(fields, identity);
907
955
  }
908
- const url = new URL(`/api/v3/canister/${canister.toString()}/read_state`, this.host);
909
- 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);
910
960
  }
961
+ // eslint-disable-next-line
911
962
  /**
912
- * Reads the state of a subnet from the `/api/v3/subnet/{subnetId}/read_state` endpoint.
913
- * @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.
914
- * @param options The options for the read state request.
915
- * @returns The response from the read state request.
963
+ * @deprecated Use `readState`
916
964
  */
917
- async readSubnetState(subnetId, options) {
918
- await this.#rootKeyGuard();
919
- const subnet = _principal_1.Principal.from(subnetId);
920
- const url = new URL(`/api/v3/subnet/${subnet.toString()}/read_state`, this.host);
921
- const transformedRequest = await this.createReadStateRequest(options, this.#identity ?? undefined);
922
- return await this.#readStateInner(url, { subnetId: subnet }, transformedRequest);
965
+ readSubnetState(subnetId, options) {
966
+ return this.readState({ subnetId: _principal_1.Principal.from(subnetId) }, options);
923
967
  }
924
- async #readStateInner(url, principal, transformedRequest, requestId) {
968
+ async #readStateInner(url, target, transformedRequest, requestId) {
925
969
  const backoff = this.#backoffStrategy();
926
970
  try {
927
971
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -942,16 +986,8 @@ class HttpAgent {
942
986
  if (error.hasCode(errors_ts_1.IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
943
987
  // if there is an ingress expiry error and the time has not been synced yet,
944
988
  // sync time with the network and try again
945
- if ('canisterId' in principal) {
946
- await this.syncTime(principal.canisterId);
947
- }
948
- else if ('subnetId' in principal) {
949
- await this.syncTimeWithSubnet(principal.subnetId);
950
- }
951
- else {
952
- throw errors_ts_1.UNREACHABLE_ERROR;
953
- }
954
- return await this.#readStateInner(url, principal, transformedRequest, requestId);
989
+ await this.syncTime(target);
990
+ return await this.#readStateInner(url, target, transformedRequest, requestId);
955
991
  }
956
992
  // override the error code to include the request details
957
993
  error.code.requestContext = {
@@ -996,20 +1032,27 @@ class HttpAgent {
996
1032
  }
997
1033
  /**
998
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
999
- * @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.
1000
1036
  */
1001
- 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
+ }
1002
1043
  this.#syncTimePromise =
1003
1044
  this.#syncTimePromise ??
1004
1045
  (async () => {
1005
1046
  await this.#rootKeyGuard();
1006
1047
  const callTime = Date.now();
1007
1048
  try {
1008
- if (!canisterIdOverride) {
1009
- 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');
1010
1051
  }
1011
1052
  // Fall back with canisterId of the ICP Ledger
1012
- 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
+ };
1013
1056
  const anonymousAgent = HttpAgent.createSync({
1014
1057
  identity: new auth_ts_1.AnonymousIdentity(),
1015
1058
  host: this.host.toString(),
@@ -1021,12 +1064,19 @@ class HttpAgent {
1021
1064
  const replicaTimes = await Promise.all(Array(3)
1022
1065
  .fill(null)
1023
1066
  .map(async () => {
1024
- const status = await (0, index_ts_1.request)({
1025
- canisterId,
1026
- agent: anonymousAgent,
1027
- paths: ['time'],
1028
- disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1029
- });
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
+ });
1030
1080
  const date = status.get('time');
1031
1081
  if (date instanceof Date) {
1032
1082
  return date.getTime();
@@ -1046,43 +1096,12 @@ class HttpAgent {
1046
1096
  this.#syncTimePromise = null;
1047
1097
  });
1048
1098
  }
1099
+ // eslint-disable-next-line
1049
1100
  /**
1050
- * Allows agent to sync its time with the network.
1051
- * @param {Principal} subnetId - Pass the subnet ID you need to sync the time with.
1101
+ * @deprecated Use {@link syncTime}
1052
1102
  */
1053
- async syncTimeWithSubnet(subnetId) {
1054
- await this.#rootKeyGuard();
1055
- const callTime = Date.now();
1056
- try {
1057
- const anonymousAgent = HttpAgent.createSync({
1058
- identity: new auth_ts_1.AnonymousIdentity(),
1059
- host: this.host.toString(),
1060
- fetch: this.#fetch,
1061
- retryTimes: 0,
1062
- rootKey: this.rootKey ?? undefined,
1063
- shouldSyncTime: false,
1064
- });
1065
- const replicaTimes = await Promise.all(Array(3)
1066
- .fill(null)
1067
- .map(async () => {
1068
- const status = await (0, index_ts_2.request)({
1069
- subnetId,
1070
- agent: anonymousAgent,
1071
- paths: ['time'],
1072
- disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1073
- });
1074
- const date = status.get('time');
1075
- if (date instanceof Date) {
1076
- return date.getTime();
1077
- }
1078
- }, []));
1079
- this.#setTimeDiffMsecs(callTime, replicaTimes);
1080
- }
1081
- catch (error) {
1082
- const syncTimeError = error instanceof errors_ts_1.AgentError ? error : errors_ts_1.UnknownError.fromCode(new errors_ts_1.UnexpectedErrorCode(error));
1083
- this.log.error('Caught exception while attempting to sync time with subnet', syncTimeError);
1084
- throw syncTimeError;
1085
- }
1103
+ syncTimeWithSubnet(subnetId) {
1104
+ return this.syncTime({ subnetId });
1086
1105
  }
1087
1106
  #setTimeDiffMsecs(callTime, replicaTimes) {
1088
1107
  const maxReplicaTime = replicaTimes.reduce((max, current) => {
@@ -1103,7 +1122,7 @@ class HttpAgent {
1103
1122
  Authorization: `Basic ${btoa(this.#credentials)}`,
1104
1123
  }
1105
1124
  : {};
1106
- const url = new URL(`/api/v2/status`, this.host);
1125
+ const url = new URL(`api/v2/status`, this.host);
1107
1126
  this.log.print(`fetching "${url.pathname}"`);
1108
1127
  const backoff = this.#backoffStrategy();
1109
1128
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -1128,8 +1147,8 @@ class HttpAgent {
1128
1147
  this.#rootKeyPromise = null;
1129
1148
  });
1130
1149
  }
1131
- async #asyncGuard(canisterIdOverride) {
1132
- await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(canisterIdOverride)]);
1150
+ async #asyncGuard(targetOverride) {
1151
+ await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(targetOverride)]);
1133
1152
  }
1134
1153
  async #rootKeyGuard() {
1135
1154
  if (this.rootKey) {
@@ -1144,9 +1163,9 @@ class HttpAgent {
1144
1163
  throw errors_ts_1.ExternalError.fromCode(new errors_ts_1.MissingRootKeyErrorCode(this.#shouldFetchRootKey));
1145
1164
  }
1146
1165
  }
1147
- async #syncTimeGuard(canisterIdOverride) {
1166
+ async #syncTimeGuard(targetOverride) {
1148
1167
  if (this.#shouldSyncTime && !this.hasSyncedTime()) {
1149
- await this.syncTime(canisterIdOverride);
1168
+ await this.syncTime(targetOverride);
1150
1169
  }
1151
1170
  }
1152
1171
  invalidateIdentity() {
@@ -1155,52 +1174,58 @@ class HttpAgent {
1155
1174
  replaceIdentity(identity) {
1156
1175
  this.#identity = Promise.resolve(identity);
1157
1176
  }
1158
- async fetchSubnetKeys(canisterId) {
1159
- 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);
1160
1184
  // Return cached result if available within the TTL.
1161
- const cached = await this.#subnetNodeKeyExpirableStore.get(effectiveCanisterId.toText());
1185
+ const cached = await this.#subnetNodeKeyExpirableStore.get(targetKey);
1162
1186
  if (cached) {
1163
1187
  return cached;
1164
1188
  }
1165
1189
  // Deduplicate parallel requests for the same canister so that concurrent
1166
1190
  // query calls share a single read_state round-trip instead of each
1167
1191
  // issuing their own.
1168
- const inflight = this.#subnetKeysFetching.get(effectiveCanisterId.toText());
1192
+ const inflight = this.#subnetKeysFetching.get(targetKey);
1169
1193
  if (inflight) {
1170
1194
  return inflight;
1171
1195
  }
1172
- const fetchPromise = this.#doFetchSubnetKeys(effectiveCanisterId).finally(() => {
1173
- this.#subnetKeysFetching.delete(effectiveCanisterId.toText());
1196
+ const fetchPromise = this.#doFetchSubnetKeys(target).finally(() => {
1197
+ this.#subnetKeysFetching.delete(targetKey);
1174
1198
  });
1175
- this.#subnetKeysFetching.set(effectiveCanisterId.toText(), fetchPromise);
1199
+ this.#subnetKeysFetching.set(targetKey, fetchPromise);
1176
1200
  return fetchPromise;
1177
1201
  }
1178
- async #doFetchSubnetKeys(effectiveCanisterId) {
1179
- await this.#asyncGuard(effectiveCanisterId);
1202
+ async #doFetchSubnetKeys(target) {
1203
+ await this.#asyncGuard(target);
1180
1204
  const rootKey = this.rootKey;
1181
- const canisterReadState = await this.readState(effectiveCanisterId, {
1182
- paths: [[(0, utils_1.utf8ToBytes)('subnet')]],
1205
+ const canisterReadState = await this.readState(target, {
1206
+ paths: [[(0, utils_js_1.utf8ToBytes)('subnet')]],
1183
1207
  });
1184
1208
  const canisterCertificate = await certificate_ts_1.Certificate.create({
1185
1209
  certificate: canisterReadState.certificate,
1186
1210
  rootKey,
1187
- principal: { canisterId: effectiveCanisterId },
1211
+ principal: target,
1188
1212
  agent: this,
1189
1213
  });
1190
- if (!canisterCertificate.cert.delegation) {
1214
+ const targetKey = (0, target_ts_1.getTargetKey)(target);
1215
+ if ('canisterId' in target && !canisterCertificate.cert.delegation) {
1191
1216
  const subnetId = _principal_1.Principal.selfAuthenticating(rootKey);
1192
1217
  const canisterInRange = (0, certificate_ts_1.check_canister_ranges)({
1193
- canisterId: effectiveCanisterId,
1218
+ canisterId: target.canisterId,
1194
1219
  subnetId,
1195
1220
  tree: canisterCertificate.cert.tree,
1196
1221
  });
1197
1222
  if (!canisterInRange) {
1198
- 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));
1199
1224
  }
1200
1225
  }
1201
1226
  const subnetId = (0, certificate_ts_1.getSubnetIdFromCertificate)(canisterCertificate.cert, rootKey);
1202
1227
  const nodeKeys = (0, readState_ts_1.lookupNodeKeysFromCertificate)(canisterCertificate.cert, subnetId);
1203
- await this.#subnetNodeKeyExpirableStore.set(effectiveCanisterId.toText(), nodeKeys);
1228
+ await this.#subnetNodeKeyExpirableStore.set(targetKey, nodeKeys);
1204
1229
  return nodeKeys;
1205
1230
  }
1206
1231
  /**
@@ -1211,9 +1236,9 @@ class HttpAgent {
1211
1236
  */
1212
1237
  async getSubnetIdFromCanister(canisterId) {
1213
1238
  const effectiveCanisterId = _principal_1.Principal.from(canisterId);
1214
- await this.#asyncGuard(effectiveCanisterId);
1215
- const canisterReadState = await this.readState(effectiveCanisterId, {
1216
- 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')]],
1217
1242
  });
1218
1243
  const canisterCertificate = await certificate_ts_1.Certificate.create({
1219
1244
  certificate: canisterReadState.certificate,