@icp-sdk/core 5.0.0-beta.0 → 5.0.0-beta.1

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 (137) hide show
  1. package/lib/cjs/agent/actor.js +2 -2
  2. package/lib/cjs/agent/actor.js.map +1 -1
  3. package/lib/cjs/agent/agent/api.d.ts +6 -6
  4. package/lib/cjs/agent/agent/api.js +4 -4
  5. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.d.ts +30 -0
  6. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.d.ts.map +1 -1
  7. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.js +33 -1
  8. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.js.map +1 -1
  9. package/lib/cjs/agent/agent/http/index.d.ts +22 -3
  10. package/lib/cjs/agent/agent/http/index.d.ts.map +1 -1
  11. package/lib/cjs/agent/agent/http/index.js +131 -51
  12. package/lib/cjs/agent/agent/http/index.js.map +1 -1
  13. package/lib/cjs/agent/canisterStatus/index.d.ts +18 -50
  14. package/lib/cjs/agent/canisterStatus/index.d.ts.map +1 -1
  15. package/lib/cjs/agent/canisterStatus/index.js +30 -92
  16. package/lib/cjs/agent/canisterStatus/index.js.map +1 -1
  17. package/lib/cjs/agent/certificate.d.ts +68 -10
  18. package/lib/cjs/agent/certificate.d.ts.map +1 -1
  19. package/lib/cjs/agent/certificate.js +198 -27
  20. package/lib/cjs/agent/certificate.js.map +1 -1
  21. package/lib/cjs/agent/constants.d.ts +4 -0
  22. package/lib/cjs/agent/constants.d.ts.map +1 -1
  23. package/lib/cjs/agent/constants.js +5 -1
  24. package/lib/cjs/agent/constants.js.map +1 -1
  25. package/lib/cjs/agent/errors.d.ts +7 -1
  26. package/lib/cjs/agent/errors.d.ts.map +1 -1
  27. package/lib/cjs/agent/errors.js +19 -7
  28. package/lib/cjs/agent/errors.js.map +1 -1
  29. package/lib/cjs/agent/index.d.ts +97 -3
  30. package/lib/cjs/agent/index.d.ts.map +1 -1
  31. package/lib/cjs/agent/index.js +92 -9
  32. package/lib/cjs/agent/index.js.map +1 -1
  33. package/lib/cjs/agent/polling/index.js +1 -1
  34. package/lib/cjs/agent/polling/index.js.map +1 -1
  35. package/lib/cjs/agent/subnetStatus/index.d.ts +70 -0
  36. package/lib/cjs/agent/subnetStatus/index.d.ts.map +1 -0
  37. package/lib/cjs/agent/subnetStatus/index.js +224 -0
  38. package/lib/cjs/agent/subnetStatus/index.js.map +1 -0
  39. package/lib/cjs/agent/utils/readState.d.ts +84 -0
  40. package/lib/cjs/agent/utils/readState.d.ts.map +1 -0
  41. package/lib/cjs/agent/utils/readState.js +149 -0
  42. package/lib/cjs/agent/utils/readState.js.map +1 -0
  43. package/lib/cjs/candid/index.d.ts +20 -1
  44. package/lib/cjs/candid/index.d.ts.map +1 -1
  45. package/lib/cjs/candid/index.js +20 -1
  46. package/lib/cjs/candid/index.js.map +1 -1
  47. package/lib/cjs/identity/index.d.ts +30 -7
  48. package/lib/cjs/identity/index.d.ts.map +1 -1
  49. package/lib/cjs/identity/index.js +31 -11
  50. package/lib/cjs/identity/index.js.map +1 -1
  51. package/lib/cjs/identity/secp256k1/index.d.ts +48 -1
  52. package/lib/cjs/identity/secp256k1/index.d.ts.map +1 -1
  53. package/lib/cjs/identity/secp256k1/index.js +48 -1
  54. package/lib/cjs/identity/secp256k1/index.js.map +1 -1
  55. package/lib/cjs/principal/index.d.ts +15 -0
  56. package/lib/cjs/principal/index.d.ts.map +1 -1
  57. package/lib/cjs/principal/index.js +15 -0
  58. package/lib/cjs/principal/index.js.map +1 -1
  59. package/lib/esm/agent/actor.js +3 -3
  60. package/lib/esm/agent/actor.js.map +1 -1
  61. package/lib/esm/agent/agent/api.d.ts +6 -6
  62. package/lib/esm/agent/agent/api.js +3 -3
  63. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.d.ts +30 -0
  64. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.d.ts.map +1 -1
  65. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.js +33 -1
  66. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.js.map +1 -1
  67. package/lib/esm/agent/agent/http/index.d.ts +22 -3
  68. package/lib/esm/agent/agent/http/index.d.ts.map +1 -1
  69. package/lib/esm/agent/agent/http/index.js +134 -54
  70. package/lib/esm/agent/agent/http/index.js.map +1 -1
  71. package/lib/esm/agent/canister-env/index.d.ts +2 -1
  72. package/lib/esm/agent/canister-env/index.d.ts.map +1 -1
  73. package/lib/esm/agent/canister-env/index.js +2 -1
  74. package/lib/esm/agent/canister-env/index.js.map +1 -1
  75. package/lib/esm/agent/canisterStatus/index.d.ts +18 -50
  76. package/lib/esm/agent/canisterStatus/index.d.ts.map +1 -1
  77. package/lib/esm/agent/canisterStatus/index.js +31 -93
  78. package/lib/esm/agent/canisterStatus/index.js.map +1 -1
  79. package/lib/esm/agent/certificate.d.ts +68 -10
  80. package/lib/esm/agent/certificate.d.ts.map +1 -1
  81. package/lib/esm/agent/certificate.js +196 -29
  82. package/lib/esm/agent/certificate.js.map +1 -1
  83. package/lib/esm/agent/constants.d.ts +4 -0
  84. package/lib/esm/agent/constants.d.ts.map +1 -1
  85. package/lib/esm/agent/constants.js +4 -0
  86. package/lib/esm/agent/constants.js.map +1 -1
  87. package/lib/esm/agent/errors.d.ts +7 -1
  88. package/lib/esm/agent/errors.d.ts.map +1 -1
  89. package/lib/esm/agent/errors.js +15 -4
  90. package/lib/esm/agent/errors.js.map +1 -1
  91. package/lib/esm/agent/index.d.ts +97 -3
  92. package/lib/esm/agent/index.d.ts.map +1 -1
  93. package/lib/esm/agent/index.js +97 -3
  94. package/lib/esm/agent/index.js.map +1 -1
  95. package/lib/esm/agent/polling/index.js +1 -1
  96. package/lib/esm/agent/polling/index.js.map +1 -1
  97. package/lib/esm/agent/subnetStatus/index.d.ts +70 -0
  98. package/lib/esm/agent/subnetStatus/index.d.ts.map +1 -0
  99. package/lib/esm/agent/subnetStatus/index.js +183 -0
  100. package/lib/esm/agent/subnetStatus/index.js.map +1 -0
  101. package/lib/esm/agent/utils/readState.d.ts +84 -0
  102. package/lib/esm/agent/utils/readState.d.ts.map +1 -0
  103. package/lib/esm/agent/utils/readState.js +107 -0
  104. package/lib/esm/agent/utils/readState.js.map +1 -0
  105. package/lib/esm/candid/index.d.ts +20 -1
  106. package/lib/esm/candid/index.d.ts.map +1 -1
  107. package/lib/esm/candid/index.js +20 -1
  108. package/lib/esm/candid/index.js.map +1 -1
  109. package/lib/esm/identity/index.d.ts +30 -7
  110. package/lib/esm/identity/index.d.ts.map +1 -1
  111. package/lib/esm/identity/index.js +30 -9
  112. package/lib/esm/identity/index.js.map +1 -1
  113. package/lib/esm/identity/secp256k1/index.d.ts +48 -1
  114. package/lib/esm/identity/secp256k1/index.d.ts.map +1 -1
  115. package/lib/esm/identity/secp256k1/index.js +48 -1
  116. package/lib/esm/identity/secp256k1/index.js.map +1 -1
  117. package/lib/esm/principal/index.d.ts +15 -0
  118. package/lib/esm/principal/index.d.ts.map +1 -1
  119. package/lib/esm/principal/index.js +15 -0
  120. package/lib/esm/principal/index.js.map +1 -1
  121. package/package.json +1 -1
  122. package/src/agent/actor.ts +3 -3
  123. package/src/agent/agent/api.ts +8 -8
  124. package/src/agent/agent/http/index.ts +171 -58
  125. package/src/agent/canister-env/index.ts +2 -1
  126. package/src/agent/canisterStatus/index.ts +46 -191
  127. package/src/agent/certificate.ts +271 -52
  128. package/src/agent/constants.ts +5 -0
  129. package/src/agent/errors.ts +17 -4
  130. package/src/agent/index.ts +97 -3
  131. package/src/agent/polling/index.ts +1 -1
  132. package/src/agent/subnetStatus/index.ts +270 -0
  133. package/src/agent/utils/readState.ts +180 -0
  134. package/src/candid/index.ts +20 -1
  135. package/src/identity/index.ts +30 -10
  136. package/src/identity/secp256k1/index.ts +48 -1
  137. package/src/principal/index.ts +16 -0
