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