@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,555 @@
1
+ import type { MetrikNetwork } from "@absol-labs/sdk";
2
+ import {
3
+ findStreamForAuthorization,
4
+ payWithX402,
5
+ X402PaymentRefusedError,
6
+ type PayWithX402Options,
7
+ type PayWithX402Result,
8
+ type SignedTransferAuthorization,
9
+ type X402PayerSigner,
10
+ type X402QuoteSummary,
11
+ } from "@absol-labs/sdk/x402";
12
+ import { decodePaymentSignatureHeader } from "@x402/core/http";
13
+ import { createPublicClient, getAddress, http, type PublicClient } from "viem";
14
+
15
+ import {
16
+ checkMandate,
17
+ verifySignedMandate,
18
+ type HireRequest,
19
+ type MandateDecision,
20
+ type SignedSpendMandate,
21
+ } from "../mandates/mandate.js";
22
+
23
+ /**
24
+ * Buyer-side x402 payments under a spend mandate (metrik-agent#121).
25
+ *
26
+ * The golden rule of this package — no spend without a mandate — applies to an
27
+ * x402 payment exactly as it applies to `metrik open`, because a Metrik x402
28
+ * payment IS a stream open: the opener facilitator settles the payer's EIP-3009
29
+ * authorization with `factory.deployAndSettle`, which opens a `StreamEscrowV2`
30
+ * stream with `deposit = price`. So the payment is mapped onto the SAME
31
+ * {@link HireRequest} a stream open is checked as, from the quote's opener terms
32
+ * (which the SDK has already proven on-chain: `payTo == factory.predict(terms)`):
33
+ *
34
+ * | Mandate field | x402 quote field |
35
+ * | ---------------------- | ------------------------------------------------ |
36
+ * | `maxPerStreamUsdc` | `amount` (the deposit; the price of the call) |
37
+ * | `maxTotalUsdc` | `spentSoFar + amount` |
38
+ * | `maxRatePerSecondUsdc` | `ratePerSecond` (how fast the seller can earn) |
39
+ * | `maxDurationSeconds` | `maxDuration` (the stream's window) |
40
+ * | `allowedOperators` | `operator` (who the stream pays) |
41
+ *
42
+ * An UPFRONT ("minimum charge") opener quote is mapped the same way, with
43
+ * `budgetUsdc = price` — the WHOLE payment, of which `upfrontAmount` is
44
+ * non-refundable (paid to the seller at settlement) and only the rest is
45
+ * escrowed. So the per-stream and total caps always count the upfront part as
46
+ * spent, and nothing a refund returns is ever credited back. Its size is also
47
+ * capped separately, before signing, by the SDK's `maxUpfrontAmount` (default
48
+ * 0.10 USDC; pass {@link PayX402WithMandateInput.maxUpfrontAmount} to tighten
49
+ * it, `0n` to refuse every upfront charge).
50
+ *
51
+ * The check runs inside the SDK's `onQuote` hook — after every SDK protection
52
+ * (scheme, network, USDC domain, EIP-3009 only, registered factory, on-chain
53
+ * `predict`, authorization lifetime) and BEFORE anything is signed — so a
54
+ * denied payment never produces a signature. It is enforced twice: the mandate's
55
+ * caps are also handed to the SDK as `maxAmount` / `maxRatePerSecond`. A quote
56
+ * that is not a Metrik opener payment (no operator/rate/duration terms) is
57
+ * refused: there would be no stream to bound and nothing to recover.
58
+ *
59
+ * The mandate itself (signature, expiry, revocation) is verified FIRST, before
60
+ * any request reaches the seller.
61
+ */
62
+
63
+ /** A payment refused by the spend mandate. Nothing was signed. */
64
+ export class X402MandateDeniedError extends Error {
65
+ readonly reason:
66
+ | NonNullable<MandateDecision["reason"]>
67
+ | "not-an-opener-quote";
68
+ readonly quote: X402QuoteSummary | null;
69
+
70
+ constructor(
71
+ reason: X402MandateDeniedError["reason"],
72
+ quote: X402QuoteSummary | null,
73
+ detail?: string,
74
+ ) {
75
+ super(
76
+ `x402 payment refused by the spend mandate: ${reason}${detail === undefined ? "" : ` (${detail})`}. Nothing was signed.`,
77
+ );
78
+ this.name = "X402MandateDeniedError";
79
+ this.reason = reason;
80
+ this.quote = quote;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * The stream-open request an x402 quote would create, or a refusal reason when
86
+ * the quote does not carry Metrik opener terms.
87
+ */
88
+ export function x402QuoteToHireRequest(
89
+ quote: X402QuoteSummary,
90
+ ): HireRequest | { readonly refused: string } {
91
+ if (
92
+ quote.operator === null ||
93
+ quote.ratePerSecond === null ||
94
+ quote.maxDuration === null
95
+ ) {
96
+ return {
97
+ refused:
98
+ "the quote carries no Metrik opener terms (operator, ratePerSecond, maxDuration), so it would not open a recoverable stream",
99
+ };
100
+ }
101
+ if (quote.maxDuration > BigInt(Number.MAX_SAFE_INTEGER)) {
102
+ return { refused: `maxDuration ${quote.maxDuration} is out of range` };
103
+ }
104
+ return {
105
+ operator: quote.operator,
106
+ budgetUsdc: quote.amount,
107
+ ratePerSecondUsdc: quote.ratePerSecond,
108
+ maxDurationSeconds: Number(quote.maxDuration),
109
+ };
110
+ }
111
+
112
+ export interface PayX402WithMandateInput {
113
+ readonly url: string | URL;
114
+ readonly init?: RequestInit;
115
+ /** The payer: signs the EIP-3009 authorization. Needs USDC, no gas. */
116
+ readonly signer: X402PayerSigner;
117
+ readonly network: MetrikNetwork;
118
+ readonly signedMandate: SignedSpendMandate;
119
+ /** USDC already spent under this mandate (the cumulative-cap input). */
120
+ readonly spentSoFarUsdc: bigint;
121
+ readonly nowSeconds: number;
122
+ readonly revokedMandateIds?: Iterable<`0x${string}`>;
123
+ /** An explicit price ceiling, tighter than the mandate (never looser). */
124
+ readonly maxAmount?: bigint;
125
+ /** An explicit rate ceiling, tighter than the mandate (never looser). */
126
+ readonly maxRatePerSecond?: bigint;
127
+ /** Refuse a quote the seller can fully earn in fewer verified seconds. */
128
+ readonly minDurationSeconds?: number;
129
+ /**
130
+ * Ceiling on the NON-REFUNDABLE upfront part of an upfront-opener quote, base
131
+ * units (the SDK's `maxUpfrontAmount`). Default the SDK's 0.10 USDC; `0n`
132
+ * refuses any upfront charge. Never above the price ceiling in effect.
133
+ */
134
+ readonly maxUpfrontAmount?: bigint;
135
+ /** Passed through to the SDK (transport, fetch, publicClient, ...). */
136
+ readonly sdkOptions?: Pick<
137
+ PayWithX402Options,
138
+ | "publicClient"
139
+ | "transport"
140
+ | "fetch"
141
+ | "allowInsecureHttp"
142
+ | "maxAuthorizationSeconds"
143
+ | "allowLegacyFactory"
144
+ >;
145
+ /** Test seam: the SDK payer. Default `payWithX402`. */
146
+ readonly payImpl?: typeof payWithX402;
147
+ /**
148
+ * Called once the mandate APPROVES a quote, BEFORE the SDK signs it. A
149
+ * caller that tracks cumulative spend reserves the payment here, so a
150
+ * failure after the signature is handed out can never leave it uncounted.
151
+ * Throwing refuses the quote (nothing is signed).
152
+ */
153
+ readonly onApproved?: (approval: {
154
+ readonly request: HireRequest;
155
+ readonly quote: X402QuoteSummary;
156
+ }) => void | Promise<void>;
157
+ /**
158
+ * Chain reads used after a post-signature failure (USDC
159
+ * `authorizationState`, the opener's `StreamOpenedFor` log). Default: the
160
+ * SDK options' `publicClient`, else a client over their `transport`, else
161
+ * the network's first RPC.
162
+ */
163
+ readonly chainReader?: Pick<
164
+ PublicClient,
165
+ "readContract" | "getLogs" | "getBlockNumber"
166
+ >;
167
+ }
168
+
169
+ /** What is known about a payment whose signature was handed out but that did not complete cleanly. */
170
+ export type X402PostSignatureState =
171
+ /** The authorization was used: the money left the payer. */
172
+ | "used"
173
+ /** It could not be established either way. Treat as used. */
174
+ | "possibly-used"
175
+ /** Not used yet, but still valid until `validBefore`: a holder can still submit it. */
176
+ | "unused-but-valid"
177
+ /** Not used and past `validBefore`: it can never move funds. */
178
+ | "unused-expired";
179
+
180
+ /**
181
+ * The payment was APPROVED and its authorization signed and handed to the
182
+ * seller, then something failed (a malformed or missing PAYMENT-RESPONSE, a
183
+ * settlement the SDK could not confirm, a dropped connection). The money may
184
+ * have moved: {@link X402PostSignatureError.state} says what is known, and
185
+ * {@link X402PostSignatureError.releasable} is `true` only when the
186
+ * authorization provably can never be used. A spend reservation must be kept
187
+ * otherwise.
188
+ */
189
+ export class X402PostSignatureError extends Error {
190
+ readonly state: X402PostSignatureState;
191
+ readonly approved: HireRequest;
192
+ readonly quote: X402QuoteSummary;
193
+ readonly authorization: SignedTransferAuthorization | null;
194
+ /** The stream the payment opened, when it could be identified. */
195
+ readonly streamId: `0x${string}` | null;
196
+ readonly opener: `0x${string}`;
197
+ /**
198
+ * `true` when the chain shows (or the signed quote implies) an UPFRONT-ONLY
199
+ * payment: no stream, the whole price was a non-refundable charge, nothing
200
+ * to recover.
201
+ */
202
+ readonly upfrontOnly: boolean;
203
+
204
+ constructor(context: {
205
+ readonly state: X402PostSignatureState;
206
+ readonly approved: HireRequest;
207
+ readonly quote: X402QuoteSummary;
208
+ readonly authorization: SignedTransferAuthorization | null;
209
+ readonly streamId: `0x${string}` | null;
210
+ readonly upfrontOnly?: boolean;
211
+ readonly cause: unknown;
212
+ }) {
213
+ const upfrontOnly =
214
+ context.upfrontOnly === true || context.quote.upfrontOnly === true;
215
+ const what =
216
+ context.state === "used"
217
+ ? upfrontOnly
218
+ ? "the payment SETTLED (the authorization was used) as an UPFRONT-ONLY charge: the whole price went to the seller, no stream was opened and there is nothing to refund"
219
+ : `the payment SETTLED (the authorization was used)${context.streamId === null ? ", but its stream could not be identified" : ` into stream ${context.streamId}`}`
220
+ : context.state === "possibly-used"
221
+ ? "the payment MAY HAVE SETTLED: whether the authorization was used could not be established, so treat it as spent"
222
+ : context.state === "unused-but-valid"
223
+ ? `the authorization has not been used, but it stays valid until ${context.authorization?.validBefore.toString() ?? "its validBefore"} and the seller still holds it — treat it as spent until then, or cancel it on USDC (cancelAuthorization)`
224
+ : "the authorization was never used and has expired: nothing moved";
225
+ super(
226
+ `x402 payment of ${context.approved.budgetUsdc.toString()} USDC base units to ${context.quote.payTo} did not complete cleanly: ${what}. Cause: ${context.cause instanceof Error ? context.cause.message : String(context.cause)}`,
227
+ { cause: context.cause },
228
+ );
229
+ this.name = "X402PostSignatureError";
230
+ this.state = context.state;
231
+ this.approved = context.approved;
232
+ this.quote = context.quote;
233
+ this.authorization = context.authorization;
234
+ this.streamId = context.streamId;
235
+ this.opener = getAddress(context.quote.payTo);
236
+ this.upfrontOnly = upfrontOnly;
237
+ }
238
+
239
+ /** Only an authorization that provably can never move funds frees its reservation. */
240
+ get releasable(): boolean {
241
+ return this.state === "unused-expired";
242
+ }
243
+ }
244
+
245
+ function headerValue(
246
+ headers: RequestInit["headers"] | undefined,
247
+ name: string,
248
+ ): string | null {
249
+ if (headers === undefined) return null;
250
+ if (headers instanceof Headers) return headers.get(name);
251
+ if (Array.isArray(headers)) {
252
+ const hit = headers.find((pair) => pair[0]?.toLowerCase() === name);
253
+ return hit?.[1] ?? null;
254
+ }
255
+ for (const [key, value] of Object.entries(headers)) {
256
+ if (key.toLowerCase() === name) {
257
+ return typeof value === "string" ? value : (value[0] ?? null);
258
+ }
259
+ }
260
+ return null;
261
+ }
262
+
263
+ /** The EIP-3009 authorization inside an x402 v2 PAYMENT-SIGNATURE header, if decodable. */
264
+ function authorizationFromHeader(
265
+ header: string,
266
+ ): SignedTransferAuthorization | null {
267
+ try {
268
+ const payload = decodePaymentSignatureHeader(header) as {
269
+ payload?: { authorization?: Record<string, string> };
270
+ };
271
+ const auth = payload.payload?.authorization;
272
+ if (auth === undefined) return null;
273
+ return {
274
+ from: getAddress(auth.from as string),
275
+ to: getAddress(auth.to as string),
276
+ value: BigInt(auth.value as string),
277
+ validAfter: BigInt(auth.validAfter as string),
278
+ validBefore: BigInt(auth.validBefore as string),
279
+ nonce: auth.nonce as `0x${string}`,
280
+ };
281
+ } catch {
282
+ return null;
283
+ }
284
+ }
285
+
286
+ export interface PayX402WithMandateResult extends PayWithX402Result {
287
+ /** The stream-open request the mandate approved (null if nothing was paid). */
288
+ readonly approved: HireRequest | null;
289
+ }
290
+
291
+ function smaller(a: bigint, b: bigint | undefined): bigint {
292
+ return b !== undefined && b < a ? b : a;
293
+ }
294
+
295
+ /**
296
+ * Pay an x402 v2 endpoint through the SDK's `payWithX402`, gated by
297
+ * `checkMandate()`. Fail closed: a mandate that does not verify, a quote it
298
+ * denies, or a quote without opener terms is a hard stop with nothing signed.
299
+ */
300
+ export async function payX402WithMandate(
301
+ input: PayX402WithMandateInput,
302
+ ): Promise<PayX402WithMandateResult> {
303
+ const mandate = input.signedMandate.mandate;
304
+ // 1. The mandate itself, before the seller is even contacted.
305
+ const verdict = await verifySignedMandate(input.signedMandate, {
306
+ nowSeconds: input.nowSeconds,
307
+ ...(input.revokedMandateIds === undefined
308
+ ? {}
309
+ : { revokedMandateIds: input.revokedMandateIds }),
310
+ });
311
+ if (!verdict.allowed) {
312
+ throw new X402MandateDeniedError(
313
+ verdict.reason ?? "invalid-signature",
314
+ null,
315
+ );
316
+ }
317
+ if (
318
+ input.signedMandate.owner.toLowerCase() !==
319
+ input.signer.address.toLowerCase()
320
+ ) {
321
+ throw new X402MandateDeniedError(
322
+ "invalid-signature",
323
+ null,
324
+ `the mandate is owned by ${input.signedMandate.owner}, not the payer ${input.signer.address}`,
325
+ );
326
+ }
327
+ if (input.signedMandate.chainId !== input.network.chain.id) {
328
+ throw new X402MandateDeniedError(
329
+ "invalid-signature",
330
+ null,
331
+ `the mandate is for chain ${input.signedMandate.chainId}, not ${input.network.name} (${input.network.chain.id})`,
332
+ );
333
+ }
334
+
335
+ // 2. The SDK's own ceilings, never looser than the mandate.
336
+ const remaining = mandate.maxTotalUsdc - input.spentSoFarUsdc;
337
+ if (remaining <= 0n) {
338
+ throw new X402MandateDeniedError(
339
+ "exceeds-total-cap",
340
+ null,
341
+ "the mandate's total cap is already spent",
342
+ );
343
+ }
344
+ const maxAmount = smaller(
345
+ smaller(mandate.maxPerStreamUsdc, remaining),
346
+ input.maxAmount,
347
+ );
348
+ const maxRatePerSecond = smaller(
349
+ mandate.maxRatePerSecondUsdc,
350
+ input.maxRatePerSecond,
351
+ );
352
+ // A negative maxUpfrontAmount is refused by the SDK (InvalidInputError)
353
+ // before the seller is contacted.
354
+
355
+ // 3. The per-quote mandate check, before signing.
356
+ let denial: X402MandateDeniedError | null = null;
357
+ let approved: HireRequest | null = null;
358
+ let approvedQuote: X402QuoteSummary | null = null;
359
+ // The authorization exactly as it left this process, read from the
360
+ // PAYMENT-SIGNATURE header on the way out — so a post-signature failure can
361
+ // still be traced on-chain even when the SDK error does not carry it.
362
+ let sentAuthorization: SignedTransferAuthorization | null = null;
363
+ const baseFetch =
364
+ input.sdkOptions?.fetch ?? globalThis.fetch.bind(globalThis);
365
+ const capturingFetch = (async (
366
+ resource: string | URL | Request,
367
+ init?: RequestInit,
368
+ ) => {
369
+ const header =
370
+ headerValue(init?.headers, "payment-signature") ??
371
+ (resource instanceof Request
372
+ ? resource.headers.get("payment-signature")
373
+ : null);
374
+ if (header !== null) {
375
+ sentAuthorization = authorizationFromHeader(header) ?? sentAuthorization;
376
+ }
377
+ return await baseFetch(resource, init);
378
+ }) as typeof fetch;
379
+ const pay = input.payImpl ?? payWithX402;
380
+ let result: PayWithX402Result;
381
+ try {
382
+ result = await pay(input.url, input.init, {
383
+ ...input.sdkOptions,
384
+ fetch: capturingFetch,
385
+ signer: input.signer,
386
+ network: input.network,
387
+ maxAmount,
388
+ maxRatePerSecond,
389
+ ...(input.maxUpfrontAmount === undefined
390
+ ? {}
391
+ : { maxUpfrontAmount: smaller(input.maxUpfrontAmount, maxAmount) }),
392
+ ...(input.minDurationSeconds === undefined
393
+ ? {}
394
+ : { minDurationSeconds: input.minDurationSeconds }),
395
+ onQuote: async (quote) => {
396
+ const request = x402QuoteToHireRequest(quote);
397
+ if ("refused" in request) {
398
+ denial = new X402MandateDeniedError(
399
+ "not-an-opener-quote",
400
+ quote,
401
+ request.refused,
402
+ );
403
+ return false;
404
+ }
405
+ const decision = await checkMandate(
406
+ input.signedMandate,
407
+ request,
408
+ input.spentSoFarUsdc,
409
+ {
410
+ nowSeconds: input.nowSeconds,
411
+ ...(input.revokedMandateIds === undefined
412
+ ? {}
413
+ : { revokedMandateIds: input.revokedMandateIds }),
414
+ },
415
+ );
416
+ if (!decision.allowed) {
417
+ denial = new X402MandateDeniedError(
418
+ decision.reason ?? "invalid-signature",
419
+ quote,
420
+ );
421
+ return false;
422
+ }
423
+ // Reserve BEFORE the SDK signs: from here on the money can move.
424
+ // A reservation hook that fails refuses the quote.
425
+ await input.onApproved?.({ request, quote });
426
+ approved = request;
427
+ approvedQuote = quote;
428
+ denial = null;
429
+ return true;
430
+ },
431
+ });
432
+ } catch (error) {
433
+ if (error instanceof X402PaymentRefusedError) {
434
+ // The SDK's own statement: nothing was signed or sent. A reservation
435
+ // made in onApproved can be released by the caller.
436
+ if (denial !== null) throw denial;
437
+ throw error;
438
+ }
439
+ if (approved === null || approvedQuote === null) throw error;
440
+ throw await classifyPostSignatureFailure(input, {
441
+ error,
442
+ approved,
443
+ quote: approvedQuote,
444
+ sentAuthorization,
445
+ });
446
+ }
447
+ return { ...result, approved: result.paid ? approved : null };
448
+ }
449
+
450
+ /**
451
+ * After a failure past the point of signing, establish what happened from the
452
+ * CHAIN, never from the seller: USDC `authorizationState(from, nonce)` and the
453
+ * opener's `StreamOpenedFor(streamId, payer, authorizationNonce, …)` log.
454
+ */
455
+ async function classifyPostSignatureFailure(
456
+ input: PayX402WithMandateInput,
457
+ context: {
458
+ readonly error: unknown;
459
+ readonly approved: HireRequest;
460
+ readonly quote: X402QuoteSummary;
461
+ readonly sentAuthorization: SignedTransferAuthorization | null;
462
+ },
463
+ ): Promise<X402PostSignatureError> {
464
+ const sdkError = context.error as {
465
+ readonly authorization?: SignedTransferAuthorization;
466
+ readonly authorizationUsed?: boolean | null;
467
+ readonly streamId?: string;
468
+ };
469
+ const authorization =
470
+ sdkError.authorization ?? context.sentAuthorization ?? null;
471
+ let used: boolean | null =
472
+ typeof sdkError.authorizationUsed === "boolean"
473
+ ? sdkError.authorizationUsed
474
+ : null;
475
+ let upfrontOnly =
476
+ (sdkError as { readonly upfrontOnly?: boolean }).upfrontOnly === true;
477
+ let streamId: `0x${string}` | null =
478
+ typeof sdkError.streamId === "string" &&
479
+ /^0x[0-9a-fA-F]{64}$/.test(sdkError.streamId)
480
+ ? (sdkError.streamId as `0x${string}`)
481
+ : null;
482
+
483
+ const reader =
484
+ input.chainReader ??
485
+ input.sdkOptions?.publicClient ??
486
+ (createPublicClient({
487
+ transport: input.sdkOptions?.transport ?? http(input.network.rpcUrls[0]),
488
+ }) as unknown as PublicClient);
489
+
490
+ if (authorization !== null) {
491
+ if (used === null) {
492
+ try {
493
+ used = await reader.readContract({
494
+ address: input.network.usdc.address,
495
+ abi: authorizationStateAbi,
496
+ functionName: "authorizationState",
497
+ args: [authorization.from, authorization.nonce],
498
+ });
499
+ } catch {
500
+ used = null;
501
+ }
502
+ }
503
+ if (streamId === null && used !== false) {
504
+ // The SDK's recovery: only a registered factory's opener
505
+ // (factory.isOpener read on-chain) can prove a stream for this nonce.
506
+ try {
507
+ const recovery = await findStreamForAuthorization({
508
+ authorization,
509
+ network: input.network,
510
+ factory: context.quote.factory ?? null,
511
+ publicClient: reader as PublicClient,
512
+ });
513
+ streamId = recovery.streamId;
514
+ // An upfront-only payment opens no stream: the opener's
515
+ // UpfrontCharged (streamId 0), read on-chain, proves it was used.
516
+ if (recovery.upfrontOnly) upfrontOnly = true;
517
+ } catch {
518
+ streamId = null;
519
+ }
520
+ if (streamId !== null || upfrontOnly) used = true;
521
+ }
522
+ }
523
+
524
+ const nowSeconds = BigInt(Math.floor(Date.now() / 1000));
525
+ const state: X402PostSignatureState =
526
+ streamId !== null || upfrontOnly || used === true
527
+ ? "used"
528
+ : used === false && authorization !== null
529
+ ? authorization.validBefore <= nowSeconds
530
+ ? "unused-expired"
531
+ : "unused-but-valid"
532
+ : "possibly-used";
533
+ return new X402PostSignatureError({
534
+ state,
535
+ approved: context.approved,
536
+ quote: context.quote,
537
+ authorization,
538
+ streamId,
539
+ upfrontOnly,
540
+ cause: context.error,
541
+ });
542
+ }
543
+
544
+ const authorizationStateAbi = [
545
+ {
546
+ type: "function",
547
+ name: "authorizationState",
548
+ stateMutability: "view",
549
+ inputs: [
550
+ { name: "authorizer", type: "address" },
551
+ { name: "nonce", type: "bytes32" },
552
+ ],
553
+ outputs: [{ name: "", type: "bool" }],
554
+ },
555
+ ] as const;