@@ -20,7 +20,7 @@ import {
20
20
  UnexpectedErrorCode,
21
21
  UnknownError,
22
22
  HttpErrorCode,
23
- HttpV3ApiNotSupportedErrorCode,
23
+ HttpV4ApiNotSupportedErrorCode,
24
24
  TransportError,
25
25
  HttpFetchErrorCode,
26
26
  AgentError,
@@ -55,8 +55,16 @@ import {
55
55
  type ReadStateRequest,
56
56
  type HttpHeaderField,
57
57
  } from './types.ts';
58
- import { type SubnetStatus, request as canisterStatusRequest } from '../../canisterStatus/index.ts';
59
- import { type HashTree, lookup_path, LookupPathStatus } from '../../certificate.ts';
58
+ import { request as canisterStatusRequest } from '../../canisterStatus/index.ts';
59
+ import { request as subnetStatusRequest } from '../../subnetStatus/index.ts';
60
+ import { lookupNodeKeysFromCertificate, type SubnetNodeKeys } from '../../utils/readState.ts';
61
+ import {
62
+ Certificate,
63
+ getSubnetIdFromCertificate,
64
+ type HashTree,
65
+ lookup_path,
66
+ LookupPathStatus,
67
+ } from '../../certificate.ts';
60
68
  import { ed25519 } from '@noble/curves/ed25519';
61
69
  import { ExpirableMap } from '../../utils/expirableMap.ts';
62
70
  import { Ed25519PublicKey } from '../../public_key.ts';
@@ -67,7 +75,7 @@ import {
67
75
  ExponentialBackoff,
68
76
  } from '../../polling/backoff.ts';
69
77
  import { decodeTime } from '../../utils/leb.ts';
70
- import { concatBytes, hexToBytes } from '@noble/hashes/utils';
78
+ import { concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';
71
79
  import { uint8Equals, uint8FromBufLike } from '../../utils/buffer.ts';
72
80
  import { IC_RESPONSE_DOMAIN_SEPARATOR } from '../../constants.ts';
73
81
  export * from './transforms.ts';
@@ -315,7 +323,7 @@ export class HttpAgent implements Agent {
315
323
  #queryPipeline: HttpAgentRequestTransformFn[] = [];
316
324
  #updatePipeline: HttpAgentRequestTransformFn[] = [];
317
325
 
318
- #subnetKeys: ExpirableMap<string, SubnetStatus> = new ExpirableMap({
326
+ #subnetKeys: ExpirableMap<string, SubnetNodeKeys> = new ExpirableMap({
319
327
  expirationTime: 5 * MINUTE_TO_MSECS,
320
328
  });
321
329
  #verifyQuerySignatures = true;
@@ -570,9 +578,9 @@ export class HttpAgent implements Agent {
570
578
  const backoff = this.#backoffStrategy();
571
579
  const requestId = requestIdOf(submit);
572
580
  try {
573
- // Attempt v3 sync call
581
+ // Attempt v4 sync call
574
582
  const requestSync = () => {
575
- const url = new URL(`/api/v3/canister/${ecid.toText()}/call`, this.host);
583
+ const url = new URL(`/api/v4/canister/${ecid.toText()}/call`, this.host);
576
584
  this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
577
585
  return this.#fetch(url, {
578
586
  ...this.#callOptions,
@@ -613,14 +621,14 @@ export class HttpAgent implements Agent {
613
621
  } catch (error) {
614
622
  let callError: AgentError;
615
623
  if (error instanceof AgentError) {
616
- // If the error is due to the v3 api not being supported, fall back to v2
617
- if (error.hasCode(HttpV3ApiNotSupportedErrorCode)) {
618
- this.log.warn('v3 api not supported. Fall back to v2');
624
+ // If the error is due to the v4 api not being supported, fall back to v2
625
+ if (error.hasCode(HttpV4ApiNotSupportedErrorCode)) {
626
+ this.log.warn('v4 api not supported. Fall back to v2');
619
627
  return this.call(
620
628
  canisterId,
621
629
  {
622
630
  ...options,
623
- // disable v3 api
631
+ // disable v4 api
624
632
  callSync: false,
625
633
  },
626
634
  identity,
@@ -660,7 +668,7 @@ export class HttpAgent implements Agent {
660
668
 
661
669
  const delay = tries === 0 ? 0 : backoff.next();
662
670
 
663
- const url = new URL(`/api/v2/canister/${ecid.toString()}/query`, this.host);
671
+ const url = new URL(`/api/v3/canister/${ecid.toString()}/query`, this.host);
664
672
 
665
673
  this.log.print(`fetching "${url.pathname}" with tries:`, {
666
674
  tries,
@@ -839,8 +847,8 @@ export class HttpAgent implements Agent {
839
847
 
840
848
  const responseText = await response.text();
841
849
 
842
- if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/v3')) {
843
- throw ProtocolError.fromCode(new HttpV3ApiNotSupportedErrorCode());
850
+ if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/v4')) {
851
+ throw ProtocolError.fromCode(new HttpV4ApiNotSupportedErrorCode());
844
852
  }
845
853
 
846
854
  // The error message comes from https://github.com/dfinity/ic/blob/23d5990bfc5277c32e54f0087b5a38fa412171e1/rs/validator/src/ingress_validation.rs#L233
@@ -933,17 +941,17 @@ export class HttpAgent implements Agent {
933
941
  };
934
942
  };
935
943
 
936
- const getSubnetStatus = async (): Promise<SubnetStatus> => {
937
- const cachedSubnetStatus = this.#subnetKeys.get(ecid.toString());
938
- if (cachedSubnetStatus) {
939
- return cachedSubnetStatus;
944
+ const getSubnetNodeKeys = async (): Promise<SubnetNodeKeys> => {
945
+ const cachedSubnetNodeKeys = this.#subnetKeys.get(ecid.toString());
946
+ if (cachedSubnetNodeKeys) {
947
+ return cachedSubnetNodeKeys;
940
948
  }
941
949
  await this.fetchSubnetKeys(ecid.toString());
942
- const subnetStatus = this.#subnetKeys.get(ecid.toString());
943
- if (!subnetStatus) {
950
+ const subnetNodeKeys = this.#subnetKeys.get(ecid.toString());
951
+ if (!subnetNodeKeys) {
944
952
  throw TrustError.fromCode(new MissingSignatureErrorCode());
945
953
  }
946
- return subnetStatus;
954
+ return subnetNodeKeys;
947
955
  };
948
956
 
949
957
  try {
@@ -953,16 +961,19 @@ export class HttpAgent implements Agent {
953
961
  }
954
962
 
955
963
  // Make query and fetch subnet keys in parallel
956
- const [queryWithDetails, subnetStatus] = await Promise.all([makeQuery(), getSubnetStatus()]);
964
+ const [queryWithDetails, subnetNodeKeys] = await Promise.all([
965
+ makeQuery(),
966
+ getSubnetNodeKeys(),
967
+ ]);
957
968
 
958
969
  try {
959
- return this.#verifyQueryResponse(queryWithDetails, subnetStatus);
970
+ return this.#verifyQueryResponse(queryWithDetails, subnetNodeKeys);
960
971
  } catch {
961
972
  // In case the node signatures have changed, refresh the subnet keys and try again
962
973
  this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');
963
974
  this.#subnetKeys.delete(ecid.toString());
964
- const updatedSubnetStatus = await getSubnetStatus();
965
- return this.#verifyQueryResponse(queryWithDetails, updatedSubnetStatus);
975
+ const updatedSubnetNodeKeys = await getSubnetNodeKeys();
976
+ return this.#verifyQueryResponse(queryWithDetails, updatedSubnetNodeKeys);
966
977
  }
967
978
  } catch (error) {
968
979
  let queryError: AgentError;
@@ -986,12 +997,12 @@ export class HttpAgent implements Agent {
986
997
  /**
987
998
  * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation
988
999
  * @param queryResponse - The response from the query
989
- * @param subnetStatus - The subnet status, including all node keys
1000
+ * @param subnetNodeKeys - The subnet node keys
990
1001
  * @returns ApiQueryResponse
991
1002
  */
992
1003
  #verifyQueryResponse = (
993
1004
  queryResponse: ApiQueryResponse,
994
- subnetStatus: SubnetStatus,
1005
+ subnetNodeKeys: SubnetNodeKeys,
995
1006
  ): ApiQueryResponse => {
996
1007
  if (this.#verifyQuerySignatures === false) {
997
1008
  // This should not be called if the user has disabled verification
@@ -1030,7 +1041,7 @@ export class HttpAgent implements Agent {
1030
1041
  const separatorWithHash = concatBytes(IC_RESPONSE_DOMAIN_SEPARATOR, hash);
1031
1042
 
1032
1043
  // FIX: check for match without verifying N times
1033
- const pubKey = subnetStatus.nodeKeys.get(nodeId);
1044
+ const pubKey = subnetNodeKeys.get(nodeId);
1034
1045
  if (!pubKey) {
1035
1046
  throw ProtocolError.fromCode(new MalformedPublicKeyErrorCode());
1036
1047
  }
@@ -1106,7 +1117,6 @@ export class HttpAgent implements Agent {
1106
1117
  if (request) {
1107
1118
  // This is a pre-signed request
1108
1119
  transformedRequest = request;
1109
- requestId = requestIdOf(transformedRequest);
1110
1120
  } else {
1111
1121
  // This is fields, we need to create a request
1112
1122
  requestId = getRequestId(fields);
@@ -1119,10 +1129,37 @@ export class HttpAgent implements Agent {
1119
1129
  transformedRequest = await this.createReadStateRequest(fields, identity);
1120
1130
  }
1121
1131
 
1122
- const url = new URL(`/api/v2/canister/${canister.toString()}/read_state`, this.host);
1132
+ const url = new URL(`/api/v3/canister/${canister.toString()}/read_state`, this.host);
1133
+
1134
+ return await this.#readStateInner(url, transformedRequest, requestId);
1135
+ }
1123
1136
 
1124
- this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
1137
+ /**
1138
+ * Reads the state of a subnet from the `/api/v3/subnet/{subnetId}/read_state` endpoint.
1139
+ * @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.
1140
+ * @param options The options for the read state request.
1141
+ * @returns The response from the read state request.
1142
+ */
1143
+ public async readSubnetState(
1144
+ subnetId: Principal | string,
1145
+ options: ReadStateOptions,
1146
+ ): Promise<ReadStateResponse> {
1147
+ await this.#rootKeyGuard();
1125
1148
 
1149
+ const url = new URL(`/api/v3/subnet/${subnetId.toString()}/read_state`, this.host);
1150
+ const transformedRequest: ReadStateRequest = await this.createReadStateRequest(
1151
+ options,
1152
+ this.#identity ?? undefined,
1153
+ );
1154
+
1155
+ return await this.#readStateInner(url, transformedRequest);
1156
+ }
1157
+
1158
+ async #readStateInner(
1159
+ url: URL,
1160
+ transformedRequest: ReadStateRequest,
1161
+ requestId?: RequestId,
1162
+ ): Promise<ReadStateResponse> {
1126
1163
  const backoff = this.#backoffStrategy();
1127
1164
  try {
1128
1165
  const { responseBodyBytes } = await this.#requestAndRetry({
@@ -1138,15 +1175,13 @@ export class HttpAgent implements Agent {
1138
1175
 
1139
1176
  const decodedResponse: ReadStateResponse = cbor.decode(responseBodyBytes);
1140
1177
 
1141
- this.log.print('Read state response:', decodedResponse);
1142
-
1143
1178
  return decodedResponse;
1144
1179
  } catch (error) {
1145
1180
  let readStateError: AgentError;
1146
1181
  if (error instanceof AgentError) {
1147
1182
  // override the error code to include the request details
1148
1183
  error.code.requestContext = {
1149
- requestId,
1184
+ requestId: requestId ?? requestIdOf(transformedRequest),
1150
1185
  senderPubKey: transformedRequest.body.sender_pubkey,
1151
1186
  senderSignature: transformedRequest.body.sender_sig,
1152
1187
  ingressExpiry: transformedRequest.body.content.ingress_expiry,
@@ -1197,7 +1232,7 @@ export class HttpAgent implements Agent {
1197
1232
  }
1198
1233
 
1199
1234
  /**
1200
- * Allows agent to sync its time with the network. Can be called during intialization 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
1235
+ * 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
1201
1236
  * @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.
1202
1237
  */
1203
1238
  public async syncTime(canisterIdOverride?: Principal): Promise<void> {
@@ -1242,18 +1277,7 @@ export class HttpAgent implements Agent {
1242
1277
  }, []),
1243
1278
  );
1244
1279
 
1245
- const maxReplicaTime = replicaTimes.reduce<number>((max, current) => {
1246
- return typeof current === 'number' && current > max ? current : max;
1247
- }, 0);
1248
-
1249
- if (maxReplicaTime > 0) {
1250
- this.#timeDiffMsecs = maxReplicaTime - callTime;
1251
- this.#hasSyncedTime = true;
1252
- this.log.notify({
1253
- message: `Syncing time: offset of ${this.#timeDiffMsecs}`,
1254
- level: 'info',
1255
- });
1256
- }
1280
+ this.#setTimeDiffMsecs(callTime, replicaTimes);
1257
1281
  } catch (error) {
1258
1282
  const syncTimeError =
1259
1283
  error instanceof AgentError
@@ -1270,6 +1294,67 @@ export class HttpAgent implements Agent {
1270
1294
  });
1271
1295
  }
1272
1296
 
1297
+ /**
1298
+ * Allows agent to sync its time with the network.
1299
+ * @param {Principal} subnetId - Pass the subnet ID you need to sync the time with.
1300
+ */
1301
+ public async syncTimeWithSubnet(subnetId: Principal): Promise<void> {
1302
+ await this.#rootKeyGuard();
1303
+ const callTime = Date.now();
1304
+
1305
+ try {
1306
+ const anonymousAgent = HttpAgent.createSync({
1307
+ identity: new AnonymousIdentity(),
1308
+ host: this.host.toString(),
1309
+ fetch: this.#fetch,
1310
+ retryTimes: 0,
1311
+ rootKey: this.rootKey ?? undefined,
1312
+ shouldSyncTime: false,
1313
+ });
1314
+
1315
+ const replicaTimes = await Promise.all(
1316
+ Array(3)
1317
+ .fill(null)
1318
+ .map(async () => {
1319
+ const status = await subnetStatusRequest({
1320
+ subnetId,
1321
+ agent: anonymousAgent,
1322
+ paths: ['time'],
1323
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1324
+ });
1325
+
1326
+ const date = status.get('time');
1327
+ if (date instanceof Date) {
1328
+ return date.getTime();
1329
+ }
1330
+ }, []),
1331
+ );
1332
+
1333
+ this.#setTimeDiffMsecs(callTime, replicaTimes);
1334
+ } catch (error) {
1335
+ const syncTimeError =
1336
+ error instanceof AgentError ? error : UnknownError.fromCode(new UnexpectedErrorCode(error));
1337
+ this.log.error('Caught exception while attempting to sync time with subnet', syncTimeError);
1338
+
1339
+ throw syncTimeError;
1340
+ }
1341
+ }
1342
+
1343
+ #setTimeDiffMsecs(callTime: number, replicaTimes: Array<number | undefined>): void {
1344
+ const maxReplicaTime = replicaTimes.reduce<number>((max, current) => {
1345
+ return typeof current === 'number' && current > max ? current : max;
1346
+ }, 0);
1347
+
1348
+ if (maxReplicaTime > 0) {
1349
+ this.#timeDiffMsecs = maxReplicaTime - callTime;
1350
+ this.#hasSyncedTime = true;
1351
+ this.log.notify({
1352
+ message: `Syncing time: offset of ${this.#timeDiffMsecs}`,
1353
+ level: 'info',
1354
+ });
1355
+ }
1356
+ }
1357
+
1273
1358
  public async status(): Promise<JsonObject> {
1274
1359
  const headers: Record<string, string> = this.#credentials
1275
1360
  ? {
@@ -1338,22 +1423,50 @@ export class HttpAgent implements Agent {
1338
1423
  this.#identity = Promise.resolve(identity);
1339
1424
  }
1340
1425
 
1341
- public async fetchSubnetKeys(canisterId: Principal | string) {
1426
+ public async fetchSubnetKeys(canisterId: Principal | string): Promise<SubnetNodeKeys> {
1342
1427
  const effectiveCanisterId: Principal = Principal.from(canisterId);
1343
1428
  await this.#asyncGuard(effectiveCanisterId);
1344
- const response = await canisterStatusRequest({
1345
- canisterId: effectiveCanisterId,
1346
- paths: ['subnet'],
1429
+
1430
+ const rootKey = this.rootKey!;
1431
+
1432
+ const canisterReadState = await this.readState(effectiveCanisterId, {
1433
+ paths: [[utf8ToBytes('subnet')]],
1434
+ });
1435
+ const canisterCertificate = await Certificate.create({
1436
+ certificate: canisterReadState.certificate,
1437
+ rootKey,
1438
+ principal: { canisterId: effectiveCanisterId },
1439
+ agent: this,
1440
+ });
1441
+
1442
+ const subnetId = getSubnetIdFromCertificate(canisterCertificate.cert, rootKey);
1443
+ const nodeKeys = lookupNodeKeysFromCertificate(canisterCertificate.cert, subnetId);
1444
+ this.#subnetKeys.set(effectiveCanisterId.toText(), nodeKeys);
1445
+
1446
+ return nodeKeys;
1447
+ }
1448
+
1449
+ /**
1450
+ * Returns the subnet ID for a given canister ID, by looking at the certificate delegation
1451
+ * returned by the canister's state obtained by requesting the `/time` path with {@link HttpAgent.readState | readState}.
1452
+ * @param canisterId The canister ID to get the subnet ID for.
1453
+ * @returns The subnet ID for the given canister ID.
1454
+ */
1455
+ public async getSubnetIdFromCanister(canisterId: Principal | string): Promise<Principal> {
1456
+ const effectiveCanisterId = Principal.from(canisterId);
1457
+ await this.#asyncGuard(effectiveCanisterId);
1458
+
1459
+ const canisterReadState = await this.readState(effectiveCanisterId, {
1460
+ paths: [[utf8ToBytes('time')]],
1461
+ });
1462
+ const canisterCertificate = await Certificate.create({
1463
+ certificate: canisterReadState.certificate,
1464
+ rootKey: this.rootKey!,
1465
+ principal: { canisterId: effectiveCanisterId },
1347
1466
  agent: this,
1348
1467
  });
1349
1468
 
1350
- const subnetResponse = response.get('subnet');
1351
- if (subnetResponse && typeof subnetResponse === 'object' && 'nodeKeys' in subnetResponse) {
1352
- this.#subnetKeys.set(effectiveCanisterId.toText(), subnetResponse as SubnetStatus);
1353
- return subnetResponse as SubnetStatus;
1354
- }
1355
- // If the subnet status is not returned, return undefined
1356
- return undefined;
1469
+ return getSubnetIdFromCertificate(canisterCertificate.cert, this.rootKey!);
1357
1470
  }
1358
1471
 
1359
1472
  protected _transform(request: HttpAgentRequest): Promise<HttpAgentRequest> {
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * @experimental
3
- * @module canister-env/api
3
+ * @see https://js.icp.build/core/latest/canister-environment
4
+ * @module libs/agent/canister-env/api
4
5
  */
5
6
 
6
7
  import { hexToBytes } from '@noble/hashes/utils';