@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,1518 @@
1
+ import { type JsonObject } from '#candid';
2
+ import { Principal } from '#principal';
3
+ import {
4
+ HashTreeDecodeErrorCode,
5
+ CreateHttpAgentErrorCode,
6
+ ExternalError,
7
+ HttpDefaultFetchErrorCode,
8
+ IdentityInvalidErrorCode,
9
+ IngressExpiryInvalidErrorCode,
10
+ InputError,
11
+ LookupErrorCode,
12
+ MalformedPublicKeyErrorCode,
13
+ MalformedSignatureErrorCode,
14
+ MissingRootKeyErrorCode,
15
+ MissingSignatureErrorCode,
16
+ ProtocolError,
17
+ QuerySignatureVerificationFailedErrorCode,
18
+ TimeoutWaitingForResponseErrorCode,
19
+ TrustError,
20
+ UnexpectedErrorCode,
21
+ UnknownError,
22
+ HttpErrorCode,
23
+ HttpV4ApiNotSupportedErrorCode,
24
+ TransportError,
25
+ HttpFetchErrorCode,
26
+ AgentError,
27
+ MalformedLookupFoundValueErrorCode,
28
+ CertificateOutdatedErrorCode,
29
+ } from '../../errors.ts';
30
+ import { AnonymousIdentity, type Identity } from '../../auth.ts';
31
+ import * as cbor from '../../cbor.ts';
32
+ import { type RequestId, hashOfMap, requestIdOf } from '../../request_id.ts';
33
+ import {
34
+ QueryResponseStatus,
35
+ type Agent,
36
+ type ApiQueryResponse,
37
+ type QueryFields,
38
+ type QueryResponse,
39
+ type ReadStateOptions,
40
+ type ReadStateResponse,
41
+ type SubmitResponse,
42
+ } from '../api.ts';
43
+ import { Expiry, httpHeadersTransform, makeNonceTransform } from './transforms.ts';
44
+ import {
45
+ type CallRequest,
46
+ Endpoint,
47
+ type HttpAgentRequest,
48
+ type HttpAgentRequestTransformFn,
49
+ type HttpAgentSubmitRequest,
50
+ makeNonce,
51
+ type Nonce,
52
+ type QueryRequest,
53
+ ReadRequestType,
54
+ SubmitRequestType,
55
+ type ReadStateRequest,
56
+ type HttpHeaderField,
57
+ } from './types.ts';
58
+ import { request as canisterStatusRequest } from '../../canisterStatus/index.ts';
59
+ import { request as subnetStatusRequest } from '../../subnetStatus/index.ts';
60
+ import { lookupNodeKeysFromCertificate, type SubnetNodeKeys } from '../../utils/readState.ts';
61
+ import {
62
+ Certificate,
63
+ getSubnetIdFromCertificate,
64
+ type HashTree,
65
+ lookup_path,
66
+ LookupPathStatus,
67
+ } from '../../certificate.ts';
68
+ import { ed25519 } from '@noble/curves/ed25519';
69
+ import { ExpirableMap } from '../../utils/expirableMap.ts';
70
+ import { Ed25519PublicKey } from '../../public_key.ts';
71
+ import { ObservableLog } from '../../observable.ts';
72
+ import {
73
+ type BackoffStrategy,
74
+ type BackoffStrategyFactory,
75
+ ExponentialBackoff,
76
+ } from '../../polling/backoff.ts';
77
+ import { decodeTime } from '../../utils/leb.ts';
78
+ import { concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';
79
+ import { uint8Equals, uint8FromBufLike } from '../../utils/buffer.ts';
80
+ import { IC_RESPONSE_DOMAIN_SEPARATOR } from '../../constants.ts';
81
+ export * from './transforms.ts';
82
+ export { type Nonce, makeNonce } from './types.ts';
83
+
84
+ export enum RequestStatusResponseStatus {
85
+ Received = 'received',
86
+ Processing = 'processing',
87
+ Replied = 'replied',
88
+ Rejected = 'rejected',
89
+ Unknown = 'unknown',
90
+ Done = 'done',
91
+ }
92
+
93
+ const MINUTE_TO_MSECS = 60 * 1_000;
94
+ const MSECS_TO_NANOSECONDS = 1_000_000;
95
+
96
+ const DEFAULT_TIME_DIFF_MSECS = 0;
97
+
98
+ // Root public key for the IC, encoded as hex
99
+ export const IC_ROOT_KEY =
100
+ '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +
101
+ 'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +
102
+ '5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +
103
+ 'b01291091c5f87b98883463f98091a0baaae';
104
+
105
+ export const MANAGEMENT_CANISTER_ID = 'aaaaa-aa';
106
+
107
+ // IC0 domain info
108
+ const IC0_DOMAIN = 'ic0.app';
109
+ const IC0_SUB_DOMAIN = '.ic0.app';
110
+
111
+ const ICP0_DOMAIN = 'icp0.io';
112
+ const ICP0_SUB_DOMAIN = '.icp0.io';
113
+
114
+ const ICP_API_DOMAIN = 'icp-api.io';
115
+ const ICP_API_SUB_DOMAIN = '.icp-api.io';
116
+
117
+ const HTTP_STATUS_OK = 200;
118
+ const HTTP_STATUS_ACCEPTED = 202;
119
+ const HTTP_STATUS_NOT_FOUND = 404;
120
+
121
+ // HttpAgent options that can be used at construction.
122
+ export interface HttpAgentOptions {
123
+ // A surrogate to the global fetch function. Useful for testing.
124
+ fetch?: typeof fetch;
125
+
126
+ // Additional options to pass along to fetch. Will not override fields that
127
+ // the agent already needs to set
128
+ // Should follow the RequestInit interface, but we intentially support non-standard fields
129
+ fetchOptions?: Record<string, unknown>;
130
+
131
+ // Additional options to pass along to fetch for the call API.
132
+ callOptions?: Record<string, unknown>;
133
+
134
+ // The host to use for the client. By default, uses the same host as
135
+ // the current page.
136
+ host?: string;
137
+
138
+ // The principal used to send messages. This cannot be empty at the request
139
+ // time (will throw).
140
+ identity?: Identity | Promise<Identity>;
141
+
142
+ /**
143
+ * The maximum time a request can be delayed before being rejected.
144
+ * @default 5 minutes
145
+ */
146
+ ingressExpiryInMinutes?: number;
147
+
148
+ credentials?: {
149
+ name: string;
150
+ password?: string;
151
+ };
152
+ /**
153
+ * Adds a unique {@link Nonce} with each query.
154
+ * Enabling will prevent queries from being answered with a cached response.
155
+ * @example
156
+ * const agent = new HttpAgent({ useQueryNonces: true });
157
+ * agent.addTransform(makeNonceTransform(makeNonce);
158
+ * @default false
159
+ */
160
+ useQueryNonces?: boolean;
161
+ /**
162
+ * Number of times to retry requests before throwing an error
163
+ * @default 3
164
+ */
165
+ retryTimes?: number;
166
+ /**
167
+ * The strategy to use for backoff when retrying requests
168
+ */
169
+ backoffStrategy?: BackoffStrategyFactory;
170
+ /**
171
+ * Whether the agent should verify signatures signed by node keys on query responses. Increases security, but adds overhead and must make a separate request to cache the node keys for the canister's subnet.
172
+ * @default true
173
+ */
174
+ verifyQuerySignatures?: boolean;
175
+ /**
176
+ * Whether to log to the console. Defaults to false.
177
+ */
178
+ logToConsole?: boolean;
179
+
180
+ /**
181
+ * Alternate root key to use for verifying certificates. If not provided, the default IC root key will be used.
182
+ */
183
+ rootKey?: Uint8Array;
184
+
185
+ /**
186
+ * Whether or not the root key should be automatically fetched during construction. Defaults to false.
187
+ */
188
+ shouldFetchRootKey?: boolean;
189
+
190
+ /**
191
+ * Whether or not to sync the time with the network during construction. Defaults to false.
192
+ */
193
+ shouldSyncTime?: boolean;
194
+ }
195
+
196
+ function getDefaultFetch(): typeof fetch {
197
+ let defaultFetch;
198
+
199
+ if (typeof window !== 'undefined') {
200
+ // Browser context
201
+ if (window.fetch) {
202
+ defaultFetch = window.fetch.bind(window);
203
+ } else {
204
+ throw ExternalError.fromCode(
205
+ new HttpDefaultFetchErrorCode(
206
+ 'Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.',
207
+ ),
208
+ );
209
+ }
210
+ } else if (typeof global !== 'undefined') {
211
+ // Node context
212
+ if (global.fetch) {
213
+ defaultFetch = global.fetch.bind(global);
214
+ } else {
215
+ throw ExternalError.fromCode(
216
+ new HttpDefaultFetchErrorCode(
217
+ 'Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.',
218
+ ),
219
+ );
220
+ }
221
+ } else if (typeof self !== 'undefined') {
222
+ if (self.fetch) {
223
+ defaultFetch = self.fetch.bind(self);
224
+ }
225
+ }
226
+
227
+ if (defaultFetch) {
228
+ return defaultFetch;
229
+ }
230
+ throw ExternalError.fromCode(
231
+ new HttpDefaultFetchErrorCode(
232
+ 'Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.',
233
+ ),
234
+ );
235
+ }
236
+
237
+ function determineHost(configuredHost: string | undefined): string {
238
+ let host: URL;
239
+ if (configuredHost !== undefined) {
240
+ if (!configuredHost.match(/^[a-z]+:/) && typeof window !== 'undefined') {
241
+ host = new URL(window.location.protocol + '//' + configuredHost);
242
+ } else {
243
+ host = new URL(configuredHost);
244
+ }
245
+ } else {
246
+ // Mainnet, local, and remote environments will have the api route available
247
+ const knownHosts = ['ic0.app', 'icp0.io', '127.0.0.1', 'localhost'];
248
+ const remoteHosts = ['.github.dev', '.gitpod.io'];
249
+ const location = typeof window !== 'undefined' ? window.location : undefined;
250
+ const hostname = location?.hostname;
251
+ let knownHost;
252
+ if (hostname && typeof hostname === 'string') {
253
+ if (remoteHosts.some(host => hostname.endsWith(host))) {
254
+ knownHost = hostname;
255
+ } else {
256
+ knownHost = knownHosts.find(host => hostname.endsWith(host));
257
+ }
258
+ }
259
+
260
+ if (location && knownHost) {
261
+ // If the user is on a boundary-node provided host, we can use the same host for the agent
262
+ host = new URL(
263
+ `${location.protocol}//${knownHost}${location.port ? ':' + location.port : ''}`,
264
+ );
265
+ } else {
266
+ host = new URL('https://icp-api.io');
267
+ }
268
+ }
269
+ return host.toString();
270
+ }
271
+
272
+ interface V1HttpAgentInterface {
273
+ _identity: Promise<Identity> | null;
274
+ readonly _fetch: typeof fetch;
275
+ readonly _fetchOptions?: Record<string, unknown>;
276
+ readonly _callOptions?: Record<string, unknown>;
277
+
278
+ readonly _host: URL;
279
+ readonly _credentials: string | undefined;
280
+ readonly _retryTimes: number; // Retry requests N times before erroring by default
281
+ _isAgent: true;
282
+ }
283
+
284
+ /**
285
+ * A HTTP agent allows users to interact with a client of the internet computer
286
+ using the available methods. It exposes an API that closely follows the
287
+ public view of the internet computer, and is not intended to be exposed
288
+ directly to the majority of users due to its low-level interface.
289
+ * There is a pipeline to apply transformations to the request before sending
290
+ it to the client. This is to decouple signature, nonce generation and
291
+ other computations so that this class can stay as simple as possible while
292
+ allowing extensions.
293
+ */
294
+ export class HttpAgent implements Agent {
295
+ public rootKey: Uint8Array | null;
296
+ #rootKeyPromise: Promise<Uint8Array> | null = null;
297
+ readonly #shouldFetchRootKey: boolean = false;
298
+
299
+ #timeDiffMsecs = DEFAULT_TIME_DIFF_MSECS;
300
+ #hasSyncedTime = false;
301
+ #syncTimePromise: Promise<void> | null = null;
302
+ readonly #shouldSyncTime: boolean = false;
303
+
304
+ #identity: Promise<Identity> | null;
305
+ readonly #fetch: typeof fetch;
306
+ readonly #fetchOptions?: Record<string, unknown>;
307
+ readonly #callOptions?: Record<string, unknown>;
308
+ readonly host: URL;
309
+ readonly #credentials: string | undefined;
310
+ readonly #retryTimes; // Retry requests N times before erroring by default
311
+ #backoffStrategy: BackoffStrategyFactory;
312
+ readonly #maxIngressExpiryInMinutes: number;
313
+ get #maxIngressExpiryInMs(): number {
314
+ return this.#maxIngressExpiryInMinutes * MINUTE_TO_MSECS;
315
+ }
316
+
317
+ // Public signature to help with type checking.
318
+ public readonly _isAgent = true;
319
+ public config: HttpAgentOptions = {};
320
+
321
+ public log: ObservableLog = new ObservableLog();
322
+
323
+ #queryPipeline: HttpAgentRequestTransformFn[] = [];
324
+ #updatePipeline: HttpAgentRequestTransformFn[] = [];
325
+
326
+ #subnetKeys: ExpirableMap<string, SubnetNodeKeys> = new ExpirableMap({
327
+ expirationTime: 5 * MINUTE_TO_MSECS,
328
+ });
329
+ #verifyQuerySignatures = true;
330
+
331
+ /**
332
+ * @param options - Options for the HttpAgent
333
+ * @deprecated Use `HttpAgent.create` or `HttpAgent.createSync` instead
334
+ */
335
+ constructor(options: HttpAgentOptions = {}) {
336
+ this.config = options;
337
+ this.#fetch = options.fetch || getDefaultFetch() || fetch.bind(global);
338
+ this.#fetchOptions = options.fetchOptions;
339
+ this.#callOptions = options.callOptions;
340
+ this.#shouldFetchRootKey = options.shouldFetchRootKey ?? false;
341
+ this.#shouldSyncTime = options.shouldSyncTime ?? false;
342
+
343
+ // Use provided root key, otherwise fall back to IC_ROOT_KEY for mainnet or null if the key needs to be fetched
344
+ if (options.rootKey) {
345
+ this.rootKey = options.rootKey;
346
+ } else if (this.#shouldFetchRootKey) {
347
+ this.rootKey = null;
348
+ } else {
349
+ this.rootKey = hexToBytes(IC_ROOT_KEY);
350
+ }
351
+
352
+ const host = determineHost(options.host);
353
+ this.host = new URL(host);
354
+
355
+ if (options.verifyQuerySignatures !== undefined) {
356
+ this.#verifyQuerySignatures = options.verifyQuerySignatures;
357
+ }
358
+ // Default is 3
359
+ this.#retryTimes = options.retryTimes ?? 3;
360
+ // Delay strategy for retries. Default is exponential backoff
361
+ const defaultBackoffFactory = () =>
362
+ new ExponentialBackoff({
363
+ maxIterations: this.#retryTimes,
364
+ });
365
+ this.#backoffStrategy = options.backoffStrategy || defaultBackoffFactory;
366
+ // Rewrite to avoid redirects
367
+ if (this.host.hostname.endsWith(IC0_SUB_DOMAIN)) {
368
+ this.host.hostname = IC0_DOMAIN;
369
+ } else if (this.host.hostname.endsWith(ICP0_SUB_DOMAIN)) {
370
+ this.host.hostname = ICP0_DOMAIN;
371
+ } else if (this.host.hostname.endsWith(ICP_API_SUB_DOMAIN)) {
372
+ this.host.hostname = ICP_API_DOMAIN;
373
+ }
374
+
375
+ if (options.credentials) {
376
+ const { name, password } = options.credentials;
377
+ this.#credentials = `${name}${password ? ':' + password : ''}`;
378
+ }
379
+ this.#identity = Promise.resolve(options.identity || new AnonymousIdentity());
380
+
381
+ if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes > 5) {
382
+ throw InputError.fromCode(
383
+ new IngressExpiryInvalidErrorCode(
384
+ 'The maximum ingress expiry time is 5 minutes.',
385
+ options.ingressExpiryInMinutes,
386
+ ),
387
+ );
388
+ }
389
+ if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes <= 0) {
390
+ throw InputError.fromCode(
391
+ new IngressExpiryInvalidErrorCode(
392
+ 'Ingress expiry time must be greater than 0.',
393
+ options.ingressExpiryInMinutes,
394
+ ),
395
+ );
396
+ }
397
+
398
+ this.#maxIngressExpiryInMinutes = options.ingressExpiryInMinutes || 5;
399
+
400
+ // Add a nonce transform to ensure calls are unique
401
+ this.addTransform('update', makeNonceTransform(makeNonce));
402
+ if (options.useQueryNonces) {
403
+ this.addTransform('query', makeNonceTransform(makeNonce));
404
+ }
405
+ if (options.logToConsole) {
406
+ this.log.subscribe(log => {
407
+ if (log.level === 'error') {
408
+ console.error(log.message);
409
+ } else if (log.level === 'warn') {
410
+ console.warn(log.message);
411
+ } else {
412
+ console.log(log.message);
413
+ }
414
+ });
415
+ }
416
+ }
417
+
418
+ public static createSync(options: HttpAgentOptions = {}): HttpAgent {
419
+ return new this({ ...options });
420
+ }
421
+
422
+ public static async create(options: HttpAgentOptions = {}): Promise<HttpAgent> {
423
+ const agent = HttpAgent.createSync(options);
424
+ await agent.#asyncGuard();
425
+ return agent;
426
+ }
427
+
428
+ public static async from(
429
+ agent: Pick<HttpAgent, 'config'> | V1HttpAgentInterface,
430
+ ): Promise<HttpAgent> {
431
+ try {
432
+ if ('config' in agent) {
433
+ return await HttpAgent.create(agent.config);
434
+ }
435
+ return await HttpAgent.create({
436
+ fetch: agent._fetch,
437
+ fetchOptions: agent._fetchOptions,
438
+ callOptions: agent._callOptions,
439
+ host: agent._host.toString(),
440
+ identity: agent._identity ?? undefined,
441
+ });
442
+ } catch {
443
+ throw InputError.fromCode(new CreateHttpAgentErrorCode());
444
+ }
445
+ }
446
+
447
+ public isLocal(): boolean {
448
+ const hostname = this.host.hostname;
449
+ return hostname === '127.0.0.1' || hostname.endsWith('127.0.0.1');
450
+ }
451
+
452
+ public addTransform(
453
+ type: 'update' | 'query',
454
+ fn: HttpAgentRequestTransformFn,
455
+ priority = fn.priority || 0,
456
+ ): void {
457
+ if (type === 'update') {
458
+ // Keep the pipeline sorted at all time, by priority.
459
+ const i = this.#updatePipeline.findIndex(x => (x.priority || 0) < priority);
460
+ this.#updatePipeline.splice(
461
+ i >= 0 ? i : this.#updatePipeline.length,
462
+ 0,
463
+ Object.assign(fn, { priority }),
464
+ );
465
+ } else if (type === 'query') {
466
+ // Keep the pipeline sorted at all time, by priority.
467
+ const i = this.#queryPipeline.findIndex(x => (x.priority || 0) < priority);
468
+ this.#queryPipeline.splice(
469
+ i >= 0 ? i : this.#queryPipeline.length,
470
+ 0,
471
+ Object.assign(fn, { priority }),
472
+ );
473
+ }
474
+ }
475
+
476
+ public async getPrincipal(): Promise<Principal> {
477
+ if (!this.#identity) {
478
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
479
+ }
480
+ return (await this.#identity).getPrincipal();
481
+ }
482
+
483
+ /**
484
+ * Makes a call to a canister method.
485
+ * @param canisterId - The ID of the canister to call. Can be a Principal or a string.
486
+ * @param options - Options for the call.
487
+ * @param options.methodName - The name of the method to call.
488
+ * @param options.arg - The argument to pass to the method, as a Uint8Array.
489
+ * @param options.effectiveCanisterId - (Optional) The effective canister ID, if different from the target canister ID.
490
+ * @param options.callSync - (Optional) Whether to use synchronous call mode. Defaults to true.
491
+ * @param options.nonce - (Optional) A unique nonce for the request. If provided, it will override any nonce set by transforms.
492
+ * @param identity - (Optional) The identity to use for the call. If not provided, the agent's current identity will be used.
493
+ * @returns A promise that resolves to the response of the call, including the request ID and response details.
494
+ */
495
+ public async call(
496
+ canisterId: Principal | string,
497
+ options: {
498
+ methodName: string;
499
+ arg: Uint8Array;
500
+ effectiveCanisterId?: Principal | string;
501
+ callSync?: boolean;
502
+ nonce?: Uint8Array | Nonce;
503
+ },
504
+ identity?: Identity | Promise<Identity>,
505
+ ): Promise<SubmitResponse> {
506
+ const callSync = options.callSync ?? true;
507
+ const id = await (identity ?? this.#identity);
508
+ if (!id) {
509
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
510
+ }
511
+ const canister = Principal.from(canisterId);
512
+ const ecid = options.effectiveCanisterId
513
+ ? Principal.from(options.effectiveCanisterId)
514
+ : canister;
515
+ await this.#asyncGuard(ecid);
516
+
517
+ const sender = id.getPrincipal();
518
+
519
+ const ingress_expiry = calculateIngressExpiry(
520
+ this.#maxIngressExpiryInMinutes,
521
+ this.#timeDiffMsecs,
522
+ );
523
+
524
+ const submit: CallRequest = {
525
+ request_type: SubmitRequestType.Call,
526
+ canister_id: canister,
527
+ method_name: options.methodName,
528
+ arg: options.arg,
529
+ sender,
530
+ ingress_expiry,
531
+ };
532
+
533
+ let transformedRequest = (await this._transform({
534
+ request: {
535
+ body: null,
536
+ method: 'POST',
537
+ headers: {
538
+ 'Content-Type': 'application/cbor',
539
+ ...(this.#credentials ? { Authorization: 'Basic ' + btoa(this.#credentials) } : {}),
540
+ },
541
+ },
542
+ endpoint: Endpoint.Call,
543
+ body: submit,
544
+ })) as HttpAgentSubmitRequest;
545
+
546
+ // Determine the nonce to use for the request
547
+ let nonce: Nonce | undefined;
548
+
549
+ // Check if a nonce is provided in the options and convert it to the correct type
550
+ if (options?.nonce) {
551
+ nonce = toNonce(options.nonce);
552
+ }
553
+ // If no nonce is provided in the options, check the transformedRequest body
554
+ else if (transformedRequest.body.nonce) {
555
+ nonce = toNonce(transformedRequest.body.nonce);
556
+ }
557
+ // If no nonce is found, set it to undefined
558
+ else {
559
+ nonce = undefined;
560
+ }
561
+
562
+ // Assign the determined nonce to the submit object
563
+ submit.nonce = nonce;
564
+
565
+ /**
566
+ * Converts a Uint8Array to a Nonce type.
567
+ * @param buf - The buffer to convert.
568
+ * @returns The buffer as a Nonce.
569
+ */
570
+ function toNonce(buf: Uint8Array): Nonce {
571
+ return Object.assign(buf, { __nonce__: undefined });
572
+ }
573
+
574
+ // Apply transform for identity.
575
+ transformedRequest = (await id.transformRequest(transformedRequest)) as HttpAgentSubmitRequest;
576
+
577
+ const body = cbor.encode(transformedRequest.body);
578
+ const backoff = this.#backoffStrategy();
579
+ const requestId = requestIdOf(submit);
580
+ try {
581
+ // Attempt v4 sync call
582
+ const requestSync = () => {
583
+ const url = new URL(`/api/v4/canister/${ecid.toText()}/call`, this.host);
584
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
585
+ return this.#fetch(url, {
586
+ ...this.#callOptions,
587
+ ...transformedRequest.request,
588
+ body,
589
+ });
590
+ };
591
+
592
+ const requestAsync = () => {
593
+ const url = new URL(`/api/v2/canister/${ecid.toText()}/call`, this.host);
594
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
595
+ return this.#fetch(url, {
596
+ ...this.#callOptions,
597
+ ...transformedRequest.request,
598
+ body,
599
+ });
600
+ };
601
+
602
+ const requestFn = callSync ? requestSync : requestAsync;
603
+ const { responseBodyBytes, ...response } = await this.#requestAndRetry({
604
+ requestFn,
605
+ backoff,
606
+ tries: 0,
607
+ });
608
+
609
+ const responseBody = (
610
+ responseBodyBytes.byteLength > 0 ? cbor.decode(responseBodyBytes) : null
611
+ ) as SubmitResponse['response']['body'];
612
+
613
+ return {
614
+ requestId,
615
+ response: {
616
+ ...response,
617
+ body: responseBody,
618
+ },
619
+ requestDetails: submit,
620
+ };
621
+ } catch (error) {
622
+ let callError: AgentError;
623
+ if (error instanceof AgentError) {
624
+ // If the error is due to the v4 api not being supported, fall back to v2
625
+ if (error.hasCode(HttpV4ApiNotSupportedErrorCode)) {
626
+ this.log.warn('v4 api not supported. Fall back to v2');
627
+ return this.call(
628
+ canisterId,
629
+ {
630
+ ...options,
631
+ // disable v4 api
632
+ callSync: false,
633
+ },
634
+ identity,
635
+ );
636
+ } else if (error.hasCode(IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
637
+ // if there is an ingress expiry error and the time has not been synced yet,
638
+ // sync time with the network and try again
639
+ await this.syncTime(canister);
640
+ return this.call(canister, options, identity);
641
+ } else {
642
+ // override the error code to include the request details
643
+ error.code.requestContext = {
644
+ requestId,
645
+ senderPubKey: transformedRequest.body.sender_pubkey,
646
+ senderSignature: transformedRequest.body.sender_sig,
647
+ ingressExpiry: transformedRequest.body.content.ingress_expiry,
648
+ };
649
+ callError = error;
650
+ }
651
+ } else {
652
+ callError = UnknownError.fromCode(new UnexpectedErrorCode(error));
653
+ }
654
+ this.log.error(`Error while making call: ${callError.message}`, callError);
655
+ throw callError;
656
+ }
657
+ }
658
+
659
+ async #requestAndRetryQuery(args: {
660
+ ecid: Principal;
661
+ transformedRequest: HttpAgentRequest;
662
+ body: Uint8Array;
663
+ requestId: RequestId;
664
+ backoff: BackoffStrategy;
665
+ tries: number;
666
+ }): Promise<ApiQueryResponse> {
667
+ const { ecid, transformedRequest, body, requestId, backoff, tries } = args;
668
+
669
+ const delay = tries === 0 ? 0 : backoff.next();
670
+
671
+ const url = new URL(`/api/v3/canister/${ecid.toString()}/query`, this.host);
672
+
673
+ this.log.print(`fetching "${url.pathname}" with tries:`, {
674
+ tries,
675
+ backoff,
676
+ delay,
677
+ });
678
+
679
+ // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason
680
+ if (delay === null) {
681
+ throw UnknownError.fromCode(
682
+ new TimeoutWaitingForResponseErrorCode(
683
+ `Backoff strategy exhausted after ${tries} attempts.`,
684
+ requestId,
685
+ ),
686
+ );
687
+ }
688
+
689
+ if (delay > 0) {
690
+ await new Promise(resolve => setTimeout(resolve, delay));
691
+ }
692
+ let response: ApiQueryResponse;
693
+ // Make the request and retry if it throws an error
694
+ try {
695
+ this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
696
+ const fetchResponse = await this.#fetch(url, {
697
+ ...this.#fetchOptions,
698
+ ...transformedRequest.request,
699
+ body,
700
+ });
701
+ if (fetchResponse.status === HTTP_STATUS_OK) {
702
+ const queryResponse: QueryResponse = cbor.decode(
703
+ uint8FromBufLike(await fetchResponse.arrayBuffer()),
704
+ );
705
+ response = {
706
+ ...queryResponse,
707
+ httpDetails: {
708
+ ok: fetchResponse.ok,
709
+ status: fetchResponse.status,
710
+ statusText: fetchResponse.statusText,
711
+ headers: httpHeadersTransform(fetchResponse.headers),
712
+ },
713
+ requestId,
714
+ };
715
+ } else {
716
+ throw ProtocolError.fromCode(
717
+ new HttpErrorCode(
718
+ fetchResponse.status,
719
+ fetchResponse.statusText,
720
+ httpHeadersTransform(fetchResponse.headers),
721
+ await fetchResponse.text(),
722
+ ),
723
+ );
724
+ }
725
+ } catch (error) {
726
+ if (tries < this.#retryTimes) {
727
+ this.log.warn(
728
+ `Caught exception while attempting to make query:\n` +
729
+ ` ${error}\n` +
730
+ ` Retrying query.`,
731
+ );
732
+ return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
733
+ }
734
+ if (error instanceof AgentError) {
735
+ // if it's an error that we have thrown, just throw it as is
736
+ throw error;
737
+ }
738
+ // if it's an error that we have not thrown, wrap it in a TransportError
739
+ throw TransportError.fromCode(new HttpFetchErrorCode(error));
740
+ }
741
+
742
+ // Skip timestamp verification if the user has set verifyQuerySignatures to false
743
+ if (!this.#verifyQuerySignatures) {
744
+ return response;
745
+ }
746
+
747
+ const signatureTimestampNs = response.signatures?.[0]?.timestamp;
748
+ if (!signatureTimestampNs) {
749
+ throw ProtocolError.fromCode(
750
+ new MalformedSignatureErrorCode(
751
+ 'Timestamp not found in query response. This suggests a malformed or malicious response.',
752
+ ),
753
+ );
754
+ }
755
+
756
+ const signatureTimestampMs = Number(
757
+ BigInt(signatureTimestampNs) / BigInt(MSECS_TO_NANOSECONDS),
758
+ );
759
+ const currentTimestampInMs = Date.now() + this.#timeDiffMsecs;
760
+
761
+ // We don't need `Math.abs` here because we allow signatures in the future
762
+ if (currentTimestampInMs - signatureTimestampMs > this.#maxIngressExpiryInMs) {
763
+ if (tries < this.#retryTimes) {
764
+ this.log.warn('Timestamp is older than the max ingress expiry. Retrying query.', {
765
+ requestId,
766
+ signatureTimestampMs,
767
+ });
768
+ return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
769
+ }
770
+ throw TrustError.fromCode(
771
+ new CertificateOutdatedErrorCode(this.#maxIngressExpiryInMinutes, requestId, tries),
772
+ );
773
+ }
774
+
775
+ return response;
776
+ }
777
+
778
+ /**
779
+ * Makes a request and retries if it fails.
780
+ * @param args - The arguments for the request.
781
+ * @param args.requestFn - A function that returns a Promise resolving to a Response.
782
+ * @param args.backoff - The backoff strategy to use for retries.
783
+ * @param args.tries - The number of retry attempts made so far.
784
+ * @returns The response from the request, if the status is 200 or 202.
785
+ * See the https://internetcomputer.org/docs/references/ic-interface-spec#http-interface for details on the response statuses.
786
+ * @throws {ProtocolError} if the response status is not 200 or 202, and the retry limit has been reached.
787
+ * @throws {TransportError} if the request fails, and the retry limit has been reached.
788
+ */
789
+ async #requestAndRetry(args: {
790
+ requestFn: () => Promise<Response>;
791
+ backoff: BackoffStrategy;
792
+ tries: number;
793
+ }): Promise<{
794
+ ok: boolean;
795
+ status: number;
796
+ statusText: string;
797
+ responseBodyBytes: Uint8Array;
798
+ headers: HttpHeaderField[];
799
+ }> {
800
+ const { requestFn, backoff, tries } = args;
801
+ const delay = tries === 0 ? 0 : backoff.next();
802
+
803
+ // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason
804
+ if (delay === null) {
805
+ throw ProtocolError.fromCode(
806
+ new TimeoutWaitingForResponseErrorCode(`Retry strategy exhausted after ${tries} attempts.`),
807
+ );
808
+ }
809
+
810
+ if (delay > 0) {
811
+ await new Promise(resolve => setTimeout(resolve, delay));
812
+ }
813
+
814
+ let response: Response;
815
+ let responseBodyBytes = new Uint8Array();
816
+ try {
817
+ response = await requestFn();
818
+ // According to the spec, only 200 responses have a non-empty body
819
+ if (response.status === HTTP_STATUS_OK) {
820
+ // Consume the response body, to ensure that the response is not closed unexpectedly
821
+ responseBodyBytes = uint8FromBufLike(await response.clone().arrayBuffer());
822
+ }
823
+ } catch (error) {
824
+ if (tries < this.#retryTimes) {
825
+ this.log.warn(
826
+ `Caught exception while attempting to make request:\n` +
827
+ ` ${error}\n` +
828
+ ` Retrying request.`,
829
+ );
830
+ // Delay the request by the configured backoff strategy
831
+ return await this.#requestAndRetry({ requestFn, backoff, tries: tries + 1 });
832
+ }
833
+ throw TransportError.fromCode(new HttpFetchErrorCode(error));
834
+ }
835
+
836
+ const headers = httpHeadersTransform(response.headers);
837
+
838
+ if (response.status === HTTP_STATUS_OK || response.status === HTTP_STATUS_ACCEPTED) {
839
+ return {
840
+ ok: response.ok, // should always be true
841
+ status: response.status,
842
+ statusText: response.statusText,
843
+ responseBodyBytes,
844
+ headers,
845
+ };
846
+ }
847
+
848
+ const responseText = await response.text();
849
+
850
+ if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/v4')) {
851
+ throw ProtocolError.fromCode(new HttpV4ApiNotSupportedErrorCode());
852
+ }
853
+
854
+ // The error message comes from https://github.com/dfinity/ic/blob/23d5990bfc5277c32e54f0087b5a38fa412171e1/rs/validator/src/ingress_validation.rs#L233
855
+ if (responseText.startsWith('Invalid request expiry: ')) {
856
+ throw InputError.fromCode(
857
+ new IngressExpiryInvalidErrorCode(responseText, this.#maxIngressExpiryInMinutes),
858
+ );
859
+ }
860
+
861
+ if (tries < this.#retryTimes) {
862
+ return await this.#requestAndRetry({ requestFn, backoff, tries: tries + 1 });
863
+ }
864
+
865
+ throw ProtocolError.fromCode(
866
+ new HttpErrorCode(response.status, response.statusText, headers, responseText),
867
+ );
868
+ }
869
+
870
+ public async query(
871
+ canisterId: Principal | string,
872
+ fields: QueryFields,
873
+ identity?: Identity | Promise<Identity>,
874
+ ): Promise<ApiQueryResponse> {
875
+ const backoff = this.#backoffStrategy();
876
+ const ecid = fields.effectiveCanisterId
877
+ ? Principal.from(fields.effectiveCanisterId)
878
+ : Principal.from(canisterId);
879
+ await this.#asyncGuard(ecid);
880
+
881
+ this.log.print(`ecid ${ecid.toString()}`);
882
+ this.log.print(`canisterId ${canisterId.toString()}`);
883
+
884
+ let transformedRequest: HttpAgentRequest | undefined;
885
+ const id = await (identity ?? this.#identity);
886
+ if (!id) {
887
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
888
+ }
889
+
890
+ const canister = Principal.from(canisterId);
891
+ const sender = id.getPrincipal();
892
+ const ingressExpiry = calculateIngressExpiry(
893
+ this.#maxIngressExpiryInMinutes,
894
+ this.#timeDiffMsecs,
895
+ );
896
+
897
+ const request: QueryRequest = {
898
+ request_type: ReadRequestType.Query,
899
+ canister_id: canister,
900
+ method_name: fields.methodName,
901
+ arg: fields.arg,
902
+ sender,
903
+ ingress_expiry: ingressExpiry,
904
+ };
905
+
906
+ const requestId = requestIdOf(request);
907
+
908
+ transformedRequest = await this._transform({
909
+ request: {
910
+ method: 'POST',
911
+ headers: {
912
+ 'Content-Type': 'application/cbor',
913
+ ...(this.#credentials ? { Authorization: 'Basic ' + btoa(this.#credentials) } : {}),
914
+ },
915
+ },
916
+ endpoint: Endpoint.Query,
917
+ body: request,
918
+ });
919
+
920
+ // Apply transform for identity.
921
+ transformedRequest = (await id.transformRequest(transformedRequest)) as HttpAgentRequest;
922
+
923
+ const body = cbor.encode(transformedRequest.body);
924
+
925
+ const args = {
926
+ canister: canister.toText(),
927
+ ecid,
928
+ transformedRequest,
929
+ body,
930
+ requestId,
931
+ backoff,
932
+ tries: 0,
933
+ };
934
+
935
+ const makeQuery = async () => {
936
+ // Attempt to make the query i=retryTimes times
937
+ const query = await this.#requestAndRetryQuery(args);
938
+ return {
939
+ requestDetails: request,
940
+ ...query,
941
+ };
942
+ };
943
+
944
+ const getSubnetNodeKeys = async (): Promise<SubnetNodeKeys> => {
945
+ const cachedSubnetNodeKeys = this.#subnetKeys.get(ecid.toString());
946
+ if (cachedSubnetNodeKeys) {
947
+ return cachedSubnetNodeKeys;
948
+ }
949
+ await this.fetchSubnetKeys(ecid.toString());
950
+ const subnetNodeKeys = this.#subnetKeys.get(ecid.toString());
951
+ if (!subnetNodeKeys) {
952
+ throw TrustError.fromCode(new MissingSignatureErrorCode());
953
+ }
954
+ return subnetNodeKeys;
955
+ };
956
+
957
+ try {
958
+ if (!this.#verifyQuerySignatures) {
959
+ // Skip verification if the user has disabled it
960
+ return await makeQuery();
961
+ }
962
+
963
+ // Make query and fetch subnet keys in parallel
964
+ const [queryWithDetails, subnetNodeKeys] = await Promise.all([
965
+ makeQuery(),
966
+ getSubnetNodeKeys(),
967
+ ]);
968
+
969
+ try {
970
+ return this.#verifyQueryResponse(queryWithDetails, subnetNodeKeys);
971
+ } catch {
972
+ // In case the node signatures have changed, refresh the subnet keys and try again
973
+ this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');
974
+ this.#subnetKeys.delete(ecid.toString());
975
+ const updatedSubnetNodeKeys = await getSubnetNodeKeys();
976
+ return this.#verifyQueryResponse(queryWithDetails, updatedSubnetNodeKeys);
977
+ }
978
+ } catch (error) {
979
+ let queryError: AgentError;
980
+ if (error instanceof AgentError) {
981
+ // override the error code to include the request details
982
+ error.code.requestContext = {
983
+ requestId,
984
+ senderPubKey: transformedRequest.body.sender_pubkey,
985
+ senderSignature: transformedRequest.body.sender_sig,
986
+ ingressExpiry: transformedRequest.body.content.ingress_expiry,
987
+ };
988
+ queryError = error;
989
+ } else {
990
+ queryError = UnknownError.fromCode(new UnexpectedErrorCode(error));
991
+ }
992
+ this.log.error(`Error while making query: ${queryError.message}`, queryError);
993
+ throw queryError;
994
+ }
995
+ }
996
+
997
+ /**
998
+ * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation
999
+ * @param queryResponse - The response from the query
1000
+ * @param subnetNodeKeys - The subnet node keys
1001
+ * @returns ApiQueryResponse
1002
+ */
1003
+ #verifyQueryResponse = (
1004
+ queryResponse: ApiQueryResponse,
1005
+ subnetNodeKeys: SubnetNodeKeys,
1006
+ ): ApiQueryResponse => {
1007
+ if (this.#verifyQuerySignatures === false) {
1008
+ // This should not be called if the user has disabled verification
1009
+ return queryResponse;
1010
+ }
1011
+ const { status, signatures = [], requestId } = queryResponse;
1012
+
1013
+ for (const sig of signatures) {
1014
+ const { timestamp, identity } = sig;
1015
+ const nodeId = Principal.fromUint8Array(identity).toText();
1016
+
1017
+ // Hash is constructed differently depending on the status
1018
+ let hash: Uint8Array;
1019
+ if (status === QueryResponseStatus.Replied) {
1020
+ const { reply } = queryResponse;
1021
+ hash = hashOfMap({
1022
+ status: status,
1023
+ reply: reply,
1024
+ timestamp: BigInt(timestamp),
1025
+ request_id: requestId,
1026
+ });
1027
+ } else if (status === QueryResponseStatus.Rejected) {
1028
+ const { reject_code, reject_message, error_code } = queryResponse;
1029
+ hash = hashOfMap({
1030
+ status: status,
1031
+ reject_code: reject_code,
1032
+ reject_message: reject_message,
1033
+ error_code: error_code,
1034
+ timestamp: BigInt(timestamp),
1035
+ request_id: requestId,
1036
+ });
1037
+ } else {
1038
+ throw UnknownError.fromCode(new UnexpectedErrorCode(`Unknown status: ${status}`));
1039
+ }
1040
+
1041
+ const separatorWithHash = concatBytes(IC_RESPONSE_DOMAIN_SEPARATOR, hash);
1042
+
1043
+ // FIX: check for match without verifying N times
1044
+ const pubKey = subnetNodeKeys.get(nodeId);
1045
+ if (!pubKey) {
1046
+ throw ProtocolError.fromCode(new MalformedPublicKeyErrorCode());
1047
+ }
1048
+ const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;
1049
+ const valid = ed25519.verify(sig.signature, separatorWithHash, rawKey);
1050
+ if (valid) return queryResponse;
1051
+
1052
+ throw TrustError.fromCode(new QuerySignatureVerificationFailedErrorCode(nodeId));
1053
+ }
1054
+ return queryResponse;
1055
+ };
1056
+
1057
+ public async createReadStateRequest(
1058
+ fields: ReadStateOptions,
1059
+ identity?: Identity | Promise<Identity>,
1060
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1061
+ ): Promise<any> {
1062
+ await this.#asyncGuard();
1063
+ const id = await (identity ?? this.#identity);
1064
+ if (!id) {
1065
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
1066
+ }
1067
+ const sender = id.getPrincipal();
1068
+
1069
+ const transformedRequest = await this._transform({
1070
+ request: {
1071
+ method: 'POST',
1072
+ headers: {
1073
+ 'Content-Type': 'application/cbor',
1074
+ ...(this.#credentials ? { Authorization: 'Basic ' + btoa(this.#credentials) } : {}),
1075
+ },
1076
+ },
1077
+ endpoint: Endpoint.ReadState,
1078
+ body: {
1079
+ request_type: ReadRequestType.ReadState,
1080
+ paths: fields.paths,
1081
+ sender,
1082
+ ingress_expiry: calculateIngressExpiry(
1083
+ this.#maxIngressExpiryInMinutes,
1084
+ this.#timeDiffMsecs,
1085
+ ),
1086
+ },
1087
+ });
1088
+
1089
+ // Apply transform for identity.
1090
+ return id.transformRequest(transformedRequest);
1091
+ }
1092
+
1093
+ public async readState(
1094
+ canisterId: Principal | string,
1095
+ fields: ReadStateOptions,
1096
+ _identity?: Identity | Promise<Identity>,
1097
+ // eslint-disable-next-line
1098
+ request?: any,
1099
+ ): Promise<ReadStateResponse> {
1100
+ await this.#rootKeyGuard();
1101
+ const canister = Principal.from(canisterId);
1102
+
1103
+ function getRequestId(options: ReadStateOptions): RequestId | undefined {
1104
+ for (const path of options.paths) {
1105
+ const [pathName, value] = path;
1106
+ const request_status = new TextEncoder().encode('request_status');
1107
+ if (uint8Equals(pathName, request_status)) {
1108
+ return value as RequestId;
1109
+ }
1110
+ }
1111
+ }
1112
+
1113
+ let transformedRequest: ReadStateRequest;
1114
+ let requestId: RequestId | undefined;
1115
+
1116
+ // If a pre-signed request is provided, use it
1117
+ if (request) {
1118
+ // This is a pre-signed request
1119
+ transformedRequest = request;
1120
+ } else {
1121
+ // This is fields, we need to create a request
1122
+ requestId = getRequestId(fields);
1123
+
1124
+ // Always create a fresh request with the current identity
1125
+ const identity = await this.#identity;
1126
+ if (!identity) {
1127
+ throw ExternalError.fromCode(new IdentityInvalidErrorCode());
1128
+ }
1129
+ transformedRequest = await this.createReadStateRequest(fields, identity);
1130
+ }
1131
+
1132
+ const url = new URL(`/api/v3/canister/${canister.toString()}/read_state`, this.host);
1133
+
1134
+ return await this.#readStateInner(url, transformedRequest, requestId);
1135
+ }
1136
+
1137
+ /**
1138
+ * Reads the state of a subnet from the `/api/v3/subnet/{subnetId}/read_state` endpoint.
1139
+ * @param subnetId The ID of the subnet to read the state of. If you have a canister ID, you can use {@link HttpAgent.getSubnetIdFromCanister | getSubnetIdFromCanister} to get the subnet ID.
1140
+ * @param options The options for the read state request.
1141
+ * @returns The response from the read state request.
1142
+ */
1143
+ public async readSubnetState(
1144
+ subnetId: Principal | string,
1145
+ options: ReadStateOptions,
1146
+ ): Promise<ReadStateResponse> {
1147
+ await this.#rootKeyGuard();
1148
+
1149
+ const url = new URL(`/api/v3/subnet/${subnetId.toString()}/read_state`, this.host);
1150
+ const transformedRequest: ReadStateRequest = await this.createReadStateRequest(
1151
+ options,
1152
+ this.#identity ?? undefined,
1153
+ );
1154
+
1155
+ return await this.#readStateInner(url, transformedRequest);
1156
+ }
1157
+
1158
+ async #readStateInner(
1159
+ url: URL,
1160
+ transformedRequest: ReadStateRequest,
1161
+ requestId?: RequestId,
1162
+ ): Promise<ReadStateResponse> {
1163
+ const backoff = this.#backoffStrategy();
1164
+ try {
1165
+ const { responseBodyBytes } = await this.#requestAndRetry({
1166
+ requestFn: () =>
1167
+ this.#fetch(url, {
1168
+ ...this.#fetchOptions,
1169
+ ...transformedRequest.request,
1170
+ body: cbor.encode(transformedRequest.body),
1171
+ }),
1172
+ backoff,
1173
+ tries: 0,
1174
+ });
1175
+
1176
+ const decodedResponse: ReadStateResponse = cbor.decode(responseBodyBytes);
1177
+
1178
+ return decodedResponse;
1179
+ } catch (error) {
1180
+ let readStateError: AgentError;
1181
+ if (error instanceof AgentError) {
1182
+ // override the error code to include the request details
1183
+ error.code.requestContext = {
1184
+ requestId: requestId ?? requestIdOf(transformedRequest),
1185
+ senderPubKey: transformedRequest.body.sender_pubkey,
1186
+ senderSignature: transformedRequest.body.sender_sig,
1187
+ ingressExpiry: transformedRequest.body.content.ingress_expiry,
1188
+ };
1189
+ readStateError = error;
1190
+ } else {
1191
+ readStateError = UnknownError.fromCode(new UnexpectedErrorCode(error));
1192
+ }
1193
+ this.log.error(`Error while making read state: ${readStateError.message}`, readStateError);
1194
+ throw readStateError;
1195
+ }
1196
+ }
1197
+
1198
+ public parseTimeFromResponse(response: { certificate: Uint8Array }): number {
1199
+ let tree: HashTree;
1200
+ if (response.certificate) {
1201
+ const decoded = cbor.decode<{ tree: HashTree } | undefined>(response.certificate);
1202
+ if (decoded && 'tree' in decoded) {
1203
+ tree = decoded.tree;
1204
+ } else {
1205
+ throw ProtocolError.fromCode(
1206
+ new HashTreeDecodeErrorCode('Could not decode time from response'),
1207
+ );
1208
+ }
1209
+ const timeLookup = lookup_path(['time'], tree);
1210
+ if (timeLookup.status !== LookupPathStatus.Found) {
1211
+ throw ProtocolError.fromCode(
1212
+ new LookupErrorCode(
1213
+ 'Time was not found in the response or was not in its expected format.',
1214
+ timeLookup.status,
1215
+ ),
1216
+ );
1217
+ }
1218
+
1219
+ if (!(timeLookup.value instanceof Uint8Array) && !ArrayBuffer.isView(timeLookup)) {
1220
+ throw ProtocolError.fromCode(
1221
+ new MalformedLookupFoundValueErrorCode('Time was not in its expected format.'),
1222
+ );
1223
+ }
1224
+ const date = decodeTime(timeLookup.value);
1225
+ this.log.print('Time from response:', date);
1226
+ this.log.print('Time from response in milliseconds:', date.getTime());
1227
+ return date.getTime();
1228
+ } else {
1229
+ this.log.warn('No certificate found in response');
1230
+ }
1231
+ return 0;
1232
+ }
1233
+
1234
+ /**
1235
+ * Allows agent to sync its time with the network. Can be called during initialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request
1236
+ * @param {Principal} canisterIdOverride - Pass a canister ID if you need to sync the time with a particular subnet. Uses the ICP ledger canister by default.
1237
+ */
1238
+ public async syncTime(canisterIdOverride?: Principal): Promise<void> {
1239
+ this.#syncTimePromise =
1240
+ this.#syncTimePromise ??
1241
+ (async () => {
1242
+ await this.#rootKeyGuard();
1243
+ const callTime = Date.now();
1244
+ try {
1245
+ if (!canisterIdOverride) {
1246
+ this.log.print(
1247
+ 'Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai',
1248
+ );
1249
+ }
1250
+ // Fall back with canisterId of the ICP Ledger
1251
+ const canisterId = canisterIdOverride ?? Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai');
1252
+
1253
+ const anonymousAgent = HttpAgent.createSync({
1254
+ identity: new AnonymousIdentity(),
1255
+ host: this.host.toString(),
1256
+ fetch: this.#fetch,
1257
+ retryTimes: 0,
1258
+ rootKey: this.rootKey ?? undefined,
1259
+ shouldSyncTime: false,
1260
+ });
1261
+
1262
+ const replicaTimes = await Promise.all(
1263
+ Array(3)
1264
+ .fill(null)
1265
+ .map(async () => {
1266
+ const status = await canisterStatusRequest({
1267
+ canisterId,
1268
+ agent: anonymousAgent,
1269
+ paths: ['time'],
1270
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1271
+ });
1272
+
1273
+ const date = status.get('time');
1274
+ if (date instanceof Date) {
1275
+ return date.getTime();
1276
+ }
1277
+ }, []),
1278
+ );
1279
+
1280
+ this.#setTimeDiffMsecs(callTime, replicaTimes);
1281
+ } catch (error) {
1282
+ const syncTimeError =
1283
+ error instanceof AgentError
1284
+ ? error
1285
+ : UnknownError.fromCode(new UnexpectedErrorCode(error));
1286
+ this.log.error('Caught exception while attempting to sync time', syncTimeError);
1287
+
1288
+ throw syncTimeError;
1289
+ }
1290
+ })();
1291
+
1292
+ await this.#syncTimePromise.finally(() => {
1293
+ this.#syncTimePromise = null;
1294
+ });
1295
+ }
1296
+
1297
+ /**
1298
+ * Allows agent to sync its time with the network.
1299
+ * @param {Principal} subnetId - Pass the subnet ID you need to sync the time with.
1300
+ */
1301
+ public async syncTimeWithSubnet(subnetId: Principal): Promise<void> {
1302
+ await this.#rootKeyGuard();
1303
+ const callTime = Date.now();
1304
+
1305
+ try {
1306
+ const anonymousAgent = HttpAgent.createSync({
1307
+ identity: new AnonymousIdentity(),
1308
+ host: this.host.toString(),
1309
+ fetch: this.#fetch,
1310
+ retryTimes: 0,
1311
+ rootKey: this.rootKey ?? undefined,
1312
+ shouldSyncTime: false,
1313
+ });
1314
+
1315
+ const replicaTimes = await Promise.all(
1316
+ Array(3)
1317
+ .fill(null)
1318
+ .map(async () => {
1319
+ const status = await subnetStatusRequest({
1320
+ subnetId,
1321
+ agent: anonymousAgent,
1322
+ paths: ['time'],
1323
+ disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
1324
+ });
1325
+
1326
+ const date = status.get('time');
1327
+ if (date instanceof Date) {
1328
+ return date.getTime();
1329
+ }
1330
+ }, []),
1331
+ );
1332
+
1333
+ this.#setTimeDiffMsecs(callTime, replicaTimes);
1334
+ } catch (error) {
1335
+ const syncTimeError =
1336
+ error instanceof AgentError ? error : UnknownError.fromCode(new UnexpectedErrorCode(error));
1337
+ this.log.error('Caught exception while attempting to sync time with subnet', syncTimeError);
1338
+
1339
+ throw syncTimeError;
1340
+ }
1341
+ }
1342
+
1343
+ #setTimeDiffMsecs(callTime: number, replicaTimes: Array<number | undefined>): void {
1344
+ const maxReplicaTime = replicaTimes.reduce<number>((max, current) => {
1345
+ return typeof current === 'number' && current > max ? current : max;
1346
+ }, 0);
1347
+
1348
+ if (maxReplicaTime > 0) {
1349
+ this.#timeDiffMsecs = maxReplicaTime - callTime;
1350
+ this.#hasSyncedTime = true;
1351
+ this.log.notify({
1352
+ message: `Syncing time: offset of ${this.#timeDiffMsecs}`,
1353
+ level: 'info',
1354
+ });
1355
+ }
1356
+ }
1357
+
1358
+ public async status(): Promise<JsonObject> {
1359
+ const headers: Record<string, string> = this.#credentials
1360
+ ? {
1361
+ Authorization: 'Basic ' + btoa(this.#credentials),
1362
+ }
1363
+ : {};
1364
+
1365
+ const url = new URL(`/api/v2/status`, this.host);
1366
+
1367
+ this.log.print(`fetching "${url.pathname}"`);
1368
+ const backoff = this.#backoffStrategy();
1369
+ const { responseBodyBytes } = await this.#requestAndRetry({
1370
+ backoff,
1371
+ requestFn: () => this.#fetch(url, { headers, ...this.#fetchOptions }),
1372
+ tries: 0,
1373
+ });
1374
+ return cbor.decode(responseBodyBytes);
1375
+ }
1376
+
1377
+ public async fetchRootKey(): Promise<Uint8Array> {
1378
+ // Wait for already pending promise to avoid duplicate calls
1379
+ this.#rootKeyPromise =
1380
+ this.#rootKeyPromise ??
1381
+ (async () => {
1382
+ const value = await this.status();
1383
+ // Hex-encoded version of the replica root key
1384
+ this.rootKey = (value as JsonObject & { root_key: Uint8Array }).root_key;
1385
+ return this.rootKey;
1386
+ })();
1387
+
1388
+ // clear rootkey promise and return result
1389
+ return await this.#rootKeyPromise.finally(() => {
1390
+ this.#rootKeyPromise = null;
1391
+ });
1392
+ }
1393
+
1394
+ async #asyncGuard(canisterIdOverride?: Principal): Promise<void> {
1395
+ await Promise.all([this.#rootKeyGuard(), this.#syncTimeGuard(canisterIdOverride)]);
1396
+ }
1397
+
1398
+ async #rootKeyGuard(): Promise<void> {
1399
+ if (this.rootKey) {
1400
+ return;
1401
+ } else if (
1402
+ this.rootKey === null &&
1403
+ this.host.toString() !== 'https://icp-api.io' &&
1404
+ this.#shouldFetchRootKey
1405
+ ) {
1406
+ await this.fetchRootKey();
1407
+ } else {
1408
+ throw ExternalError.fromCode(new MissingRootKeyErrorCode(this.#shouldFetchRootKey));
1409
+ }
1410
+ }
1411
+
1412
+ async #syncTimeGuard(canisterIdOverride?: Principal): Promise<void> {
1413
+ if (this.#shouldSyncTime && !this.hasSyncedTime()) {
1414
+ await this.syncTime(canisterIdOverride);
1415
+ }
1416
+ }
1417
+
1418
+ public invalidateIdentity(): void {
1419
+ this.#identity = null;
1420
+ }
1421
+
1422
+ public replaceIdentity(identity: Identity): void {
1423
+ this.#identity = Promise.resolve(identity);
1424
+ }
1425
+
1426
+ public async fetchSubnetKeys(canisterId: Principal | string): Promise<SubnetNodeKeys> {
1427
+ const effectiveCanisterId: Principal = Principal.from(canisterId);
1428
+ await this.#asyncGuard(effectiveCanisterId);
1429
+
1430
+ const rootKey = this.rootKey!;
1431
+
1432
+ const canisterReadState = await this.readState(effectiveCanisterId, {
1433
+ paths: [[utf8ToBytes('subnet')]],
1434
+ });
1435
+ const canisterCertificate = await Certificate.create({
1436
+ certificate: canisterReadState.certificate,
1437
+ rootKey,
1438
+ principal: { canisterId: effectiveCanisterId },
1439
+ agent: this,
1440
+ });
1441
+
1442
+ const subnetId = getSubnetIdFromCertificate(canisterCertificate.cert, rootKey);
1443
+ const nodeKeys = lookupNodeKeysFromCertificate(canisterCertificate.cert, subnetId);
1444
+ this.#subnetKeys.set(effectiveCanisterId.toText(), nodeKeys);
1445
+
1446
+ return nodeKeys;
1447
+ }
1448
+
1449
+ /**
1450
+ * Returns the subnet ID for a given canister ID, by looking at the certificate delegation
1451
+ * returned by the canister's state obtained by requesting the `/time` path with {@link HttpAgent.readState | readState}.
1452
+ * @param canisterId The canister ID to get the subnet ID for.
1453
+ * @returns The subnet ID for the given canister ID.
1454
+ */
1455
+ public async getSubnetIdFromCanister(canisterId: Principal | string): Promise<Principal> {
1456
+ const effectiveCanisterId = Principal.from(canisterId);
1457
+ await this.#asyncGuard(effectiveCanisterId);
1458
+
1459
+ const canisterReadState = await this.readState(effectiveCanisterId, {
1460
+ paths: [[utf8ToBytes('time')]],
1461
+ });
1462
+ const canisterCertificate = await Certificate.create({
1463
+ certificate: canisterReadState.certificate,
1464
+ rootKey: this.rootKey!,
1465
+ principal: { canisterId: effectiveCanisterId },
1466
+ agent: this,
1467
+ });
1468
+
1469
+ return getSubnetIdFromCertificate(canisterCertificate.cert, this.rootKey!);
1470
+ }
1471
+
1472
+ protected _transform(request: HttpAgentRequest): Promise<HttpAgentRequest> {
1473
+ let p = Promise.resolve(request);
1474
+ if (request.endpoint === Endpoint.Call) {
1475
+ for (const fn of this.#updatePipeline) {
1476
+ p = p.then(r => fn(r).then(r2 => r2 || r));
1477
+ }
1478
+ } else {
1479
+ for (const fn of this.#queryPipeline) {
1480
+ p = p.then(r => fn(r).then(r2 => r2 || r));
1481
+ }
1482
+ }
1483
+
1484
+ return p;
1485
+ }
1486
+
1487
+ /**
1488
+ * Returns the time difference in milliseconds between the IC network clock and the client's clock,
1489
+ * after the clock has been synced.
1490
+ *
1491
+ * If the time has not been synced, returns `0`.
1492
+ */
1493
+ public getTimeDiffMsecs(): number {
1494
+ return this.#timeDiffMsecs;
1495
+ }
1496
+
1497
+ /**
1498
+ * Returns `true` if the time has been synced at least once with the IC network, `false` otherwise.
1499
+ */
1500
+ public hasSyncedTime(): boolean {
1501
+ return this.#hasSyncedTime;
1502
+ }
1503
+ }
1504
+
1505
+ /**
1506
+ * Calculates the ingress expiry time based on the maximum allowed expiry in minutes and the time difference in milliseconds.
1507
+ * The expiry is rounded down according to the {@link Expiry.fromDeltaInMilliseconds} method.
1508
+ * @param maxIngressExpiryInMinutes - The maximum ingress expiry time in minutes.
1509
+ * @param timeDiffMsecs - The time difference in milliseconds to adjust the expiry.
1510
+ * @returns The calculated ingress expiry as an Expiry object.
1511
+ */
1512
+ export function calculateIngressExpiry(
1513
+ maxIngressExpiryInMinutes: number,
1514
+ timeDiffMsecs: number,
1515
+ ): Expiry {
1516
+ const ingressExpiryMs = maxIngressExpiryInMinutes * MINUTE_TO_MSECS;
1517
+ return Expiry.fromDeltaInMilliseconds(ingressExpiryMs, timeDiffMsecs);
1518
+ }