@absol-labs/agent 0.11.0 → 0.12.0-rc.2

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 (366) hide show
  1. package/README.md +43 -51
  2. package/dist/capability/invocation-capability.d.ts +2 -2
  3. package/dist/capability/probe-capability.d.ts +225 -0
  4. package/dist/capability/probe-capability.d.ts.map +1 -0
  5. package/dist/capability/probe-capability.js +248 -0
  6. package/dist/capability/probe-capability.js.map +1 -0
  7. package/dist/cli/args.d.ts +11 -0
  8. package/dist/cli/args.d.ts.map +1 -1
  9. package/dist/cli/args.js +23 -0
  10. package/dist/cli/args.js.map +1 -1
  11. package/dist/cli/commands/claim.d.ts +32 -0
  12. package/dist/cli/commands/claim.d.ts.map +1 -1
  13. package/dist/cli/commands/claim.js +116 -28
  14. package/dist/cli/commands/claim.js.map +1 -1
  15. package/dist/cli/commands/close.d.ts.map +1 -1
  16. package/dist/cli/commands/close.js +35 -3
  17. package/dist/cli/commands/close.js.map +1 -1
  18. package/dist/cli/commands/invoke.d.ts +2 -0
  19. package/dist/cli/commands/invoke.d.ts.map +1 -1
  20. package/dist/cli/commands/invoke.js +2 -2
  21. package/dist/cli/commands/invoke.js.map +1 -1
  22. package/dist/cli/commands/mcp.d.ts.map +1 -1
  23. package/dist/cli/commands/mcp.js +15 -2
  24. package/dist/cli/commands/mcp.js.map +1 -1
  25. package/dist/cli/commands/open.d.ts.map +1 -1
  26. package/dist/cli/commands/open.js +58 -4
  27. package/dist/cli/commands/open.js.map +1 -1
  28. package/dist/cli/commands/pay.d.ts +34 -0
  29. package/dist/cli/commands/pay.d.ts.map +1 -0
  30. package/dist/cli/commands/pay.js +479 -0
  31. package/dist/cli/commands/pay.js.map +1 -0
  32. package/dist/cli/commands/reclaim-unverified.d.ts.map +1 -1
  33. package/dist/cli/commands/reclaim-unverified.js +3 -2
  34. package/dist/cli/commands/reclaim-unverified.js.map +1 -1
  35. package/dist/cli/commands/reclaim.d.ts +23 -2
  36. package/dist/cli/commands/reclaim.d.ts.map +1 -1
  37. package/dist/cli/commands/reclaim.js +204 -20
  38. package/dist/cli/commands/reclaim.js.map +1 -1
  39. package/dist/cli/commands/refund.d.ts +31 -0
  40. package/dist/cli/commands/refund.d.ts.map +1 -0
  41. package/dist/cli/commands/refund.js +397 -0
  42. package/dist/cli/commands/refund.js.map +1 -0
  43. package/dist/cli/commands/status.d.ts.map +1 -1
  44. package/dist/cli/commands/status.js +21 -2
  45. package/dist/cli/commands/status.js.map +1 -1
  46. package/dist/cli/commands/streams.js +8 -12
  47. package/dist/cli/commands/streams.js.map +1 -1
  48. package/dist/cli/commands/watch.d.ts.map +1 -1
  49. package/dist/cli/commands/watch.js +4 -1
  50. package/dist/cli/commands/watch.js.map +1 -1
  51. package/dist/cli/config.d.ts +44 -26
  52. package/dist/cli/config.d.ts.map +1 -1
  53. package/dist/cli/config.js +88 -38
  54. package/dist/cli/config.js.map +1 -1
  55. package/dist/cli/context.d.ts +19 -0
  56. package/dist/cli/context.d.ts.map +1 -1
  57. package/dist/cli/deps.d.ts +53 -0
  58. package/dist/cli/deps.d.ts.map +1 -1
  59. package/dist/cli/deps.js +51 -1
  60. package/dist/cli/deps.js.map +1 -1
  61. package/dist/cli/errors.d.ts.map +1 -1
  62. package/dist/cli/errors.js +21 -1
  63. package/dist/cli/errors.js.map +1 -1
  64. package/dist/cli/escape-hatch.d.ts +6 -4
  65. package/dist/cli/escape-hatch.d.ts.map +1 -1
  66. package/dist/cli/escape-hatch.js +6 -2
  67. package/dist/cli/escape-hatch.js.map +1 -1
  68. package/dist/cli/listings.d.ts +18 -0
  69. package/dist/cli/listings.d.ts.map +1 -1
  70. package/dist/cli/listings.js +22 -12
  71. package/dist/cli/listings.js.map +1 -1
  72. package/dist/cli/preflight.d.ts +20 -14
  73. package/dist/cli/preflight.d.ts.map +1 -1
  74. package/dist/cli/preflight.js +34 -20
  75. package/dist/cli/preflight.js.map +1 -1
  76. package/dist/cli/privy.d.ts.map +1 -1
  77. package/dist/cli/privy.js +4 -2
  78. package/dist/cli/privy.js.map +1 -1
  79. package/dist/cli/progress.d.ts +13 -1
  80. package/dist/cli/progress.d.ts.map +1 -1
  81. package/dist/cli/progress.js +7 -1
  82. package/dist/cli/progress.js.map +1 -1
  83. package/dist/cli/reclaimability.d.ts +82 -0
  84. package/dist/cli/reclaimability.d.ts.map +1 -0
  85. package/dist/cli/reclaimability.js +80 -0
  86. package/dist/cli/reclaimability.js.map +1 -0
  87. package/dist/cli/run.d.ts +2 -1
  88. package/dist/cli/run.d.ts.map +1 -1
  89. package/dist/cli/run.js +62 -21
  90. package/dist/cli/run.js.map +1 -1
  91. package/dist/cli/scan-range.d.ts +2 -2
  92. package/dist/cli/scan-range.js +2 -2
  93. package/dist/cli/status.d.ts +106 -1
  94. package/dist/cli/status.d.ts.map +1 -1
  95. package/dist/cli/status.js +325 -44
  96. package/dist/cli/status.js.map +1 -1
  97. package/dist/cli/wallet.d.ts +2 -2
  98. package/dist/cli/wallet.d.ts.map +1 -1
  99. package/dist/cli/wallet.js +29 -5
  100. package/dist/cli/wallet.js.map +1 -1
  101. package/dist/discovery/rate-band.d.ts +74 -0
  102. package/dist/discovery/rate-band.d.ts.map +1 -0
  103. package/dist/discovery/rate-band.js +114 -0
  104. package/dist/discovery/rate-band.js.map +1 -0
  105. package/dist/escrow-generation.d.ts +81 -0
  106. package/dist/escrow-generation.d.ts.map +1 -0
  107. package/dist/escrow-generation.js +76 -0
  108. package/dist/escrow-generation.js.map +1 -0
  109. package/dist/frameworks/agentkit.d.ts +8 -4
  110. package/dist/frameworks/agentkit.d.ts.map +1 -1
  111. package/dist/frameworks/agentkit.js +27 -10
  112. package/dist/frameworks/agentkit.js.map +1 -1
  113. package/dist/frameworks/eliza.d.ts +3 -3
  114. package/dist/frameworks/eliza.d.ts.map +1 -1
  115. package/dist/frameworks/eliza.js +15 -6
  116. package/dist/frameworks/eliza.js.map +1 -1
  117. package/dist/frameworks/langchain.d.ts.map +1 -1
  118. package/dist/frameworks/langchain.js +8 -0
  119. package/dist/frameworks/langchain.js.map +1 -1
  120. package/dist/gateway/caller-auth-gateway.d.ts +83 -31
  121. package/dist/gateway/caller-auth-gateway.d.ts.map +1 -1
  122. package/dist/gateway/caller-auth-gateway.js +180 -27
  123. package/dist/gateway/caller-auth-gateway.js.map +1 -1
  124. package/dist/gateway/http-server.d.ts +128 -44
  125. package/dist/gateway/http-server.d.ts.map +1 -1
  126. package/dist/gateway/http-server.js +506 -155
  127. package/dist/gateway/http-server.js.map +1 -1
  128. package/dist/gateway/probe-auth.d.ts +112 -0
  129. package/dist/gateway/probe-auth.d.ts.map +1 -0
  130. package/dist/gateway/probe-auth.js +127 -0
  131. package/dist/gateway/probe-auth.js.map +1 -0
  132. package/dist/gateway/signed-rate-bounds.d.ts +51 -0
  133. package/dist/gateway/signed-rate-bounds.d.ts.map +1 -0
  134. package/dist/gateway/signed-rate-bounds.js +94 -0
  135. package/dist/gateway/signed-rate-bounds.js.map +1 -0
  136. package/dist/gateway/x402-opener-mode.d.ts +252 -0
  137. package/dist/gateway/x402-opener-mode.d.ts.map +1 -0
  138. package/dist/gateway/x402-opener-mode.js +772 -0
  139. package/dist/gateway/x402-opener-mode.js.map +1 -0
  140. package/dist/index.d.ts +6 -2
  141. package/dist/index.d.ts.map +1 -1
  142. package/dist/index.js +10 -5
  143. package/dist/index.js.map +1 -1
  144. package/dist/mcp/server.d.ts +64 -1
  145. package/dist/mcp/server.d.ts.map +1 -1
  146. package/dist/mcp/server.js +247 -37
  147. package/dist/mcp/server.js.map +1 -1
  148. package/dist/mcp/x402-tools.d.ts +109 -0
  149. package/dist/mcp/x402-tools.d.ts.map +1 -0
  150. package/dist/mcp/x402-tools.js +554 -0
  151. package/dist/mcp/x402-tools.js.map +1 -0
  152. package/dist/network.d.ts +119 -0
  153. package/dist/network.d.ts.map +1 -0
  154. package/dist/network.js +199 -0
  155. package/dist/network.js.map +1 -0
  156. package/dist/sdk/client.d.ts +13 -0
  157. package/dist/sdk/client.d.ts.map +1 -1
  158. package/dist/sdk/client.js +15 -0
  159. package/dist/sdk/client.js.map +1 -1
  160. package/dist/sdk/invoke.d.ts +4 -0
  161. package/dist/sdk/invoke.d.ts.map +1 -1
  162. package/dist/sdk/invoke.js +2 -5
  163. package/dist/sdk/invoke.js.map +1 -1
  164. package/dist/wallet/autonomous-wallet-broker.d.ts +3 -0
  165. package/dist/wallet/autonomous-wallet-broker.d.ts.map +1 -1
  166. package/dist/wallet/autonomous-wallet-broker.js +27 -23
  167. package/dist/wallet/autonomous-wallet-broker.js.map +1 -1
  168. package/dist/wallet/autonomous-wallet-protocol.d.ts +8 -2
  169. package/dist/wallet/autonomous-wallet-protocol.d.ts.map +1 -1
  170. package/dist/wallet/autonomous-wallet-protocol.js +9 -2
  171. package/dist/wallet/autonomous-wallet-protocol.js.map +1 -1
  172. package/dist/wallet/autonomous-wallet.d.ts.map +1 -1
  173. package/dist/wallet/autonomous-wallet.js +3 -2
  174. package/dist/wallet/autonomous-wallet.js.map +1 -1
  175. package/dist/wallet/broker-escrows.d.ts +222 -0
  176. package/dist/wallet/broker-escrows.d.ts.map +1 -0
  177. package/dist/wallet/broker-escrows.js +36 -0
  178. package/dist/wallet/broker-escrows.js.map +1 -0
  179. package/dist/wallet/lifecycle.d.ts +21 -5
  180. package/dist/wallet/lifecycle.d.ts.map +1 -1
  181. package/dist/wallet/lifecycle.js +32 -12
  182. package/dist/wallet/lifecycle.js.map +1 -1
  183. package/dist/wallet/privy-broker-server.d.ts.map +1 -1
  184. package/dist/wallet/privy-broker-server.js +31 -26
  185. package/dist/wallet/privy-broker-server.js.map +1 -1
  186. package/dist/wallet/privy-session-broker.d.ts +14 -5
  187. package/dist/wallet/privy-session-broker.d.ts.map +1 -1
  188. package/dist/wallet/privy-session-broker.js +29 -17
  189. package/dist/wallet/privy-session-broker.js.map +1 -1
  190. package/dist/wallet/privy-session-provider.d.ts +3 -1
  191. package/dist/wallet/privy-session-provider.d.ts.map +1 -1
  192. package/dist/wallet/privy-session-provider.js +5 -3
  193. package/dist/wallet/privy-session-provider.js.map +1 -1
  194. package/dist/wallet/provider.d.ts.map +1 -1
  195. package/dist/wallet/provider.js +15 -8
  196. package/dist/wallet/provider.js.map +1 -1
  197. package/dist/x402/facilitator.d.ts +3 -30
  198. package/dist/x402/facilitator.d.ts.map +1 -1
  199. package/dist/x402/facilitator.js +0 -27
  200. package/dist/x402/facilitator.js.map +1 -1
  201. package/dist/x402-buyer/guarded-fetch.d.ts +51 -0
  202. package/dist/x402-buyer/guarded-fetch.d.ts.map +1 -0
  203. package/dist/x402-buyer/guarded-fetch.js +147 -0
  204. package/dist/x402-buyer/guarded-fetch.js.map +1 -0
  205. package/dist/x402-buyer/index.d.ts +10 -0
  206. package/dist/x402-buyer/index.d.ts.map +1 -0
  207. package/dist/x402-buyer/index.js +10 -0
  208. package/dist/x402-buyer/index.js.map +1 -0
  209. package/dist/x402-buyer/pay.d.ts +157 -0
  210. package/dist/x402-buyer/pay.d.ts.map +1 -0
  211. package/dist/x402-buyer/pay.js +366 -0
  212. package/dist/x402-buyer/pay.js.map +1 -0
  213. package/dist/x402-opener/abi.d.ts +684 -0
  214. package/dist/x402-opener/abi.d.ts.map +1 -0
  215. package/dist/x402-opener/abi.js +880 -0
  216. package/dist/x402-opener/abi.js.map +1 -0
  217. package/dist/x402-opener/facilitator-entry.d.ts +3 -0
  218. package/dist/x402-opener/facilitator-entry.d.ts.map +1 -0
  219. package/dist/x402-opener/facilitator-entry.js +40 -0
  220. package/dist/x402-opener/facilitator-entry.js.map +1 -0
  221. package/dist/x402-opener/facilitator-server.d.ts +209 -0
  222. package/dist/x402-opener/facilitator-server.d.ts.map +1 -0
  223. package/dist/x402-opener/facilitator-server.js +762 -0
  224. package/dist/x402-opener/facilitator-server.js.map +1 -0
  225. package/dist/x402-opener/index.d.ts +14 -0
  226. package/dist/x402-opener/index.d.ts.map +1 -0
  227. package/dist/x402-opener/index.js +14 -0
  228. package/dist/x402-opener/index.js.map +1 -0
  229. package/dist/x402-opener/listing-resolver.d.ts +55 -0
  230. package/dist/x402-opener/listing-resolver.d.ts.map +1 -0
  231. package/dist/x402-opener/listing-resolver.js +125 -0
  232. package/dist/x402-opener/listing-resolver.js.map +1 -0
  233. package/dist/x402-opener/refund-relay.d.ts +266 -0
  234. package/dist/x402-opener/refund-relay.d.ts.map +1 -0
  235. package/dist/x402-opener/refund-relay.js +1341 -0
  236. package/dist/x402-opener/refund-relay.js.map +1 -0
  237. package/dist/x402-opener/relayer-queue.d.ts +14 -0
  238. package/dist/x402-opener/relayer-queue.d.ts.map +1 -0
  239. package/dist/x402-opener/relayer-queue.js +18 -0
  240. package/dist/x402-opener/relayer-queue.js.map +1 -0
  241. package/dist/x402-opener/scheme.d.ts +296 -0
  242. package/dist/x402-opener/scheme.d.ts.map +1 -0
  243. package/dist/x402-opener/scheme.js +1035 -0
  244. package/dist/x402-opener/scheme.js.map +1 -0
  245. package/dist/x402-opener/terms.d.ts +165 -0
  246. package/dist/x402-opener/terms.d.ts.map +1 -0
  247. package/dist/x402-opener/terms.js +304 -0
  248. package/dist/x402-opener/terms.js.map +1 -0
  249. package/dist/zktls/reclaim.d.ts +2 -2
  250. package/dist/zktls/t2-delivery-proof.d.ts +6 -6
  251. package/docs/agent-layer.md +3 -2
  252. package/docs/autonomous-privy-wallet.md +188 -0
  253. package/docs/cli.md +265 -34
  254. package/docs/langchain.md +5 -0
  255. package/docs/mcp-reference.md +91 -5
  256. package/docs/probe-capability.md +191 -0
  257. package/docs/quickstart.md +39 -4
  258. package/docs/threat-model.md +20 -0
  259. package/docs/x402.md +766 -593
  260. package/package.json +19 -17
  261. package/src/capability/probe-capability.ts +355 -0
  262. package/src/cli/args.ts +29 -0
  263. package/src/cli/commands/claim.ts +168 -33
  264. package/src/cli/commands/close.ts +36 -3
  265. package/src/cli/commands/invoke.ts +5 -2
  266. package/src/cli/commands/mcp.ts +18 -2
  267. package/src/cli/commands/open.ts +75 -4
  268. package/src/cli/commands/pay.ts +584 -0
  269. package/src/cli/commands/reclaim-unverified.ts +8 -2
  270. package/src/cli/commands/reclaim.ts +277 -19
  271. package/src/cli/commands/refund.ts +475 -0
  272. package/src/cli/commands/status.ts +28 -2
  273. package/src/cli/commands/streams.ts +10 -14
  274. package/src/cli/commands/watch.ts +11 -1
  275. package/src/cli/config.ts +139 -52
  276. package/src/cli/context.ts +16 -0
  277. package/src/cli/deps.ts +111 -1
  278. package/src/cli/errors.ts +24 -1
  279. package/src/cli/escape-hatch.ts +19 -5
  280. package/src/cli/listings.ts +43 -10
  281. package/src/cli/preflight.ts +36 -21
  282. package/src/cli/privy.ts +4 -2
  283. package/src/cli/progress.ts +21 -2
  284. package/src/cli/reclaimability.ts +154 -0
  285. package/src/cli/run.ts +77 -21
  286. package/src/cli/scan-range.ts +2 -2
  287. package/src/cli/status.ts +454 -44
  288. package/src/cli/wallet.ts +45 -8
  289. package/src/discovery/rate-band.ts +172 -0
  290. package/src/escrow-generation.ts +135 -0
  291. package/src/frameworks/agentkit.ts +45 -11
  292. package/src/frameworks/eliza.ts +27 -5
  293. package/src/frameworks/langchain.ts +14 -0
  294. package/src/gateway/caller-auth-gateway.ts +320 -68
  295. package/src/gateway/http-server.ts +717 -220
  296. package/src/gateway/probe-auth.ts +191 -0
  297. package/src/gateway/signed-rate-bounds.ts +164 -0
  298. package/src/gateway/x402-opener-mode.ts +1171 -0
  299. package/src/index.ts +82 -19
  300. package/src/mcp/server.ts +351 -42
  301. package/src/mcp/x402-tools.ts +785 -0
  302. package/src/network.ts +302 -0
  303. package/src/sdk/client.ts +25 -0
  304. package/src/sdk/invoke.ts +6 -5
  305. package/src/wallet/autonomous-wallet-broker.ts +46 -20
  306. package/src/wallet/autonomous-wallet-protocol.ts +11 -2
  307. package/src/wallet/autonomous-wallet.ts +4 -2
  308. package/src/wallet/broker-escrows.ts +66 -0
  309. package/src/wallet/lifecycle.ts +53 -18
  310. package/src/wallet/privy-broker-server.ts +35 -25
  311. package/src/wallet/privy-session-broker.ts +58 -25
  312. package/src/wallet/privy-session-provider.ts +7 -3
  313. package/src/wallet/provider.ts +20 -15
  314. package/src/x402/facilitator.ts +3 -43
  315. package/src/x402-buyer/guarded-fetch.ts +213 -0
  316. package/src/x402-buyer/index.ts +9 -0
  317. package/src/x402-buyer/pay.ts +555 -0
  318. package/src/x402-opener/abi.ts +881 -0
  319. package/src/x402-opener/facilitator-entry.ts +48 -0
  320. package/src/x402-opener/facilitator-server.ts +1114 -0
  321. package/src/x402-opener/index.ts +13 -0
  322. package/src/x402-opener/listing-resolver.ts +202 -0
  323. package/src/x402-opener/refund-relay.ts +1873 -0
  324. package/src/x402-opener/relayer-queue.ts +18 -0
  325. package/src/x402-opener/scheme.ts +1551 -0
  326. package/src/x402-opener/terms.ts +453 -0
  327. package/dist/gateway/x402-mode.d.ts +0 -123
  328. package/dist/gateway/x402-mode.d.ts.map +0 -1
  329. package/dist/gateway/x402-mode.js +0 -212
  330. package/dist/gateway/x402-mode.js.map +0 -1
  331. package/dist/x402/delivery-oracle.d.ts +0 -108
  332. package/dist/x402/delivery-oracle.d.ts.map +0 -1
  333. package/dist/x402/delivery-oracle.js +0 -174
  334. package/dist/x402/delivery-oracle.js.map +0 -1
  335. package/dist/x402/facilitator-server-entry.d.ts +0 -3
  336. package/dist/x402/facilitator-server-entry.d.ts.map +0 -1
  337. package/dist/x402/facilitator-server-entry.js +0 -27
  338. package/dist/x402/facilitator-server-entry.js.map +0 -1
  339. package/dist/x402/facilitator-server.d.ts +0 -73
  340. package/dist/x402/facilitator-server.d.ts.map +0 -1
  341. package/dist/x402/facilitator-server.js +0 -305
  342. package/dist/x402/facilitator-server.js.map +0 -1
  343. package/dist/x402/payment-requirements.d.ts +0 -106
  344. package/dist/x402/payment-requirements.d.ts.map +0 -1
  345. package/dist/x402/payment-requirements.js +0 -138
  346. package/dist/x402/payment-requirements.js.map +0 -1
  347. package/dist/x402/relayer.d.ts +0 -41
  348. package/dist/x402/relayer.d.ts.map +0 -1
  349. package/dist/x402/relayer.js +0 -64
  350. package/dist/x402/relayer.js.map +0 -1
  351. package/dist/x402/resource-index.d.ts +0 -75
  352. package/dist/x402/resource-index.d.ts.map +0 -1
  353. package/dist/x402/resource-index.js +0 -126
  354. package/dist/x402/resource-index.js.map +0 -1
  355. package/dist/x402/verified-delivery-facilitator.d.ts +0 -285
  356. package/dist/x402/verified-delivery-facilitator.d.ts.map +0 -1
  357. package/dist/x402/verified-delivery-facilitator.js +0 -423
  358. package/dist/x402/verified-delivery-facilitator.js.map +0 -1
  359. package/src/gateway/x402-mode.ts +0 -350
  360. package/src/x402/delivery-oracle.ts +0 -285
  361. package/src/x402/facilitator-server-entry.ts +0 -35
  362. package/src/x402/facilitator-server.ts +0 -445
  363. package/src/x402/payment-requirements.ts +0 -231
  364. package/src/x402/relayer.ts +0 -122
  365. package/src/x402/resource-index.ts +0 -228
  366. package/src/x402/verified-delivery-facilitator.ts +0 -744
