tenjin-cli 0.1.0-alpha.14 → 0.1.0-alpha.16

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 (253) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +41 -295
  3. package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
  5. package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
  6. package/dist/chunk-25TJPVBF.js +353 -0
  7. package/dist/chunk-25TJPVBF.js.map +1 -0
  8. package/dist/chunk-2BKS2FVE.js +93 -0
  9. package/dist/chunk-2BKS2FVE.js.map +1 -0
  10. package/dist/chunk-2QYORQBF.js +55 -0
  11. package/dist/chunk-2QYORQBF.js.map +1 -0
  12. package/dist/{chunk-ACBEHJAH.js → chunk-2U5ZVEV3.js} +14 -16
  13. package/dist/chunk-2U5ZVEV3.js.map +1 -0
  14. package/dist/{chunk-MJSXP4LW.js → chunk-3AJS6LLN.js} +11 -8
  15. package/dist/chunk-3AJS6LLN.js.map +1 -0
  16. package/dist/{chunk-OWVVI4VQ.js → chunk-3AUDA53C.js} +7650 -7361
  17. package/dist/chunk-3AUDA53C.js.map +1 -0
  18. package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
  19. package/dist/chunk-56MOAIP5.js.map +1 -0
  20. package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
  21. package/dist/chunk-5X4SZ5BF.js +227 -0
  22. package/dist/chunk-5X4SZ5BF.js.map +1 -0
  23. package/dist/chunk-7WEQQJLG.js +68 -0
  24. package/dist/chunk-7WEQQJLG.js.map +1 -0
  25. package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
  26. package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
  27. package/dist/{chunk-PAOVPSP6.js → chunk-BBVUVBUO.js} +517 -138
  28. package/dist/chunk-BBVUVBUO.js.map +1 -0
  29. package/dist/{chunk-ETKZWJ4B.js → chunk-BFFM2WFK.js} +8 -8
  30. package/dist/chunk-BFFM2WFK.js.map +1 -0
  31. package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
  32. package/dist/chunk-DMZZLPZN.js +205 -0
  33. package/dist/chunk-DMZZLPZN.js.map +1 -0
  34. package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
  35. package/dist/chunk-EGELTSPU.js.map +1 -0
  36. package/dist/chunk-GULLJQXA.js +698 -0
  37. package/dist/chunk-GULLJQXA.js.map +1 -0
  38. package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-HVRC33OL.js +174 -0
  40. package/dist/chunk-HVRC33OL.js.map +1 -0
  41. package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
  42. package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
  43. package/dist/chunk-L3PVMIYQ.js +10328 -0
  44. package/dist/chunk-L3PVMIYQ.js.map +1 -0
  45. package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
  46. package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
  47. package/dist/chunk-MEFB5KHA.js.map +1 -0
  48. package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
  49. package/dist/chunk-N35E6CM2.js.map +1 -0
  50. package/dist/chunk-OCBHUHWB.js +69 -0
  51. package/dist/chunk-OCBHUHWB.js.map +1 -0
  52. package/dist/chunk-OIM4HLN6.js +1405 -0
  53. package/dist/chunk-OIM4HLN6.js.map +1 -0
  54. package/dist/{chunk-PKW3H26Z.js → chunk-OJLYNM4Z.js} +56 -33
  55. package/dist/chunk-OJLYNM4Z.js.map +1 -0
  56. package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
  57. package/dist/chunk-PZEN5PHN.js +285 -0
  58. package/dist/chunk-PZEN5PHN.js.map +1 -0
  59. package/dist/chunk-SKAHDQH7.js +1785 -0
  60. package/dist/chunk-SKAHDQH7.js.map +1 -0
  61. package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
  62. package/dist/{chunk-QWBUKIP2.js → chunk-U5DXNFJC.js} +23 -94
  63. package/dist/chunk-U5DXNFJC.js.map +1 -0
  64. package/dist/chunk-USS336NF.js +165 -0
  65. package/dist/chunk-USS336NF.js.map +1 -0
  66. package/dist/{chunk-UO22YNY4.js → chunk-WH7OWT6G.js} +49 -1
  67. package/dist/chunk-WH7OWT6G.js.map +1 -0
  68. package/dist/chunk-WXC57XGG.js +29 -0
  69. package/dist/chunk-WXC57XGG.js.map +1 -0
  70. package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
  71. package/dist/{chunk-7GJQ5RGA.js → chunk-YEETV6IW.js} +1077 -1039
  72. package/dist/chunk-YEETV6IW.js.map +1 -0
  73. package/dist/{chunk-B676GPS2.js → chunk-YJHHCWM3.js} +39 -16
  74. package/dist/chunk-YJHHCWM3.js.map +1 -0
  75. package/dist/{cli-U2BEUA55.js → cli-M3XCSOU6.js} +295 -349
  76. package/dist/cli-M3XCSOU6.js.map +1 -0
  77. package/dist/config-MXOX7XDR.js +41 -0
  78. package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
  79. package/dist/doctor-LU4YIZWM.js +349 -0
  80. package/dist/doctor-LU4YIZWM.js.map +1 -0
  81. package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  82. package/dist/{chunk-3ZW7HPY5.js → fund-A54P2QFK.js} +81 -22
  83. package/dist/fund-A54P2QFK.js.map +1 -0
  84. package/dist/hook-command-U6KWPEDQ.js +377 -0
  85. package/dist/hook-command-U6KWPEDQ.js.map +1 -0
  86. package/dist/index.js +8 -3
  87. package/dist/index.js.map +1 -1
  88. package/dist/install-XUM2XSHW.js +53 -0
  89. package/dist/install-wallet-QIOFORTX.js +105 -0
  90. package/dist/install-wallet-QIOFORTX.js.map +1 -0
  91. package/dist/{run-CJWPGMIQ.js → mcp-HJC2PLRV.js} +3725 -10661
  92. package/dist/mcp-HJC2PLRV.js.map +1 -0
  93. package/dist/paths-P2N4JTDZ.js +49 -0
  94. package/dist/pay-SBXZEPEP.js +37 -0
  95. package/dist/redact-46ZHF2NH.js +17 -0
  96. package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
  97. package/dist/{send-C5EOKXOU.js → send-ASD2ZXJD.js} +28 -30
  98. package/dist/send-ASD2ZXJD.js.map +1 -0
  99. package/dist/{chunk-NAAMHWSI.js → skill-placement-NFVHY6A3.js} +159 -12
  100. package/dist/skill-placement-NFVHY6A3.js.map +1 -0
  101. package/dist/status-T2SDB57A.js +63 -0
  102. package/dist/status-T2SDB57A.js.map +1 -0
  103. package/dist/status-line-CGPUSDMC.js +71 -0
  104. package/dist/status-line-CGPUSDMC.js.map +1 -0
  105. package/dist/status-line-wiring-BYPHTYZE.js +30 -0
  106. package/dist/tenjin-daemon.mjs +20060 -0
  107. package/dist/tenjin-shim.mjs +251 -0
  108. package/dist/tenjin-vitest-reporter.mjs +49 -0
  109. package/dist/uninstall-FKYZHAM3.js +144 -0
  110. package/dist/uninstall-FKYZHAM3.js.map +1 -0
  111. package/dist/{update-24Y2CQTT.js → update-ANJ2AOTN.js} +133 -17
  112. package/dist/update-ANJ2AOTN.js.map +1 -0
  113. package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  114. package/dist/wallet-PWAHVKWW.js +31 -0
  115. package/dist/wallet-kdf-worker.mjs +980 -0
  116. package/docs/agent-permissions.md +68 -342
  117. package/docs/safety-model.md +25 -6
  118. package/package.json +8 -7
  119. package/LICENSE +0 -21
  120. package/dist/buy-2JBYPHAI.js +0 -46
  121. package/dist/chunk-3P3ES4XU.js +0 -144
  122. package/dist/chunk-3P3ES4XU.js.map +0 -1
  123. package/dist/chunk-3ZW7HPY5.js.map +0 -1
  124. package/dist/chunk-47PP7TAG.js.map +0 -1
  125. package/dist/chunk-4UHNXY6B.js +0 -786
  126. package/dist/chunk-4UHNXY6B.js.map +0 -1
  127. package/dist/chunk-4Y53PDH6.js +0 -213
  128. package/dist/chunk-4Y53PDH6.js.map +0 -1
  129. package/dist/chunk-54AJIO3E.js +0 -198
  130. package/dist/chunk-54AJIO3E.js.map +0 -1
  131. package/dist/chunk-736DW4V3.js +0 -65
  132. package/dist/chunk-736DW4V3.js.map +0 -1
  133. package/dist/chunk-7GJQ5RGA.js.map +0 -1
  134. package/dist/chunk-7NADDA2V.js +0 -161
  135. package/dist/chunk-7NADDA2V.js.map +0 -1
  136. package/dist/chunk-ACBEHJAH.js.map +0 -1
  137. package/dist/chunk-B676GPS2.js.map +0 -1
  138. package/dist/chunk-DAZAXFSF.js +0 -1357
  139. package/dist/chunk-DAZAXFSF.js.map +0 -1
  140. package/dist/chunk-DTCXO7HS.js +0 -791
  141. package/dist/chunk-DTCXO7HS.js.map +0 -1
  142. package/dist/chunk-ETKZWJ4B.js.map +0 -1
  143. package/dist/chunk-FDUD3W5V.js +0 -317
  144. package/dist/chunk-FDUD3W5V.js.map +0 -1
  145. package/dist/chunk-GEHL43VE.js +0 -711
  146. package/dist/chunk-GEHL43VE.js.map +0 -1
  147. package/dist/chunk-IU2HVT3Y.js +0 -313
  148. package/dist/chunk-IU2HVT3Y.js.map +0 -1
  149. package/dist/chunk-IUQZ4Z7M.js +0 -162
  150. package/dist/chunk-IUQZ4Z7M.js.map +0 -1
  151. package/dist/chunk-IXZJ3JOO.js +0 -614
  152. package/dist/chunk-IXZJ3JOO.js.map +0 -1
  153. package/dist/chunk-J6FUAIRR.js +0 -205
  154. package/dist/chunk-J6FUAIRR.js.map +0 -1
  155. package/dist/chunk-L6G35FU5.js +0 -105
  156. package/dist/chunk-L6G35FU5.js.map +0 -1
  157. package/dist/chunk-LSWP7MU2.js +0 -290
  158. package/dist/chunk-LSWP7MU2.js.map +0 -1
  159. package/dist/chunk-M2O56UK7.js.map +0 -1
  160. package/dist/chunk-MJSXP4LW.js.map +0 -1
  161. package/dist/chunk-MJZZTKCC.js.map +0 -1
  162. package/dist/chunk-NAAMHWSI.js.map +0 -1
  163. package/dist/chunk-O75FOHXS.js +0 -372
  164. package/dist/chunk-O75FOHXS.js.map +0 -1
  165. package/dist/chunk-OWVVI4VQ.js.map +0 -1
  166. package/dist/chunk-PAOVPSP6.js.map +0 -1
  167. package/dist/chunk-PCX2JQ2J.js +0 -233
  168. package/dist/chunk-PCX2JQ2J.js.map +0 -1
  169. package/dist/chunk-PKW3H26Z.js.map +0 -1
  170. package/dist/chunk-PQZVDCCA.js +0 -125
  171. package/dist/chunk-PQZVDCCA.js.map +0 -1
  172. package/dist/chunk-QWBUKIP2.js.map +0 -1
  173. package/dist/chunk-SGK2B724.js +0 -67
  174. package/dist/chunk-SGK2B724.js.map +0 -1
  175. package/dist/chunk-UHTVXQ2O.js +0 -140
  176. package/dist/chunk-UHTVXQ2O.js.map +0 -1
  177. package/dist/chunk-UO22YNY4.js.map +0 -1
  178. package/dist/chunk-VEAERJVJ.js +0 -43
  179. package/dist/chunk-VEAERJVJ.js.map +0 -1
  180. package/dist/chunk-VRPLZERE.js +0 -1421
  181. package/dist/chunk-VRPLZERE.js.map +0 -1
  182. package/dist/chunk-W4VW5XYB.js +0 -149
  183. package/dist/chunk-W4VW5XYB.js.map +0 -1
  184. package/dist/chunk-WU5CZPLD.js +0 -145
  185. package/dist/chunk-WU5CZPLD.js.map +0 -1
  186. package/dist/chunk-WYLMJQVH.js +0 -240
  187. package/dist/chunk-WYLMJQVH.js.map +0 -1
  188. package/dist/chunk-XGZ5EVMB.js +0 -35
  189. package/dist/chunk-XGZ5EVMB.js.map +0 -1
  190. package/dist/chunk-XVPQGCH4.js +0 -176
  191. package/dist/chunk-XVPQGCH4.js.map +0 -1
  192. package/dist/chunk-ZOBNS7CX.js.map +0 -1
  193. package/dist/chunk-ZQIQ55KK.js +0 -51
  194. package/dist/chunk-ZQIQ55KK.js.map +0 -1
  195. package/dist/cli-U2BEUA55.js.map +0 -1
  196. package/dist/config-CNUIX23Q.js +0 -32
  197. package/dist/doctor-QJJXRWTO.js +0 -31
  198. package/dist/edit-HJ44P44P.js +0 -40
  199. package/dist/fund-Y5IAHZ5D.js +0 -40
  200. package/dist/inspect-NFQ6SQQQ.js +0 -37
  201. package/dist/install-DXX7PVUP.js +0 -854
  202. package/dist/install-DXX7PVUP.js.map +0 -1
  203. package/dist/outcome-ANV4QIED.js +0 -24
  204. package/dist/publish-PCBTCXCZ.js +0 -42
  205. package/dist/read-W7QVRBVD.js +0 -160
  206. package/dist/read-W7QVRBVD.js.map +0 -1
  207. package/dist/run-CJWPGMIQ.js.map +0 -1
  208. package/dist/search-JGAVKTYJ.js +0 -25
  209. package/dist/secp256k1-XRPVBC6V.js.map +0 -1
  210. package/dist/send-C5EOKXOU.js.map +0 -1
  211. package/dist/session-OBCUUIFX.js +0 -89
  212. package/dist/session-OBCUUIFX.js.map +0 -1
  213. package/dist/skill-heal-D6EPLPS6.js +0 -84
  214. package/dist/skill-heal-D6EPLPS6.js.map +0 -1
  215. package/dist/uninstall-OWJNJ5LI.js +0 -73
  216. package/dist/uninstall-OWJNJ5LI.js.map +0 -1
  217. package/dist/update-24Y2CQTT.js.map +0 -1
  218. package/dist/usdc-4VCDHFWX.js +0 -38
  219. package/dist/usdc-4VCDHFWX.js.map +0 -1
  220. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
  221. package/dist/wallet-OFXDIIGP.js +0 -33
  222. package/dist/wallet-OFXDIIGP.js.map +0 -1
  223. package/dist/wallet-SLRIYJ2U.js +0 -42
  224. package/dist/wallet-SLRIYJ2U.js.map +0 -1
  225. package/docs/command-reference.md +0 -261
  226. package/skills/tenjin/SKILL.md +0 -364
  227. package/skills/tenjin-publish/SKILL.md +0 -224
  228. package/skills/tenjin-publish/references/maintain.md +0 -39
  229. package/skills/tenjin-search/SKILL.md +0 -149
  230. package/skills/tenjin-search/references/permissions.md +0 -106
  231. /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
  232. /package/dist/{buy-2JBYPHAI.js.map → ccip-7RMRLAGV.js.map} +0 -0
  233. /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
  234. /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
  235. /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
  236. /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
  237. /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  238. /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
  239. /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
  240. /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
  241. /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
  242. /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
  243. /package/dist/{ccip-ZGGWQN4X.js.map → config-MXOX7XDR.js.map} +0 -0
  244. /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
  245. /package/dist/{config-CNUIX23Q.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  246. /package/dist/{doctor-QJJXRWTO.js.map → install-XUM2XSHW.js.map} +0 -0
  247. /package/dist/{edit-HJ44P44P.js.map → paths-P2N4JTDZ.js.map} +0 -0
  248. /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-SBXZEPEP.js.map} +0 -0
  249. /package/dist/{fund-Y5IAHZ5D.js.map → redact-46ZHF2NH.js.map} +0 -0
  250. /package/dist/{inspect-NFQ6SQQQ.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
  251. /package/dist/{outcome-ANV4QIED.js.map → status-line-wiring-BYPHTYZE.js.map} +0 -0
  252. /package/dist/{publish-PCBTCXCZ.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
  253. /package/dist/{search-JGAVKTYJ.js.map → wallet-PWAHVKWW.js.map} +0 -0
@@ -1,1357 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- promptYesNo
4
- } from "./chunk-QW2Q2KAH.js";
5
- import {
6
- deliverExisting,
7
- deliverFresh,
8
- parseSectionsBudget
9
- } from "./chunk-L6G35FU5.js";
10
- import {
11
- fetchRead
12
- } from "./chunk-PCX2JQ2J.js";
13
- import {
14
- buildSiwxHeader,
15
- createPublicClient,
16
- findByNetworkAndScheme,
17
- findSchemesByNetwork,
18
- http,
19
- x402HTTPClient,
20
- x402Version
21
- } from "./chunk-OWVVI4VQ.js";
22
- import {
23
- encodeFunctionData,
24
- getAddress as getAddress2,
25
- keccak256,
26
- maxUint256,
27
- toBytes,
28
- toHex
29
- } from "./chunk-KZAAWQNP.js";
30
- import {
31
- findDelivered,
32
- findDeliveredByUrl,
33
- resolveResourceRef
34
- } from "./chunk-4Y53PDH6.js";
35
- import {
36
- findSearchForResource
37
- } from "./chunk-7NADDA2V.js";
38
- import {
39
- USDC_ADDRESS
40
- } from "./chunk-MJZZTKCC.js";
41
- import {
42
- describeWallet,
43
- resolveSpendAuthorizer,
44
- resolveWalletProvider
45
- } from "./chunk-7GJQ5RGA.js";
46
- import {
47
- sanitizeForTerminal
48
- } from "./chunk-B676GPS2.js";
49
- import {
50
- resolveContextSettings
51
- } from "./chunk-PKW3H26Z.js";
52
- import {
53
- parseUsdToAtomic,
54
- toMoney
55
- } from "./chunk-736DW4V3.js";
56
- import {
57
- CliError
58
- } from "./chunk-PAOVPSP6.js";
59
- import {
60
- getAddress
61
- } from "./chunk-47PP7TAG.js";
62
-
63
- // node_modules/.pnpm/@x402+core@2.17.0/node_modules/@x402/core/dist/esm/client/index.mjs
64
- var x402Client = class _x402Client {
65
- /**
66
- * Creates a new x402Client instance.
67
- *
68
- * @param paymentRequirementsSelector - Function to select payment requirements from available options
69
- */
70
- constructor(paymentRequirementsSelector) {
71
- this.registeredClientSchemes = /* @__PURE__ */ new Map();
72
- this.schemeClientHookAdapters = /* @__PURE__ */ new Map();
73
- this.policies = [];
74
- this.registeredExtensions = /* @__PURE__ */ new Map();
75
- this.beforePaymentCreationHooks = [];
76
- this.afterPaymentCreationHooks = [];
77
- this.onPaymentCreationFailureHooks = [];
78
- this.paymentResponseHooks = [];
79
- this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version2, accepts) => accepts[0]);
80
- }
81
- /**
82
- * Creates a new x402Client instance from a configuration object.
83
- *
84
- * @param config - The client configuration including schemes, policies, and payment requirements selector
85
- * @returns A configured x402Client instance
86
- */
87
- static fromConfig(config) {
88
- const client = new _x402Client(config.paymentRequirementsSelector);
89
- config.schemes.forEach((scheme) => {
90
- if (scheme.x402Version === 1) {
91
- client.registerV1(scheme.network, scheme.client);
92
- } else {
93
- client.register(scheme.network, scheme.client);
94
- }
95
- });
96
- config.policies?.forEach((policy) => {
97
- client.registerPolicy(policy);
98
- });
99
- return client;
100
- }
101
- /**
102
- * Registers a scheme client for the current x402 version.
103
- *
104
- * @param network - The network to register the client for
105
- * @param client - The scheme network client to register
106
- * @returns The x402Client instance for chaining
107
- */
108
- register(network, client) {
109
- return this._registerScheme(x402Version, network, client);
110
- }
111
- /**
112
- * Registers a scheme client for x402 version 1.
113
- *
114
- * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')
115
- * @param client - The scheme network client to register
116
- * @returns The x402Client instance for chaining
117
- */
118
- registerV1(network, client) {
119
- return this._registerScheme(1, network, client);
120
- }
121
- /**
122
- * Registers a policy to filter or transform payment requirements.
123
- *
124
- * Policies are applied in order after filtering by registered schemes
125
- * and before the selector chooses the final payment requirement.
126
- *
127
- * @param policy - Function to filter/transform payment requirements
128
- * @returns The x402Client instance for chaining
129
- *
130
- * @example
131
- * ```typescript
132
- * // Prefer cheaper options
133
- * client.registerPolicy((version, reqs) =>
134
- * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))
135
- * );
136
- *
137
- * // Prefer specific networks
138
- * client.registerPolicy((version, reqs) =>
139
- * reqs.filter(r => r.network.startsWith('eip155:'))
140
- * );
141
- * ```
142
- */
143
- registerPolicy(policy) {
144
- this.policies.push(policy);
145
- return this;
146
- }
147
- /**
148
- * Registers a client extension that can enrich payment payloads.
149
- *
150
- * Extensions are invoked after the scheme creates the base payload and the
151
- * payload is wrapped with extensions/resource/accepted data. If the extension's
152
- * key is present in `paymentRequired.extensions`, the extension's
153
- * `enrichPaymentPayload` hook is called to modify the payload.
154
- *
155
- * @param extension - The client extension to register
156
- * @returns The x402Client instance for chaining
157
- */
158
- registerExtension(extension) {
159
- this.registeredExtensions.set(extension.key, extension);
160
- return this;
161
- }
162
- /**
163
- * Get all registered client extensions.
164
- *
165
- * @returns Array of registered extensions
166
- */
167
- getExtensions() {
168
- return Array.from(this.registeredExtensions.values());
169
- }
170
- /**
171
- * Register a hook to execute before payment payload creation.
172
- * Can abort creation by returning { abort: true, reason: string }
173
- *
174
- * @param hook - The hook function to register
175
- * @returns The x402Client instance for chaining
176
- */
177
- onBeforePaymentCreation(hook) {
178
- this.beforePaymentCreationHooks.push(hook);
179
- return this;
180
- }
181
- /**
182
- * Register a hook to execute after successful payment payload creation.
183
- *
184
- * @param hook - The hook function to register
185
- * @returns The x402Client instance for chaining
186
- */
187
- onAfterPaymentCreation(hook) {
188
- this.afterPaymentCreationHooks.push(hook);
189
- return this;
190
- }
191
- /**
192
- * Register a hook to execute when payment payload creation fails.
193
- * Can recover from failure by returning { recovered: true, payload: PaymentPayload }
194
- *
195
- * @param hook - The hook function to register
196
- * @returns The x402Client instance for chaining
197
- */
198
- onPaymentCreationFailure(hook) {
199
- this.onPaymentCreationFailureHooks.push(hook);
200
- return this;
201
- }
202
- /**
203
- * Register a hook to execute after a paid request completes.
204
- * Can signal recovery by returning { recovered: true }, causing the transport to retry.
205
- *
206
- * @param hook - The hook function to register
207
- * @returns The x402Client instance for chaining
208
- */
209
- onPaymentResponse(hook) {
210
- this.paymentResponseHooks.push(hook);
211
- return this;
212
- }
213
- /**
214
- * Fires all registered payment response hooks in order.
215
- * Returns `{ recovered: true }` if any hook signals recovery (first wins).
216
- *
217
- * @param ctx - The payment response context
218
- * @returns Recovery signal or undefined
219
- */
220
- async handlePaymentResponse(ctx) {
221
- for (const hook of this.getLabeledHooks(
222
- "onPaymentResponse",
223
- ctx.paymentPayload.x402Version,
224
- ctx.requirements,
225
- ctx.paymentRequired?.extensions ?? ctx.paymentPayload.extensions
226
- )) {
227
- const result = await hook(ctx);
228
- if (result && "recovered" in result && result.recovered) {
229
- return { recovered: true };
230
- }
231
- }
232
- return void 0;
233
- }
234
- /**
235
- * Creates a payment payload based on a PaymentRequired response.
236
- *
237
- * Automatically extracts x402Version, resource, and extensions from the PaymentRequired
238
- * response and constructs a complete PaymentPayload with the accepted requirements.
239
- *
240
- * @param paymentRequired - The PaymentRequired response from the server
241
- * @returns Promise resolving to the complete payment payload
242
- */
243
- async createPaymentPayload(paymentRequired) {
244
- const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);
245
- if (!clientSchemesByNetwork) {
246
- throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);
247
- }
248
- const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);
249
- const context = {
250
- paymentRequired,
251
- selectedRequirements: requirements
252
- };
253
- for (const hook of this.getLabeledHooks(
254
- "beforePaymentCreation",
255
- paymentRequired.x402Version,
256
- requirements,
257
- paymentRequired.extensions
258
- )) {
259
- const result = await hook(context);
260
- if (result && "abort" in result && result.abort) {
261
- throw new Error(`Payment creation aborted: ${result.reason}`);
262
- }
263
- }
264
- try {
265
- const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);
266
- if (!schemeNetworkClient) {
267
- throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);
268
- }
269
- const partialPayload = await schemeNetworkClient.createPaymentPayload(
270
- paymentRequired.x402Version,
271
- requirements,
272
- { extensions: paymentRequired.extensions }
273
- );
274
- let paymentPayload;
275
- if (partialPayload.x402Version == 1) {
276
- paymentPayload = partialPayload;
277
- } else {
278
- const mergedExtensions = this.mergeExtensions(
279
- paymentRequired.extensions,
280
- partialPayload.extensions
281
- );
282
- paymentPayload = {
283
- x402Version: partialPayload.x402Version,
284
- payload: partialPayload.payload,
285
- extensions: mergedExtensions,
286
- resource: paymentRequired.resource,
287
- accepted: requirements
288
- };
289
- }
290
- paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);
291
- const createdContext = {
292
- ...context,
293
- paymentPayload
294
- };
295
- for (const hook of this.getLabeledHooks(
296
- "afterPaymentCreation",
297
- paymentRequired.x402Version,
298
- requirements,
299
- paymentRequired.extensions
300
- )) {
301
- await hook(createdContext);
302
- }
303
- return paymentPayload;
304
- } catch (error) {
305
- const failureContext = {
306
- ...context,
307
- error
308
- };
309
- for (const hook of this.getLabeledHooks(
310
- "onPaymentCreationFailure",
311
- paymentRequired.x402Version,
312
- requirements,
313
- paymentRequired.extensions
314
- )) {
315
- const result = await hook(failureContext);
316
- if (result && "recovered" in result && result.recovered) {
317
- return result.payload;
318
- }
319
- }
320
- throw error;
321
- }
322
- }
323
- /**
324
- * Merges server-declared extensions with client extension echoes.
325
- * Client extension data may add fields, but server-declared fields remain intact.
326
- *
327
- * @param serverExtensions - Extensions declared by the server in the 402 response
328
- * @param clientExtensions - Extensions provided by the client or scheme
329
- * @returns The merged extensions object, or undefined if both inputs are undefined
330
- */
331
- mergeExtensions(serverExtensions, clientExtensions) {
332
- if (!clientExtensions) return serverExtensions;
333
- if (!serverExtensions) return clientExtensions;
334
- const merged = { ...serverExtensions };
335
- for (const [key, clientValue] of Object.entries(clientExtensions)) {
336
- const serverValue = merged[key];
337
- if (serverValue === null || typeof serverValue !== "object" || Array.isArray(serverValue) || clientValue === null || typeof clientValue !== "object" || Array.isArray(clientValue)) {
338
- merged[key] = clientValue;
339
- continue;
340
- }
341
- const serverRecord = serverValue;
342
- const clientRecord = clientValue;
343
- const extensionValue = { ...serverRecord };
344
- const pending = [{ target: extensionValue, source: clientRecord }];
345
- for (const item of pending) {
346
- for (const [fieldKey, clientFieldValue] of Object.entries(item.source)) {
347
- const serverFieldValue = item.target[fieldKey];
348
- if (serverFieldValue !== null && typeof serverFieldValue === "object" && !Array.isArray(serverFieldValue) && clientFieldValue !== null && typeof clientFieldValue === "object" && !Array.isArray(clientFieldValue)) {
349
- const nestedValue = { ...serverFieldValue };
350
- item.target[fieldKey] = nestedValue;
351
- pending.push({
352
- target: nestedValue,
353
- source: clientFieldValue
354
- });
355
- continue;
356
- }
357
- if (!Object.prototype.hasOwnProperty.call(item.target, fieldKey)) {
358
- item.target[fieldKey] = clientFieldValue;
359
- }
360
- }
361
- }
362
- merged[key] = extensionValue;
363
- }
364
- return merged;
365
- }
366
- /**
367
- * Enriches a payment payload by calling registered extension hooks.
368
- * For each extension key present in the PaymentRequired response,
369
- * invokes the corresponding extension's enrichPaymentPayload callback.
370
- *
371
- * @param paymentPayload - The payment payload to enrich with extension data
372
- * @param paymentRequired - The PaymentRequired response containing extension declarations
373
- * @returns The enriched payment payload with extension data applied
374
- */
375
- async enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired) {
376
- if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {
377
- return paymentPayload;
378
- }
379
- let enriched = paymentPayload;
380
- for (const [key, extension] of this.registeredExtensions) {
381
- if (key in paymentRequired.extensions && extension.enrichPaymentPayload) {
382
- enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);
383
- }
384
- }
385
- return {
386
- ...enriched,
387
- extensions: this.mergeExtensions(paymentRequired.extensions, enriched.extensions)
388
- };
389
- }
390
- /**
391
- * Selects appropriate payment requirements based on registered clients and policies.
392
- *
393
- * Selection process:
394
- * 1. Filter by registered schemes (network + scheme support)
395
- * 2. Apply all registered policies in order
396
- * 3. Use selector to choose final requirement
397
- *
398
- * @param x402Version - The x402 protocol version
399
- * @param paymentRequirements - Array of available payment requirements
400
- * @returns The selected payment requirements
401
- */
402
- selectPaymentRequirements(x402Version2, paymentRequirements) {
403
- const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
404
- if (!clientSchemesByNetwork) {
405
- throw new Error(`No client registered for x402 version: ${x402Version2}`);
406
- }
407
- const supportedPaymentRequirements = paymentRequirements.filter((requirement) => {
408
- let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);
409
- if (!clientSchemes) {
410
- return false;
411
- }
412
- return clientSchemes.has(requirement.scheme);
413
- });
414
- if (supportedPaymentRequirements.length === 0) {
415
- throw new Error(`No network/scheme registered for x402 version: ${x402Version2} which comply with the payment requirements. ${JSON.stringify({
416
- x402Version: x402Version2,
417
- paymentRequirements,
418
- x402Versions: Array.from(this.registeredClientSchemes.keys()),
419
- networks: Array.from(clientSchemesByNetwork.keys()),
420
- schemes: Array.from(clientSchemesByNetwork.values()).map((schemes) => Array.from(schemes.keys())).flat()
421
- })}`);
422
- }
423
- let filteredRequirements = supportedPaymentRequirements;
424
- for (const policy of this.policies) {
425
- filteredRequirements = policy(x402Version2, filteredRequirements);
426
- if (filteredRequirements.length === 0) {
427
- throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version2}`);
428
- }
429
- }
430
- return this.paymentRequirementsSelector(x402Version2, filteredRequirements);
431
- }
432
- /**
433
- * Internal method to register a scheme client.
434
- *
435
- * @param x402Version - The x402 protocol version
436
- * @param network - The network to register the client for
437
- * @param client - The scheme network client to register
438
- * @returns The x402Client instance for chaining
439
- */
440
- _registerScheme(x402Version2, network, client) {
441
- if (!this.registeredClientSchemes.has(x402Version2)) {
442
- this.registeredClientSchemes.set(x402Version2, /* @__PURE__ */ new Map());
443
- }
444
- const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
445
- if (!clientSchemesByNetwork.has(network)) {
446
- clientSchemesByNetwork.set(network, /* @__PURE__ */ new Map());
447
- }
448
- const clientByScheme = clientSchemesByNetwork.get(network);
449
- clientByScheme.set(client.scheme, client);
450
- if (!this.schemeClientHookAdapters.has(x402Version2)) {
451
- this.schemeClientHookAdapters.set(x402Version2, /* @__PURE__ */ new Map());
452
- }
453
- const adaptersByNetwork = this.schemeClientHookAdapters.get(x402Version2);
454
- if (!adaptersByNetwork.has(network)) {
455
- adaptersByNetwork.set(network, /* @__PURE__ */ new Map());
456
- }
457
- const adaptersByScheme = adaptersByNetwork.get(network);
458
- const hooks = client.schemeHooks;
459
- if (!hooks) {
460
- adaptersByScheme.delete(client.scheme);
461
- return this;
462
- }
463
- const handles = {};
464
- if (hooks.onBeforePaymentCreation) {
465
- handles.beforePaymentCreation = hooks.onBeforePaymentCreation;
466
- }
467
- if (hooks.onAfterPaymentCreation) {
468
- handles.afterPaymentCreation = hooks.onAfterPaymentCreation;
469
- }
470
- if (hooks.onPaymentCreationFailure) {
471
- handles.onPaymentCreationFailure = hooks.onPaymentCreationFailure;
472
- }
473
- if (hooks.onPaymentResponse) {
474
- handles.onPaymentResponse = hooks.onPaymentResponse;
475
- }
476
- if (Object.keys(handles).length > 0) {
477
- adaptersByScheme.set(client.scheme, handles);
478
- } else {
479
- adaptersByScheme.delete(client.scheme);
480
- }
481
- return this;
482
- }
483
- /**
484
- * Returns manual hooks followed by the selected scheme hook and declared extension hooks.
485
- *
486
- * @param phase - Hook slot to collect
487
- * @param x402Version - Protocol version for the selected requirement
488
- * @param requirements - Selected payment requirement
489
- * @param declaredExtensions - Extension declarations that scope extension hooks
490
- * @returns Hooks in invocation order
491
- */
492
- getLabeledHooks(phase, x402Version2, requirements, declaredExtensions) {
493
- let manual;
494
- switch (phase) {
495
- case "beforePaymentCreation":
496
- manual = this.beforePaymentCreationHooks;
497
- break;
498
- case "afterPaymentCreation":
499
- manual = this.afterPaymentCreationHooks;
500
- break;
501
- case "onPaymentCreationFailure":
502
- manual = this.onPaymentCreationFailureHooks;
503
- break;
504
- case "onPaymentResponse":
505
- manual = this.paymentResponseHooks;
506
- break;
507
- }
508
- const out = [...manual];
509
- const adaptersByNetwork = this.schemeClientHookAdapters.get(x402Version2);
510
- const schemeAdapter = adaptersByNetwork ? findByNetworkAndScheme(adaptersByNetwork, requirements.scheme, requirements.network) : void 0;
511
- const hook = schemeAdapter?.[phase];
512
- if (hook !== void 0) {
513
- out.push(hook);
514
- }
515
- if (!declaredExtensions) {
516
- return out;
517
- }
518
- const extensionHookKey = this.getClientExtensionHookKey(phase);
519
- for (const [extensionKey, extension] of this.registeredExtensions) {
520
- if (!(extensionKey in declaredExtensions)) continue;
521
- const extensionHook = extension.hooks?.[extensionHookKey];
522
- if (!extensionHook) continue;
523
- out.push((async (ctx) => {
524
- return extensionHook(declaredExtensions[extensionKey], ctx);
525
- }));
526
- }
527
- return out;
528
- }
529
- /**
530
- * Maps internal hook phases to extension hook names.
531
- *
532
- * @param phase - Internal hook phase
533
- * @returns Extension hook key for the phase
534
- */
535
- getClientExtensionHookKey(phase) {
536
- switch (phase) {
537
- case "beforePaymentCreation":
538
- return "onBeforePaymentCreation";
539
- case "afterPaymentCreation":
540
- return "onAfterPaymentCreation";
541
- case "onPaymentCreationFailure":
542
- return "onPaymentCreationFailure";
543
- case "onPaymentResponse":
544
- return "onPaymentResponse";
545
- }
546
- }
547
- };
548
-
549
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-MACPBXCT.mjs
550
- var authorizationTypes = {
551
- TransferWithAuthorization: [
552
- { name: "from", type: "address" },
553
- { name: "to", type: "address" },
554
- { name: "value", type: "uint256" },
555
- { name: "validAfter", type: "uint256" },
556
- { name: "validBefore", type: "uint256" },
557
- { name: "nonce", type: "bytes32" }
558
- ]
559
- };
560
- var permit2WitnessTypes = {
561
- PermitWitnessTransferFrom: [
562
- { name: "permitted", type: "TokenPermissions" },
563
- { name: "spender", type: "address" },
564
- { name: "nonce", type: "uint256" },
565
- { name: "deadline", type: "uint256" },
566
- { name: "witness", type: "Witness" }
567
- ],
568
- TokenPermissions: [
569
- { name: "token", type: "address" },
570
- { name: "amount", type: "uint256" }
571
- ],
572
- Witness: [
573
- { name: "to", type: "address" },
574
- { name: "validAfter", type: "uint256" }
575
- ]
576
- };
577
- var eip2612PermitTypes = {
578
- Permit: [
579
- { name: "owner", type: "address" },
580
- { name: "spender", type: "address" },
581
- { name: "value", type: "uint256" },
582
- { name: "nonce", type: "uint256" },
583
- { name: "deadline", type: "uint256" }
584
- ]
585
- };
586
- var eip2612NoncesAbi = [
587
- {
588
- type: "function",
589
- name: "nonces",
590
- inputs: [{ name: "owner", type: "address" }],
591
- outputs: [{ type: "uint256" }],
592
- stateMutability: "view"
593
- }
594
- ];
595
- var erc20ApproveAbi = [
596
- {
597
- type: "function",
598
- name: "approve",
599
- inputs: [
600
- { name: "spender", type: "address" },
601
- { name: "amount", type: "uint256" }
602
- ],
603
- outputs: [{ type: "bool" }],
604
- stateMutability: "nonpayable"
605
- }
606
- ];
607
- var erc20AllowanceAbi = [
608
- {
609
- type: "function",
610
- name: "allowance",
611
- inputs: [
612
- { name: "owner", type: "address" },
613
- { name: "spender", type: "address" }
614
- ],
615
- outputs: [{ type: "uint256" }],
616
- stateMutability: "view"
617
- }
618
- ];
619
- var ERC20_APPROVE_GAS_LIMIT = 70000n;
620
- var DEFAULT_MAX_FEE_PER_GAS = 1000000000n;
621
- var DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100000000n;
622
- var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
623
- var x402ExactPermit2ProxyAddress = "0x402085c248EeA27D92E8b30b2C58ed07f9E20001";
624
-
625
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-7KTOBWB2.mjs
626
- var PAYMENT_INFO_TYPEHASH = keccak256(
627
- new TextEncoder().encode(
628
- "PaymentInfo(address operator,address payer,address receiver,address token,uint120 maxAmount,uint48 preApprovalExpiry,uint48 authorizationExpiry,uint48 refundExpiry,uint16 minFeeBps,uint16 maxFeeBps,address feeReceiver,uint256 salt)"
629
- )
630
- );
631
-
632
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-TW7Z65AO.mjs
633
- function getEvmChainId(network) {
634
- if (network.startsWith("eip155:")) {
635
- const idStr = network.split(":")[1];
636
- const chainId = parseInt(idStr, 10);
637
- if (isNaN(chainId)) {
638
- throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
639
- }
640
- return chainId;
641
- }
642
- throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);
643
- }
644
- function getCrypto() {
645
- const cryptoObj = globalThis.crypto;
646
- if (!cryptoObj) {
647
- throw new Error("Crypto API not available");
648
- }
649
- return cryptoObj;
650
- }
651
- function createNonce() {
652
- return toHex(getCrypto().getRandomValues(new Uint8Array(32)));
653
- }
654
- function createPermit2Nonce() {
655
- const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));
656
- return BigInt(toHex(randomBytes)).toString();
657
- }
658
-
659
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-BQS2RW2S.mjs
660
- var CHANNEL_CONFIG_TYPEHASH = keccak256(
661
- toBytes(
662
- "ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)"
663
- )
664
- );
665
-
666
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-27MWX225.mjs
667
- var EIP2612_GAS_SPONSORING_KEY = "eip2612GasSponsoring";
668
- var ERC20_APPROVAL_GAS_SPONSORING_KEY = "erc20ApprovalGasSponsoring";
669
- var ERC20_APPROVAL_GAS_SPONSORING_VERSION = "1";
670
- async function signEip2612Permit(signer, tokenAddress, tokenName, tokenVersion, chainId, deadline, permittedAmount) {
671
- const owner = signer.address;
672
- const spender = getAddress2(PERMIT2_ADDRESS);
673
- const nonce = await signer.readContract({
674
- address: tokenAddress,
675
- abi: eip2612NoncesAbi,
676
- functionName: "nonces",
677
- args: [owner]
678
- });
679
- const domain = {
680
- name: tokenName,
681
- version: tokenVersion,
682
- chainId,
683
- verifyingContract: tokenAddress
684
- };
685
- const approvalAmount = BigInt(permittedAmount);
686
- const message = {
687
- owner,
688
- spender,
689
- value: approvalAmount,
690
- nonce,
691
- deadline: BigInt(deadline)
692
- };
693
- const signature = await signer.signTypedData({
694
- domain,
695
- types: eip2612PermitTypes,
696
- primaryType: "Permit",
697
- message
698
- });
699
- return {
700
- from: owner,
701
- asset: tokenAddress,
702
- spender,
703
- amount: approvalAmount.toString(),
704
- nonce: nonce.toString(),
705
- deadline,
706
- signature,
707
- version: "1"
708
- };
709
- }
710
- async function signErc20ApprovalTransaction(signer, tokenAddress, chainId) {
711
- const from = signer.address;
712
- const spender = getAddress2(PERMIT2_ADDRESS);
713
- const data = encodeFunctionData({
714
- abi: erc20ApproveAbi,
715
- functionName: "approve",
716
- args: [spender, maxUint256]
717
- });
718
- const nonce = await signer.getTransactionCount({ address: from });
719
- let maxFeePerGas;
720
- let maxPriorityFeePerGas;
721
- try {
722
- const fees = await signer.estimateFeesPerGas?.();
723
- if (!fees) {
724
- throw new Error("no fee estimates available");
725
- }
726
- maxFeePerGas = fees.maxFeePerGas;
727
- maxPriorityFeePerGas = fees.maxPriorityFeePerGas;
728
- } catch {
729
- maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;
730
- maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;
731
- }
732
- const signedTransaction = await signer.signTransaction({
733
- to: tokenAddress,
734
- data,
735
- nonce,
736
- gas: ERC20_APPROVE_GAS_LIMIT,
737
- maxFeePerGas,
738
- maxPriorityFeePerGas,
739
- chainId
740
- });
741
- return {
742
- from,
743
- asset: tokenAddress,
744
- spender,
745
- amount: maxUint256.toString(),
746
- signedTransaction,
747
- version: ERC20_APPROVAL_GAS_SPONSORING_VERSION
748
- };
749
- }
750
- var rpcClientCache = /* @__PURE__ */ new Map();
751
- function isConfigByChainId(options) {
752
- const keys = Object.keys(options);
753
- return keys.length > 0 && keys.every((key) => /^\d+$/.test(key));
754
- }
755
- function getRpcClient(rpcUrl) {
756
- const existing = rpcClientCache.get(rpcUrl);
757
- if (existing) {
758
- return existing;
759
- }
760
- const client = createPublicClient({
761
- transport: http(rpcUrl)
762
- });
763
- rpcClientCache.set(rpcUrl, client);
764
- return client;
765
- }
766
- function resolveRpcUrl(network, options) {
767
- if (!options) {
768
- return void 0;
769
- }
770
- if (isConfigByChainId(options)) {
771
- const chainId = getEvmChainId(network);
772
- const optionsByChainId = options;
773
- return optionsByChainId[chainId]?.rpcUrl;
774
- }
775
- return options.rpcUrl;
776
- }
777
- function resolveExtensionRpcCapabilities(network, signer, options) {
778
- const capabilities = {
779
- signTransaction: signer.signTransaction,
780
- readContract: signer.readContract,
781
- getTransactionCount: signer.getTransactionCount,
782
- estimateFeesPerGas: signer.estimateFeesPerGas
783
- };
784
- const needsRpcBackfill = !capabilities.readContract || !capabilities.getTransactionCount || !capabilities.estimateFeesPerGas;
785
- if (!needsRpcBackfill) {
786
- return capabilities;
787
- }
788
- const rpcUrl = resolveRpcUrl(network, options);
789
- if (!rpcUrl) {
790
- return capabilities;
791
- }
792
- const rpcClient = getRpcClient(rpcUrl);
793
- if (!capabilities.readContract) {
794
- capabilities.readContract = (args) => rpcClient.readContract(args);
795
- }
796
- if (!capabilities.getTransactionCount) {
797
- capabilities.getTransactionCount = async (args) => rpcClient.getTransactionCount({ address: args.address });
798
- }
799
- if (!capabilities.estimateFeesPerGas) {
800
- capabilities.estimateFeesPerGas = async () => rpcClient.estimateFeesPerGas();
801
- }
802
- return capabilities;
803
- }
804
- async function trySignEip2612PermitExtension(signer, options, requirements, result, context, approvalAmount) {
805
- const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
806
- if (!capabilities.readContract) {
807
- return void 0;
808
- }
809
- if (!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY]) {
810
- return void 0;
811
- }
812
- const tokenName = requirements.extra?.name;
813
- const tokenVersion = requirements.extra?.version;
814
- if (!tokenName || !tokenVersion) {
815
- return void 0;
816
- }
817
- const chainId = getEvmChainId(requirements.network);
818
- const tokenAddress = getAddress2(requirements.asset);
819
- const requiredAllowance = approvalAmount ?? requirements.amount;
820
- try {
821
- const allowance = await capabilities.readContract({
822
- address: tokenAddress,
823
- abi: erc20AllowanceAbi,
824
- functionName: "allowance",
825
- args: [signer.address, PERMIT2_ADDRESS]
826
- });
827
- if (allowance >= BigInt(requiredAllowance)) {
828
- return void 0;
829
- }
830
- } catch {
831
- }
832
- const permit2Auth = result.payload?.permit2Authorization;
833
- const deadline = permit2Auth?.deadline ?? Math.floor(Date.now() / 1e3 + requirements.maxTimeoutSeconds).toString();
834
- const info = await signEip2612Permit(
835
- {
836
- address: signer.address,
837
- signTypedData: (msg) => signer.signTypedData(msg),
838
- readContract: capabilities.readContract
839
- },
840
- tokenAddress,
841
- tokenName,
842
- tokenVersion,
843
- chainId,
844
- deadline,
845
- requiredAllowance
846
- );
847
- return {
848
- [EIP2612_GAS_SPONSORING_KEY]: { info }
849
- };
850
- }
851
- async function trySignErc20ApprovalExtension(signer, options, requirements, context, approvalAmount) {
852
- const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
853
- if (!capabilities.readContract) {
854
- return void 0;
855
- }
856
- if (!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY]) {
857
- return void 0;
858
- }
859
- if (!capabilities.signTransaction || !capabilities.getTransactionCount) {
860
- return void 0;
861
- }
862
- const chainId = getEvmChainId(requirements.network);
863
- const tokenAddress = getAddress2(requirements.asset);
864
- const requiredAllowance = approvalAmount ?? requirements.amount;
865
- try {
866
- const allowance = await capabilities.readContract({
867
- address: tokenAddress,
868
- abi: erc20AllowanceAbi,
869
- functionName: "allowance",
870
- args: [signer.address, PERMIT2_ADDRESS]
871
- });
872
- if (allowance >= BigInt(requiredAllowance)) {
873
- return void 0;
874
- }
875
- } catch {
876
- }
877
- const info = await signErc20ApprovalTransaction(
878
- {
879
- address: signer.address,
880
- signTransaction: capabilities.signTransaction,
881
- getTransactionCount: capabilities.getTransactionCount,
882
- estimateFeesPerGas: capabilities.estimateFeesPerGas
883
- },
884
- tokenAddress,
885
- chainId
886
- );
887
- return {
888
- [ERC20_APPROVAL_GAS_SPONSORING_KEY]: { info }
889
- };
890
- }
891
-
892
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-2GHXG5WB.mjs
893
- var EVM_NETWORK_CHAIN_ID_MAP = {
894
- ethereum: 1,
895
- sepolia: 11155111,
896
- abstract: 2741,
897
- "abstract-testnet": 11124,
898
- "base-sepolia": 84532,
899
- base: 8453,
900
- "avalanche-fuji": 43113,
901
- avalanche: 43114,
902
- iotex: 4689,
903
- sei: 1329,
904
- "sei-testnet": 1328,
905
- polygon: 137,
906
- "polygon-amoy": 80002,
907
- peaq: 3338,
908
- story: 1514,
909
- educhain: 41923,
910
- "skale-base-sepolia": 324705682,
911
- megaeth: 4326,
912
- monad: 143,
913
- stable: 988,
914
- "stable-testnet": 2201
915
- };
916
- var NETWORKS = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);
917
-
918
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-4NBQRJBB.mjs
919
- async function createPermit2PayloadForProxy(proxyAddress, signer, x402Version2, paymentRequirements) {
920
- const now = Math.floor(Date.now() / 1e3);
921
- const nonce = createPermit2Nonce();
922
- const validAfter = "0";
923
- const deadline = (now + paymentRequirements.maxTimeoutSeconds).toString();
924
- const permit2Authorization = {
925
- from: signer.address,
926
- permitted: {
927
- token: getAddress2(paymentRequirements.asset),
928
- amount: paymentRequirements.amount
929
- },
930
- spender: proxyAddress,
931
- nonce,
932
- deadline,
933
- witness: {
934
- to: getAddress2(paymentRequirements.payTo),
935
- validAfter
936
- }
937
- };
938
- const signature = await signPermit2Authorization(
939
- signer,
940
- permit2Authorization,
941
- paymentRequirements
942
- );
943
- return {
944
- x402Version: x402Version2,
945
- payload: { signature, permit2Authorization }
946
- };
947
- }
948
- async function signPermit2Authorization(signer, permit2Authorization, requirements) {
949
- const chainId = getEvmChainId(requirements.network);
950
- return await signer.signTypedData({
951
- domain: { name: "Permit2", chainId, verifyingContract: PERMIT2_ADDRESS },
952
- types: permit2WitnessTypes,
953
- primaryType: "PermitWitnessTransferFrom",
954
- message: {
955
- permitted: {
956
- token: getAddress2(permit2Authorization.permitted.token),
957
- amount: BigInt(permit2Authorization.permitted.amount)
958
- },
959
- spender: getAddress2(permit2Authorization.spender),
960
- nonce: BigInt(permit2Authorization.nonce),
961
- deadline: BigInt(permit2Authorization.deadline),
962
- witness: {
963
- to: getAddress2(permit2Authorization.witness.to),
964
- validAfter: BigInt(permit2Authorization.witness.validAfter)
965
- }
966
- }
967
- });
968
- }
969
-
970
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-UUEZJ3RH.mjs
971
- var MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
972
- async function createPermit2Payload(signer, x402Version2, paymentRequirements) {
973
- return createPermit2PayloadForProxy(
974
- x402ExactPermit2ProxyAddress,
975
- signer,
976
- x402Version2,
977
- paymentRequirements
978
- );
979
- }
980
-
981
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-VFVBY5MG.mjs
982
- async function createEIP3009Payload(signer, x402Version2, paymentRequirements) {
983
- const nonce = createNonce();
984
- const now = Math.floor(Date.now() / 1e3);
985
- const authorization = {
986
- from: signer.address,
987
- to: getAddress2(paymentRequirements.payTo),
988
- value: paymentRequirements.amount,
989
- validAfter: "0",
990
- validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),
991
- nonce
992
- };
993
- const signature = await signEIP3009Authorization(signer, authorization, paymentRequirements);
994
- const payload = {
995
- authorization,
996
- signature
997
- };
998
- return {
999
- x402Version: x402Version2,
1000
- payload
1001
- };
1002
- }
1003
- async function signEIP3009Authorization(signer, authorization, requirements) {
1004
- const chainId = getEvmChainId(requirements.network);
1005
- if (!requirements.extra?.name || !requirements.extra?.version) {
1006
- throw new Error(
1007
- `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`
1008
- );
1009
- }
1010
- const { name, version } = requirements.extra;
1011
- const domain = {
1012
- name,
1013
- version,
1014
- chainId,
1015
- verifyingContract: getAddress2(requirements.asset)
1016
- };
1017
- const message = {
1018
- from: getAddress2(authorization.from),
1019
- to: getAddress2(authorization.to),
1020
- value: BigInt(authorization.value),
1021
- validAfter: BigInt(authorization.validAfter),
1022
- validBefore: BigInt(authorization.validBefore),
1023
- nonce: authorization.nonce
1024
- };
1025
- return await signer.signTypedData({
1026
- domain,
1027
- types: authorizationTypes,
1028
- primaryType: "TransferWithAuthorization",
1029
- message
1030
- });
1031
- }
1032
- var ExactEvmScheme = class {
1033
- /**
1034
- * Creates a new ExactEvmClient instance.
1035
- *
1036
- * @param signer - The EVM signer for client operations.
1037
- * Base flow only requires `address` + `signTypedData`.
1038
- * Extension enrichment (EIP-2612 / ERC-20 approval sponsoring) additionally
1039
- * requires optional capabilities like `readContract` and tx signing helpers.
1040
- * @param options - Optional RPC configuration used to backfill extension capabilities.
1041
- */
1042
- constructor(signer, options) {
1043
- this.signer = signer;
1044
- this.options = options;
1045
- this.scheme = "exact";
1046
- }
1047
- /**
1048
- * Creates a payment payload for the Exact scheme.
1049
- * Routes to EIP-3009 or Permit2 based on requirements.extra.assetTransferMethod.
1050
- *
1051
- * For Permit2 flows, if the server advertises `eip2612GasSponsoring` and the
1052
- * signer supports `readContract`, automatically signs an EIP-2612 permit
1053
- * when Permit2 allowance is insufficient.
1054
- *
1055
- * @param x402Version - The x402 protocol version
1056
- * @param paymentRequirements - The payment requirements
1057
- * @param context - Optional context with server-declared extensions
1058
- * @returns Promise resolving to a payment payload result (with optional extensions)
1059
- */
1060
- async createPaymentPayload(x402Version2, paymentRequirements, context) {
1061
- const assetTransferMethod = paymentRequirements.extra?.assetTransferMethod ?? "eip3009";
1062
- if (assetTransferMethod === "permit2") {
1063
- const result = await createPermit2Payload(this.signer, x402Version2, paymentRequirements);
1064
- const eip2612Extensions = await trySignEip2612PermitExtension(
1065
- this.signer,
1066
- this.options,
1067
- paymentRequirements,
1068
- result,
1069
- context
1070
- );
1071
- if (eip2612Extensions) {
1072
- return {
1073
- ...result,
1074
- extensions: eip2612Extensions
1075
- };
1076
- }
1077
- const erc20Extensions = await trySignErc20ApprovalExtension(
1078
- this.signer,
1079
- this.options,
1080
- paymentRequirements,
1081
- context
1082
- );
1083
- if (erc20Extensions) {
1084
- return {
1085
- ...result,
1086
- extensions: erc20Extensions
1087
- };
1088
- }
1089
- return result;
1090
- }
1091
- return createEIP3009Payload(this.signer, x402Version2, paymentRequirements);
1092
- }
1093
- };
1094
-
1095
- // src/lib/x402-pay.ts
1096
- function toClientSigner(signer) {
1097
- return {
1098
- address: signer.address,
1099
- signTypedData: (message) => signer.signTypedData(message)
1100
- };
1101
- }
1102
- var ALLOWED_USDC_BY_NETWORK = {
1103
- "eip155:8453": USDC_ADDRESS,
1104
- "eip155:84532": "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
1105
- };
1106
- async function buildExactPayment(paymentRequired, signer) {
1107
- const requirement = paymentRequired.accepts[0];
1108
- if (requirement === void 0) {
1109
- throw new CliError("PAYMENT_FAILED", "The 402 advertised no payment requirements.", {
1110
- fix: "The resource may be misconfigured; try another candidate."
1111
- });
1112
- }
1113
- if (requirement.scheme !== "exact") {
1114
- throw new CliError("PAYMENT_FAILED", `Unsupported payment scheme "${requirement.scheme}".`, {
1115
- fix: "This CLI pays the x402 exact scheme only."
1116
- });
1117
- }
1118
- const allowedAsset = ALLOWED_USDC_BY_NETWORK[requirement.network];
1119
- if (allowedAsset === void 0) {
1120
- throw new CliError(
1121
- "PAYMENT_FAILED",
1122
- `The 402 names a chain this CLI will not pay on: ${requirement.network}.`,
1123
- {
1124
- fix: "Only USDC on Base (eip155:8453) or Base Sepolia previews (eip155:84532) is supported."
1125
- }
1126
- );
1127
- }
1128
- let assetChecksummed;
1129
- try {
1130
- assetChecksummed = getAddress(requirement.asset);
1131
- } catch {
1132
- throw new CliError(
1133
- "PAYMENT_FAILED",
1134
- `The 402 names an invalid asset address: ${JSON.stringify(requirement.asset)}.`
1135
- );
1136
- }
1137
- if (assetChecksummed !== getAddress(allowedAsset)) {
1138
- throw new CliError(
1139
- "PAYMENT_FAILED",
1140
- `The 402 names an asset this CLI will not pay: ${assetChecksummed} on ${requirement.network}.`,
1141
- {
1142
- fix: "Only canonical USDC is supported; the resource or server looks misconfigured or hostile."
1143
- }
1144
- );
1145
- }
1146
- const core = new x402Client();
1147
- core.register(requirement.network, new ExactEvmScheme(toClientSigner(signer)));
1148
- const http2 = new x402HTTPClient(core);
1149
- const bound = { ...paymentRequired, accepts: [requirement] };
1150
- let headers;
1151
- try {
1152
- const payload = await http2.createPaymentPayload(bound);
1153
- headers = http2.encodePaymentSignatureHeader(payload);
1154
- } catch (err) {
1155
- throw new CliError("PAYMENT_FAILED", "Could not build the x402 payment authorization.", {
1156
- fix: "Confirm the wallet is a supported EVM account on the advertised network.",
1157
- cause: err
1158
- });
1159
- }
1160
- return { headers, amountAtomic: BigInt(requirement.amount) };
1161
- }
1162
-
1163
- // src/commands/buy.ts
1164
- async function runBuy(args, ctx, deps = {}) {
1165
- const settings = await resolveContextSettings(ctx);
1166
- const sectionsBudget = parseSectionsBudget(args.sections);
1167
- const maxPriceAtomic = args.maxPrice !== void 0 ? BigInt(parseUsdToAtomic(args.maxPrice)) : void 0;
1168
- const ref = await resolveResourceRef(args.ref, ctx.dataDir, settings.baseUrl);
1169
- const existing = ref.resourceId !== void 0 ? await findDelivered(ctx.dataDir, ref.resourceId) : await findDeliveredByUrl(ctx.dataDir, ref.url);
1170
- const presentOpts = { printBody: args.printBody === true, sectionsBudget };
1171
- if (existing !== null) {
1172
- return deliverExisting(existing, presentOpts);
1173
- }
1174
- const searchId = await findSearchForResource(ctx.dataDir, {
1175
- ...ref.resourceId !== void 0 ? { resourceId: ref.resourceId } : {},
1176
- url: ref.url
1177
- }) ?? void 0;
1178
- const fetchOpts = {
1179
- timeoutMs: ctx.flags.timeout,
1180
- ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
1181
- };
1182
- const first = await fetchRead(ref.url, fetchOpts);
1183
- if (first.kind === "entitled") {
1184
- return await deliverFresh(ctx.dataDir, ref.url, first.body, "free", void 0, presentOpts);
1185
- }
1186
- if (first.kind === "already_purchased") {
1187
- throw new CliError("API_UNREACHABLE", "Unexpected 409 on an unauthenticated read.", {
1188
- fix: "Retry; if it persists, update tenjin-cli."
1189
- });
1190
- }
1191
- const firstRequirement = first.paymentRequired.accepts[0];
1192
- if (firstRequirement === void 0) {
1193
- throw new CliError("PAYMENT_FAILED", "The 402 advertised no payment requirements.", {
1194
- fix: "Try another candidate; this resource looks misconfigured."
1195
- });
1196
- }
1197
- const firstSeenAmount = BigInt(firstRequirement.amount);
1198
- const provider = resolveWalletProvider(
1199
- ctx,
1200
- deps.provider !== void 0 ? { provider: deps.provider } : {}
1201
- );
1202
- await describeWallet(provider);
1203
- const signer = await provider.getSigner();
1204
- const siwxHeader = await buildSiwxHeader(signer, {
1205
- baseUrl: settings.baseUrl,
1206
- chainId: firstRequirement.network
1207
- });
1208
- const recheck = await fetchRead(ref.url, { ...fetchOpts, siwxHeader });
1209
- if (recheck.kind === "entitled") {
1210
- return await deliverFresh(
1211
- ctx.dataDir,
1212
- ref.url,
1213
- recheck.body,
1214
- "entitled",
1215
- void 0,
1216
- presentOpts
1217
- );
1218
- }
1219
- if (recheck.kind !== "payment_required") {
1220
- throw new CliError(
1221
- "API_UNREACHABLE",
1222
- "Unexpected read response during the entitlement re-check.",
1223
- {
1224
- fix: "Retry; if it persists, update tenjin-cli."
1225
- }
1226
- );
1227
- }
1228
- const paymentRequired = recheck.paymentRequired;
1229
- const requirement = paymentRequired.accepts[0];
1230
- if (requirement === void 0) {
1231
- throw new CliError("PAYMENT_FAILED", "The fresh 402 advertised no payment requirements.", {
1232
- fix: "Try another candidate; this resource looks misconfigured."
1233
- });
1234
- }
1235
- const amountAtomic = BigInt(requirement.amount);
1236
- if (amountAtomic > firstSeenAmount) {
1237
- throw new CliError("PAYMENT_FAILED", "The price increased before signing; refusing to pay.", {
1238
- fix: "Re-run `tenjin buy` to review the new price, and set --max-price to cap it.",
1239
- details: {
1240
- firstSeenAtomic: firstSeenAmount.toString(),
1241
- currentAtomic: amountAtomic.toString()
1242
- }
1243
- });
1244
- }
1245
- const network = requirement.network;
1246
- const creator = creatorFrom(recheck.preview);
1247
- const authorizer = resolveSpendAuthorizer(
1248
- ctx,
1249
- settings.policy,
1250
- deps.authorizer !== void 0 ? { authorizer: deps.authorizer } : {}
1251
- );
1252
- const authorization = await authorizer.authorize({
1253
- amountAtomic,
1254
- creator,
1255
- ...maxPriceAtomic !== void 0 ? { maxPriceAtomic } : {}
1256
- });
1257
- if (authorization.decision === "deny") {
1258
- throw new CliError("POLICY_REFUSED", authorization.message, {
1259
- fix: policyFix(authorization.reason),
1260
- details: { reason: authorization.reason, amountAtomic: amountAtomic.toString() }
1261
- });
1262
- }
1263
- const reservationId = authorization.reservationId;
1264
- if (authorization.decision === "confirm") {
1265
- const approved = await confirmSpend(ctx, deps, args.yes === true, amountAtomic, creator);
1266
- if (!approved) {
1267
- await authorizer.release(reservationId);
1268
- throw new CliError("POLICY_REFUSED", "Purchase not confirmed.", {
1269
- fix: "Re-run with --yes, or set a policy that auto-approves this spend.",
1270
- details: { reason: authorization.reason, amountAtomic: amountAtomic.toString() }
1271
- });
1272
- }
1273
- }
1274
- try {
1275
- const payment = await buildExactPayment(paymentRequired, signer);
1276
- const paid = await fetchRead(ref.url, {
1277
- ...fetchOpts,
1278
- paymentHeaders: payment.headers,
1279
- ...searchId !== void 0 ? { searchId } : {}
1280
- });
1281
- if (paid.kind === "entitled") {
1282
- await authorizer.commit(reservationId, payment.amountAtomic);
1283
- return await deliverFresh(
1284
- ctx.dataDir,
1285
- ref.url,
1286
- paid.body,
1287
- "purchased",
1288
- { paidAtomic: payment.amountAtomic, settlementTxHash: paid.settlementTxHash },
1289
- presentOpts
1290
- );
1291
- }
1292
- if (paid.kind === "already_purchased") {
1293
- await authorizer.release(reservationId);
1294
- return await siwxRedeliver(
1295
- ctx,
1296
- ref.url,
1297
- settings.baseUrl,
1298
- signer,
1299
- fetchOpts,
1300
- presentOpts,
1301
- network
1302
- );
1303
- }
1304
- throw new CliError("PAYMENT_FAILED", "Payment was not accepted by the read route.", {
1305
- fix: "Check the wallet balance and network, then retry.",
1306
- details: paid.paymentRequired.error
1307
- });
1308
- } catch (err) {
1309
- await authorizer.release(reservationId);
1310
- throw err;
1311
- }
1312
- }
1313
- async function siwxRedeliver(ctx, url, baseUrl, signer, fetchOpts, presentOpts, network) {
1314
- const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: network });
1315
- const res = await fetchRead(url, { ...fetchOpts, siwxHeader });
1316
- if (res.kind !== "entitled") {
1317
- throw new CliError("PAYMENT_FAILED", "The resource is owned but could not be re-read.", {
1318
- fix: "Retry; if it persists the entitlement may not have propagated yet."
1319
- });
1320
- }
1321
- return await deliverFresh(ctx.dataDir, url, res.body, "entitled", void 0, presentOpts);
1322
- }
1323
- function creatorFrom(preview) {
1324
- const creator = preview.creator;
1325
- if (creator !== void 0) {
1326
- const handle = creator.handle;
1327
- const wallet = creator.walletAddress;
1328
- if (typeof handle === "string" && handle.length > 0) return handle;
1329
- if (typeof wallet === "string" && wallet.length > 0) return wallet;
1330
- }
1331
- return "";
1332
- }
1333
- function policyFix(reason) {
1334
- switch (reason) {
1335
- case "price_cap_exceeded":
1336
- return "Raise --max-price if this price is acceptable.";
1337
- case "not_allowlisted":
1338
- return "Add the creator to allowlistCreators, or clear the allowlist.";
1339
- case "session_budget_exceeded":
1340
- return "Raise sessionBudget with `tenjin config set sessionBudget <usd>`, or wait for the window to roll over.";
1341
- default:
1342
- return "Adjust your spend policy with `tenjin config set`.";
1343
- }
1344
- }
1345
- async function confirmSpend(ctx, deps, yes, amountAtomic, creator) {
1346
- if (yes) return true;
1347
- const prompt = `Pay ${toMoney(amountAtomic.toString()).usd} USD to ${sanitizeForTerminal(creator) || "this creator"}? [y/N] `;
1348
- if (deps.confirm !== void 0) return deps.confirm(prompt);
1349
- if (!ctx.io.isTTY) return false;
1350
- if (!process.stdin.isTTY) return false;
1351
- return promptYesNo(prompt);
1352
- }
1353
-
1354
- export {
1355
- runBuy
1356
- };
1357
- //# sourceMappingURL=chunk-DAZAXFSF.js.map