@icp-sdk/core 4.2.3 → 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 (474) hide show
  1. package/lib/cjs/agent/actor.d.ts +203 -0
  2. package/lib/cjs/agent/actor.d.ts.map +1 -0
  3. package/lib/cjs/agent/actor.js +341 -0
  4. package/lib/cjs/agent/actor.js.map +1 -0
  5. package/lib/cjs/agent/agent/api.d.ts +216 -0
  6. package/lib/cjs/agent/agent/api.d.ts.map +1 -0
  7. package/lib/cjs/agent/agent/api.js +39 -0
  8. package/lib/cjs/agent/agent/api.js.map +1 -0
  9. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.d.ts +37 -0
  10. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.d.ts.map +1 -0
  11. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.js +51 -0
  12. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.js.map +1 -0
  13. package/lib/cjs/agent/agent/http/index.d.ts +190 -0
  14. package/lib/cjs/agent/agent/http/index.d.ts.map +1 -0
  15. package/lib/cjs/agent/agent/http/index.js +1159 -0
  16. package/lib/cjs/agent/agent/http/index.js.map +1 -0
  17. package/lib/cjs/agent/agent/http/transforms.d.ts +54 -0
  18. package/lib/cjs/agent/agent/http/transforms.d.ts.map +1 -0
  19. package/lib/cjs/agent/agent/http/transforms.js +135 -0
  20. package/lib/cjs/agent/agent/http/transforms.js.map +1 -0
  21. package/lib/cjs/agent/agent/http/types.d.ts +81 -0
  22. package/lib/cjs/agent/agent/http/types.d.ts.map +1 -0
  23. package/lib/cjs/agent/agent/http/types.js +43 -0
  24. package/lib/cjs/agent/agent/http/types.js.map +1 -0
  25. package/lib/cjs/agent/agent/index.d.ts +3 -0
  26. package/lib/cjs/agent/agent/index.d.ts.map +1 -0
  27. package/lib/cjs/agent/agent/index.js +19 -0
  28. package/lib/cjs/agent/agent/index.js.map +1 -0
  29. package/lib/cjs/agent/auth.d.ts +91 -0
  30. package/lib/cjs/agent/auth.d.ts.map +1 -0
  31. package/lib/cjs/agent/auth.js +65 -0
  32. package/lib/cjs/agent/auth.js.map +1 -0
  33. package/lib/cjs/agent/canisterStatus/index.d.ts +61 -0
  34. package/lib/cjs/agent/canisterStatus/index.d.ts.map +1 -0
  35. package/lib/cjs/agent/canisterStatus/index.js +239 -0
  36. package/lib/cjs/agent/canisterStatus/index.js.map +1 -0
  37. package/lib/cjs/agent/cbor.d.ts +26 -0
  38. package/lib/cjs/agent/cbor.d.ts.map +1 -0
  39. package/lib/cjs/agent/cbor.js +93 -0
  40. package/lib/cjs/agent/cbor.js.map +1 -0
  41. package/lib/cjs/agent/certificate.d.ts +286 -0
  42. package/lib/cjs/agent/certificate.d.ts.map +1 -0
  43. package/lib/cjs/agent/certificate.js +762 -0
  44. package/lib/cjs/agent/certificate.js.map +1 -0
  45. package/lib/cjs/agent/constants.d.ts +18 -0
  46. package/lib/cjs/agent/constants.d.ts.map +1 -0
  47. package/lib/cjs/agent/constants.js +22 -0
  48. package/lib/cjs/agent/constants.js.map +1 -0
  49. package/lib/cjs/agent/der.d.ts +34 -0
  50. package/lib/cjs/agent/der.d.ts.map +1 -0
  51. package/lib/cjs/agent/der.js +175 -0
  52. package/lib/cjs/agent/der.js.map +1 -0
  53. package/lib/cjs/agent/errors.d.ts +386 -0
  54. package/lib/cjs/agent/errors.d.ts.map +1 -0
  55. package/lib/cjs/agent/errors.js +745 -0
  56. package/lib/cjs/agent/errors.js.map +1 -0
  57. package/lib/cjs/agent/fetch_candid.d.ts +9 -0
  58. package/lib/cjs/agent/fetch_candid.d.ts.map +1 -0
  59. package/lib/cjs/agent/fetch_candid.js +69 -0
  60. package/lib/cjs/agent/fetch_candid.js.map +1 -0
  61. package/lib/cjs/agent/index.d.ts +125 -1
  62. package/lib/cjs/agent/index.d.ts.map +1 -1
  63. package/lib/cjs/agent/index.js +142 -1
  64. package/lib/cjs/agent/index.js.map +1 -1
  65. package/lib/cjs/agent/observable.d.ts +24 -0
  66. package/lib/cjs/agent/observable.d.ts.map +1 -0
  67. package/lib/cjs/agent/observable.js +34 -0
  68. package/lib/cjs/agent/observable.js.map +1 -0
  69. package/lib/cjs/agent/polling/backoff.d.ts +50 -0
  70. package/lib/cjs/agent/polling/backoff.d.ts.map +1 -0
  71. package/lib/cjs/agent/polling/backoff.js +90 -0
  72. package/lib/cjs/agent/polling/backoff.js.map +1 -0
  73. package/lib/cjs/agent/polling/index.d.ts +63 -0
  74. package/lib/cjs/agent/polling/index.d.ts.map +1 -0
  75. package/lib/cjs/agent/polling/index.js +183 -0
  76. package/lib/cjs/agent/polling/index.js.map +1 -0
  77. package/lib/cjs/agent/polling/strategy.d.ts +52 -0
  78. package/lib/cjs/agent/polling/strategy.d.ts.map +1 -0
  79. package/lib/cjs/agent/polling/strategy.js +104 -0
  80. package/lib/cjs/agent/polling/strategy.js.map +1 -0
  81. package/lib/cjs/agent/public_key.d.ts +16 -0
  82. package/lib/cjs/agent/public_key.d.ts.map +1 -0
  83. package/lib/cjs/agent/public_key.js +52 -0
  84. package/lib/cjs/agent/public_key.js.map +1 -0
  85. package/lib/cjs/agent/request_id.d.ts +24 -0
  86. package/lib/cjs/agent/request_id.d.ts.map +1 -0
  87. package/lib/cjs/agent/request_id.js +88 -0
  88. package/lib/cjs/agent/request_id.js.map +1 -0
  89. package/lib/cjs/agent/subnetStatus/index.d.ts +70 -0
  90. package/lib/cjs/agent/subnetStatus/index.d.ts.map +1 -0
  91. package/lib/cjs/agent/subnetStatus/index.js +224 -0
  92. package/lib/cjs/agent/subnetStatus/index.js.map +1 -0
  93. package/lib/cjs/agent/utils/bls.d.ts +10 -0
  94. package/lib/cjs/agent/utils/bls.d.ts.map +1 -0
  95. package/lib/cjs/agent/utils/bls.js +20 -0
  96. package/lib/cjs/agent/utils/bls.js.map +1 -0
  97. package/lib/cjs/agent/utils/buffer.d.ts +22 -0
  98. package/lib/cjs/agent/utils/buffer.d.ts.map +1 -0
  99. package/lib/cjs/agent/utils/buffer.js +55 -0
  100. package/lib/cjs/agent/utils/buffer.js.map +1 -0
  101. package/lib/cjs/agent/utils/expirableMap.d.ts +80 -0
  102. package/lib/cjs/agent/utils/expirableMap.d.ts.map +1 -0
  103. package/lib/cjs/agent/utils/expirableMap.js +148 -0
  104. package/lib/cjs/agent/utils/expirableMap.js.map +1 -0
  105. package/lib/cjs/agent/utils/leb.d.ts +3 -0
  106. package/lib/cjs/agent/utils/leb.d.ts.map +1 -0
  107. package/lib/cjs/agent/utils/leb.js +17 -0
  108. package/lib/cjs/agent/utils/leb.js.map +1 -0
  109. package/lib/cjs/agent/utils/random.d.ts +6 -0
  110. package/lib/cjs/agent/utils/random.d.ts.map +1 -0
  111. package/lib/cjs/agent/utils/random.js +29 -0
  112. package/lib/cjs/agent/utils/random.js.map +1 -0
  113. package/lib/cjs/agent/utils/readState.d.ts +84 -0
  114. package/lib/cjs/agent/utils/readState.d.ts.map +1 -0
  115. package/lib/cjs/agent/utils/readState.js +149 -0
  116. package/lib/cjs/agent/utils/readState.js.map +1 -0
  117. package/lib/cjs/candid/candid-core.d.ts +72 -0
  118. package/lib/cjs/candid/candid-core.d.ts.map +1 -0
  119. package/lib/cjs/candid/candid-core.js +251 -0
  120. package/lib/cjs/candid/candid-core.js.map +1 -0
  121. package/lib/cjs/candid/candid-ui.d.ts +35 -0
  122. package/lib/cjs/candid/candid-ui.d.ts.map +1 -0
  123. package/lib/cjs/candid/candid-ui.js +317 -0
  124. package/lib/cjs/candid/candid-ui.js.map +1 -0
  125. package/lib/cjs/candid/idl.d.ts +579 -0
  126. package/lib/cjs/candid/idl.d.ts.map +1 -0
  127. package/lib/cjs/candid/idl.js +2228 -0
  128. package/lib/cjs/candid/idl.js.map +1 -0
  129. package/lib/cjs/candid/index.d.ts +30 -1
  130. package/lib/cjs/candid/index.d.ts.map +1 -1
  131. package/lib/cjs/candid/index.js +52 -1
  132. package/lib/cjs/candid/index.js.map +1 -1
  133. package/lib/cjs/candid/types.d.ts +6 -0
  134. package/lib/cjs/candid/types.d.ts.map +1 -0
  135. package/lib/cjs/candid/types.js +4 -0
  136. package/lib/cjs/candid/types.js.map +1 -0
  137. package/lib/cjs/candid/utils/bigint-math.d.ts +14 -0
  138. package/lib/cjs/candid/utils/bigint-math.d.ts.map +1 -0
  139. package/lib/cjs/candid/utils/bigint-math.js +30 -0
  140. package/lib/cjs/candid/utils/bigint-math.js.map +1 -0
  141. package/lib/cjs/candid/utils/buffer.d.ts +86 -0
  142. package/lib/cjs/candid/utils/buffer.d.ts.map +1 -0
  143. package/lib/cjs/candid/utils/buffer.js +191 -0
  144. package/lib/cjs/candid/utils/buffer.js.map +1 -0
  145. package/lib/cjs/candid/utils/hash.d.ts +7 -0
  146. package/lib/cjs/candid/utils/hash.d.ts.map +1 -0
  147. package/lib/cjs/candid/utils/hash.js +33 -0
  148. package/lib/cjs/candid/utils/hash.js.map +1 -0
  149. package/lib/cjs/candid/utils/leb128.d.ts +65 -0
  150. package/lib/cjs/candid/utils/leb128.d.ts.map +1 -0
  151. package/lib/cjs/candid/utils/leb128.js +228 -0
  152. package/lib/cjs/candid/utils/leb128.js.map +1 -0
  153. package/lib/cjs/identity/identity/delegation.d.ts +164 -0
  154. package/lib/cjs/identity/identity/delegation.d.ts.map +1 -0
  155. package/lib/cjs/identity/identity/delegation.js +302 -0
  156. package/lib/cjs/identity/identity/delegation.js.map +1 -0
  157. package/lib/cjs/identity/identity/ecdsa.d.ts +62 -0
  158. package/lib/cjs/identity/identity/ecdsa.d.ts.map +1 -0
  159. package/lib/cjs/identity/identity/ecdsa.js +117 -0
  160. package/lib/cjs/identity/identity/ecdsa.js.map +1 -0
  161. package/lib/cjs/identity/identity/ed25519.d.ts +67 -0
  162. package/lib/cjs/identity/identity/ed25519.d.ts.map +1 -0
  163. package/lib/cjs/identity/identity/ed25519.js +200 -0
  164. package/lib/cjs/identity/identity/ed25519.js.map +1 -0
  165. package/lib/cjs/identity/identity/partial.d.ts +34 -0
  166. package/lib/cjs/identity/identity/partial.d.ts.map +1 -0
  167. package/lib/cjs/identity/identity/partial.js +54 -0
  168. package/lib/cjs/identity/identity/partial.js.map +1 -0
  169. package/lib/cjs/identity/identity/webauthn.d.ts +51 -0
  170. package/lib/cjs/identity/identity/webauthn.d.ts.map +1 -0
  171. package/lib/cjs/identity/identity/webauthn.js +197 -0
  172. package/lib/cjs/identity/identity/webauthn.js.map +1 -0
  173. package/lib/cjs/identity/index.d.ts +38 -1
  174. package/lib/cjs/identity/index.d.ts.map +1 -1
  175. package/lib/cjs/identity/index.js +44 -1
  176. package/lib/cjs/identity/index.js.map +1 -1
  177. package/lib/cjs/identity/secp256k1/der.d.ts +33 -0
  178. package/lib/cjs/identity/secp256k1/der.d.ts.map +1 -0
  179. package/lib/cjs/identity/secp256k1/der.js +165 -0
  180. package/lib/cjs/identity/secp256k1/der.js.map +1 -0
  181. package/lib/cjs/identity/secp256k1/index.d.ts +51 -1
  182. package/lib/cjs/identity/secp256k1/index.d.ts.map +1 -1
  183. package/lib/cjs/identity/secp256k1/index.js +51 -1
  184. package/lib/cjs/identity/secp256k1/index.js.map +1 -1
  185. package/lib/cjs/identity/secp256k1/pem.d.ts +7 -0
  186. package/lib/cjs/identity/secp256k1/pem.d.ts.map +1 -0
  187. package/lib/cjs/identity/secp256k1/pem.js +75 -0
  188. package/lib/cjs/identity/secp256k1/pem.js.map +1 -0
  189. package/lib/cjs/identity/secp256k1/secp256k1.d.ts +87 -0
  190. package/lib/cjs/identity/secp256k1/secp256k1.d.ts.map +1 -0
  191. package/lib/cjs/identity/secp256k1/secp256k1.js +260 -0
  192. package/lib/cjs/identity/secp256k1/secp256k1.js.map +1 -0
  193. package/lib/cjs/principal/index.d.ts +18 -1
  194. package/lib/cjs/principal/index.d.ts.map +1 -1
  195. package/lib/cjs/principal/index.js +22 -1
  196. package/lib/cjs/principal/index.js.map +1 -1
  197. package/lib/cjs/principal/principal.d.ts +50 -0
  198. package/lib/cjs/principal/principal.d.ts.map +1 -0
  199. package/lib/cjs/principal/principal.js +148 -0
  200. package/lib/cjs/principal/principal.js.map +1 -0
  201. package/lib/cjs/principal/utils/base32.d.ts +10 -0
  202. package/lib/cjs/principal/utils/base32.d.ts.map +1 -0
  203. package/lib/cjs/principal/utils/base32.js +90 -0
  204. package/lib/cjs/principal/utils/base32.js.map +1 -0
  205. package/lib/cjs/principal/utils/getCrc.d.ts +6 -0
  206. package/lib/cjs/principal/utils/getCrc.d.ts.map +1 -0
  207. package/lib/cjs/principal/utils/getCrc.js +53 -0
  208. package/lib/cjs/principal/utils/getCrc.js.map +1 -0
  209. package/lib/esm/agent/actor.d.ts +203 -0
  210. package/lib/esm/agent/actor.d.ts.map +1 -0
  211. package/lib/esm/agent/actor.js +337 -0
  212. package/lib/esm/agent/actor.js.map +1 -0
  213. package/lib/esm/agent/agent/api.d.ts +216 -0
  214. package/lib/esm/agent/agent/api.d.ts.map +1 -0
  215. package/lib/esm/agent/agent/api.js +34 -0
  216. package/lib/esm/agent/agent/api.js.map +1 -0
  217. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.d.ts +37 -0
  218. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.d.ts.map +1 -0
  219. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.js +48 -0
  220. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.js.map +1 -0
  221. package/lib/esm/agent/agent/http/index.d.ts +190 -0
  222. package/lib/esm/agent/agent/http/index.d.ts.map +1 -0
  223. package/lib/esm/agent/agent/http/index.js +1117 -0
  224. package/lib/esm/agent/agent/http/index.js.map +1 -0
  225. package/lib/esm/agent/agent/http/transforms.d.ts +54 -0
  226. package/lib/esm/agent/agent/http/transforms.d.ts.map +1 -0
  227. package/lib/esm/agent/agent/http/transforms.js +128 -0
  228. package/lib/esm/agent/agent/http/transforms.js.map +1 -0
  229. package/lib/esm/agent/agent/http/types.d.ts +81 -0
  230. package/lib/esm/agent/agent/http/types.d.ts.map +1 -0
  231. package/lib/esm/agent/agent/http/types.js +39 -0
  232. package/lib/esm/agent/agent/http/types.js.map +1 -0
  233. package/lib/esm/agent/agent/index.d.ts +3 -0
  234. package/lib/esm/agent/agent/index.d.ts.map +1 -0
  235. package/lib/esm/agent/agent/index.js +3 -0
  236. package/lib/esm/agent/agent/index.js.map +1 -0
  237. package/lib/esm/agent/auth.d.ts +91 -0
  238. package/lib/esm/agent/auth.d.ts.map +1 -0
  239. package/lib/esm/agent/auth.js +59 -0
  240. package/lib/esm/agent/auth.js.map +1 -0
  241. package/lib/esm/agent/canister-env/index.d.ts +111 -1
  242. package/lib/esm/agent/canister-env/index.d.ts.map +1 -1
  243. package/lib/esm/agent/canister-env/index.js +111 -1
  244. package/lib/esm/agent/canister-env/index.js.map +1 -1
  245. package/lib/esm/agent/canisterStatus/index.d.ts +61 -0
  246. package/lib/esm/agent/canisterStatus/index.d.ts.map +1 -0
  247. package/lib/esm/agent/canisterStatus/index.js +199 -0
  248. package/lib/esm/agent/canisterStatus/index.js.map +1 -0
  249. package/lib/esm/agent/cbor.d.ts +26 -0
  250. package/lib/esm/agent/cbor.d.ts.map +1 -0
  251. package/lib/esm/agent/cbor.js +54 -0
  252. package/lib/esm/agent/cbor.js.map +1 -0
  253. package/lib/esm/agent/certificate.d.ts +286 -0
  254. package/lib/esm/agent/certificate.d.ts.map +1 -0
  255. package/lib/esm/agent/certificate.js +712 -0
  256. package/lib/esm/agent/certificate.js.map +1 -0
  257. package/lib/esm/agent/constants.d.ts +18 -0
  258. package/lib/esm/agent/constants.d.ts.map +1 -0
  259. package/lib/esm/agent/constants.js +19 -0
  260. package/lib/esm/agent/constants.js.map +1 -0
  261. package/lib/esm/agent/der.d.ts +34 -0
  262. package/lib/esm/agent/der.d.ts.map +1 -0
  263. package/lib/esm/agent/der.js +166 -0
  264. package/lib/esm/agent/der.js.map +1 -0
  265. package/lib/esm/agent/errors.d.ts +386 -0
  266. package/lib/esm/agent/errors.d.ts.map +1 -0
  267. package/lib/esm/agent/errors.js +689 -0
  268. package/lib/esm/agent/errors.js.map +1 -0
  269. package/lib/esm/agent/fetch_candid.d.ts +9 -0
  270. package/lib/esm/agent/fetch_candid.d.ts.map +1 -0
  271. package/lib/esm/agent/fetch_candid.js +33 -0
  272. package/lib/esm/agent/fetch_candid.js.map +1 -0
  273. package/lib/esm/agent/index.d.ts +125 -1
  274. package/lib/esm/agent/index.d.ts.map +1 -1
  275. package/lib/esm/agent/index.js +125 -1
  276. package/lib/esm/agent/index.js.map +1 -1
  277. package/lib/esm/agent/observable.d.ts +24 -0
  278. package/lib/esm/agent/observable.d.ts.map +1 -0
  279. package/lib/esm/agent/observable.js +29 -0
  280. package/lib/esm/agent/observable.js.map +1 -0
  281. package/lib/esm/agent/polling/backoff.d.ts +50 -0
  282. package/lib/esm/agent/polling/backoff.d.ts.map +1 -0
  283. package/lib/esm/agent/polling/backoff.js +85 -0
  284. package/lib/esm/agent/polling/backoff.js.map +1 -0
  285. package/lib/esm/agent/polling/index.d.ts +63 -0
  286. package/lib/esm/agent/polling/index.d.ts.map +1 -0
  287. package/lib/esm/agent/polling/index.js +144 -0
  288. package/lib/esm/agent/polling/index.js.map +1 -0
  289. package/lib/esm/agent/polling/strategy.d.ts +52 -0
  290. package/lib/esm/agent/polling/strategy.d.ts.map +1 -0
  291. package/lib/esm/agent/polling/strategy.js +94 -0
  292. package/lib/esm/agent/polling/strategy.js.map +1 -0
  293. package/lib/esm/agent/public_key.d.ts +16 -0
  294. package/lib/esm/agent/public_key.d.ts.map +1 -0
  295. package/lib/esm/agent/public_key.js +48 -0
  296. package/lib/esm/agent/public_key.js.map +1 -0
  297. package/lib/esm/agent/request_id.d.ts +24 -0
  298. package/lib/esm/agent/request_id.d.ts.map +1 -0
  299. package/lib/esm/agent/request_id.js +83 -0
  300. package/lib/esm/agent/request_id.js.map +1 -0
  301. package/lib/esm/agent/subnetStatus/index.d.ts +70 -0
  302. package/lib/esm/agent/subnetStatus/index.d.ts.map +1 -0
  303. package/lib/esm/agent/subnetStatus/index.js +183 -0
  304. package/lib/esm/agent/subnetStatus/index.js.map +1 -0
  305. package/lib/esm/agent/utils/bls.d.ts +10 -0
  306. package/lib/esm/agent/utils/bls.d.ts.map +1 -0
  307. package/lib/esm/agent/utils/bls.js +17 -0
  308. package/lib/esm/agent/utils/bls.js.map +1 -0
  309. package/lib/esm/agent/utils/buffer.d.ts +22 -0
  310. package/lib/esm/agent/utils/buffer.d.ts.map +1 -0
  311. package/lib/esm/agent/utils/buffer.js +50 -0
  312. package/lib/esm/agent/utils/buffer.js.map +1 -0
  313. package/lib/esm/agent/utils/expirableMap.d.ts +80 -0
  314. package/lib/esm/agent/utils/expirableMap.d.ts.map +1 -0
  315. package/lib/esm/agent/utils/expirableMap.js +144 -0
  316. package/lib/esm/agent/utils/expirableMap.js.map +1 -0
  317. package/lib/esm/agent/utils/leb.d.ts +3 -0
  318. package/lib/esm/agent/utils/leb.d.ts.map +1 -0
  319. package/lib/esm/agent/utils/leb.js +12 -0
  320. package/lib/esm/agent/utils/leb.js.map +1 -0
  321. package/lib/esm/agent/utils/random.d.ts +6 -0
  322. package/lib/esm/agent/utils/random.d.ts.map +1 -0
  323. package/lib/esm/agent/utils/random.js +25 -0
  324. package/lib/esm/agent/utils/random.js.map +1 -0
  325. package/lib/esm/agent/utils/readState.d.ts +84 -0
  326. package/lib/esm/agent/utils/readState.d.ts.map +1 -0
  327. package/lib/esm/agent/utils/readState.js +107 -0
  328. package/lib/esm/agent/utils/readState.js.map +1 -0
  329. package/lib/esm/candid/candid-core.d.ts +72 -0
  330. package/lib/esm/candid/candid-core.d.ts.map +1 -0
  331. package/lib/esm/candid/candid-core.js +241 -0
  332. package/lib/esm/candid/candid-core.js.map +1 -0
  333. package/lib/esm/candid/candid-ui.d.ts +35 -0
  334. package/lib/esm/candid/candid-ui.d.ts.map +1 -0
  335. package/lib/esm/candid/candid-ui.js +272 -0
  336. package/lib/esm/candid/candid-ui.js.map +1 -0
  337. package/lib/esm/candid/idl.d.ts +579 -0
  338. package/lib/esm/candid/idl.d.ts.map +1 -0
  339. package/lib/esm/candid/idl.js +2189 -0
  340. package/lib/esm/candid/idl.js.map +1 -0
  341. package/lib/esm/candid/index.d.ts +30 -1
  342. package/lib/esm/candid/index.d.ts.map +1 -1
  343. package/lib/esm/candid/index.js +29 -1
  344. package/lib/esm/candid/index.js.map +1 -1
  345. package/lib/esm/candid/types.d.ts +6 -0
  346. package/lib/esm/candid/types.d.ts.map +1 -0
  347. package/lib/esm/candid/types.js +3 -0
  348. package/lib/esm/candid/types.js.map +1 -0
  349. package/lib/esm/candid/utils/bigint-math.d.ts +14 -0
  350. package/lib/esm/candid/utils/bigint-math.d.ts.map +1 -0
  351. package/lib/esm/candid/utils/bigint-math.js +26 -0
  352. package/lib/esm/candid/utils/bigint-math.js.map +1 -0
  353. package/lib/esm/candid/utils/buffer.d.ts +86 -0
  354. package/lib/esm/candid/utils/buffer.d.ts.map +1 -0
  355. package/lib/esm/candid/utils/buffer.js +182 -0
  356. package/lib/esm/candid/utils/buffer.js.map +1 -0
  357. package/lib/esm/candid/utils/hash.d.ts +7 -0
  358. package/lib/esm/candid/utils/hash.d.ts.map +1 -0
  359. package/lib/esm/candid/utils/hash.js +30 -0
  360. package/lib/esm/candid/utils/hash.js.map +1 -0
  361. package/lib/esm/candid/utils/leb128.d.ts +65 -0
  362. package/lib/esm/candid/utils/leb128.d.ts.map +1 -0
  363. package/lib/esm/candid/utils/leb128.js +216 -0
  364. package/lib/esm/candid/utils/leb128.js.map +1 -0
  365. package/lib/esm/identity/identity/delegation.d.ts +164 -0
  366. package/lib/esm/identity/identity/delegation.d.ts.map +1 -0
  367. package/lib/esm/identity/identity/delegation.js +294 -0
  368. package/lib/esm/identity/identity/delegation.js.map +1 -0
  369. package/lib/esm/identity/identity/ecdsa.d.ts +62 -0
  370. package/lib/esm/identity/identity/ecdsa.d.ts.map +1 -0
  371. package/lib/esm/identity/identity/ecdsa.js +112 -0
  372. package/lib/esm/identity/identity/ecdsa.js.map +1 -0
  373. package/lib/esm/identity/identity/ed25519.d.ts +67 -0
  374. package/lib/esm/identity/identity/ed25519.d.ts.map +1 -0
  375. package/lib/esm/identity/identity/ed25519.js +195 -0
  376. package/lib/esm/identity/identity/ed25519.js.map +1 -0
  377. package/lib/esm/identity/identity/partial.d.ts +34 -0
  378. package/lib/esm/identity/identity/partial.d.ts.map +1 -0
  379. package/lib/esm/identity/identity/partial.js +50 -0
  380. package/lib/esm/identity/identity/partial.js.map +1 -0
  381. package/lib/esm/identity/identity/webauthn.d.ts +51 -0
  382. package/lib/esm/identity/identity/webauthn.d.ts.map +1 -0
  383. package/lib/esm/identity/identity/webauthn.js +192 -0
  384. package/lib/esm/identity/identity/webauthn.js.map +1 -0
  385. package/lib/esm/identity/index.d.ts +38 -1
  386. package/lib/esm/identity/index.d.ts.map +1 -1
  387. package/lib/esm/identity/index.js +38 -1
  388. package/lib/esm/identity/index.js.map +1 -1
  389. package/lib/esm/identity/secp256k1/der.d.ts +33 -0
  390. package/lib/esm/identity/secp256k1/der.d.ts.map +1 -0
  391. package/lib/esm/identity/secp256k1/der.js +156 -0
  392. package/lib/esm/identity/secp256k1/der.js.map +1 -0
  393. package/lib/esm/identity/secp256k1/index.d.ts +51 -1
  394. package/lib/esm/identity/secp256k1/index.d.ts.map +1 -1
  395. package/lib/esm/identity/secp256k1/index.js +51 -1
  396. package/lib/esm/identity/secp256k1/index.js.map +1 -1
  397. package/lib/esm/identity/secp256k1/pem.d.ts +7 -0
  398. package/lib/esm/identity/secp256k1/pem.d.ts.map +1 -0
  399. package/lib/esm/identity/secp256k1/pem.js +39 -0
  400. package/lib/esm/identity/secp256k1/pem.js.map +1 -0
  401. package/lib/esm/identity/secp256k1/secp256k1.d.ts +87 -0
  402. package/lib/esm/identity/secp256k1/secp256k1.d.ts.map +1 -0
  403. package/lib/esm/identity/secp256k1/secp256k1.js +222 -0
  404. package/lib/esm/identity/secp256k1/secp256k1.js.map +1 -0
  405. package/lib/esm/principal/index.d.ts +18 -1
  406. package/lib/esm/principal/index.d.ts.map +1 -1
  407. package/lib/esm/principal/index.js +18 -1
  408. package/lib/esm/principal/index.js.map +1 -1
  409. package/lib/esm/principal/principal.d.ts +50 -0
  410. package/lib/esm/principal/principal.d.ts.map +1 -0
  411. package/lib/esm/principal/principal.js +144 -0
  412. package/lib/esm/principal/principal.js.map +1 -0
  413. package/lib/esm/principal/utils/base32.d.ts +10 -0
  414. package/lib/esm/principal/utils/base32.d.ts.map +1 -0
  415. package/lib/esm/principal/utils/base32.js +86 -0
  416. package/lib/esm/principal/utils/base32.js.map +1 -0
  417. package/lib/esm/principal/utils/getCrc.d.ts +6 -0
  418. package/lib/esm/principal/utils/getCrc.d.ts.map +1 -0
  419. package/lib/esm/principal/utils/getCrc.js +50 -0
  420. package/lib/esm/principal/utils/getCrc.js.map +1 -0
  421. package/package.json +17 -11
  422. package/src/agent/actor.ts +576 -0
  423. package/src/agent/agent/api.ts +262 -0
  424. package/src/agent/agent/http/index.ts +1518 -0
  425. package/src/agent/agent/http/transforms.ts +158 -0
  426. package/src/agent/agent/http/types.ts +126 -0
  427. package/src/agent/agent/index.ts +2 -0
  428. package/src/agent/auth.ts +147 -0
  429. package/src/agent/canister-env/index.ts +192 -1
  430. package/src/agent/canisterStatus/index.ts +267 -0
  431. package/src/agent/cbor.ts +63 -0
  432. package/src/agent/certificate.ts +1060 -0
  433. package/src/agent/constants.ts +24 -0
  434. package/src/agent/der.ts +170 -0
  435. package/src/agent/errors.ts +881 -0
  436. package/src/agent/fetch_candid.ts +37 -0
  437. package/src/agent/index.ts +131 -1
  438. package/src/agent/observable.ts +49 -0
  439. package/src/agent/polling/backoff.ts +130 -0
  440. package/src/agent/polling/index.ts +250 -0
  441. package/src/agent/polling/strategy.ts +144 -0
  442. package/src/agent/public_key.ts +65 -0
  443. package/src/agent/request_id.ts +92 -0
  444. package/src/agent/subnetStatus/index.ts +270 -0
  445. package/src/agent/utils/bls.ts +18 -0
  446. package/src/agent/utils/buffer.ts +60 -0
  447. package/src/agent/utils/expirableMap.ts +163 -0
  448. package/src/agent/utils/leb.ts +14 -0
  449. package/src/agent/utils/random.ts +30 -0
  450. package/src/agent/utils/readState.ts +180 -0
  451. package/src/candid/candid-core.ts +276 -0
  452. package/src/candid/candid-ui.ts +289 -0
  453. package/src/candid/idl.ts +2556 -0
  454. package/src/candid/index.ts +35 -1
  455. package/src/candid/types.ts +7 -0
  456. package/src/candid/utils/bigint-math.ts +26 -0
  457. package/src/candid/utils/buffer.ts +221 -0
  458. package/src/candid/utils/hash.ts +31 -0
  459. package/src/candid/utils/leb128.ts +234 -0
  460. package/src/identity/identity/delegation.ts +411 -0
  461. package/src/identity/identity/ecdsa.ts +158 -0
  462. package/src/identity/identity/ed25519.ts +239 -0
  463. package/src/identity/identity/partial.ts +60 -0
  464. package/src/identity/identity/webauthn.ts +265 -0
  465. package/src/identity/index.ts +39 -1
  466. package/src/identity/secp256k1/der.ts +156 -0
  467. package/src/identity/secp256k1/index.ts +52 -1
  468. package/src/identity/secp256k1/pem.ts +40 -0
  469. package/src/identity/secp256k1/secp256k1.ts +270 -0
  470. package/src/package.json +4 -0
  471. package/src/principal/index.ts +19 -1
  472. package/src/principal/principal.ts +171 -0
  473. package/src/principal/utils/base32.ts +101 -0
  474. package/src/principal/utils/getCrc.ts +52 -0