@@ -0,0 +1,1171 @@
1
+ import {
2
+ HTTPFacilitatorClient,
3
+ SETTLEMENT_OVERRIDES_HEADER,
4
+ withPrivateCacheControl,
5
+ x402HTTPResourceServer,
6
+ x402ResourceServer,
7
+ type FacilitatorClient,
8
+ type HTTPAdapter,
9
+ type HTTPProcessResult,
10
+ type HTTPRequestContext,
11
+ type HTTPResponseInstructions,
12
+ type ProcessSettleResultResponse,
13
+ type RouteConfig,
14
+ type SettleResultContext,
15
+ } from "@x402/core/server";
16
+ import type { Network } from "@x402/core/types";
17
+ import { decodePaymentSignatureHeader } from "@x402/core/http";
18
+ import { ExactEvmScheme } from "@x402/evm/exact/server";
19
+ import {
20
+ createPublicClient,
21
+ formatUnits,
22
+ getAddress,
23
+ http,
24
+ isAddress,
25
+ type Address,
26
+ type PublicClient,
27
+ } from "viem";
28
+
29
+ import {
30
+ predictUpfrontOpenerAddress,
31
+ x402UpfrontStreamOpenerFactoryAbi,
32
+ } from "@absol-labs/shared";
33
+
34
+ import { x402StreamOpenerFactoryAbi } from "../x402-opener/abi.js";
35
+ import {
36
+ RegistryListingResolver,
37
+ type OperatorSignedListingResolver,
38
+ } from "../x402-opener/listing-resolver.js";
39
+ import { readOpenerFacilitatorMarker } from "../x402-opener/scheme.js";
40
+ import {
41
+ assertValidPrice,
42
+ assertValidTerms,
43
+ assertValidUpfrontTerms,
44
+ chainIdFromNetwork,
45
+ assertSchemaDeclaration,
46
+ DEFAULT_OPENER_DOCS_URL,
47
+ isHttpLink,
48
+ OPENER_EXTRA_KEY,
49
+ OPENER_SCHEME,
50
+ termsToExtra,
51
+ termsTuple,
52
+ upfrontTermsToExtra,
53
+ upfrontTermsTuple,
54
+ type OpenerKind,
55
+ type OpenerTerms,
56
+ type UpfrontOpenerTerms,
57
+ type X402SchemaDeclaration,
58
+ } from "../x402-opener/terms.js";
59
+
60
+ /**
61
+ * The gateway's x402 v2 mode (metrik-agent#116): answer an uncapabilitied
62
+ * request with a standard x402 v2 `402` whose `payTo` is the listing's
63
+ * `X402StreamOpener` address, and settle every accepted payment INTO a
64
+ * `StreamEscrowV2` stream through the Metrik opener facilitator.
65
+ *
66
+ * The wire format is the official `@x402/core` resource server's, not a
67
+ * re-implementation: `x402HTTPResourceServer` builds `PAYMENT-REQUIRED`,
68
+ * matches `PAYMENT-SIGNATURE`, verifies and settles through the facilitator and
69
+ * builds `PAYMENT-RESPONSE`.
70
+ *
71
+ * ## The opener payTo must ONLY ever be settled by the Metrik opener facilitator
72
+ *
73
+ * A stock x402 `exact` facilitator settles by calling
74
+ * `USDC.transferWithAuthorization(to = payTo)` directly. Pointed at an opener,
75
+ * that strands 100% of the payer's funds in the opener permanently (there is,
76
+ * deliberately, no sweep). So this mode:
77
+ *
78
+ * - refuses to START unless the configured facilitator's `GET /supported`
79
+ * advertises the opener marker for exactly this factory, escrow, token and
80
+ * chain; and re-checks that marker on a timer, failing CLOSED (503, no
81
+ * `payTo` quoted, nothing verified or settled) whenever it cannot;
82
+ * - uses exactly one facilitator client, never a fallback list;
83
+ * - registers no discovery (Bazaar) extension and never submits the route to
84
+ * any catalog. When (and only when) the operator configures an input/output
85
+ * schema, it is DECLARED in the 402 in the standard `extensions.bazaar`
86
+ * shape so a client can read what to send; only the Metrik opener
87
+ * facilitator ever sees the payment, and it catalogs nothing;
88
+ * - states plainly in the 402 `description` what is bought (the stream
89
+ * window, rate, that the seller earns only verified seconds, and that
90
+ * unearned money is refundable without ETH through the facilitator's
91
+ * refund relay) and refuses to start unless that facilitator advertises
92
+ * the relay (`refundRelay: true` in its marker) — the 402 never promises a
93
+ * refund path that is not there. Refunds are not automatic;
94
+ * - authenticates the opener only as `factory.predict(terms)` — never by code
95
+ * or codehash, which a clone outside the factory can reproduce;
96
+ * - serves one EIP-3009 authorization at most once: a `PAYMENT-SIGNATURE`
97
+ * whose authorization is in flight or already settled gets `409` WITHOUT an
98
+ * upstream call (in-memory, per gateway instance). A retry after
99
+ * `settlement_pending` is let through so it can reconcile;
100
+ * - refuses to start if its price is below the facilitator's advertised
101
+ * minimum, or if its facilitator timeout would not outlast the facilitator's
102
+ * receipt wait.
103
+ *
104
+ * ## Two opener kinds
105
+ *
106
+ * Without `upfrontAmount` the listing quotes the `X402StreamOpenerFactory`
107
+ * (`"stream"`): the whole price funds a metered stream. With `upfrontAmount`
108
+ * it quotes the `X402UpfrontStreamOpenerFactory` (`"upfront"`, the "minimum
109
+ * charge"): `amount == price`, `payTo = predict(6 terms)`, the
110
+ * `upfrontAmount` is paid to the seller at settlement and is NOT refundable,
111
+ * and only `price - upfrontAmount` funds a metered, refundable stream. The 402
112
+ * description states that split. `upfrontAmount == price` is an upfront-only
113
+ * listing: no stream opens (the settlement reports `streamId: null`), the
114
+ * response is served, and no metered session or refund exists for it.
115
+ */
116
+
117
+ /** How long a successful `/supported` marker check is trusted, seconds. */
118
+ export const DEFAULT_FACILITATOR_MARKER_TTL_SECONDS = 300;
119
+
120
+ /** Default per-request facilitator HTTP timeout. Must outlast its receipt wait. */
121
+ export const DEFAULT_FACILITATOR_TIMEOUT_MS = 120_000;
122
+
123
+ /** Headroom the facilitator timeout must leave over the facilitator's receipt wait. */
124
+ const FACILITATOR_TIMEOUT_HEADROOM_MS = 30_000;
125
+
126
+ export interface GatewayX402OpenerModeConfig {
127
+ /** Base URL of the Metrik opener facilitator (e.g. `https://facilitator.example`). */
128
+ readonly facilitatorUrl: string;
129
+ /** Bearer token the facilitator requires on `/settle`. */
130
+ readonly facilitatorToken: string;
131
+ /** CAIP-2 network (`eip155:<chainId>`), as the registry gives it. */
132
+ readonly network: Network;
133
+ readonly factoryAddress: Address;
134
+ /** The escrow this gateway checks streams against; the factory must point at it. */
135
+ readonly escrowAddress: Address;
136
+ /** Settlement token; must equal the factory's. */
137
+ readonly asset: Address;
138
+ /** EIP-712 domain of the token (Circle USDC: `USDC` / `2`). */
139
+ readonly assetName: string;
140
+ readonly assetVersion: string;
141
+ /** Opener terms. `operator` + `serviceRef` must resolve to one operator-signed listing. */
142
+ readonly terms: OpenerTerms;
143
+ /**
144
+ * Price per paid request in token base units. For a stream opener it is the
145
+ * whole stream deposit; for an upfront opener the exact x402 amount, split
146
+ * into `upfrontAmount` (non-refundable) and `price - upfrontAmount` (deposit).
147
+ */
148
+ readonly price: bigint;
149
+ /**
150
+ * Selects the UPFRONT opener kind (`factoryAddress` must then be an
151
+ * `X402UpfrontStreamOpenerFactory`): the non-refundable per-call part, base
152
+ * units, `0 <= upfrontAmount <= price`. Unset = the stream opener kind.
153
+ */
154
+ readonly upfrontAmount?: bigint;
155
+ /**
156
+ * The implementation the upfront factory must report (e.g. the registry's);
157
+ * checked at startup when given. `payTo` is always recomputed offline from
158
+ * the factory's own `implementation()` and must equal its on-chain `predict`.
159
+ */
160
+ readonly upfrontImplementation?: Address;
161
+ /** Authorization validity the client signs for. Default 300s. */
162
+ readonly maxTimeoutSeconds?: number;
163
+ /** Public origin clients reach this gateway at, for the 402 `resource.url`. */
164
+ readonly resourceBaseUrl?: string;
165
+ /**
166
+ * What the service does, in one sentence. Prefixed to the fixed disclosure
167
+ * of what the payment buys ({@link describeOpenerPurchase}); it can never
168
+ * replace that disclosure.
169
+ */
170
+ readonly description?: string;
171
+ /**
172
+ * Public base URL of the facilitator's refund relay (`/streams/:streamId`).
173
+ * Default `facilitatorUrl`. When different, its `/supported` must advertise
174
+ * the same opener marker with `refundRelay: true` (checked at startup).
175
+ */
176
+ readonly refundBaseUrl?: string;
177
+ /** Docs link carried in the 402. Default {@link DEFAULT_OPENER_DOCS_URL}. */
178
+ readonly docsUrl?: string;
179
+ /** Token decimals for the human-readable amounts in the description. Default 6 (USDC). */
180
+ readonly assetDecimals?: number;
181
+ /**
182
+ * Optional input/output schema, declared in the 402 as
183
+ * `extensions.bazaar` (`{info: {input, output}, schema}`). Declared only;
184
+ * never registered with any discovery catalog.
185
+ */
186
+ readonly schemaDeclaration?: X402SchemaDeclaration;
187
+ /** Registry used to prove the listing at startup. Default the public registry. */
188
+ readonly registryUrl?: string;
189
+ readonly markerTtlSeconds?: number;
190
+ /**
191
+ * Per-request facilitator HTTP timeout, ms. Default
192
+ * {@link DEFAULT_FACILITATOR_TIMEOUT_MS}. Must exceed the facilitator's
193
+ * advertised receipt timeout by 30 s, so the gateway never gives up on a
194
+ * settlement the facilitator is still waiting for.
195
+ */
196
+ readonly facilitatorTimeoutMs?: number;
197
+ }
198
+
199
+ /**
200
+ * The plain statement of what one payment buys, used as the 402 resource
201
+ * `description`. It names the window, the rate, that the seller earns only for
202
+ * seconds Metrik's verifier confirms, and where unearned money is refundable
203
+ * without ETH. It says that refunds are not automatic, because they are not:
204
+ * someone has to call the refund relay.
205
+ */
206
+ export function describeOpenerPurchase(input: {
207
+ readonly terms: OpenerTerms;
208
+ readonly price: bigint;
209
+ /**
210
+ * Upfront openers only: the non-refundable per-call part. The description
211
+ * then states the split (non-refundable vs metered and refundable).
212
+ */
213
+ readonly upfrontAmount?: bigint;
214
+ readonly assetDecimals: number;
215
+ readonly assetSymbol: string;
216
+ /** Refund URL template containing `{streamId}`. */
217
+ readonly refundUrlTemplate: string;
218
+ readonly docsUrl: string;
219
+ readonly serviceDescription?: string;
220
+ }): string {
221
+ const amount = (value: bigint) =>
222
+ `${formatUnits(value, input.assetDecimals)} ${input.assetSymbol}`;
223
+ const { ratePerSecond, maxDuration } = input.terms;
224
+ const prefix =
225
+ input.serviceDescription === undefined ||
226
+ input.serviceDescription.trim().length === 0
227
+ ? ""
228
+ : `${input.serviceDescription.trim()} `;
229
+ if (input.upfrontAmount !== undefined) {
230
+ const upfront = input.upfrontAmount;
231
+ const metered = input.price - upfront;
232
+ if (metered === 0n) {
233
+ return (
234
+ `${prefix}Pays for one call: ${amount(input.price)}, charged in full at settlement as a NON-REFUNDABLE per-call charge ` +
235
+ "(paid to the seller whatever is delivered). No escrow stream is opened, so nothing is metered and there is nothing to refund or reclaim. " +
236
+ `Docs: ${input.docsUrl}`
237
+ );
238
+ }
239
+ const meteredCap =
240
+ metered < ratePerSecond * maxDuration
241
+ ? ` (the seller can earn at most ${amount(metered)} of it)`
242
+ : "";
243
+ return (
244
+ `${prefix}Pays for one call: ${amount(input.price)} in total. ` +
245
+ (upfront === 0n
246
+ ? "Nothing of it is charged upfront. "
247
+ : `${amount(upfront)} is a NON-REFUNDABLE per-call charge, paid to the seller at settlement whatever is delivered. `) +
248
+ `The remaining ${amount(metered)} is metered and refundable: it funds a Metrik escrow stream of ` +
249
+ `${maxDuration.toString()} seconds at ${amount(ratePerSecond)}/s${meteredCap}; ` +
250
+ "the seller earns it only for seconds Metrik's verifier confirms the service is delivering, " +
251
+ `and any unearned part of it (at most ${amount(metered)}) is refundable to you (no ETH needed) via ${input.refundUrlTemplate}. ` +
252
+ "Refunds are not automatic: close the stream and reclaim there, using the streamId from the PAYMENT-RESPONSE. " +
253
+ `Docs: ${input.docsUrl}`
254
+ );
255
+ }
256
+ const cap =
257
+ input.price < ratePerSecond * maxDuration
258
+ ? ` (the seller can earn at most ${amount(input.price)})`
259
+ : "";
260
+ return (
261
+ `${prefix}Pays for one call. Your payment of ${amount(input.price)} funds a Metrik escrow stream of ` +
262
+ `${maxDuration.toString()} seconds at ${amount(ratePerSecond)}/s${cap}; ` +
263
+ "the seller earns only for seconds Metrik's verifier confirms the service is delivering, " +
264
+ `and anything unearned is refundable to you (no ETH needed) via ${input.refundUrlTemplate}. ` +
265
+ "Refunds are not automatic: close the stream and reclaim there, using the streamId from the PAYMENT-RESPONSE. " +
266
+ `Docs: ${input.docsUrl}`
267
+ );
268
+ }
269
+
270
+ /**
271
+ * The stock `exact` server scheme, plus ONE additive settlement enrichment:
272
+ * the successful `PAYMENT-RESPONSE` gets `extra.metrikStreamOpener.refundUrl`
273
+ * for the opened stream. It never touches the settlement outcome fields
274
+ * (`@x402/core` enforces that the enrichment is additive).
275
+ */
276
+ class OpenerExactServerScheme extends ExactEvmScheme {
277
+ constructor(private readonly refundBaseUrl: string) {
278
+ super();
279
+ }
280
+
281
+ enrichSettlementResponse = async (
282
+ context: SettleResultContext,
283
+ ): Promise<Record<string, unknown> | undefined> => {
284
+ if (!context.result.success) return undefined;
285
+ const opened = context.result.extra?.[OPENER_EXTRA_KEY] as
286
+ | Record<string, unknown>
287
+ | undefined;
288
+ const streamId = opened?.streamId;
289
+ // An upfront-only payment reports `streamId: null` (no stream): it gets no
290
+ // refund URL, since there is nothing to refund. bytes32(0) is treated the
291
+ // same, defensively.
292
+ if (
293
+ typeof streamId !== "string" ||
294
+ !/^0x[0-9a-fA-F]{64}$/.test(streamId) ||
295
+ /^0x0{64}$/i.test(streamId) ||
296
+ opened?.refundUrl !== undefined
297
+ ) {
298
+ return undefined;
299
+ }
300
+ return {
301
+ [OPENER_EXTRA_KEY]: {
302
+ refundUrl: `${this.refundBaseUrl}/streams/${streamId.toLowerCase()}`,
303
+ },
304
+ };
305
+ };
306
+ }
307
+
308
+ export interface GatewayX402OpenerModeDeps {
309
+ /** Read client for the factory. Default built from `rpcUrl`. */
310
+ readonly publicClient?: PublicClient;
311
+ readonly rpcUrl?: string;
312
+ readonly listingResolver?: OperatorSignedListingResolver;
313
+ /** Override the facilitator transport (tests). Default {@link HTTPFacilitatorClient}. */
314
+ readonly facilitatorClient?: FacilitatorClient;
315
+ readonly now?: () => number;
316
+ /** HTTP client for checking a separate `refundBaseUrl`. Default global fetch. */
317
+ readonly fetch?: typeof fetch;
318
+ }
319
+
320
+ export interface GatewayX402OpenerMode {
321
+ /** The predicted opener address quoted as `payTo`. */
322
+ readonly payTo: Address;
323
+ readonly network: Network;
324
+ readonly terms: OpenerTerms;
325
+ readonly price: bigint;
326
+ /** `"stream"` or `"upfront"` (selected by `upfrontAmount`). */
327
+ readonly openerKind: OpenerKind;
328
+ /** The upfront kind's non-refundable part; `null` for the stream kind. */
329
+ readonly upfrontAmount: bigint | null;
330
+ readonly resourceBaseUrl: string | undefined;
331
+ /** The 402 `description` (what the payment buys). */
332
+ readonly description: string;
333
+ /** Refund relay base; a stream's refund page is `${refundBaseUrl}/streams/:streamId`. */
334
+ readonly refundBaseUrl: string;
335
+ readonly httpServer: x402HTTPResourceServer;
336
+ /** One-use accounting of authorizations this gateway has seen. */
337
+ readonly authorizations: GatewayAuthorizationLedger;
338
+ /**
339
+ * Resolves once the facilitator is proven to be the Metrik opener
340
+ * facilitator for this factory (cached for the marker TTL) and the resource
341
+ * server is initialized. Rejects otherwise — callers must fail closed.
342
+ */
343
+ ready(): Promise<void>;
344
+ /** Serves one x402-mode request over the supplied transport. Never throws. */
345
+ handle(io: X402GatewayRequestIO): Promise<void>;
346
+ }
347
+
348
+ /** JSON reasons the x402 path can answer with, beyond the gateway's own. */
349
+ export type X402GatewayResponseReason =
350
+ | "x402-facilitator-unavailable"
351
+ | "x402-settlement-failed"
352
+ | "internal-error"
353
+ | "upstream-unavailable"
354
+ | "x402-payment-already-used";
355
+
356
+ export interface X402UpstreamResult {
357
+ readonly status: number;
358
+ readonly headers: Record<string, string>;
359
+ readonly body: Buffer;
360
+ }
361
+
362
+ /** The transport the HTTP server hands the x402 path. */
363
+ export interface X402GatewayRequestIO {
364
+ readonly requestUrl: URL;
365
+ readonly method: string;
366
+ /** Lower-cased request headers. */
367
+ readonly headers: Readonly<Record<string, string | undefined>>;
368
+ /** Proxies the request upstream (payment headers stripped) and buffers the response. */
369
+ callUpstream(): Promise<X402UpstreamResult>;
370
+ writeJson(status: number, reason: X402GatewayResponseReason): void;
371
+ write(
372
+ status: number,
373
+ headers: Record<string, string>,
374
+ body: Buffer | string,
375
+ ): void;
376
+ logError(context: string, error: unknown): void;
377
+ }
378
+
379
+ const PAYMENT_SIGNATURE_HEADER = "payment-signature";
380
+
381
+ /**
382
+ * Per-gateway, in-memory record of EIP-3009 authorizations (chain + asset +
383
+ * payer + nonce): `in-flight` while a request is being verified/served/
384
+ * settled, `pending` after a `settlement_pending` (a retry may reconcile), and
385
+ * `settled` once a success was delivered. In-flight and settled
386
+ * authorizations are refused before the upstream is ever called. Entries are
387
+ * dropped once the authorization's `validBefore` has passed (plus a grace).
388
+ */
389
+ export class GatewayAuthorizationLedger {
390
+ private readonly entries = new Map<
391
+ string,
392
+ { state: "in-flight" | "pending" | "settled"; validBefore: bigint }
393
+ >();
394
+
395
+ constructor(
396
+ private readonly now: () => number,
397
+ private readonly maxEntries = 100_000,
398
+ ) {}
399
+
400
+ /** Claims the authorization for one request; false if it is in flight or settled. */
401
+ claim(key: string, validBefore: bigint): boolean {
402
+ this.prune();
403
+ const entry = this.entries.get(key);
404
+ if (entry !== undefined && entry.state !== "pending") return false;
405
+ if (entry === undefined && this.entries.size >= this.maxEntries)
406
+ return false;
407
+ this.entries.set(key, { state: "in-flight", validBefore });
408
+ return true;
409
+ }
410
+
411
+ release(key: string): void {
412
+ this.entries.delete(key);
413
+ }
414
+
415
+ markPending(key: string, validBefore: bigint): void {
416
+ this.entries.set(key, { state: "pending", validBefore });
417
+ }
418
+
419
+ markSettled(key: string, validBefore: bigint): void {
420
+ this.entries.set(key, { state: "settled", validBefore });
421
+ }
422
+
423
+ private prune(): void {
424
+ const now = BigInt(this.now());
425
+ for (const [key, entry] of this.entries) {
426
+ if (entry.state !== "in-flight" && entry.validBefore + 600n < now) {
427
+ this.entries.delete(key);
428
+ }
429
+ }
430
+ }
431
+ }
432
+
433
+ /** Ledger key for a `PAYMENT-SIGNATURE`, or undefined if it does not decode. */
434
+ function authorizationKey(
435
+ header: string,
436
+ ): { readonly key: string; readonly validBefore: bigint } | undefined {
437
+ try {
438
+ const payload = decodePaymentSignatureHeader(header);
439
+ const authorization = (
440
+ payload.payload as {
441
+ authorization?: {
442
+ from?: unknown;
443
+ nonce?: unknown;
444
+ validBefore?: unknown;
445
+ };
446
+ }
447
+ ).authorization;
448
+ const network = payload.accepted?.network;
449
+ const asset = payload.accepted?.asset;
450
+ if (
451
+ typeof authorization?.from !== "string" ||
452
+ typeof authorization.nonce !== "string" ||
453
+ typeof authorization.validBefore !== "string" ||
454
+ !/^\d+$/.test(authorization.validBefore) ||
455
+ typeof network !== "string" ||
456
+ typeof asset !== "string"
457
+ ) {
458
+ return undefined;
459
+ }
460
+ return {
461
+ key: [
462
+ network,
463
+ asset.toLowerCase(),
464
+ authorization.from.toLowerCase(),
465
+ authorization.nonce.toLowerCase(),
466
+ ].join(":"),
467
+ validBefore: BigInt(authorization.validBefore),
468
+ };
469
+ } catch {
470
+ return undefined;
471
+ }
472
+ }
473
+
474
+ export class X402OpenerModeConfigError extends Error {
475
+ constructor(message: string) {
476
+ super(message);
477
+ this.name = "X402OpenerModeConfigError";
478
+ }
479
+ }
480
+
481
+ export class X402OpenerFacilitatorUnverifiedError extends Error {
482
+ constructor(message: string, options?: { readonly cause?: unknown }) {
483
+ super(message, options);
484
+ this.name = "X402OpenerFacilitatorUnverifiedError";
485
+ }
486
+ }
487
+
488
+ /**
489
+ * Builds the x402 mode and proves, before returning, every fact it will quote:
490
+ * valid terms and price, one operator-signed listing for the terms, the
491
+ * factory's escrow and token, the predicted `payTo`, and the facilitator's
492
+ * opener marker. Throws on any doubt; the gateway then refuses to start.
493
+ */
494
+ export async function buildGatewayX402OpenerMode(
495
+ config: GatewayX402OpenerModeConfig,
496
+ deps: GatewayX402OpenerModeDeps = {},
497
+ ): Promise<GatewayX402OpenerMode> {
498
+ const kind: OpenerKind =
499
+ config.upfrontAmount === undefined ? "stream" : "upfront";
500
+ const upfrontTerms: UpfrontOpenerTerms | undefined =
501
+ config.upfrontAmount === undefined
502
+ ? undefined
503
+ : {
504
+ ...config.terms,
505
+ price: config.price,
506
+ upfrontAmount: config.upfrontAmount,
507
+ };
508
+ try {
509
+ if (upfrontTerms === undefined) {
510
+ assertValidTerms(config.terms);
511
+ assertValidPrice(config.price, config.terms);
512
+ } else {
513
+ // The factory's own validateTerms rules + amount == price + the metered
514
+ // part within rate * maxDuration: exactly what the SDK buyer requires.
515
+ assertValidUpfrontTerms(upfrontTerms);
516
+ }
517
+ } catch (error) {
518
+ throw new X402OpenerModeConfigError(
519
+ error instanceof Error ? error.message : String(error),
520
+ );
521
+ }
522
+ const chainId = chainIdFromNetwork(config.network);
523
+ for (const [name, value] of [
524
+ ["factoryAddress", config.factoryAddress],
525
+ ["escrowAddress", config.escrowAddress],
526
+ ["asset", config.asset],
527
+ ] as const) {
528
+ if (!isAddress(value)) {
529
+ throw new X402OpenerModeConfigError(`${name} must be an EVM address`);
530
+ }
531
+ }
532
+ const maxTimeoutSeconds = config.maxTimeoutSeconds ?? 300;
533
+ if (!Number.isInteger(maxTimeoutSeconds) || maxTimeoutSeconds < 30) {
534
+ throw new X402OpenerModeConfigError(
535
+ "maxTimeoutSeconds must be an integer >= 30",
536
+ );
537
+ }
538
+ if (config.facilitatorToken.length === 0) {
539
+ throw new X402OpenerModeConfigError("facilitatorToken is required");
540
+ }
541
+ if (config.resourceBaseUrl !== undefined) {
542
+ // eslint-disable-next-line no-new -- validates the URL is well-formed.
543
+ new URL(config.resourceBaseUrl);
544
+ }
545
+ const refundBaseUrl = (config.refundBaseUrl ?? config.facilitatorUrl).replace(
546
+ /\/+$/,
547
+ "",
548
+ );
549
+ const docsUrl = config.docsUrl ?? DEFAULT_OPENER_DOCS_URL;
550
+ for (const [name, value] of [
551
+ ["refundBaseUrl", refundBaseUrl],
552
+ ["docsUrl", docsUrl],
553
+ ] as const) {
554
+ if (!isHttpLink(value)) {
555
+ throw new X402OpenerModeConfigError(`${name} must be an http(s) URL`);
556
+ }
557
+ }
558
+ const assetDecimals = config.assetDecimals ?? 6;
559
+ if (
560
+ !Number.isInteger(assetDecimals) ||
561
+ assetDecimals < 0 ||
562
+ assetDecimals > 36
563
+ ) {
564
+ throw new X402OpenerModeConfigError(
565
+ "assetDecimals must be an integer in [0, 36]",
566
+ );
567
+ }
568
+ if (config.schemaDeclaration !== undefined) {
569
+ try {
570
+ assertSchemaDeclaration(config.schemaDeclaration);
571
+ } catch (error) {
572
+ throw new X402OpenerModeConfigError(
573
+ error instanceof Error ? error.message : String(error),
574
+ );
575
+ }
576
+ }
577
+
578
+ const publicClient =
579
+ deps.publicClient ??
580
+ (deps.rpcUrl === undefined
581
+ ? undefined
582
+ : createPublicClient({ transport: http(deps.rpcUrl) }));
583
+ if (publicClient === undefined) {
584
+ throw new X402OpenerModeConfigError(
585
+ "an RPC (publicClient or rpcUrl) is required to predict the opener address",
586
+ );
587
+ }
588
+ const rpcChainId = await publicClient.getChainId();
589
+ if (rpcChainId !== chainId) {
590
+ throw new X402OpenerModeConfigError(
591
+ `RPC chain id ${rpcChainId} does not match network ${config.network}`,
592
+ );
593
+ }
594
+
595
+ const factory = getAddress(config.factoryAddress);
596
+ const escrow = getAddress(config.escrowAddress);
597
+ const asset = getAddress(config.asset);
598
+ let factoryEscrow: Address;
599
+ let factoryUsdc: Address;
600
+ let predicted: Address;
601
+ if (upfrontTerms === undefined) {
602
+ [factoryEscrow, factoryUsdc, predicted] = await Promise.all([
603
+ publicClient.readContract({
604
+ address: factory,
605
+ abi: x402StreamOpenerFactoryAbi,
606
+ functionName: "escrow",
607
+ }),
608
+ publicClient.readContract({
609
+ address: factory,
610
+ abi: x402StreamOpenerFactoryAbi,
611
+ functionName: "usdc",
612
+ }),
613
+ publicClient.readContract({
614
+ address: factory,
615
+ abi: x402StreamOpenerFactoryAbi,
616
+ functionName: "predict",
617
+ args: [termsTuple(config.terms)],
618
+ }),
619
+ ]);
620
+ } else {
621
+ let implementation: Address;
622
+ [factoryEscrow, factoryUsdc, predicted, implementation] = await Promise.all(
623
+ [
624
+ publicClient.readContract({
625
+ address: factory,
626
+ abi: x402UpfrontStreamOpenerFactoryAbi,
627
+ functionName: "escrow",
628
+ }),
629
+ publicClient.readContract({
630
+ address: factory,
631
+ abi: x402UpfrontStreamOpenerFactoryAbi,
632
+ functionName: "usdc",
633
+ }),
634
+ publicClient.readContract({
635
+ address: factory,
636
+ abi: x402UpfrontStreamOpenerFactoryAbi,
637
+ functionName: "predict",
638
+ args: [upfrontTermsTuple(upfrontTerms)],
639
+ }),
640
+ publicClient.readContract({
641
+ address: factory,
642
+ abi: x402UpfrontStreamOpenerFactoryAbi,
643
+ functionName: "implementation",
644
+ }),
645
+ ],
646
+ ).catch((error: unknown) => {
647
+ throw new X402OpenerModeConfigError(
648
+ `factory ${factory} is not an X402UpfrontStreamOpenerFactory that accepts these upfront terms (${error instanceof Error ? (error.message.split("\n")[0] ?? "error") : String(error)})`,
649
+ );
650
+ });
651
+ if (
652
+ config.upfrontImplementation !== undefined &&
653
+ getAddress(implementation) !== getAddress(config.upfrontImplementation)
654
+ ) {
655
+ throw new X402OpenerModeConfigError(
656
+ `upfront factory ${factory} reports implementation ${implementation}, not the expected ${config.upfrontImplementation}`,
657
+ );
658
+ }
659
+ // The SDK buyer recomputes payTo OFFLINE; quote only a payTo both agree on.
660
+ const offline = predictUpfrontOpenerAddress({
661
+ factory,
662
+ implementation: getAddress(implementation),
663
+ terms: {
664
+ operator: getAddress(upfrontTerms.operator),
665
+ serviceRef: upfrontTerms.serviceRef.toLowerCase() as `0x${string}`,
666
+ ratePerSecond: upfrontTerms.ratePerSecond,
667
+ maxDuration: upfrontTerms.maxDuration,
668
+ price: upfrontTerms.price,
669
+ upfrontAmount: upfrontTerms.upfrontAmount,
670
+ },
671
+ });
672
+ if (getAddress(offline) !== getAddress(predicted)) {
673
+ throw new X402OpenerModeConfigError(
674
+ `factory.predict(terms) = ${predicted} disagrees with the offline CREATE2 derivation ${offline}; refusing to quote it`,
675
+ );
676
+ }
677
+ }
678
+ if (getAddress(factoryEscrow) !== escrow) {
679
+ throw new X402OpenerModeConfigError(
680
+ `factory ${factory} settles into ${factoryEscrow}, not this gateway's escrow ${escrow}`,
681
+ );
682
+ }
683
+ if (getAddress(factoryUsdc) !== asset) {
684
+ throw new X402OpenerModeConfigError(
685
+ `factory token ${factoryUsdc} is not the configured asset ${asset}`,
686
+ );
687
+ }
688
+ const payTo = getAddress(predicted);
689
+
690
+ const resolver =
691
+ deps.listingResolver ??
692
+ new RegistryListingResolver(
693
+ config.registryUrl === undefined
694
+ ? {}
695
+ : { registryUrl: config.registryUrl },
696
+ );
697
+ const listing = await resolver.resolve(config.terms);
698
+ if (!listing.ok) {
699
+ throw new X402OpenerModeConfigError(
700
+ `listing check failed (${listing.reason}): ${listing.message}`,
701
+ );
702
+ }
703
+
704
+ const facilitatorTimeoutMs =
705
+ config.facilitatorTimeoutMs ?? DEFAULT_FACILITATOR_TIMEOUT_MS;
706
+ if (!Number.isInteger(facilitatorTimeoutMs) || facilitatorTimeoutMs <= 0) {
707
+ throw new X402OpenerModeConfigError(
708
+ "facilitatorTimeoutMs must be a positive integer",
709
+ );
710
+ }
711
+ const facilitatorClient =
712
+ deps.facilitatorClient ??
713
+ new HTTPFacilitatorClient({
714
+ url: config.facilitatorUrl,
715
+ timeoutMs: facilitatorTimeoutMs,
716
+ createAuthHeaders: async () => {
717
+ const headers = { Authorization: `Bearer ${config.facilitatorToken}` };
718
+ return { verify: headers, settle: headers, supported: headers };
719
+ },
720
+ });
721
+
722
+ const now = deps.now ?? (() => Math.floor(Date.now() / 1000));
723
+ const markerTtl =
724
+ config.markerTtlSeconds ?? DEFAULT_FACILITATOR_MARKER_TTL_SECONDS;
725
+ let markerCheckedAt: number | undefined;
726
+ const checkMarker = async (): Promise<void> => {
727
+ let supported;
728
+ try {
729
+ supported = await facilitatorClient.getSupported();
730
+ } catch (cause) {
731
+ throw new X402OpenerFacilitatorUnverifiedError(
732
+ `the x402 facilitator at ${config.facilitatorUrl} is unreachable`,
733
+ { cause },
734
+ );
735
+ }
736
+ const supportedKind = supported.kinds.find(
737
+ (candidate) =>
738
+ candidate.x402Version === 2 &&
739
+ candidate.scheme === OPENER_SCHEME &&
740
+ candidate.network === config.network,
741
+ );
742
+ const marker = readOpenerFacilitatorMarker(supportedKind?.extra);
743
+ if (
744
+ marker === undefined ||
745
+ !markerSettles(
746
+ marker,
747
+ upfrontTerms === undefined ? "stream" : "upfront",
748
+ factory,
749
+ escrow,
750
+ ) ||
751
+ marker.usdc !== asset ||
752
+ marker.chainId !== chainId
753
+ ) {
754
+ throw new X402OpenerFacilitatorUnverifiedError(
755
+ `the x402 facilitator at ${config.facilitatorUrl} does not advertise Metrik ${upfrontTerms === undefined ? "" : "upfront "}opener settlement for factory ${factory} on ${config.network}. ` +
756
+ "Refusing to quote an opener payTo: a stock exact facilitator would transfer the payment straight to the opener and strand it permanently.",
757
+ );
758
+ }
759
+ if (marker.refundRelay !== true) {
760
+ throw new X402OpenerFacilitatorUnverifiedError(
761
+ `the x402 facilitator at ${config.facilitatorUrl} does not advertise the gasless refund relay (refundRelay: true). ` +
762
+ "Refusing to quote: the 402 tells payers unearned money is refundable without ETH, which needs that relay.",
763
+ );
764
+ }
765
+ if (config.price < BigInt(marker.minAmount)) {
766
+ throw new X402OpenerModeConfigError(
767
+ `price ${config.price} is below the facilitator minimum ${marker.minAmount}`,
768
+ );
769
+ }
770
+ if (
771
+ facilitatorTimeoutMs <
772
+ marker.receiptTimeoutSeconds * 1000 + FACILITATOR_TIMEOUT_HEADROOM_MS
773
+ ) {
774
+ throw new X402OpenerModeConfigError(
775
+ `the facilitator timeout ${facilitatorTimeoutMs}ms does not outlast the facilitator's ${marker.receiptTimeoutSeconds}s receipt wait by ${FACILITATOR_TIMEOUT_HEADROOM_MS / 1000}s`,
776
+ );
777
+ }
778
+ };
779
+
780
+ const resourceServer = new x402ResourceServer(facilitatorClient).register(
781
+ config.network,
782
+ new OpenerExactServerScheme(refundBaseUrl),
783
+ );
784
+ const description = describeOpenerPurchase({
785
+ terms: config.terms,
786
+ price: config.price,
787
+ ...(config.upfrontAmount === undefined
788
+ ? {}
789
+ : { upfrontAmount: config.upfrontAmount }),
790
+ assetDecimals,
791
+ assetSymbol: config.assetName,
792
+ refundUrlTemplate: `${refundBaseUrl}/streams/{streamId}`,
793
+ docsUrl,
794
+ ...(config.description === undefined
795
+ ? {}
796
+ : { serviceDescription: config.description }),
797
+ });
798
+ const route: RouteConfig = {
799
+ accepts: {
800
+ scheme: OPENER_SCHEME,
801
+ network: config.network,
802
+ payTo,
803
+ price: {
804
+ asset,
805
+ amount: config.price.toString(),
806
+ extra: {
807
+ name: config.assetName,
808
+ version: config.assetVersion,
809
+ assetTransferMethod: "eip3009",
810
+ [OPENER_EXTRA_KEY]:
811
+ upfrontTerms === undefined
812
+ ? {
813
+ ...termsToExtra(factory, config.terms),
814
+ refundUrl: `${refundBaseUrl}/streams/{streamId}`,
815
+ docsUrl,
816
+ }
817
+ : {
818
+ ...upfrontTermsToExtra(factory, upfrontTerms),
819
+ // An upfront-only listing opens no stream: no refund URL.
820
+ ...(upfrontTerms.upfrontAmount === upfrontTerms.price
821
+ ? {}
822
+ : { refundUrl: `${refundBaseUrl}/streams/{streamId}` }),
823
+ docsUrl,
824
+ },
825
+ },
826
+ },
827
+ maxTimeoutSeconds,
828
+ },
829
+ description,
830
+ mimeType: "application/json",
831
+ ...(config.schemaDeclaration === undefined
832
+ ? {}
833
+ : { extensions: { bazaar: config.schemaDeclaration } }),
834
+ unpaidResponseBody: () => ({
835
+ contentType: "application/json",
836
+ body: { authorized: false, reason: "payment-required" },
837
+ }),
838
+ };
839
+ const httpServer = new x402HTTPResourceServer(resourceServer, route);
840
+
841
+ let initialized: Promise<void> | undefined;
842
+ const ready = async (): Promise<void> => {
843
+ const nowSeconds = now();
844
+ if (
845
+ markerCheckedAt === undefined ||
846
+ nowSeconds - markerCheckedAt >= markerTtl
847
+ ) {
848
+ markerCheckedAt = undefined;
849
+ await checkMarker();
850
+ markerCheckedAt = nowSeconds;
851
+ }
852
+ if (initialized === undefined) {
853
+ initialized = httpServer.initialize().catch((error: unknown) => {
854
+ initialized = undefined;
855
+ throw new X402OpenerFacilitatorUnverifiedError(
856
+ "the x402 resource server could not initialize against the facilitator",
857
+ { cause: error },
858
+ );
859
+ });
860
+ }
861
+ await initialized;
862
+ };
863
+
864
+ // Prove the facilitator at startup: refuse to start otherwise.
865
+ await ready();
866
+ if (refundBaseUrl !== config.facilitatorUrl.replace(/\/+$/, "")) {
867
+ await checkRefundRelayAt(refundBaseUrl, deps.fetch ?? fetch, {
868
+ kind,
869
+ factory,
870
+ escrow,
871
+ asset,
872
+ chainId,
873
+ network: config.network,
874
+ });
875
+ }
876
+
877
+ const mode: GatewayX402OpenerMode = {
878
+ payTo,
879
+ network: config.network,
880
+ terms: config.terms,
881
+ price: config.price,
882
+ openerKind: kind,
883
+ upfrontAmount: config.upfrontAmount ?? null,
884
+ resourceBaseUrl: config.resourceBaseUrl,
885
+ description,
886
+ refundBaseUrl,
887
+ httpServer,
888
+ authorizations: new GatewayAuthorizationLedger(now),
889
+ ready,
890
+ handle: (io) =>
891
+ handleX402GatewayRequest(mode, io).catch((error: unknown) => {
892
+ io.logError("x402 request failed", error);
893
+ io.writeJson(500, "internal-error");
894
+ }),
895
+ };
896
+ return mode;
897
+ }
898
+
899
+ /**
900
+ * A refund base URL other than the facilitator URL (e.g. the public origin of
901
+ * the same service) must serve the same opener marker with the relay on, so
902
+ * the 402 never points payers at a URL that cannot refund them.
903
+ */
904
+ async function checkRefundRelayAt(
905
+ refundBaseUrl: string,
906
+ fetchImpl: typeof fetch,
907
+ expected: {
908
+ readonly kind: OpenerKind;
909
+ readonly factory: Address;
910
+ readonly escrow: Address;
911
+ readonly asset: Address;
912
+ readonly chainId: number;
913
+ readonly network: Network;
914
+ },
915
+ ): Promise<void> {
916
+ let supported: {
917
+ kinds?: {
918
+ x402Version?: unknown;
919
+ scheme?: unknown;
920
+ network?: unknown;
921
+ extra?: Record<string, unknown>;
922
+ }[];
923
+ };
924
+ try {
925
+ const response = await fetchImpl(`${refundBaseUrl}/supported`, {
926
+ signal: AbortSignal.timeout(10_000),
927
+ });
928
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
929
+ supported = (await response.json()) as typeof supported;
930
+ } catch (cause) {
931
+ throw new X402OpenerFacilitatorUnverifiedError(
932
+ `the refund relay at ${refundBaseUrl} is unreachable`,
933
+ { cause },
934
+ );
935
+ }
936
+ const kind = supported.kinds?.find(
937
+ (candidate) =>
938
+ candidate.x402Version === 2 &&
939
+ candidate.scheme === OPENER_SCHEME &&
940
+ candidate.network === expected.network,
941
+ );
942
+ const marker = readOpenerFacilitatorMarker(kind?.extra);
943
+ if (
944
+ marker === undefined ||
945
+ !markerSettles(marker, expected.kind, expected.factory, expected.escrow) ||
946
+ marker.usdc !== expected.asset ||
947
+ marker.chainId !== expected.chainId ||
948
+ marker.refundRelay !== true
949
+ ) {
950
+ throw new X402OpenerFacilitatorUnverifiedError(
951
+ `${refundBaseUrl} does not serve the Metrik opener refund relay for factory ${expected.factory}; refusing to advertise it as the refund URL`,
952
+ );
953
+ }
954
+ }
955
+
956
+ /**
957
+ * Whether a facilitator marker settles THIS listing's opener kind: the stream
958
+ * factory is the marker's `factory`; the upfront factory its `upfrontOpener`.
959
+ */
960
+ function markerSettles(
961
+ marker: NonNullable<ReturnType<typeof readOpenerFacilitatorMarker>>,
962
+ kind: OpenerKind,
963
+ factory: Address,
964
+ escrow: Address,
965
+ ): boolean {
966
+ if (kind === "upfront") {
967
+ return (
968
+ marker.upfrontOpener !== undefined &&
969
+ marker.upfrontOpener.factory === factory &&
970
+ marker.upfrontOpener.escrow === escrow &&
971
+ marker.escrow === escrow
972
+ );
973
+ }
974
+ return marker.factory === factory && marker.escrow === escrow;
975
+ }
976
+
977
+ /**
978
+ * One x402-mode request, mirroring the reference `@x402/*` middleware: verify
979
+ * via the facilitator, run the upstream, and settle ONLY when the upstream
980
+ * status is < 400 — before any upstream byte is sent. A failed settlement sends
981
+ * no upstream body. Every facilitator error fails closed: never a free call.
982
+ */
983
+ async function handleX402GatewayRequest(
984
+ mode: GatewayX402OpenerMode,
985
+ io: X402GatewayRequestIO,
986
+ ): Promise<void> {
987
+ try {
988
+ await mode.ready();
989
+ } catch (error) {
990
+ // The facilitator is not provably the Metrik opener facilitator right now:
991
+ // quote no payTo and verify nothing (a stock facilitator would strand it).
992
+ io.logError("x402 facilitator unverified", error);
993
+ io.writeJson(503, "x402-facilitator-unavailable");
994
+ return;
995
+ }
996
+
997
+ const { requestUrl, method, headers } = io;
998
+ const origin =
999
+ mode.resourceBaseUrl ?? `http://${headers.host ?? "localhost"}`;
1000
+ const fullUrl = new URL(
1001
+ requestUrl.pathname + requestUrl.search,
1002
+ origin,
1003
+ ).toString();
1004
+ const adapter: HTTPAdapter = {
1005
+ getHeader: (name) => headers[name.toLowerCase()],
1006
+ getMethod: () => method,
1007
+ getPath: () => requestUrl.pathname,
1008
+ getUrl: () => fullUrl,
1009
+ getAcceptHeader: () => headers.accept ?? "",
1010
+ getUserAgent: () => headers["user-agent"] ?? "",
1011
+ };
1012
+ const paymentHeader = headers[PAYMENT_SIGNATURE_HEADER]?.trim();
1013
+ const context: HTTPRequestContext = {
1014
+ adapter,
1015
+ path: requestUrl.pathname,
1016
+ method,
1017
+ ...(paymentHeader === undefined || paymentHeader.length === 0
1018
+ ? {}
1019
+ : { paymentHeader }),
1020
+ };
1021
+
1022
+ // One authorization, at most one served response: claim it before verify so
1023
+ // a concurrent duplicate never reaches the facilitator or the upstream.
1024
+ const claim =
1025
+ paymentHeader === undefined || paymentHeader.length === 0
1026
+ ? undefined
1027
+ : authorizationKey(paymentHeader);
1028
+ if (
1029
+ claim !== undefined &&
1030
+ !mode.authorizations.claim(claim.key, claim.validBefore)
1031
+ ) {
1032
+ io.writeJson(409, "x402-payment-already-used");
1033
+ return;
1034
+ }
1035
+ const release = () => {
1036
+ if (claim !== undefined) mode.authorizations.release(claim.key);
1037
+ };
1038
+
1039
+ let result: HTTPProcessResult;
1040
+ try {
1041
+ result = await mode.httpServer.processHTTPRequest(context);
1042
+ } catch (error) {
1043
+ release();
1044
+ io.logError("x402 verification failed", error);
1045
+ io.writeJson(402, "x402-facilitator-unavailable");
1046
+ return;
1047
+ }
1048
+
1049
+ if (result.type === "no-payment-required") {
1050
+ // The route covers every path; reaching here is a misconfiguration.
1051
+ release();
1052
+ io.writeJson(500, "internal-error");
1053
+ return;
1054
+ }
1055
+ if (result.type === "payment-error") {
1056
+ release();
1057
+ writeInstructions(io, result.response);
1058
+ return;
1059
+ }
1060
+
1061
+ const {
1062
+ cancellationDispatcher,
1063
+ beforeHandlerSettlement,
1064
+ paymentPayload,
1065
+ paymentRequirements,
1066
+ declaredExtensions,
1067
+ } = result;
1068
+
1069
+ let upstream: X402UpstreamResult;
1070
+ try {
1071
+ upstream = await io.callUpstream();
1072
+ } catch (error) {
1073
+ await cancellationDispatcher
1074
+ .cancel({ reason: "handler_threw", error })
1075
+ .catch(() => undefined);
1076
+ release();
1077
+ io.logError("upstream request failed", error);
1078
+ io.writeJson(502, "upstream-unavailable");
1079
+ return;
1080
+ }
1081
+
1082
+ // The seller's upstream must not steer settlement.
1083
+ const upstreamHeaders: Record<string, string> = {};
1084
+ for (const [key, value] of Object.entries(upstream.headers)) {
1085
+ if (key.toLowerCase() === SETTLEMENT_OVERRIDES_HEADER.toLowerCase())
1086
+ continue;
1087
+ upstreamHeaders[key] = value;
1088
+ }
1089
+
1090
+ if (upstream.status >= 400) {
1091
+ // Nothing is settled for a failed upstream: the authorization is never
1092
+ // submitted, so no funds move.
1093
+ await cancellationDispatcher
1094
+ .cancel({ reason: "handler_failed", responseStatus: upstream.status })
1095
+ .catch(() => undefined);
1096
+ release();
1097
+ io.write(upstream.status, upstreamHeaders, upstream.body);
1098
+ return;
1099
+ }
1100
+
1101
+ let settled: ProcessSettleResultResponse;
1102
+ try {
1103
+ settled = await mode.httpServer.processSettlement(
1104
+ paymentPayload,
1105
+ paymentRequirements,
1106
+ declaredExtensions,
1107
+ {
1108
+ request: context,
1109
+ responseBody: upstream.body,
1110
+ responseHeaders: upstreamHeaders,
1111
+ },
1112
+ undefined,
1113
+ beforeHandlerSettlement,
1114
+ );
1115
+ } catch (error) {
1116
+ // Unknown outcome (e.g. the facilitator timed out): let a retry of the same
1117
+ // signature through so the facilitator's ledger can reconcile it — that
1118
+ // ledger, not this one, guarantees at most one success.
1119
+ if (claim !== undefined) {
1120
+ mode.authorizations.markPending(claim.key, claim.validBefore);
1121
+ }
1122
+ io.logError("x402 settlement failed", error);
1123
+ io.writeJson(402, "x402-settlement-failed");
1124
+ return;
1125
+ }
1126
+ if (!settled.success) {
1127
+ if (claim !== undefined) {
1128
+ if (settled.errorReason === "settlement_pending") {
1129
+ mode.authorizations.markPending(claim.key, claim.validBefore);
1130
+ } else if (settled.errorReason === "duplicate_settlement") {
1131
+ mode.authorizations.markSettled(claim.key, claim.validBefore);
1132
+ } else {
1133
+ release();
1134
+ }
1135
+ }
1136
+ // No upstream body on a failed settlement.
1137
+ writeInstructions(io, settled.response);
1138
+ return;
1139
+ }
1140
+ if (claim !== undefined) {
1141
+ mode.authorizations.markSettled(claim.key, claim.validBefore);
1142
+ }
1143
+
1144
+ const responseHeaders: Record<string, string> = {};
1145
+ let existingCacheControl: string | null = null;
1146
+ for (const [key, value] of Object.entries(upstreamHeaders)) {
1147
+ if (key.toLowerCase() === "cache-control") {
1148
+ existingCacheControl = value;
1149
+ continue;
1150
+ }
1151
+ responseHeaders[key] = value;
1152
+ }
1153
+ Object.assign(responseHeaders, settled.headers);
1154
+ responseHeaders["Cache-Control"] =
1155
+ withPrivateCacheControl(existingCacheControl);
1156
+ io.write(upstream.status, responseHeaders, upstream.body);
1157
+ }
1158
+
1159
+ function writeInstructions(
1160
+ io: X402GatewayRequestIO,
1161
+ response: HTTPResponseInstructions,
1162
+ ): void {
1163
+ const headers: Record<string, string> = { ...response.headers };
1164
+ if (response.isHtml === true) {
1165
+ headers["Content-Type"] = "text/html; charset=utf-8";
1166
+ io.write(response.status, headers, String(response.body ?? ""));
1167
+ return;
1168
+ }
1169
+ headers["Content-Type"] = "application/json";
1170
+ io.write(response.status, headers, JSON.stringify(response.body ?? {}));
1171
+ }