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