@bsv/sdk 1.6.8 → 1.6.10

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 (92) hide show
  1. package/README.md +9 -4
  2. package/dist/cjs/package.json +7 -5
  3. package/dist/cjs/src/wallet/substrates/HTTPWalletJSON.js +11 -3
  4. package/dist/cjs/src/wallet/substrates/HTTPWalletJSON.js.map +1 -1
  5. package/dist/cjs/src/wallet/substrates/WalletWireProcessor.js +1 -1
  6. package/dist/cjs/src/wallet/substrates/WalletWireProcessor.js.map +1 -1
  7. package/dist/cjs/src/wallet/substrates/utils/toOriginHeader.js +21 -0
  8. package/dist/cjs/src/wallet/substrates/utils/toOriginHeader.js.map +1 -0
  9. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  10. package/dist/esm/src/wallet/substrates/HTTPWalletJSON.js +9 -1
  11. package/dist/esm/src/wallet/substrates/HTTPWalletJSON.js.map +1 -1
  12. package/dist/esm/src/wallet/substrates/WalletWireProcessor.js +1 -1
  13. package/dist/esm/src/wallet/substrates/WalletWireProcessor.js.map +1 -1
  14. package/dist/esm/src/wallet/substrates/utils/toOriginHeader.js +17 -0
  15. package/dist/esm/src/wallet/substrates/utils/toOriginHeader.js.map +1 -0
  16. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  17. package/dist/types/src/wallet/substrates/HTTPWalletJSON.d.ts.map +1 -1
  18. package/dist/types/src/wallet/substrates/utils/toOriginHeader.d.ts +2 -0
  19. package/dist/types/src/wallet/substrates/utils/toOriginHeader.d.ts.map +1 -0
  20. package/dist/types/tsconfig.types.tsbuildinfo +1 -1
  21. package/dist/umd/bundle.js +1 -1
  22. package/docs/concepts/beef.md +84 -0
  23. package/docs/concepts/chain-tracking.md +122 -0
  24. package/docs/concepts/decentralized-identity.md +184 -0
  25. package/docs/concepts/fees.md +217 -0
  26. package/docs/concepts/identity-certificates.md +255 -0
  27. package/docs/concepts/index.md +62 -0
  28. package/docs/concepts/key-management.md +176 -0
  29. package/docs/concepts/script-templates.md +163 -0
  30. package/docs/concepts/sdk-philosophy.md +72 -0
  31. package/docs/concepts/signatures.md +179 -0
  32. package/docs/concepts/spv-verification.md +106 -0
  33. package/docs/concepts/transaction-encoding.md +148 -0
  34. package/docs/concepts/transaction-structure.md +63 -0
  35. package/docs/concepts/trust-model.md +123 -0
  36. package/docs/concepts/verification.md +219 -0
  37. package/docs/concepts/wallet-integration.md +95 -0
  38. package/docs/guides/direct-transaction-creation.md +137 -0
  39. package/docs/guides/http-client-configuration.md +414 -0
  40. package/docs/guides/index.md +30 -0
  41. package/docs/guides/transaction-signing-methods.md +268 -0
  42. package/docs/index.md +74 -0
  43. package/docs/reference/arc-config.md +698 -0
  44. package/docs/reference/brc-100.md +33 -0
  45. package/docs/reference/configuration.md +829 -0
  46. package/docs/reference/debugging.md +700 -0
  47. package/docs/reference/errors.md +547 -0
  48. package/docs/reference/index.md +98 -0
  49. package/docs/reference/network-config.md +914 -0
  50. package/docs/reference/op-codes.md +306 -0
  51. package/docs/reference/transaction-signatures.md +94 -0
  52. package/docs/{wallet.md → reference/wallet.md} +9 -0
  53. package/docs/requirements.txt +3 -0
  54. package/docs/tutorials/advanced-transaction.md +575 -0
  55. package/docs/tutorials/aes-encryption.md +947 -0
  56. package/docs/tutorials/authfetch-tutorial.md +957 -0
  57. package/docs/tutorials/ecdh-key-exchange.md +547 -0
  58. package/docs/tutorials/elliptic-curve-fundamentals.md +603 -0
  59. package/docs/tutorials/error-handling.md +1215 -0
  60. package/docs/tutorials/first-transaction-low-level.md +204 -0
  61. package/docs/tutorials/first-transaction.md +278 -0
  62. package/docs/tutorials/hashes-and-hmacs.md +814 -0
  63. package/docs/tutorials/identity-management.md +702 -0
  64. package/docs/tutorials/index.md +182 -0
  65. package/docs/tutorials/key-management.md +536 -0
  66. package/docs/tutorials/protowallet-development.md +716 -0
  67. package/docs/tutorials/script-construction.md +690 -0
  68. package/docs/tutorials/spv-merkle-proofs.md +682 -0
  69. package/docs/tutorials/testnet-transactions-low-level.md +352 -0
  70. package/docs/tutorials/transaction-broadcasting.md +535 -0
  71. package/docs/tutorials/transaction-types.md +419 -0
  72. package/docs/tutorials/type-42.md +582 -0
  73. package/docs/tutorials/uhrp-storage.md +579 -0
  74. package/package.json +7 -5
  75. package/src/transaction/__tests/Transaction.test.ts +1 -1
  76. package/src/wallet/substrates/HTTPWalletJSON.ts +11 -1
  77. package/src/wallet/substrates/WalletWireProcessor.ts +1 -1
  78. package/src/wallet/substrates/__tests/toOriginHeader.test.ts +34 -0
  79. package/src/wallet/substrates/utils/toOriginHeader.ts +15 -0
  80. package/docs/README.md +0 -21
  81. /package/docs/{auth.md → reference/auth.md} +0 -0
  82. /package/docs/{compat.md → reference/compat.md} +0 -0
  83. /package/docs/{identity.md → reference/identity.md} +0 -0
  84. /package/docs/{kvstore.md → reference/kvstore.md} +0 -0
  85. /package/docs/{messages.md → reference/messages.md} +0 -0
  86. /package/docs/{overlay-tools.md → reference/overlay-tools.md} +0 -0
  87. /package/docs/{primitives.md → reference/primitives.md} +0 -0
  88. /package/docs/{registry.md → reference/registry.md} +0 -0
  89. /package/docs/{script.md → reference/script.md} +0 -0
  90. /package/docs/{storage.md → reference/storage.md} +0 -0
  91. /package/docs/{totp.md → reference/totp.md} +0 -0
  92. /package/docs/{transaction.md → reference/transaction.md} +0 -0