@@ -0,0 +1,1117 @@
1
+ import { Principal } from '../../../principal/index.js';
2
+ import { HashTreeDecodeErrorCode, CreateHttpAgentErrorCode, ExternalError, HttpDefaultFetchErrorCode, IdentityInvalidErrorCode, IngressExpiryInvalidErrorCode, InputError, LookupErrorCode, MalformedPublicKeyErrorCode, MalformedSignatureErrorCode, MissingRootKeyErrorCode, MissingSignatureErrorCode, ProtocolError, QuerySignatureVerificationFailedErrorCode, TimeoutWaitingForResponseErrorCode, TrustError, UnexpectedErrorCode, UnknownError, HttpErrorCode, HttpV4ApiNotSupportedErrorCode, TransportError, HttpFetchErrorCode, AgentError, MalformedLookupFoundValueErrorCode, CertificateOutdatedErrorCode, } from "../../errors.js";
3
+ import { AnonymousIdentity } from "../../auth.js";
4
+ import * as cbor from "../../cbor.js";
5
+ import { hashOfMap, requestIdOf } from "../../request_id.js";
6
+ import { QueryResponseStatus, } from "../api.js";
7
+ import { Expiry, httpHeadersTransform, makeNonceTransform } from "./transforms.js";
8
+ import { Endpoint, makeNonce, ReadRequestType, SubmitRequestType, } from "./types.js";
9
+ import { request as canisterStatusRequest } from "../../canisterStatus/index.js";
10
+ import { request as subnetStatusRequest } from "../../subnetStatus/index.js";
11
+ import { lookupNodeKeysFromCertificate } from "../../utils/readState.js";
12
+ import { Certificate, getSubnetIdFromCertificate, lookup_path, LookupPathStatus, } from "../../certificate.js";
13
+ import { ed25519 } from '@noble/curves/ed25519';
14
+ import { ExpirableMap } from "../../utils/expirableMap.js";
15
+ import { Ed25519PublicKey } from "../../public_key.js";
16
+ import { ObservableLog } from "../../observable.js";
17
+ import { ExponentialBackoff, } from "../../polling/backoff.js";
18
+ import { decodeTime } from "../../utils/leb.js";
19
+ import { concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';
20
+ import { uint8Equals, uint8FromBufLike } from "../../utils/buffer.js";
21
+ import { IC_RESPONSE_DOMAIN_SEPARATOR } from "../../constants.js";
22
+ export * from "./transforms.js";
23
+ export { makeNonce } from "./types.js";
24
+ export var RequestStatusResponseStatus;
25
+ (function (RequestStatusResponseStatus) {
26
+ RequestStatusResponseStatus["Received"] = "received";
27
+ RequestStatusResponseStatus["Processing"] = "processing";
28
+ RequestStatusResponseStatus["Replied"] = "replied";
29
+ RequestStatusResponseStatus["Rejected"] = "rejected";
30
+ RequestStatusResponseStatus["Unknown"] = "unknown";
31
+ RequestStatusResponseStatus["Done"] = "done";
32
+ })(RequestStatusResponseStatus || (RequestStatusResponseStatus = {}));
33
+ const MINUTE_TO_MSECS = 60 * 1_000;
34
+ const MSECS_TO_NANOSECONDS = 1_000_000;
35
+ const DEFAULT_TIME_DIFF_MSECS = 0;
36
+ // Root public key for the IC, encoded as hex
37
+ export const IC_ROOT_KEY = '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +
38
+ 'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +
39
+ '5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +
40
+ 'b01291091c5f87b98883463f98091a0baaae';
41
+ export const MANAGEMENT_CANISTER_ID = 'aaaaa-aa';
42
+ // IC0 domain info
43
+ const IC0_DOMAIN = 'ic0.app';
44
+ const IC0_SUB_DOMAIN = '.ic0.app';
45
+ const ICP0_DOMAIN = 'icp0.io';
46
+ const ICP0_SUB_DOMAIN = '.icp0.io';
47
+ const ICP_API_DOMAIN = 'icp-api.io';
48
+ const ICP_API_SUB_DOMAIN = '.icp-api.io';
49
+ const HTTP_STATUS_OK = 200;
50
+ const HTTP_STATUS_ACCEPTED = 202;
51
+ const HTTP_STATUS_NOT_FOUND = 404;
52
+ function getDefaultFetch() {
53
+ let defaultFetch;
54
+ if (typeof window !== 'undefined') {
55
+ // Browser context
56
+ if (window.fetch) {
57
+ defaultFetch = window.fetch.bind(window);
58
+ }
59
+ else {
60
+ throw ExternalError.fromCode(new HttpDefaultFetchErrorCode('Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.'));
61
+ }
62
+ }
63
+ else if (typeof global !== 'undefined') {
64
+ // Node context
65
+ if (global.fetch) {
66
+ defaultFetch = global.fetch.bind(global);
67
+ }
68
+ else {
69
+ throw ExternalError.fromCode(new HttpDefaultFetchErrorCode('Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.'));
70
+ }
71
+ }
72
+ else if (typeof self !== 'undefined') {
73
+ if (self.fetch) {
74
+ defaultFetch = self.fetch.bind(self);
75
+ }
76
+ }
77
+ if (defaultFetch) {
78
+ return defaultFetch;
79
+ }
80
+ throw ExternalError.fromCode(new HttpDefaultFetchErrorCode('Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.'));
81
+ }
82
+ function determineHost(configuredHost) {
83
+ let host;
84
+ if (configuredHost !== undefined) {
85
+ if (!configuredHost.match(/^[a-z]+:/) && typeof window !== 'undefined') {
86
+ host = new URL(window.location.protocol + '//' + configuredHost);
87
+ }
88
+ else {
89
+ host = new URL(configuredHost);
90
+ }
91
+ }
92
+ else {
93
+ // Mainnet, local, and remote environments will have the api route available
94
+ const knownHosts = ['ic0.app', 'icp0.io', '127.0.0.1', 'localhost'];
95
+ const remoteHosts = ['.github.dev', '.gitpod.io'];
96
+ const location = typeof window !== 'undefined' ? window.location : undefined;
97
+ const hostname = location?.hostname;
98
+ let knownHost;
99
+ if (hostname && typeof hostname === 'string') {
100
+ if (remoteHosts.some(host => hostname.endsWith(host))) {
101
+ knownHost = hostname;
102
+ }
103
+ else {
104
+ knownHost = knownHosts.find(host => hostname.endsWith(host));
105
+ }
106
+ }
107
+ if (location && knownHost) {
108
+ // If the user is on a boundary-node provided host, we can use the same host for the agent
109
+ host = new URL(`${location.protocol}//${knownHost}${location.port ? ':' + location.port : ''}`);
110
+ }
111
+ else {
112
+ host = new URL('https://icp-api.io');
113
+ }
114
+ }
115
+ return host.toString();
116
+ }
117
+ /**
118
+ * A HTTP agent allows users to interact with a client of the internet computer
119
+ using the available methods. It exposes an API that closely follows the
120
+ public view of the internet computer, and is not intended to be exposed
121
+ directly to the majority of users due to its low-level interface.
122
+ * There is a pipeline to apply transformations to the request before sending
123
+ it to the client. This is to decouple signature, nonce generation and
124
+ other computations so that this class can stay as simple as possible while
125
+ allowing extensions.
126
+ */
127
+ export class HttpAgent {
128
+ #rootKeyPromise;
129
+ #shouldFetchRootKey;
130
+ #timeDiffMsecs;
131
+ #hasSyncedTime;
132
+ #syncTimePromise;
133
+ #shouldSyncTime;
134
+ #identity;
135
+ #fetch;
136
+ #fetchOptions;
137
+ #callOptions;
138
+ #credentials;
139
+ #retryTimes; // Retry requests N times before erroring by default
140
+ #backoffStrategy;
141
+ #maxIngressExpiryInMinutes;
142
+ get #maxIngressExpiryInMs() {
143
+ return this.#maxIngressExpiryInMinutes * MINUTE_TO_MSECS;
144
+ }
145
+ #queryPipeline;
146
+ #updatePipeline;
147
+ #subnetKeys;
148
+ #verifyQuerySignatures;
149
+ /**
150
+ * @param options - Options for the HttpAgent
151
+ * @deprecated Use `HttpAgent.create` or `HttpAgent.createSync` instead
152
+ */
153
+ constructor(options = {}) {
154
+ this.#rootKeyPromise = null;
155
+ this.#shouldFetchRootKey = false;
156
+ this.#timeDiffMsecs = DEFAULT_TIME_DIFF_MSECS;
157
+ this.#hasSyncedTime = false;
158
+ this.#syncTimePromise = null;
159
+ this.#shouldSyncTime = false;
160
+ // Public signature to help with type checking.
161
+ this._isAgent = true;
162
+ this.config = {};
163
+ this.log = new ObservableLog();
164
+ this.#queryPipeline = [];
165
+ this.#updatePipeline = [];
166
+ this.#subnetKeys = new ExpirableMap({
167
+ expirationTime: 5 * MINUTE_TO_MSECS,
168
+ });
169
+ this.#verifyQuerySignatures = true;
170
+ /**
171
+ * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation
172
+ * @param queryResponse - The response from the query
173
+ * @param subnetNodeKeys - The subnet node keys
174
+ * @returns ApiQueryResponse
175
+ */
176
+ this.#verifyQueryResponse = (queryResponse, subnetNodeKeys) => {
177
+ if (this.#verifyQuerySignatures === false) {
178
+ // This should not be called if the user has disabled verification
179
+ return queryResponse;
180
+ }
181
+ const { status, signatures = [], requestId } = queryResponse;
182
+ for (const sig of signatures) {
183
+ const { timestamp, identity } = sig;
184
+ const nodeId = Principal.fromUint8Array(identity).toText();
185
+ // Hash is constructed differently depending on the status
186
+ let hash;
187
+ if (status === QueryResponseStatus.Replied) {
188
+ const { reply } = queryResponse;
189
+ hash = hashOfMap({
190
+ status: status,
191
+ reply: reply,
192
+ timestamp: BigInt(timestamp),
193
+ request_id: requestId,
194
+ });
195
+ }
196
+ else if (status === QueryResponseStatus.Rejected) {
197
+ const { reject_code, reject_message, error_code } = queryResponse;
198
+ hash = hashOfMap({
199
+ status: status,
200
+ reject_code: reject_code,
201
+ reject_message: reject_message,
202
+ error_code: error_code,
203
+ timestamp: BigInt(timestamp),
204
+ request_id: requestId,
205
+ });
206
+ }
207
+ else {
208
+ throw UnknownError.fromCode(new UnexpectedErrorCode(`Unknown status: ${status}`));
209
+ }
210
+ const separatorWithHash = concatBytes(IC_RESPONSE_DOMAIN_SEPARATOR, hash);
211
+ // FIX: check for match without verifying N times
212
+ const pubKey = subnetNodeKeys.get(nodeId);
213
+ if (!pubKey) {
214
+ throw ProtocolError.fromCode(new MalformedPublicKeyErrorCode());
215
+ }
216
+ const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;
217
+ const valid = ed25519.verify(sig.signature, separatorWithHash, rawKey);
218
+ if (valid)
219
+ return queryResponse;
220
+ throw TrustError.fromCode(new QuerySignatureVerificationFailedErrorCode(nodeId));
221
+ }
222
+ return queryResponse;
223
+ };
224
+ this.config = options;
225
+ this.#fetch = options.fetch || getDefaultFetch() || fetch.bind(global);
226
+ this.#fetchOptions = options.fetchOptions;
227
+ this.#callOptions = options.callOptions;
228
+ this.#shouldFetchRootKey = options.shouldFetchRootKey ?? false;
229
+ this.#shouldSyncTime = options.shouldSyncTime ?? false;
230
+ // Use provided root key, otherwise fall back to IC_ROOT_KEY for mainnet or null if the key needs to be fetched
231
+ if (options.rootKey) {
232
+ this.rootKey = options.rootKey;
233
+ }
234
+ else if (this.#shouldFetchRootKey) {
235
+ this.rootKey = null;
236
+ }
237
+ else {
238
+ this.rootKey = hexToBytes(IC_ROOT_KEY);
239
+ }
240
+ const host = determineHost(options.host);
241
+ this.host = new URL(host);
242
+ if (options.verifyQuerySignatures !== undefined) {
243
+ this.#verifyQuerySignatures = options.verifyQuerySignatures;
244
+ }
245
+ // Default is 3
246
+ this.#retryTimes = options.retryTimes ?? 3;
247
+ // Delay strategy for retries. Default is exponential backoff
248
+ const defaultBackoffFactory = () => new ExponentialBackoff({
249
+ maxIterations: this.#retryTimes,
250
+ });
251
+ this.#backoffStrategy = options.backoffStrategy || defaultBackoffFactory;
252
+ // Rewrite to avoid redirects
253
+ if (this.host.hostname.endsWith(IC0_SUB_DOMAIN)) {
254
+ this.host.hostname = IC0_DOMAIN;
255
+ }
256
+ else if (this.host.hostname.endsWith(ICP0_SUB_DOMAIN)) {
257
+ this.host.hostname = ICP0_DOMAIN;
258
+ }
259
+ else if (this.host.hostname.endsWith(ICP_API_SUB_DOMAIN)) {
260
+ this.host.hostname = ICP_API_DOMAIN;
261
+ }
262
+ if (options.credentials) {
263
+ const { name, password } = options.credentials;
264
+ this.#credentials = `${name}${password ? ':' + password : ''}`;
265
+ }
266
+ this.#identity = Promise.resolve(options.identity || new AnonymousIdentity());
267
+ if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes > 5) {
268
+ throw InputError.fromCode(new IngressExpiryInvalidErrorCode('The maximum ingress expiry time is 5 minutes.', options.ingressExpiryInMinutes));
269
+ }
270
+ if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes <= 0) {
271
+ throw InputError.fromCode(new IngressExpiryInvalidErrorCode('Ingress expiry time must be greater than 0.', options.ingressExpiryInMinutes));
272
+ }
273
+ this.#maxIngressExpiryInMinutes = options.ingressExpiryInMinutes || 5;
274
+ // Add a nonce transform to ensure calls are unique
275
+ this.addTransform('update', makeNonceTransform(makeNonce));
276
+ if (options.useQueryNonces) {
277
+ this.addTransform('query', makeNonceTransform(makeNonce));
278
+ }
279
+ if (options.logToConsole) {
280
+ this.log.subscribe(log => {
281
+ if (log.level === 'error') {
282
+ console.error(log.message);
283
+ }
284
+ else if (log.level === 'warn') {
285
+ console.warn(log.message);
286
+ }
287
+ else {
288
+ console.log(log.message);
289
+ }
290
+ });
291
+ }
292
+ }
293
+ static createSync(options = {}) {
294
+ return new this({ ...options });
295
+ }
296
+ static async create(options = {}) {
297
+ const agent = HttpAgent.createSync(options);
298
+ await agent.#asyncGuard();
299
+ return agent;
300
+ }
301
+ static async from(agent) {
302
+ try {
303
+ if ('config' in agent) {
304
+ return await HttpAgent.create(agent.config);
305
+ }
306
+ return await HttpAgent.create({
307
+ fetch: agent._fetch,
308
+ fetchOptions: agent._fetchOptions,
309
+ callOptions: agent._callOptions,
310
+ host: agent._host.toString(),
311
+ identity: agent._identity ?? undefined,
312
+ });
313
+ }
314
+ catch {
315
+ throw InputError.fromCode(new CreateHttpAgentErrorCode());
316
+ }
317
+ }
318
+ isLocal() {
319
+ const hostname = this.host.hostname;
320
+ return hostname === '127.0.0.1' || hostname.endsWith('127.0.0.1');
321
+ }
322
+ addTransform(type, fn, priority = fn.priority || 0) {
323
+ if (type === 'update') {
324
+ // Keep the pipeline sorted at all time, by priority.
325
+ const i = this.#updatePipeline.findIndex(x => (x.priority || 0) < priority);
326
+ this.#updatePipeline.splice(i >= 0 ? i : this.#updatePipeline.length, 0, Object.assign(fn, { priority }));
327
+ }
328
+ else if (type === 'query') {
329
+ // Keep the pipeline sorted at all time, by priority.
330
+ const i = this.#queryPipeline.findIndex(x => (x.priority || 0) < priority);
331
+ this.#queryPipeline.splice(i >= 0 ? i : this.#queryPipeline.length, 0, Object.assign(fn, { priority }));
332
+ }
333
+ }
334
+ async getPrincipal() {
335
+ if (!this.#identity) {
336
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
337
+ }
338
+ return (await this.#identity).getPrincipal();
339
+ }
340
+ /**
341
+ * Makes a call to a canister method.
342
+ * @param canisterId - The ID of the canister to call. Can be a Principal or a string.
343
+ * @param options - Options for the call.
344
+ * @param options.methodName - The name of the method to call.
345
+ * @param options.arg - The argument to pass to the method, as a Uint8Array.
346
+ * @param options.effectiveCanisterId - (Optional) The effective canister ID, if different from the target canister ID.
347
+ * @param options.callSync - (Optional) Whether to use synchronous call mode. Defaults to true.
348
+ * @param options.nonce - (Optional) A unique nonce for the request. If provided, it will override any nonce set by transforms.
349
+ * @param identity - (Optional) The identity to use for the call. If not provided, the agent's current identity will be used.
350
+ * @returns A promise that resolves to the response of the call, including the request ID and response details.
351
+ */
352
+ async call(canisterId, options, identity) {
353
+ const callSync = options.callSync ?? true;
354
+ const id = await (identity ?? this.#identity);
355
+ if (!id) {
356
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
357
+ }
358
+ const canister = Principal.from(canisterId);
359
+ const ecid = options.effectiveCanisterId
360
+ ? Principal.from(options.effectiveCanisterId)
361
+ : canister;
362
+ await this.#asyncGuard(ecid);
363
+ const sender = id.getPrincipal();
364
+ const ingress_expiry = calculateIngressExpiry(this.#maxIngressExpiryInMinutes, this.#timeDiffMsecs);
365
+ const submit = {
366
+ request_type: SubmitRequestType.Call,
367
+ canister_id: canister,
368
+ method_name: options.methodName,
369
+ arg: options.arg,
370
+ sender,
371
+ ingress_expiry,
372
+ };
373
+ let transformedRequest = (await this._transform({
374
+ request: {
375
+ body: null,
376
+ method: 'POST',
377
+ headers: {
378
+ 'Content-Type': 'application/cbor',
379
+ ...(this.#credentials ? { Authorization: 'Basic ' + btoa(this.#credentials) } : {}),
380
+ },
381
+ },
382
+ endpoint: Endpoint.Call,
383
+ body: submit,
384
+ }));
385
+ // Determine the nonce to use for the request
386
+ let nonce;
387
+ // Check if a nonce is provided in the options and convert it to the correct type
388
+ if (options?.nonce) {
389
+ nonce = toNonce(options.nonce);
390
+ }
391
+ // If no nonce is provided in the options, check the transformedRequest body
392
+ else if (transformedRequest.body.nonce) {
393
+ nonce = toNonce(transformedRequest.body.nonce);
394
+ }
395
+ // If no nonce is found, set it to undefined
396
+ else {
397
+ nonce = undefined;
398
+ }
399
+ // Assign the determined nonce to the submit object
400
+ submit.nonce = nonce;
401
+ /**
402
+ * Converts a Uint8Array to a Nonce type.
403
+ * @param buf - The buffer to convert.
404
+ * @returns The buffer as a Nonce.
405
+ */
406
+ function toNonce(buf) {
407
+ return Object.assign(buf, { __nonce__: undefined });
408
+ }
409
+ // Apply transform for identity.
410
+ transformedRequest = (await id.transformRequest(transformedRequest));
411
+ const body = cbor.encode(transformedRequest.body);
412
+ const backoff = this.#backoffStrategy();
413
+ const requestId = requestIdOf(submit);
414
+ try {
415
+ // Attempt v4 sync call
416
+ const requestSync = () => {
417
+ const url = new URL(`/api/v4/canister/${ecid.toText()}/call`, this.host);
418
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
419
+ return this.#fetch(url, {
420
+ ...this.#callOptions,
421
+ ...transformedRequest.request,
422
+ body,
423
+ });
424
+ };
425
+ const requestAsync = () => {
426
+ const url = new URL(`/api/v2/canister/${ecid.toText()}/call`, this.host);
427
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
428
+ return this.#fetch(url, {
429
+ ...this.#callOptions,
430
+ ...transformedRequest.request,
431
+ body,
432
+ });
433
+ };
434
+ const requestFn = callSync ? requestSync : requestAsync;
435
+ const { responseBodyBytes, ...response } = await this.#requestAndRetry({
436
+ requestFn,
437
+ backoff,
438
+ tries: 0,
439
+ });
440
+ const responseBody = (responseBodyBytes.byteLength > 0 ? cbor.decode(responseBodyBytes) : null);
441
+ return {
442
+ requestId,
443
+ response: {
444
+ ...response,
445
+ body: responseBody,
446
+ },
447
+ requestDetails: submit,
448
+ };
449
+ }
450
+ catch (error) {
451
+ let callError;
452
+ if (error instanceof AgentError) {
453
+ // If the error is due to the v4 api not being supported, fall back to v2
454
+ if (error.hasCode(HttpV4ApiNotSupportedErrorCode)) {
455
+ this.log.warn('v4 api not supported. Fall back to v2');
456
+ return this.call(canisterId, {
457
+ ...options,
458
+ // disable v4 api
459
+ callSync: false,
460
+ }, identity);
461
+ }
462
+ else if (error.hasCode(IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
463
+ // if there is an ingress expiry error and the time has not been synced yet,
464
+ // sync time with the network and try again
465
+ await this.syncTime(canister);
466
+ return this.call(canister, options, identity);
467
+ }
468
+ else {
469
+ // override the error code to include the request details
470
+ error.code.requestContext = {
471
+ requestId,
472
+ senderPubKey: transformedRequest.body.sender_pubkey,
473
+ senderSignature: transformedRequest.body.sender_sig,
474
+ ingressExpiry: transformedRequest.body.content.ingress_expiry,
475
+ };
476
+ callError = error;
477
+ }
478
+ }
479
+ else {
480
+ callError = UnknownError.fromCode(new UnexpectedErrorCode(error));
481
+ }
482
+ this.log.error(`Error while making call: ${callError.message}`, callError);
483
+ throw callError;
484
+ }
485
+ }
486
+ async #requestAndRetryQuery(args) {
487
+ const { ecid, transformedRequest, body, requestId, backoff, tries } = args;
488
+ const delay = tries === 0 ? 0 : backoff.next();
489
+ const url = new URL(`/api/v3/canister/${ecid.toString()}/query`, this.host);
490
+ this.log.print(`fetching "${url.pathname}" with tries:`, {
491
+ tries,
492
+ backoff,
493
+ delay,
494
+ });
495
+ // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason
496
+ if (delay === null) {
497
+ throw UnknownError.fromCode(new TimeoutWaitingForResponseErrorCode(`Backoff strategy exhausted after ${tries} attempts.`, requestId));
498
+ }
499
+ if (delay > 0) {
500
+ await new Promise(resolve => setTimeout(resolve, delay));
501
+ }
502
+ let response;
503
+ // Make the request and retry if it throws an error
504
+ try {
505
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
506
+ const fetchResponse = await this.#fetch(url, {
507
+ ...this.#fetchOptions,
508
+ ...transformedRequest.request,
509
+ body,
510
+ });
511
+ if (fetchResponse.status === HTTP_STATUS_OK) {
512
+ const queryResponse = cbor.decode(uint8FromBufLike(await fetchResponse.arrayBuffer()));
513
+ response = {
514
+ ...queryResponse,
515
+ httpDetails: {
516
+ ok: fetchResponse.ok,
517
+ status: fetchResponse.status,
518
+ statusText: fetchResponse.statusText,
519
+ headers: httpHeadersTransform(fetchResponse.headers),
520
+ },
521
+ requestId,
522
+ };
523
+ }
524
+ else {
525
+ throw ProtocolError.fromCode(new HttpErrorCode(fetchResponse.status, fetchResponse.statusText, httpHeadersTransform(fetchResponse.headers), await fetchResponse.text()));
526
+ }
527
+ }
528
+ catch (error) {
529
+ if (tries < this.#retryTimes) {
530
+ this.log.warn(`Caught exception while attempting to make query:\n` +
531
+ ` ${error}\n` +
532
+ ` Retrying query.`);
533
+ return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
534
+ }
535
+ if (error instanceof AgentError) {
536
+ // if it's an error that we have thrown, just throw it as is
537
+ throw error;
538
+ }
539
+ // if it's an error that we have not thrown, wrap it in a TransportError
540
+ throw TransportError.fromCode(new HttpFetchErrorCode(error));
541
+ }
542
+ // Skip timestamp verification if the user has set verifyQuerySignatures to false
543
+ if (!this.#verifyQuerySignatures) {
544
+ return response;
545
+ }
546
+ const signatureTimestampNs = response.signatures?.[0]?.timestamp;
547
+ if (!signatureTimestampNs) {
548
+ throw ProtocolError.fromCode(new MalformedSignatureErrorCode('Timestamp not found in query response. This suggests a malformed or malicious response.'));
549
+ }
550
+ const signatureTimestampMs = Number(BigInt(signatureTimestampNs) / BigInt(MSECS_TO_NANOSECONDS));
551
+ const currentTimestampInMs = Date.now() + this.#timeDiffMsecs;
552
+ // We don't need `Math.abs` here because we allow signatures in the future
553
+ if (currentTimestampInMs - signatureTimestampMs > this.#maxIngressExpiryInMs) {
554
+ if (tries < this.#retryTimes) {
555
+ this.log.warn('Timestamp is older than the max ingress expiry. Retrying query.', {
556
+ requestId,
557
+ signatureTimestampMs,
558
+ });
559
+ return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
560
+ }
561
+ throw TrustError.fromCode(new CertificateOutdatedErrorCode(this.#maxIngressExpiryInMinutes, requestId, tries));
562
+ }
563
+ return response;
564
+ }
565
+ /**
566
+ * Makes a request and retries if it fails.
567
+ * @param args - The arguments for the request.
568
+ * @param args.requestFn - A function that returns a Promise resolving to a Response.
569
+ * @param args.backoff - The backoff strategy to use for retries.
570
+ * @param args.tries - The number of retry attempts made so far.
571
+ * @returns The response from the request, if the status is 200 or 202.
572
+ * See the https://internetcomputer.org/docs/references/ic-interface-spec#http-interface for details on the response statuses.
573
+ * @throws {ProtocolError} if the response status is not 200 or 202, and the retry limit has been reached.
574
+ * @throws {TransportError} if the request fails, and the retry limit has been reached.
575
+ */
576
+ async #requestAndRetry(args) {
577
+ const { requestFn, backoff, tries } = args;
578
+ const delay = tries === 0 ? 0 : backoff.next();
579
+ // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason
580
+ if (delay === null) {
581
+ throw ProtocolError.fromCode(new TimeoutWaitingForResponseErrorCode(`Retry strategy exhausted after ${tries} attempts.`));
582
+ }
583
+ if (delay > 0) {
584
+ await new Promise(resolve => setTimeout(resolve, delay));
585
+ }
586
+ let response;
587
+ let responseBodyBytes = new Uint8Array();
588
+ try {
589
+ response = await requestFn();
590
+ // According to the spec, only 200 responses have a non-empty body
591
+ if (response.status === HTTP_STATUS_OK) {
592
+ // Consume the response body, to ensure that the response is not closed unexpectedly
593
+ responseBodyBytes = uint8FromBufLike(await response.clone().arrayBuffer());
594
+ }
595
+ }
596
+ catch (error) {
597
+ if (tries < this.#retryTimes) {
598
+ this.log.warn(`Caught exception while attempting to make request:\n` +
599
+ ` ${error}\n` +
600
+ ` Retrying request.`);
601
+ // Delay the request by the configured backoff strategy
602
+ return await this.#requestAndRetry({ requestFn, backoff, tries: tries + 1 });
603
+ }
604
+ throw TransportError.fromCode(new HttpFetchErrorCode(error));
605
+ }
606
+ const headers = httpHeadersTransform(response.headers);
607
+ if (response.status === HTTP_STATUS_OK || response.status === HTTP_STATUS_ACCEPTED) {
608
+ return {
609
+ ok: response.ok, // should always be true
610
+ status: response.status,
611
+ statusText: response.statusText,
612
+ responseBodyBytes,
613
+ headers,
614
+ };
615
+ }
616
+ const responseText = await response.text();
617
+ if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/v4')) {
618
+ throw ProtocolError.fromCode(new HttpV4ApiNotSupportedErrorCode());
619
+ }
620
+ // The error message comes from https://github.com/dfinity/ic/blob/23d5990bfc5277c32e54f0087b5a38fa412171e1/rs/validator/src/ingress_validation.rs#L233
621
+ if (responseText.startsWith('Invalid request expiry: ')) {
622
+ throw InputError.fromCode(new IngressExpiryInvalidErrorCode(responseText, this.#maxIngressExpiryInMinutes));
623
+ }
624
+ if (tries < this.#retryTimes) {
625
+ return await this.#requestAndRetry({ requestFn, backoff, tries: tries + 1 });
626
+ }
627
+ throw ProtocolError.fromCode(new HttpErrorCode(response.status, response.statusText, headers, responseText));
628
+ }
629
+ async query(canisterId, fields, identity) {
630
+ const backoff = this.#backoffStrategy();
631
+ const ecid = fields.effectiveCanisterId
632
+ ? Principal.from(fields.effectiveCanisterId)
633
+ : Principal.from(canisterId);
634
+ await this.#asyncGuard(ecid);
635
+ this.log.print(`ecid ${ecid.toString()}`);
636
+ this.log.print(`canisterId ${canisterId.toString()}`);
637
+ let transformedRequest;
638
+ const id = await (identity ?? this.#identity);
639
+ if (!id) {
640
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
641
+ }
642
+ const canister = Principal.from(canisterId);
643
+ const sender = id.getPrincipal();
644
+ const ingressExpiry = calculateIngressExpiry(this.#maxIngressExpiryInMinutes, this.#timeDiffMsecs);
645
+ const request = {
646
+ request_type: ReadRequestType.Query,
647
+ canister_id: canister,
648
+ method_name: fields.methodName,
649
+ arg: fields.arg,
650
+ sender,
651
+ ingress_expiry: ingressExpiry,
652
+ };
653
+ const requestId = requestIdOf(request);
654
+ transformedRequest = await this._transform({
655
+ request: {
656
+ method: 'POST',
657
+ headers: {
658
+ 'Content-Type': 'application/cbor',
659
+ ...(this.#credentials ? { Authorization: 'Basic ' + btoa(this.#credentials) } : {}),
660
+ },
661
+ },
662
+ endpoint: Endpoint.Query,
663
+ body: request,
664
+ });
665
+ // Apply transform for identity.
666
+ transformedRequest = (await id.transformRequest(transformedRequest));
667
+ const body = cbor.encode(transformedRequest.body);
668
+ const args = {
669
+ canister: canister.toText(),
670
+ ecid,
671
+ transformedRequest,
672
+ body,
673
+ requestId,
674
+ backoff,
675
+ tries: 0,
676
+ };
677
+ const makeQuery = async () => {
678
+ // Attempt to make the query i=retryTimes times
679
+ const query = await this.#requestAndRetryQuery(args);
680
+ return {
681
+ requestDetails: request,
682
+ ...query,
683
+ };
684
+ };
685
+ const getSubnetNodeKeys = async () => {
686
+ const cachedSubnetNodeKeys = this.#subnetKeys.get(ecid.toString());
687
+ if (cachedSubnetNodeKeys) {
688
+ return cachedSubnetNodeKeys;
689
+ }
690
+ await this.fetchSubnetKeys(ecid.toString());
691
+ const subnetNodeKeys = this.#subnetKeys.get(ecid.toString());
692
+ if (!subnetNodeKeys) {
693
+ throw TrustError.fromCode(new MissingSignatureErrorCode());
694
+ }
695
+ return subnetNodeKeys;
696
+ };
697
+ try {
698
+ if (!this.#verifyQuerySignatures) {
699
+ // Skip verification if the user has disabled it
700
+ return await makeQuery();
701
+ }
702
+ // Make query and fetch subnet keys in parallel
703
+ const [queryWithDetails, subnetNodeKeys] = await Promise.all([
704
+ makeQuery(),
705
+ getSubnetNodeKeys(),
706
+ ]);
707
+ try {
708
+ return this.#verifyQueryResponse(queryWithDetails, subnetNodeKeys);
709
+ }
710
+ catch {
711
+ // In case the node signatures have changed, refresh the subnet keys and try again
712
+ this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');
713
+ this.#subnetKeys.delete(ecid.toString());
714
+ const updatedSubnetNodeKeys = await getSubnetNodeKeys();
715
+ return this.#verifyQueryResponse(queryWithDetails, updatedSubnetNodeKeys);
716
+ }
717
+ }
718
+ catch (error) {
719
+ let queryError;
720
+ if (error instanceof AgentError) {
721
+ // override the error code to include the request details
722
+ error.code.requestContext = {
723
+ requestId,
724
+ senderPubKey: transformedRequest.body.sender_pubkey,
725
+ senderSignature: transformedRequest.body.sender_sig,
726
+ ingressExpiry: transformedRequest.body.content.ingress_expiry,
727
+ };
728
+ queryError = error;
729
+ }
730
+ else {
731
+ queryError = UnknownError.fromCode(new UnexpectedErrorCode(error));
732
+ }
733
+ this.log.error(`Error while making query: ${queryError.message}`, queryError);
734
+ throw queryError;
735
+ }
736
+ }
737
+ /**
738
+ * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation
739
+ * @param queryResponse - The response from the query
740
+ * @param subnetNodeKeys - The subnet node keys
741
+ * @returns ApiQueryResponse
742
+ */
743
+ #verifyQueryResponse;
744
+ async createReadStateRequest(fields, identity) {
745
+ await this.#asyncGuard();
746
+ const id = await (identity ?? this.#identity);
747
+ if (!id) {
748
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
749
+ }
750
+ const sender = id.getPrincipal();
751
+ const transformedRequest = await this._transform({
752
+ request: {
753
+ method: 'POST',
754
+ headers: {
755
+ 'Content-Type': 'application/cbor',
756
+ ...(this.#credentials ? { Authorization: 'Basic ' + btoa(this.#credentials) } : {}),
757
+ },
758
+ },
759
+ endpoint: Endpoint.ReadState,
760
+ body: {
761
+ request_type: ReadRequestType.ReadState,
762
+ paths: fields.paths,
763
+ sender,
764
+ ingress_expiry: calculateIngressExpiry(this.#maxIngressExpiryInMinutes, this.#timeDiffMsecs),
765
+ },
766
+ });
767
+ // Apply transform for identity.
768
+ return id.transformRequest(transformedRequest);
769
+ }
770
+ async readState(canisterId, fields, _identity,
771
+ // eslint-disable-next-line
772
+ request) {
773
+ await this.#rootKeyGuard();
774
+ const canister = Principal.from(canisterId);
775
+ function getRequestId(options) {
776
+ for (const path of options.paths) {
777
+ const [pathName, value] = path;
778
+ const request_status = new TextEncoder().encode('request_status');
779
+ if (uint8Equals(pathName, request_status)) {
780
+ return value;
781
+ }
782
+ }
783
+ }
784
+ let transformedRequest;
785
+ let requestId;
786
+ // If a pre-signed request is provided, use it
787
+ if (request) {
788
+ // This is a pre-signed request
789
+ transformedRequest = request;
790
+ }
791
+ else {
792
+ // This is fields, we need to create a request
793
+ requestId = getRequestId(fields);
794
+ // Always create a fresh request with the current identity
795
+ const identity = await this.#identity;
796
+ if (!identity) {
797
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
798
+ }
799
+ transformedRequest = await this.createReadStateRequest(fields, identity);
800
+ }
801
+ const url = new URL(`/api/v3/canister/${canister.toString()}/read_state`, this.host);
802
+ return await this.#readStateInner(url, transformedRequest, requestId);
803
+ }
804
+ /**
805
+ * Reads the state of a subnet from the `/api/v3/subnet/{subnetId}/read_state` endpoint.
806
+ * @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.
807
+ * @param options The options for the read state request.
808
+ * @returns The response from the read state request.
809
+ */
810
+ async readSubnetState(subnetId, options) {
811
+ await this.#rootKeyGuard();
812
+ const url = new URL(`/api/v3/subnet/${subnetId.toString()}/read_state`, this.host);
813
+ const transformedRequest = await this.createReadStateRequest(options, this.#identity ?? undefined);
814
+ return await this.#readStateInner(url, transformedRequest);
815
+ }
816
+ async #readStateInner(url, transformedRequest, requestId) {
817
+ const backoff = this.#backoffStrategy();
818
+ try {
819
+ const { responseBodyBytes } = await this.#requestAndRetry({
820
+ requestFn: () => this.#fetch(url, {
821
+ ...this.#fetchOptions,
822
+ ...transformedRequest.request,
823
+ body: cbor.encode(transformedRequest.body),
824
+ }),
825
+ backoff,
826
+ tries: 0,
827
+ });
828
+ const decodedResponse = cbor.decode(responseBodyBytes);
829
+ return decodedResponse;
830
+ }
831
+ catch (error) {
832
+ let readStateError;
833
+ if (error instanceof AgentError) {
834
+ // override the error code to include the request details
835
+ error.code.requestContext = {
836
+ requestId: requestId ?? requestIdOf(transformedRequest),
837
+ senderPubKey: transformedRequest.body.sender_pubkey,
838
+ senderSignature: transformedRequest.body.sender_sig,
839
+ ingressExpiry: transformedRequest.body.content.ingress_expiry,
840
+ };
841
+ readStateError = error;
842
+ }
843
+ else {
844
+ readStateError = UnknownError.fromCode(new UnexpectedErrorCode(error));
845
+ }
846
+ this.log.error(`Error while making read state: ${readStateError.message}`, readStateError);
847
+ throw readStateError;
848
+ }
849
+ }
850
+ parseTimeFromResponse(response) {
851
+ let tree;
852
+ if (response.certificate) {
853
+ const decoded = cbor.decode(response.certificate);
854
+ if (decoded && 'tree' in decoded) {
855
+ tree = decoded.tree;
856
+ }
857
+ else {
858
+ throw ProtocolError.fromCode(new HashTreeDecodeErrorCode('Could not decode time from response'));
859
+ }
860
+ const timeLookup = lookup_path(['time'], tree);
861
+ if (timeLookup.status !== LookupPathStatus.Found) {
862
+ throw ProtocolError.fromCode(new LookupErrorCode('Time was not found in the response or was not in its expected format.', timeLookup.status));
863
+ }
864
+ if (!(timeLookup.value instanceof Uint8Array) && !ArrayBuffer.isView(timeLookup)) {
865
+ throw ProtocolError.fromCode(new MalformedLookupFoundValueErrorCode('Time was not in its expected format.'));
866
+ }
867
+ const date = decodeTime(timeLookup.value);
868
+ this.log.print('Time from response:', date);
869
+ this.log.print('Time from response in milliseconds:', date.getTime());
870
+ return date.getTime();
871
+ }
872
+ else {
873
+ this.log.warn('No certificate found in response');
874
+ }
875
+ return 0;
876
+ }
877
+ /**
878
+ * 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
879
+ * @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.
880
+ */
881
+ async syncTime(canisterIdOverride) {
882
+ this.#syncTimePromise =
883
+ this.#syncTimePromise ??
884
+ (async () => {
885
+ await this.#rootKeyGuard();
886
+ const callTime = Date.now();
887
+ try {
888
+ if (!canisterIdOverride) {
889
+ this.log.print('Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');
890
+ }
891
+ // Fall back with canisterId of the ICP Ledger
892
+ const canisterId = canisterIdOverride ?? Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai');
893
+ const anonymousAgent = HttpAgent.createSync({
894
+ identity: new AnonymousIdentity(),
895
+ host: this.host.toString(),
896
+ fetch: this.#fetch,
897
+ retryTimes: 0,
898
+ rootKey: this.rootKey ?? undefined,
899
+ shouldSyncTime: false,
900
+ });
901
+ const replicaTimes = await Promise.all(Array(3)
902
+ .fill(null)
903
+ .map(async () => {
904
+ const status = await canisterStatusRequest({
905
+ canisterId,
906
+ agent: anonymousAgent,
907
+ paths: ['time'],
908
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
909
+ });
910
+ const date = status.get('time');
911
+ if (date instanceof Date) {
912
+ return date.getTime();
913
+ }
914
+ }, []));
915
+ this.#setTimeDiffMsecs(callTime, replicaTimes);
916
+ }
917
+ catch (error) {
918
+ const syncTimeError = error instanceof AgentError
919
+ ? error
920
+ : UnknownError.fromCode(new UnexpectedErrorCode(error));
921
+ this.log.error('Caught exception while attempting to sync time', syncTimeError);
922
+ throw syncTimeError;
923
+ }
924
+ })();
925
+ await this.#syncTimePromise.finally(() => {
926
+ this.#syncTimePromise = null;
927
+ });
928
+ }
929
+ /**
930
+ * Allows agent to sync its time with the network.
931
+ * @param {Principal} subnetId - Pass the subnet ID you need to sync the time with.
932
+ */
933
+ async syncTimeWithSubnet(subnetId) {
934
+ await this.#rootKeyGuard();
935
+ const callTime = Date.now();
936
+ try {
937
+ const anonymousAgent = HttpAgent.createSync({
938
+ identity: new AnonymousIdentity(),
939
+ host: this.host.toString(),
940
+ fetch: this.#fetch,
941
+ retryTimes: 0,
942
+ rootKey: this.rootKey ?? undefined,
943
+ shouldSyncTime: false,
944
+ });
945
+ const replicaTimes = await Promise.all(Array(3)
946
+ .fill(null)
947
+ .map(async () => {
948
+ const status = await subnetStatusRequest({
949
+ subnetId,
950
+ agent: anonymousAgent,
951
+ paths: ['time'],
952
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
953
+ });
954
+ const date = status.get('time');
955
+ if (date instanceof Date) {
956
+ return date.getTime();
957
+ }
958
+ }, []));
959
+ this.#setTimeDiffMsecs(callTime, replicaTimes);
960
+ }
961
+ catch (error) {
962
+ const syncTimeError = error instanceof AgentError ? error : UnknownError.fromCode(new UnexpectedErrorCode(error));
963
+ this.log.error('Caught exception while attempting to sync time with subnet', syncTimeError);
964
+ throw syncTimeError;
965
+ }
966
+ }
967
+ #setTimeDiffMsecs(callTime, replicaTimes) {
968
+ const maxReplicaTime = replicaTimes.reduce((max, current) => {
969
+ return typeof current === 'number' && current > max ? current : max;
970
+ }, 0);
971
+ if (maxReplicaTime > 0) {
972
+ this.#timeDiffMsecs = maxReplicaTime - callTime;
973
+ this.#hasSyncedTime = true;
974
+ this.log.notify({
975
+ message: `Syncing time: offset of ${this.#timeDiffMsecs}`,
976
+ level: 'info',
977
+ });
978
+ }
979
+ }
980
+ async status() {
981
+ const headers = this.#credentials
982
+ ? {
983
+ Authorization: 'Basic ' + btoa(this.#credentials),
984
+ }
985
+ : {};
986
+ const url = new URL(`/api/v2/status`, this.host);
987
+ this.log.print(`fetching "${url.pathname}"`);
988
+ const backoff = this.#backoffStrategy();
989
+ const { responseBodyBytes } = await this.#requestAndRetry({
990
+ backoff,
991
+ requestFn: () => this.#fetch(url, { headers, ...this.#fetchOptions }),
992
+ tries: 0,
993
+ });
994
+ return cbor.decode(responseBodyBytes);
995
+ }
996
+ async fetchRootKey() {
997
+ // Wait for already pending promise to avoid duplicate calls
998
+ this.#rootKeyPromise =
999
+ this.#rootKeyPromise ??
1000
+ (async () => {
1001
+ const value = await this.status();
1002
+ // Hex-encoded version of the replica root key
1003
+ this.rootKey = value.root_key;
1004
+ return this.rootKey;
1005
+ })();
1006
+ // clear rootkey promise and return result
1007
+ return await this.#rootKeyPromise.finally(() => {
1008
+ this.#rootKeyPromise = null;
1009
+ });
1010
+ }
1011
+ async #asyncGuard(canisterIdOverride) {
1012
+ await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(canisterIdOverride)]);
1013
+ }
1014
+ async #rootKeyGuard() {
1015
+ if (this.rootKey) {
1016
+ return;
1017
+ }
1018
+ else if (this.rootKey === null &&
1019
+ this.host.toString() !== 'https://icp-api.io' &&
1020
+ this.#shouldFetchRootKey) {
1021
+ await this.fetchRootKey();
1022
+ }
1023
+ else {
1024
+ throw ExternalError.fromCode(new MissingRootKeyErrorCode(this.#shouldFetchRootKey));
1025
+ }
1026
+ }
1027
+ async #syncTimeGuard(canisterIdOverride) {
1028
+ if (this.#shouldSyncTime && !this.hasSyncedTime()) {
1029
+ await this.syncTime(canisterIdOverride);
1030
+ }
1031
+ }
1032
+ invalidateIdentity() {
1033
+ this.#identity = null;
1034
+ }
1035
+ replaceIdentity(identity) {
1036
+ this.#identity = Promise.resolve(identity);
1037
+ }
1038
+ async fetchSubnetKeys(canisterId) {
1039
+ const effectiveCanisterId = Principal.from(canisterId);
1040
+ await this.#asyncGuard(effectiveCanisterId);
1041
+ const rootKey = this.rootKey;
1042
+ const canisterReadState = await this.readState(effectiveCanisterId, {
1043
+ paths: [[utf8ToBytes('subnet')]],
1044
+ });
1045
+ const canisterCertificate = await Certificate.create({
1046
+ certificate: canisterReadState.certificate,
1047
+ rootKey,
1048
+ principal: { canisterId: effectiveCanisterId },
1049
+ agent: this,
1050
+ });
1051
+ const subnetId = getSubnetIdFromCertificate(canisterCertificate.cert, rootKey);
1052
+ const nodeKeys = lookupNodeKeysFromCertificate(canisterCertificate.cert, subnetId);
1053
+ this.#subnetKeys.set(effectiveCanisterId.toText(), nodeKeys);
1054
+ return nodeKeys;
1055
+ }
1056
+ /**
1057
+ * Returns the subnet ID for a given canister ID, by looking at the certificate delegation
1058
+ * returned by the canister's state obtained by requesting the `/time` path with {@link HttpAgent.readState | readState}.
1059
+ * @param canisterId The canister ID to get the subnet ID for.
1060
+ * @returns The subnet ID for the given canister ID.
1061
+ */
1062
+ async getSubnetIdFromCanister(canisterId) {
1063
+ const effectiveCanisterId = Principal.from(canisterId);
1064
+ await this.#asyncGuard(effectiveCanisterId);
1065
+ const canisterReadState = await this.readState(effectiveCanisterId, {
1066
+ paths: [[utf8ToBytes('time')]],
1067
+ });
1068
+ const canisterCertificate = await Certificate.create({
1069
+ certificate: canisterReadState.certificate,
1070
+ rootKey: this.rootKey,
1071
+ principal: { canisterId: effectiveCanisterId },
1072
+ agent: this,
1073
+ });
1074
+ return getSubnetIdFromCertificate(canisterCertificate.cert, this.rootKey);
1075
+ }
1076
+ _transform(request) {
1077
+ let p = Promise.resolve(request);
1078
+ if (request.endpoint === Endpoint.Call) {
1079
+ for (const fn of this.#updatePipeline) {
1080
+ p = p.then(r => fn(r).then(r2 => r2 || r));
1081
+ }
1082
+ }
1083
+ else {
1084
+ for (const fn of this.#queryPipeline) {
1085
+ p = p.then(r => fn(r).then(r2 => r2 || r));
1086
+ }
1087
+ }
1088
+ return p;
1089
+ }
1090
+ /**
1091
+ * Returns the time difference in milliseconds between the IC network clock and the client's clock,
1092
+ * after the clock has been synced.
1093
+ *
1094
+ * If the time has not been synced, returns `0`.
1095
+ */
1096
+ getTimeDiffMsecs() {
1097
+ return this.#timeDiffMsecs;
1098
+ }
1099
+ /**
1100
+ * Returns `true` if the time has been synced at least once with the IC network, `false` otherwise.
1101
+ */
1102
+ hasSyncedTime() {
1103
+ return this.#hasSyncedTime;
1104
+ }
1105
+ }
1106
+ /**
1107
+ * Calculates the ingress expiry time based on the maximum allowed expiry in minutes and the time difference in milliseconds.
1108
+ * The expiry is rounded down according to the {@link Expiry.fromDeltaInMilliseconds} method.
1109
+ * @param maxIngressExpiryInMinutes - The maximum ingress expiry time in minutes.
1110
+ * @param timeDiffMsecs - The time difference in milliseconds to adjust the expiry.
1111
+ * @returns The calculated ingress expiry as an Expiry object.
1112
+ */
1113
+ export function calculateIngressExpiry(maxIngressExpiryInMinutes, timeDiffMsecs) {
1114
+ const ingressExpiryMs = maxIngressExpiryInMinutes * MINUTE_TO_MSECS;
1115
+ return Expiry.fromDeltaInMilliseconds(ingressExpiryMs, timeDiffMsecs);
1116
+ }
1117
+ //# sourceMappingURL=index.js.map