-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_client.go
More file actions
477 lines (415 loc) · 13.2 KB
/
base_client.go
File metadata and controls
477 lines (415 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package blockrun
import (
"bytes"
"context"
"crypto/ecdsa"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/crypto"
)
// baseClient contains the shared fields and methods for all BlockRun clients.
// It handles HTTP requests, x402 payment negotiation, and spending tracking.
type baseClient struct {
privateKey *ecdsa.PrivateKey
address string
apiURL string
httpClient *http.Client
cache *Cache
mu sync.Mutex
sessionTotalUSD float64
sessionCalls int
costLog *CostLog
}
// newBaseClient creates a new baseClient with the given private key, API URL, and timeout.
//
// If privateKey is empty, it checks BLOCKRUN_WALLET_KEY then BASE_CHAIN_WALLET_KEY env vars.
// If apiURL is empty, DefaultAPIURL is used; BLOCKRUN_API_URL env var can override.
func newBaseClient(privateKey, apiURL string, timeout time.Duration) (*baseClient, error) {
// Get private key from param or environment
key := privateKey
if key == "" {
key = os.Getenv("BLOCKRUN_WALLET_KEY")
}
if key == "" {
key = os.Getenv("BASE_CHAIN_WALLET_KEY")
}
if key == "" {
return nil, &ValidationError{
Field: "privateKey",
Message: "Private key required. Pass privateKey parameter or set BLOCKRUN_WALLET_KEY environment variable. NOTE: Your key never leaves your machine - only signatures are sent.",
}
}
// Parse private key
key = strings.TrimPrefix(key, "0x")
ecdsaKey, err := crypto.HexToECDSA(key)
if err != nil {
return nil, &ValidationError{
Field: "privateKey",
Message: fmt.Sprintf("Invalid private key format: %v", err),
}
}
// Get wallet address
address := crypto.PubkeyToAddress(ecdsaKey.PublicKey).Hex()
// Determine API URL
if apiURL == "" {
apiURL = DefaultAPIURL
}
bc := &baseClient{
privateKey: ecdsaKey,
address: address,
apiURL: apiURL,
httpClient: &http.Client{Timeout: timeout},
costLog: NewCostLog(),
}
return bc, nil
}
// checkEnvAPIURL overrides apiURL with BLOCKRUN_API_URL env var if still at default.
// Called after options are applied so user-set URLs take precedence.
func (bc *baseClient) checkEnvAPIURL() {
if envURL := os.Getenv("BLOCKRUN_API_URL"); envURL != "" && bc.apiURL == DefaultAPIURL {
bc.apiURL = strings.TrimSuffix(envURL, "/")
}
}
// GetWalletAddress returns the wallet address being used for payments.
func (bc *baseClient) GetWalletAddress() string {
return bc.address
}
// GetSpending returns session spending information.
func (bc *baseClient) GetSpending() Spending {
bc.mu.Lock()
defer bc.mu.Unlock()
return Spending{
TotalUSD: bc.sessionTotalUSD,
Calls: bc.sessionCalls,
}
}
// doRequest makes a POST request to the given endpoint with automatic x402
// payment handling. It returns the raw response bytes for the caller to unmarshal.
func (bc *baseClient) doRequest(ctx context.Context, endpoint string, body map[string]any) ([]byte, error) {
// Check cache before making request
if bc.cache != nil {
if cached, ok := bc.cache.Get(endpoint, body); ok {
return cached, nil
}
}
url := bc.apiURL + endpoint
// Encode body
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("failed to encode request body: %w", err)
}
// First attempt (will likely return 402)
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonBody))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := bc.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
// Handle 402 Payment Required
if resp.StatusCode == http.StatusPaymentRequired {
return bc.handlePaymentAndRetry(ctx, url, jsonBody, resp)
}
// Handle other errors
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, &APIError{
StatusCode: resp.StatusCode,
Message: fmt.Sprintf("API error: %s", string(bodyBytes)),
}
}
// Read successful response
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// Store in cache
if bc.cache != nil {
bc.cache.Set(endpoint, body, data)
}
return data, nil
}
// doGet makes a GET request to the given endpoint and returns raw response bytes.
func (bc *baseClient) doGet(ctx context.Context, endpoint string) ([]byte, error) {
// Check cache before making request
if bc.cache != nil {
if cached, ok := bc.cache.Get(endpoint, nil); ok {
return cached, nil
}
}
url := bc.apiURL + endpoint
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
resp, err := bc.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, &APIError{
StatusCode: resp.StatusCode,
Message: fmt.Sprintf("API error: %s", string(bodyBytes)),
}
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// Store in cache
if bc.cache != nil {
bc.cache.Set(endpoint, nil, data)
}
return data, nil
}
// doGetWithPayment issues a GET, and if it comes back 402, signs the payment
// and retries. This is used for Pyth-backed market-data endpoints where the
// same path may be free (crypto/fx/commodity) or paid (stocks/usstock).
func (bc *baseClient) doGetWithPayment(ctx context.Context, endpoint string, query map[string]string) ([]byte, error) {
url := bc.apiURL + endpoint
if len(query) > 0 {
sep := "?"
for k, v := range query {
url += sep + k + "=" + urlQueryEscape(v)
sep = "&"
}
}
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
resp, err := bc.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusPaymentRequired {
if bc.privateKey == nil {
return nil, &PaymentError{Message: "endpoint returned 402 but no wallet is configured"}
}
return bc.handleGetPaymentAndRetry(ctx, url, resp)
}
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, &APIError{
StatusCode: resp.StatusCode,
Message: fmt.Sprintf("API error: %s", string(bodyBytes)),
}
}
return io.ReadAll(resp.Body)
}
// handleGetPaymentAndRetry mirrors handlePaymentAndRetry for GET requests
// (no body to re-send; PAYMENT-SIGNATURE rides on a second GET to the same URL).
func (bc *baseClient) handleGetPaymentAndRetry(ctx context.Context, url string, resp *http.Response) ([]byte, error) {
paymentHeader := resp.Header.Get("payment-required")
if paymentHeader == "" {
var respBody map[string]any
if err := json.NewDecoder(resp.Body).Decode(&respBody); err == nil {
if _, ok := respBody["x402"]; ok {
jsonBytes, _ := json.Marshal(respBody["x402"])
paymentHeader = string(jsonBytes)
} else if _, ok := respBody["accepts"]; ok {
jsonBytes, _ := json.Marshal(respBody)
paymentHeader = string(jsonBytes)
}
}
}
if paymentHeader == "" {
return nil, &PaymentError{Message: "402 response but no payment requirements found"}
}
paymentReq, err := ParsePaymentRequired(paymentHeader)
if err != nil {
return nil, &PaymentError{Message: fmt.Sprintf("Failed to parse payment requirements: %v", err)}
}
paymentOption, err := ExtractPaymentDetails(paymentReq)
if err != nil {
return nil, &PaymentError{Message: fmt.Sprintf("Failed to extract payment details: %v", err)}
}
resourceURL := paymentReq.Resource.URL
if resourceURL == "" {
resourceURL = url
}
paymentPayload, err := CreatePaymentPayload(
bc.privateKey,
paymentOption.PayTo,
paymentOption.Amount,
paymentOption.Network,
resourceURL,
paymentReq.Resource.Description,
paymentOption.MaxTimeoutSeconds,
paymentOption.Extra,
paymentReq.Extensions,
)
if err != nil {
return nil, &PaymentError{Message: fmt.Sprintf("Failed to create payment: %v", err)}
}
retryReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create retry request: %w", err)
}
retryReq.Header.Set("PAYMENT-SIGNATURE", paymentPayload)
retryResp, err := bc.httpClient.Do(retryReq)
if err != nil {
return nil, fmt.Errorf("retry request failed: %w", err)
}
defer retryResp.Body.Close()
if retryResp.StatusCode == http.StatusPaymentRequired {
return nil, &PaymentError{Message: "Payment was rejected. Check your wallet balance."}
}
if retryResp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(retryResp.Body)
return nil, &APIError{
StatusCode: retryResp.StatusCode,
Message: fmt.Sprintf("API error after payment: %s", string(bodyBytes)),
}
}
respBytes, err := io.ReadAll(retryResp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
bc.mu.Lock()
bc.sessionCalls++
var costUSD float64
if amountStr := paymentOption.Amount; amountStr != "" {
var amountMicro float64
if _, err := fmt.Sscanf(amountStr, "%f", &amountMicro); err == nil {
costUSD = amountMicro / 1_000_000
bc.sessionTotalUSD += costUSD
}
}
bc.mu.Unlock()
if bc.costLog != nil && costUSD > 0 {
endpoint := strings.TrimPrefix(url, bc.apiURL)
if idx := strings.Index(endpoint, "?"); idx != -1 {
endpoint = endpoint[:idx]
}
bc.costLog.Append(endpoint, costUSD)
}
return respBytes, nil
}
// urlQueryEscape is a minimal query-string escaper used by doGetWithPayment.
// It avoids pulling in net/url just for this single use site.
func urlQueryEscape(s string) string {
const hex = "0123456789ABCDEF"
var b strings.Builder
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z', '0' <= c && c <= '9',
c == '-', c == '_', c == '.', c == '~':
b.WriteByte(c)
default:
b.WriteByte('%')
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&15])
}
}
return b.String()
}
// handlePaymentAndRetry handles a 402 response by signing a payment and retrying.
func (bc *baseClient) handlePaymentAndRetry(ctx context.Context, url string, body []byte, resp *http.Response) ([]byte, error) {
// Get payment required header
paymentHeader := resp.Header.Get("payment-required")
if paymentHeader == "" {
// Try to get from response body
var respBody map[string]any
if err := json.NewDecoder(resp.Body).Decode(&respBody); err == nil {
if _, ok := respBody["x402"]; ok {
// Response body contains payment info - re-encode as header
jsonBytes, _ := json.Marshal(respBody)
paymentHeader = string(jsonBytes)
}
}
}
if paymentHeader == "" {
return nil, &PaymentError{Message: "402 response but no payment requirements found"}
}
// Parse payment requirements
paymentReq, err := ParsePaymentRequired(paymentHeader)
if err != nil {
return nil, &PaymentError{Message: fmt.Sprintf("Failed to parse payment requirements: %v", err)}
}
// Extract payment details
paymentOption, err := ExtractPaymentDetails(paymentReq)
if err != nil {
return nil, &PaymentError{Message: fmt.Sprintf("Failed to extract payment details: %v", err)}
}
// Determine resource URL
resourceURL := paymentReq.Resource.URL
if resourceURL == "" {
resourceURL = url
}
// Create signed payment payload
paymentPayload, err := CreatePaymentPayload(
bc.privateKey,
paymentOption.PayTo,
paymentOption.Amount,
paymentOption.Network,
resourceURL,
paymentReq.Resource.Description,
paymentOption.MaxTimeoutSeconds,
paymentOption.Extra,
paymentReq.Extensions,
)
if err != nil {
return nil, &PaymentError{Message: fmt.Sprintf("Failed to create payment: %v", err)}
}
// Retry with payment signature
retryReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to create retry request: %w", err)
}
retryReq.Header.Set("Content-Type", "application/json")
retryReq.Header.Set("PAYMENT-SIGNATURE", paymentPayload)
retryResp, err := bc.httpClient.Do(retryReq)
if err != nil {
return nil, fmt.Errorf("retry request failed: %w", err)
}
defer retryResp.Body.Close()
// Check for payment rejection
if retryResp.StatusCode == http.StatusPaymentRequired {
return nil, &PaymentError{Message: "Payment was rejected. Check your wallet balance."}
}
// Handle other errors
if retryResp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(retryResp.Body)
return nil, &APIError{
StatusCode: retryResp.StatusCode,
Message: fmt.Sprintf("API error after payment: %s", string(bodyBytes)),
}
}
// Read successful response
respBytes, err := io.ReadAll(retryResp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
// Track spending - convert amount from micro-USDC to USD
bc.mu.Lock()
bc.sessionCalls++
var costUSD float64
if amountStr := paymentOption.Amount; amountStr != "" {
var amountMicro float64
if _, err := fmt.Sscanf(amountStr, "%f", &amountMicro); err == nil {
costUSD = amountMicro / 1_000_000
bc.sessionTotalUSD += costUSD
}
}
bc.mu.Unlock()
// Log cost to persistent JSONL file
if bc.costLog != nil && costUSD > 0 {
endpoint := strings.TrimPrefix(url, bc.apiURL)
bc.costLog.Append(endpoint, costUSD)
}
return respBytes, nil
}