@@ -0,0 +1,414 @@
1
+ # Configuring HTTP Clients
2
+
3
+ This guide covers how to configure HTTP clients for use with the BSV TypeScript SDK, focusing on Axios and alternatives.
4
+
5
+ ## Using Axios with the SDK
6
+
7
+ The BSV TypeScript SDK allows you to provide your own HTTP client implementation for network requests. This is particularly useful when you need custom configuration for transaction broadcasting, network queries, or when working in specific environments.
8
+
9
+ ### Basic Axios Setup
10
+
11
+ ```typescript
12
+ import axios from 'axios'
13
+ import { BSV } from '@bsv/sdk'
14
+
15
+ // Create a configured Axios instance
16
+ const customAxios = axios.create({
17
+ timeout: 10000, // 10 seconds
18
+ headers: {
19
+ 'Content-Type': 'application/json',
20
+ 'Accept': 'application/json'
21
+ }
22
+ })
23
+
24
+ // Use the custom client when broadcasting transactions
25
+ const broadcastTransaction = async (tx) => {
26
+ try {
27
+ // Convert the transaction to hex format
28
+ const txHex = tx.toHex()
29
+
30
+ // Use your custom axios instance for the request
31
+ const response = await customAxios.post('https://api.example.com/v1/tx/broadcast', {
32
+ rawTx: txHex
33
+ })
34
+
35
+ return response.data
36
+ } catch (error) {
37
+ console.error('Error broadcasting transaction:', error)
38
+ throw error
39
+ }
40
+ }
41
+ ```
42
+
43
+ ### Using Axios with ARC Broadcaster
44
+
45
+ The ARC (Alternative Revenue Channel) broadcaster can be configured with a custom HTTP client:
46
+
47
+ ```typescript
48
+ import axios from 'axios'
49
+ import { ARC } from '@bsv/sdk'
50
+
51
+ // Configure Axios
52
+ const customAxios = axios.create({
53
+ timeout: 15000,
54
+ headers: {
55
+ 'Authorization': 'Bearer YOUR_API_KEY',
56
+ 'Content-Type': 'application/json'
57
+ }
58
+ })
59
+
60
+ // Create an ARC instance with custom HTTP client
61
+ const arc = new ARC({
62
+ apiUrl: 'https://api.taal.com/arc',
63
+ httpClient: customAxios
64
+ })
65
+
66
+ // Use the configured ARC instance to broadcast a transaction
67
+ const broadcastWithARC = async (tx) => {
68
+ try {
69
+ // ARC expects hex format
70
+ const txid = await arc.broadcast(tx.toHex())
71
+ return txid
72
+ } catch (error) {
73
+ console.error('ARC broadcast error:', error)
74
+ throw error
75
+ }
76
+ }
77
+ ```
78
+
79
+ ## Advanced HTTP Client Configuration
80
+
81
+ ### Handling Timeouts and Retries
82
+
83
+ ```typescript
84
+ import axios from 'axios'
85
+ import axiosRetry from 'axios-retry'
86
+
87
+ // Create a custom Axios instance
88
+ const client = axios.create({
89
+ timeout: 30000 // 30 seconds
90
+ })
91
+
92
+ // Configure automatic retries
93
+ axiosRetry(client, {
94
+ retries: 3,
95
+ retryDelay: axiosRetry.exponentialDelay,
96
+ retryCondition: (error) => {
97
+ // Retry on network errors or 5xx responses
98
+ return axiosRetry.isNetworkOrIdempotentRequestError(error) ||
99
+ (error.response && error.response.status >= 500)
100
+ }
101
+ })
102
+
103
+ // Add request interceptor for logging
104
+ client.interceptors.request.use(request => {
105
+ console.log('Starting request:', request.url)
106
+ return request
107
+ })
108
+
109
+ // Add response interceptor for error handling
110
+ client.interceptors.response.use(
111
+ response => response,
112
+ error => {
113
+ if (error.response) {
114
+ console.error('Server responded with error:', error.response.status, error.response.data)
115
+ } else if (error.request) {
116
+ console.error('No response received:', error.request)
117
+ } else {
118
+ console.error('Error setting up request:', error.message)
119
+ }
120
+ return Promise.reject(error)
121
+ }
122
+ )
123
+ ```
124
+
125
+ ### Environment-specific Configuration
126
+
127
+ ```typescript
128
+ import axios from 'axios'
129
+
130
+ const getConfiguredClient = (environment = 'production') => {
131
+ const baseURLs = {
132
+ production: 'https://api.taal.com',
133
+ staging: 'https://api-staging.taal.com',
134
+ development: 'http://localhost:3000'
135
+ }
136
+
137
+ const timeouts = {
138
+ production: 10000,
139
+ staging: 15000,
140
+ development: 30000
141
+ }
142
+
143
+ return axios.create({
144
+ baseURL: baseURLs[environment],
145
+ timeout: timeouts[environment],
146
+ headers: {
147
+ 'Content-Type': 'application/json'
148
+ }
149
+ })
150
+ }
151
+
152
+ const productionClient = getConfiguredClient('production')
153
+ const developmentClient = getConfiguredClient('development')
154
+ ```
155
+
156
+ ## SDK Built-in HTTP Clients
157
+
158
+ The BSV TypeScript SDK comes with built-in HTTP client implementations that you can use directly. The SDK automatically selects the appropriate client based on your environment through the `defaultHttpClient()` function.
159
+
160
+ ### Using NodejsHttpClient
161
+
162
+ The SDK includes a Node.js-specific HTTP client implementation that uses the Node.js `https` module:
163
+
164
+ ```typescript
165
+ import { NodejsHttpClient } from '@bsv/sdk'
166
+ import https from 'https'
167
+
168
+ // Create a NodejsHttpClient instance
169
+ const nodeClient = new NodejsHttpClient(https)
170
+
171
+ // Use with ARC
172
+ const arc = new ARC('https://api.taal.com/arc', {
173
+ apiKey: 'your-api-key',
174
+ httpClient: nodeClient
175
+ })
176
+
177
+ // Example of broadcasting a transaction
178
+ const broadcastTx = async (tx) => {
179
+ try {
180
+ const txid = await arc.broadcast(tx)
181
+ console.log('Transaction broadcast successful. TXID:', txid)
182
+ return txid
183
+ } catch (error) {
184
+ console.error('Error broadcasting transaction:', error)
185
+ throw error
186
+ }
187
+ }
188
+ ```
189
+
190
+ ### Using Built-in FetchHttpClient
191
+
192
+ In browser environments, the SDK provides a `FetchHttpClient` implementation that uses the Fetch API:
193
+
194
+ ```typescript
195
+ import { FetchHttpClient, ARC } from '@bsv/sdk'
196
+
197
+ // Create a FetchHttpClient instance with custom fetch options
198
+ const fetchClient = new FetchHttpClient(window.fetch.bind(window))
199
+
200
+ // Use with ARC
201
+ const arc = new ARC('https://api.taal.com/arc', {
202
+ apiKey: 'your-api-key',
203
+ httpClient: fetchClient
204
+ })
205
+ ```
206
+
207
+ ### Using defaultHttpClient
208
+
209
+ The SDK provides a `defaultHttpClient()` function that automatically selects the appropriate HTTP client based on the environment:
210
+
211
+ ```typescript
212
+ import { defaultHttpClient, ARC } from '@bsv/sdk'
213
+
214
+ // Get the default HTTP client for the current environment
215
+ const client = defaultHttpClient()
216
+
217
+ // Use with ARC
218
+ const arc = new ARC('https://api.taal.com/arc', {
219
+ apiKey: 'your-api-key',
220
+ httpClient: client
221
+ })
222
+ ```
223
+
224
+ ## Alternative HTTP Clients
225
+
226
+ While the SDK provides built-in HTTP clients and Axios is commonly used, you can implement your own HTTP clients with the BSV TypeScript SDK:
227
+
228
+ ### Using Fetch API
229
+
230
+ ```typescript
231
+ import { ARC } from '@bsv/sdk'
232
+
233
+ // Create a fetch-based HTTP client
234
+ const fetchClient = {
235
+ post: async (url, data, options = {}) => {
236
+ const response = await fetch(url, {
237
+ method: 'POST',
238
+ headers: {
239
+ 'Content-Type': 'application/json',
240
+ ...options.headers
241
+ },
242
+ body: JSON.stringify(data)
243
+ })
244
+
245
+ if (!response.ok) {
246
+ const errorText = await response.text()
247
+ throw new Error(`HTTP error ${response.status}: ${errorText}`)
248
+ }
249
+
250
+ return await response.json()
251
+ },
252
+
253
+ get: async (url, options = {}) => {
254
+ const response = await fetch(url, {
255
+ method: 'GET',
256
+ headers: {
257
+ 'Accept': 'application/json',
258
+ ...options.headers
259
+ }
260
+ })
261
+
262
+ if (!response.ok) {
263
+ const errorText = await response.text()
264
+ throw new Error(`HTTP error ${response.status}: ${errorText}`)
265
+ }
266
+
267
+ return await response.json()
268
+ }
269
+ }
270
+
271
+ // Use with ARC
272
+ const arc = new ARC({
273
+ apiUrl: 'https://api.taal.com/arc',
274
+ httpClient: fetchClient
275
+ })
276
+ ```
277
+
278
+ ## Testing and Mocking HTTP Clients
279
+
280
+ When testing your application, you may want to mock HTTP responses:
281
+
282
+ ```typescript
283
+ import { ARC } from '@bsv/sdk'
284
+
285
+ // Create a mock HTTP client for testing
286
+ const mockHttpClient = {
287
+ post: jest.fn().mockResolvedValue({ data: { txid: '1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' } }),
288
+ get: jest.fn().mockResolvedValue({ data: { status: 'confirmed' } })
289
+ }
290
+
291
+ // Create an ARC instance with the mock client
292
+ const arc = new ARC({
293
+ apiUrl: 'https://api.example.com/arc',
294
+ httpClient: mockHttpClient
295
+ })
296
+
297
+ // Test transaction broadcasting
298
+ const testBroadcast = async () => {
299
+ const mockTxHex = '0100000001...'
300
+ const result = await arc.broadcast(mockTxHex)
301
+
302
+ // Verify the mock was called correctly
303
+ expect(mockHttpClient.post).toHaveBeenCalledWith(
304
+ 'https://api.example.com/arc/tx',
305
+ { rawTx: mockTxHex },
306
+ expect.any(Object)
307
+ )
308
+
309
+ return result
310
+ }
311
+ ```
312
+
313
+ ## Implementing a Custom HTTP Client
314
+
315
+ You can create your own HTTP client implementation by implementing the `HttpClient` interface from the SDK. This gives you complete control over how HTTP requests are handled:
316
+
317
+ ```typescript
318
+ import { HttpClient, HttpClientResponse, HttpClientRequestOptions, ARC } from '@bsv/sdk'
319
+
320
+ // Implement the HttpClient interface
321
+ class CustomHttpClient implements HttpClient {
322
+ constructor(private readonly options: { timeout?: number } = {}) {}
323
+
324
+ async request<T = any>(
325
+ url: string,
326
+ options: HttpClientRequestOptions
327
+ ): Promise<HttpClientResponse<T>> {
328
+ console.log(`Making ${options.method} request to ${url}`)
329
+
330
+ try {
331
+ // Set up timeout
332
+ const timeout = this.options.timeout || 10000
333
+ const controller = new AbortController()
334
+ const timeoutId = setTimeout(() => controller.abort(), timeout)
335
+
336
+ // Prepare fetch options
337
+ const fetchOptions: RequestInit = {
338
+ method: options.method || 'GET',
339
+ headers: options.headers,
340
+ signal: controller.signal,
341
+ body: options.data ? JSON.stringify(options.data) : undefined
342
+ }
343
+
344
+ // Make the request
345
+ const response = await fetch(url, fetchOptions)
346
+ clearTimeout(timeoutId)
347
+
348
+ // Parse response
349
+ let data: any
350
+ const contentType = response.headers.get('content-type')
351
+ if (contentType && contentType.includes('application/json')) {
352
+ data = await response.json()
353
+ } else {
354
+ data = await response.text()
355
+ }
356
+
357
+ // Return formatted response
358
+ return {
359
+ status: response.status,
360
+ statusText: response.statusText,
361
+ ok: response.ok,
362
+ data
363
+ }
364
+ } catch (error) {
365
+ console.error('Request failed:', error)
366
+ return {
367
+ status: 500,
368
+ statusText: error.message || 'Request failed',
369
+ ok: false,
370
+ data: { error: error.message }
371
+ }
372
+ }
373
+ }
374
+ }
375
+
376
+ // Use the custom client with ARC
377
+ const customClient = new CustomHttpClient({ timeout: 15000 })
378
+ const arc = new ARC('https://api.taal.com/arc', {
379
+ apiKey: 'your-api-key',
380
+ httpClient: customClient
381
+ })
382
+
383
+ // Example broadcasting a transaction with the custom client
384
+ const broadcastTx = async (tx) => {
385
+ try {
386
+ // Make sure to use toHex() for proper serialization
387
+ const txHex = tx.toHex()
388
+ const result = await arc.broadcast(tx)
389
+
390
+ // Transaction ID needs specific handling
391
+ console.log('Transaction broadcast successful. TXID:', result.txid)
392
+ return result
393
+ } catch (error) {
394
+ console.error('Error broadcasting transaction:', error)
395
+ throw error
396
+ }
397
+ }
398
+ ```
399
+
400
+ ## Best Practices
401
+
402
+ 1. **Always set timeouts** - Network requests can hang indefinitely without proper timeouts
403
+ 2. **Implement retries** - Especially for transaction broadcasting, retries can improve reliability
404
+ 3. **Add proper error handling** - Parse and handle HTTP errors appropriately
405
+ 4. **Configure request logging** - Log requests and responses for debugging purposes
406
+ 5. **Use environment variables** - Store API keys and endpoints in environment variables
407
+ 6. **Consider rate limiting** - Implement backoff strategies for rate-limited APIs
408
+ 7. **Use the built-in clients** - The SDK's `defaultHttpClient()` handles environment detection automatically
409
+
410
+ ## Related Resources
411
+
412
+ - [Axios Documentation](https://axios-http.com/docs/intro)
413
+ - [ARC API Reference](../reference/arc.md)
414
+ - [Transaction Broadcasting Guide](./transaction-monitoring.md)
@@ -0,0 +1,30 @@
1
+ # How-To Guides
2
+
3
+ Practical, problem-oriented guides to help you accomplish specific tasks with the BSV TypeScript SDK.
4
+
5
+ ## Transaction Management
6
+
7
+ ### [Transaction Signing Methods](./transaction-signing-methods.md)
8
+ - `WalletClient` approach for secure key management
9
+ - Low-level API approach for direct control
10
+ - Comparison of different signing methods
11
+ - Best practices for transaction signing
12
+
13
+ ### [Creating Transactions with Direct Interfaces](./direct-transaction-creation.md)
14
+ - Lower-level transaction construction using direct SDK interfaces
15
+ - Custom transaction types not supported by `WalletClient`
16
+ - Precise control over UTXO selection
17
+ - Educational examples for understanding transaction structure
18
+
19
+ ## Network Integration
20
+
21
+ ### [Configuring HTTP Clients](./http-client-configuration.md)
22
+ - Axios integration and setup
23
+ - Custom request timeout configuration
24
+ - Error handling and retries
25
+ - Alternative HTTP client options
26
+ - Browser and Node.js environment considerations
27
+
28
+ ---
29
+
30
+ *More guides are planned for future releases. Check back regularly for updates on transaction batching, security best practices, wallet integration, and more advanced topics.*