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

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