@coinbase/agentkit 0.8.0 → 0.8.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.
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.x402ActionProvider = exports.X402ActionProvider = void 0;
16
+ const zod_1 = require("zod");
17
+ const actionProvider_1 = require("../actionProvider");
18
+ const actionDecorator_1 = require("../actionDecorator");
19
+ const schemas_1 = require("./schemas");
20
+ const wallet_providers_1 = require("../../wallet-providers");
21
+ const axios_1 = __importDefault(require("axios"));
22
+ const x402_axios_1 = require("x402-axios");
23
+ const SUPPORTED_NETWORKS = ["base-mainnet", "base-sepolia"];
24
+ /**
25
+ * X402ActionProvider is an action provider for making paid requests to x402-protected APIs.
26
+ */
27
+ class X402ActionProvider extends actionProvider_1.ActionProvider {
28
+ /**
29
+ * Constructor for the X402ActionProvider.
30
+ */
31
+ constructor() {
32
+ super("x402", []);
33
+ /**
34
+ * Checks if the X402 action provider supports the given network.
35
+ *
36
+ * @param network - The network to check.
37
+ * @returns True if the X402 action provider supports the network, false otherwise.
38
+ */
39
+ this.supportsNetwork = (network) => network.protocolFamily === "evm" && SUPPORTED_NETWORKS.includes(network.networkId);
40
+ }
41
+ /**
42
+ * Makes a paid request to an x402-protected API endpoint.
43
+ *
44
+ * @param walletProvider - The wallet provider to use for payment signing.
45
+ * @param args - The input arguments for the action.
46
+ * @returns A message containing the API response data.
47
+ */
48
+ async paidRequest(walletProvider, args) {
49
+ try {
50
+ // Get the viem account from the wallet provider for x402-axios
51
+ const account = walletProvider.toSigner();
52
+ // Create an axios instance with the payment interceptor
53
+ const api = (0, x402_axios_1.withPaymentInterceptor)(axios_1.default.create({}), account);
54
+ // Make the request
55
+ const response = await api.request({
56
+ url: args.url,
57
+ method: args.method,
58
+ headers: args.headers,
59
+ data: args.body,
60
+ });
61
+ // Extract payment information if available
62
+ const paymentResponseHeader = response.headers["x-payment-response"];
63
+ let paymentResponse = null;
64
+ if (paymentResponseHeader) {
65
+ try {
66
+ paymentResponse = (0, x402_axios_1.decodeXPaymentResponse)(paymentResponseHeader);
67
+ }
68
+ catch {
69
+ // Fall back to JSON parsing if decodeXPaymentResponse fails
70
+ try {
71
+ paymentResponse = JSON.parse(paymentResponseHeader);
72
+ }
73
+ catch {
74
+ paymentResponse = {
75
+ error: "Failed to decode payment response",
76
+ rawHeader: paymentResponseHeader,
77
+ };
78
+ }
79
+ }
80
+ }
81
+ // Structure the response to clearly separate API response and payment details
82
+ const result = {
83
+ success: true,
84
+ url: args.url,
85
+ method: args.method,
86
+ status: response.status,
87
+ data: response.data,
88
+ paymentResponse: paymentResponse,
89
+ };
90
+ return JSON.stringify(result, null, 2);
91
+ }
92
+ catch (error) {
93
+ const axiosError = error;
94
+ if (axiosError.response) {
95
+ return `Error making paid request to ${args.url}: HTTP ${axiosError.response.status} - ${axiosError.response.data?.error || axiosError.response.statusText}`;
96
+ }
97
+ else if (axiosError.request) {
98
+ return `Error making paid request to ${args.url}: Network error - ${axiosError.message}`;
99
+ }
100
+ else {
101
+ return `Error making paid request to ${args.url}: ${axiosError.message}`;
102
+ }
103
+ }
104
+ }
105
+ /**
106
+ * Fetches payment information from an x402-protected API endpoint without making the payment.
107
+ *
108
+ * @param walletProvider - The wallet provider (not used for this action but required by interface).
109
+ * @param args - The input arguments for the action.
110
+ * @returns A message containing the payment requirements and endpoint information.
111
+ */
112
+ async fetchPaymentInfo(walletProvider, args) {
113
+ try {
114
+ // Make a simple axios request without payment interceptor to get the 402 response
115
+ const response = await axios_1.default.request({
116
+ url: args.url,
117
+ method: args.method,
118
+ headers: args.headers,
119
+ validateStatus: status => status === 402 || (status >= 200 && status < 300), // Accept 402 responses
120
+ });
121
+ if (response.status === 402) {
122
+ return JSON.stringify({
123
+ paymentRequired: true,
124
+ url: args.url,
125
+ status: response.status,
126
+ data: response.data,
127
+ }, null, 2);
128
+ }
129
+ else {
130
+ // Endpoint is not payment-protected or request succeeded without payment
131
+ return JSON.stringify({
132
+ paymentRequired: false,
133
+ url: args.url,
134
+ status: response.status,
135
+ data: response.data,
136
+ }, null, 2);
137
+ }
138
+ }
139
+ catch (error) {
140
+ const axiosError = error;
141
+ if (axiosError.response) {
142
+ if (axiosError.response.status === 402) {
143
+ // Handle 402 responses that axios might treat as errors
144
+ const paymentResponseHeader = axiosError.response.headers["x-payment-response"];
145
+ let paymentDetails = null;
146
+ if (paymentResponseHeader) {
147
+ try {
148
+ paymentDetails = (0, x402_axios_1.decodeXPaymentResponse)(paymentResponseHeader);
149
+ }
150
+ catch {
151
+ // Fall back to JSON parsing if decodeXPaymentResponse fails
152
+ try {
153
+ paymentDetails = JSON.parse(paymentResponseHeader);
154
+ }
155
+ catch {
156
+ paymentDetails = {
157
+ error: "Failed to decode payment response",
158
+ rawHeader: paymentResponseHeader,
159
+ };
160
+ }
161
+ }
162
+ }
163
+ return JSON.stringify({
164
+ paymentRequired: true,
165
+ url: args.url,
166
+ status: 402,
167
+ paymentDetails: paymentDetails,
168
+ data: axiosError.response.data,
169
+ }, null, 2);
170
+ }
171
+ else {
172
+ return `Error fetching payment info from ${args.url}: HTTP ${axiosError.response.status} - ${axiosError.response.data?.error || axiosError.response.statusText}`;
173
+ }
174
+ }
175
+ else if (axiosError.request) {
176
+ return `Error fetching payment info from ${args.url}: Network error - ${axiosError.message}`;
177
+ }
178
+ else {
179
+ return `Error fetching payment info from ${args.url}: ${axiosError.message}`;
180
+ }
181
+ }
182
+ }
183
+ }
184
+ exports.X402ActionProvider = X402ActionProvider;
185
+ __decorate([
186
+ (0, actionDecorator_1.CreateAction)({
187
+ name: "paid_request",
188
+ description: `
189
+ This tool makes HTTP requests to APIs that are protected by x402 paywalls. It automatically handles the payment flow when a 402 Payment Required response is received.
190
+
191
+ Inputs:
192
+ - url: The full URL of the x402-protected API endpoint
193
+ - method: The HTTP method (GET, POST, PUT, DELETE, PATCH) - defaults to GET
194
+ - headers: Optional additional headers to include in the request
195
+ - body: Optional request body for POST/PUT/PATCH requests
196
+
197
+ The tool will:
198
+ 1. Make the initial request to the protected endpoint
199
+ 2. If a 402 Payment Required response is received, automatically handle the payment using the wallet
200
+ 3. Retry the request with payment proof
201
+ 4. Return the API response data
202
+
203
+ Supported on EVM networks where the wallet can sign payment transactions.
204
+ `,
205
+ schema: schemas_1.PaidRequestSchema,
206
+ }),
207
+ __metadata("design:type", Function),
208
+ __metadata("design:paramtypes", [wallet_providers_1.EvmWalletProvider, void 0]),
209
+ __metadata("design:returntype", Promise)
210
+ ], X402ActionProvider.prototype, "paidRequest", null);
211
+ __decorate([
212
+ (0, actionDecorator_1.CreateAction)({
213
+ name: "fetch_payment_info",
214
+ description: `
215
+ This tool fetches payment information from x402-protected API endpoints without actually making any payments. It's useful for checking payment requirements before deciding whether to proceed with a paid request.
216
+
217
+ Inputs:
218
+ - url: The full URL of the x402-protected API endpoint
219
+ - method: The HTTP method (GET, POST, PUT, DELETE, PATCH) - defaults to GET
220
+ - headers: Optional additional headers to include in the request
221
+
222
+ The tool will:
223
+ 1. Make a request to the protected endpoint
224
+ 2. Receive the 402 Payment Required response with payment details
225
+ 3. Return information about the payment requirements (amount, token, etc.)
226
+
227
+ Note: Payment amounts are returned in the smallest unit of the token. For example, for USDC (which has 6 decimal places) maxAmountRequired "10000" corresponds to 0.01 USDC.
228
+
229
+ This is useful for understanding what payment will be required before using the paid_request action.
230
+ `,
231
+ schema: schemas_1.FetchPaymentInfoSchema,
232
+ }),
233
+ __metadata("design:type", Function),
234
+ __metadata("design:paramtypes", [wallet_providers_1.EvmWalletProvider, void 0]),
235
+ __metadata("design:returntype", Promise)
236
+ ], X402ActionProvider.prototype, "fetchPaymentInfo", null);
237
+ const x402ActionProvider = () => new X402ActionProvider();
238
+ exports.x402ActionProvider = x402ActionProvider;