@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,84 @@
1
+ # BEEF Format
2
+
3
+ Bitcoin Extras Extension Format (BEEF) - an efficient way to package Bitcoin transactions with their verification data.
4
+
5
+ ## What is BEEF?
6
+
7
+ BEEF is a standardized format that combines:
8
+ - **Transaction Data**: The actual Bitcoin transaction
9
+ - **Merkle Proofs**: SPV verification data
10
+ - **Block Headers**: Chain validation information
11
+ - **Metadata**: Additional context and references
12
+
13
+ ## BEEF in the SDK
14
+
15
+ ```typescript
16
+ import { Transaction } from '@bsv/sdk'
17
+
18
+ // Create transaction with BEEF data
19
+ const tx = Transaction.fromHexBEEF(beefHex)
20
+
21
+ // Serialize transaction to BEEF
22
+ const beefData = transaction.toBEEF()
23
+
24
+ // Verify transaction using included proofs
25
+ const isValid = await tx.verify(chainTracker)
26
+ ```
27
+
28
+ ## Key Benefits
29
+
30
+ ### Efficiency
31
+ - **Compact**: Includes only necessary verification data
32
+ - **Self-Contained**: No external lookups required
33
+ - **Batch Processing**: Multiple transactions in one package
34
+
35
+ ### SPV Integration
36
+ - **Merkle Proofs**: Verify transaction inclusion
37
+ - **Block Headers**: Validate proof of work
38
+ - **Chain Context**: Understand transaction position
39
+
40
+ ### Interoperability
41
+ - **Standardized**: Consistent format across applications
42
+ - **Portable**: Easy to transmit and store
43
+ - **Compatible**: Works with SPV clients
44
+
45
+ ## Use Cases
46
+
47
+ ### Transaction Broadcasting
48
+ ```typescript
49
+ // Broadcast transaction with proof
50
+ const beefTx = Transaction.fromHexBEEF(beefData)
51
+ await beefTx.broadcast(arcConfig)
52
+ ```
53
+
54
+ ### Data Exchange
55
+ - Share transactions between applications
56
+ - Provide verification data to SPV clients
57
+ - Archive transactions with proofs
58
+
59
+ ### Wallet Integration
60
+ - Import transactions with full context
61
+ - Verify historical transactions
62
+ - Synchronize between devices
63
+
64
+ ## BEEF Structure
65
+
66
+ The format includes:
67
+ 1. **Version**: BEEF format version
68
+ 2. **Transactions**: One or more Bitcoin transactions
69
+ 3. **Proofs**: Merkle proofs for each transaction
70
+ 4. **Headers**: Relevant block headers
71
+ 5. **Metadata**: Additional application data
72
+
73
+ ## Best Practices
74
+
75
+ - Use BEEF for transactions that need verification
76
+ - Include minimal necessary proof data
77
+ - Validate BEEF structure before processing
78
+ - Cache parsed BEEF data for performance
79
+
80
+ ## Next Steps
81
+
82
+ - Learn about [SPV Verification](./spv-verification.md) concepts
83
+ - Understand [Transaction Encoding](./transaction-encoding.md) formats
84
+ - Explore [Chain Tracking](./chain-tracking.md) integration
@@ -0,0 +1,122 @@
1
+ # Chain Tracking
2
+
3
+ How the BSV TypeScript SDK interacts with the Bitcoin network to retrieve transaction and blockchain data.
4
+
5
+ ## Chain Tracker Concept
6
+
7
+ A chain tracker provides access to Bitcoin blockchain data without running a full node:
8
+
9
+ ```typescript
10
+ import { WhatsOnChain } from '@bsv/sdk'
11
+
12
+ // Create a chain tracker
13
+ const chainTracker = new WhatsOnChain('mainnet')
14
+
15
+ // Get transaction data
16
+ const txData = await chainTracker.getTransaction('txid')
17
+ ```
18
+
19
+ ## Key Functions
20
+
21
+ ### Transaction Lookup
22
+ - Retrieve transaction details by ID
23
+ - Get transaction status and confirmations
24
+ - Access transaction inputs and outputs
25
+
26
+ ### UTXO Queries
27
+ - Find unspent transaction outputs
28
+ - Check UTXO availability and value
29
+ - Retrieve UTXO locking scripts
30
+
31
+ ### Block Information
32
+ - Get block headers and merkle proofs
33
+ - Verify transaction inclusion in blocks
34
+ - Access block timestamps and difficulty
35
+
36
+ ### Network Status
37
+ - Check network connectivity
38
+ - Monitor chain tip and height
39
+ - Get fee rate recommendations
40
+
41
+ ## SPV Integration
42
+
43
+ Chain trackers enable SPV (Simplified Payment Verification):
44
+ - **Merkle Proofs**: Verify transaction inclusion without full blocks
45
+ - **Header Chain**: Maintain block headers for proof verification
46
+ - **Lightweight**: Minimal data requirements compared to full nodes
47
+
48
+ ## Multiple Providers
49
+
50
+ The SDK supports multiple chain tracking services:
51
+
52
+ ```typescript
53
+ // Primary and fallback providers
54
+ const config = {
55
+ chainTracker: {
56
+ provider: 'WhatsOnChain',
57
+ network: 'mainnet',
58
+ fallbacks: ['GorillaPool', 'TAAL']
59
+ }
60
+ }
61
+ ```
62
+
63
+ ## Benefits
64
+
65
+ ### Scalability
66
+ - No need to store the entire blockchain
67
+ - Fast startup and synchronization
68
+ - Minimal storage requirements
69
+
70
+ ### Reliability
71
+ - Multiple provider support
72
+ - Automatic failover capabilities
73
+ - Redundant data sources
74
+
75
+ ### Performance
76
+ - Targeted data queries
77
+ - Caching of frequently accessed data
78
+ - Optimized for application needs
79
+
80
+ ## Common Patterns
81
+
82
+ ### Transaction Verification
83
+ ```typescript
84
+ // Verify a transaction exists
85
+ const exists = await chainTracker.getTransaction(txid)
86
+ if (exists) {
87
+ // Transaction is confirmed on-chain
88
+ }
89
+ ```
90
+
91
+ ### UTXO Validation
92
+ ```typescript
93
+ // Check if UTXO is still unspent
94
+ const utxo = await chainTracker.getUTXO(txid, outputIndex)
95
+ if (utxo) {
96
+ // UTXO is available for spending
97
+ }
98
+ ```
99
+
100
+ ## Error Handling
101
+
102
+ Chain tracker operations can fail due to:
103
+ - Network connectivity issues
104
+ - Service provider downtime
105
+ - Invalid transaction IDs
106
+ - Rate limiting
107
+
108
+ The SDK provides automatic retry and failover mechanisms.
109
+
110
+ ## Configuration
111
+
112
+ Chain trackers can be configured for:
113
+ - **Network**: Mainnet, testnet, or regtest
114
+ - **Endpoints**: Custom service URLs
115
+ - **Timeouts**: Request timeout settings
116
+ - **Retry Logic**: Failure handling behavior
117
+
118
+ ## Next Steps
119
+
120
+ - Understand [SPV Verification](./spv-verification.md) concepts
121
+ - Learn about [BEEF Format](./beef.md) for efficient data exchange
122
+ - Explore [Trust Model](./trust-model.md) considerations
@@ -0,0 +1,184 @@
1
+ # Decentralized Identity
2
+
3
+ Understanding how decentralized identity works in BSV and why it matters for building trustless applications.
4
+
5
+ ## What is Decentralized Identity?
6
+
7
+ Imagine a world where you control your own identity credentials, just like you control your own wallet. Instead of relying on Facebook, Google, or government agencies to verify who you are, you can prove your identity using cryptographic certificates that anyone can independently verify.
8
+
9
+ This is the promise of decentralized identity: **self-sovereign identity** that puts users in control while maintaining security and trust.
10
+
11
+ ## Why Decentralized Identity Matters
12
+
13
+ ### The Problem with Centralized Identity
14
+ Traditional identity systems have significant limitations:
15
+ - **Single Points of Failure**: If the identity provider goes down, you lose access
16
+ - **Privacy Concerns**: Companies collect and monetize your personal data
17
+ - **Vendor Lock-in**: You can't easily move your identity between services
18
+ - **Censorship Risk**: Providers can revoke your identity for any reason
19
+ - **Data Breaches**: Centralized databases are attractive targets for hackers
20
+
21
+ ### The Decentralized Solution
22
+ Decentralized identity addresses these issues by:
23
+ - **User Control**: You own and manage your identity data
24
+ - **No Central Authority**: No single entity controls the verification process
25
+ - **Interoperability**: Your identity works across different applications
26
+ - **Privacy by Design**: You choose what information to reveal and when
27
+ - **Censorship Resistance**: No one can arbitrarily revoke your identity
28
+
29
+ ## How It Works in BSV
30
+
31
+ ### Identity Keys vs Transaction Keys
32
+ BSV uses different types of keys for different purposes:
33
+
34
+ **Identity Keys** are long-term, stable identifiers used for:
35
+ - Establishing your digital identity
36
+ - Signing identity certificates
37
+ - Resolving your public profile information
38
+ - Authenticating with services
39
+
40
+ **Transaction Keys** are used for:
41
+ - Signing Bitcoin transactions
42
+ - Managing UTXOs and payments
43
+ - Protocol-specific operations
44
+
45
+ This separation provides both security and privacy benefits.
46
+
47
+ ### Identity Resolution
48
+ Your identity key serves as a unique identifier that can be used to discover:
49
+ - Your chosen display name and profile information
50
+ - Verification badges and trust indicators
51
+ - Public certificates and credentials
52
+ - Contact preferences and communication methods
53
+
54
+ Think of it like a decentralized phone book where your identity key is your number, but instead of just finding your phone number, people can discover rich identity information that you've chosen to make public.
55
+
56
+ ### Certificate-Based Trust
57
+ Instead of trusting a central authority, decentralized identity relies on a web of cryptographic certificates. These certificates are like digital testimonials that others can independently verify:
58
+
59
+ - **Self-Signed Certificates**: Claims you make about yourself
60
+ - **Peer Certificates**: Verifications from other users
61
+ - **Institutional Certificates**: Credentials from recognized organizations
62
+ - **Service Certificates**: Verifications from specialized services
63
+
64
+ ## Trust and Verification Models
65
+
66
+ ### Web of Trust
67
+ In a web of trust model, users verify each other's identities, creating networks of trusted relationships. This is similar to how you might trust a friend's recommendation about a restaurant - the more trusted connections someone has, the more credible they become.
68
+
69
+ ### Institutional Trust
70
+ Some applications require higher assurance levels, so they rely on certificates from recognized institutions like universities, professional licensing boards, or government agencies. These certificates carry more weight because the issuers have established reputations and verification processes.
71
+
72
+ ### Hybrid Approaches
73
+ Most real-world applications use a combination of trust models, adjusting requirements based on context. For example:
74
+ - **Low-risk interactions** might accept self-signed certificates
75
+ - **Financial transactions** might require institutional verification
76
+ - **Professional networking** might emphasize peer verification within industry groups
77
+
78
+ ## Privacy and Selective Disclosure
79
+
80
+ ### Controlling Your Information
81
+ One of the key benefits of decentralized identity is granular control over your personal information. You can:
82
+ - Choose which attributes to make publicly discoverable
83
+ - Reveal different information to different parties
84
+ - Prove claims without revealing underlying data
85
+ - Revoke access to previously shared information
86
+
87
+ ### Zero-Knowledge Proofs
88
+ Advanced cryptographic techniques allow you to prove things about yourself without revealing the underlying information. For example, you could prove you're over 21 without revealing your exact age or birthdate.
89
+
90
+ ### Progressive Disclosure
91
+ As trust builds between parties, you might choose to reveal more information. This allows relationships to develop naturally while maintaining privacy protection.
92
+
93
+ ## Identity Lifecycle
94
+
95
+ ### Getting Started
96
+ Creating a decentralized identity involves:
97
+ 1. **Generating an identity key pair** (handled by your wallet)
98
+ 2. **Creating basic profile information** (name, avatar, contact preferences)
99
+ 3. **Obtaining initial certificates** to establish credibility
100
+ 4. **Making your identity discoverable** through resolution networks
101
+
102
+ ### Building Trust
103
+ Over time, you accumulate certificates and verifications that build your reputation:
104
+ - Verify your email address and social media accounts
105
+ - Get endorsements from colleagues and friends
106
+ - Obtain professional certifications and credentials
107
+ - Participate in community verification programs
108
+
109
+ ### Maintaining Privacy
110
+ As your identity grows, you maintain control by:
111
+ - Regularly reviewing what information is public
112
+ - Updating privacy preferences as needs change
113
+ - Revoking outdated or unwanted certificates
114
+ - Managing consent for data sharing
115
+
116
+ ## Real-World Applications
117
+
118
+ ### Passwordless Authentication
119
+ Instead of remembering dozens of passwords, you can authenticate using your identity certificates. This is more secure than passwords and eliminates the need for password managers.
120
+
121
+ ### Professional Networking
122
+ Verify professional credentials, work history, and skills through cryptographic certificates rather than relying on self-reported information on traditional platforms.
123
+
124
+ ### Age and Identity Verification
125
+ Prove your age for restricted services without revealing your exact birthdate, or verify your identity for account creation without sharing unnecessary personal information.
126
+
127
+ ### Reputation Systems
128
+ Build portable reputation that follows you across different platforms and applications, creating incentives for good behavior and reducing fraud.
129
+
130
+ ### Decentralized Social Networks
131
+ Participate in social networks where your identity and connections are owned by you, not the platform, enabling true social media portability.
132
+
133
+ ## Benefits for Developers
134
+
135
+ ### Simplified User Onboarding
136
+ Instead of building complex registration and verification systems, applications can rely on existing identity infrastructure and certificates.
137
+
138
+ ### Enhanced Security
139
+ Cryptographic identity verification is more secure than traditional username/password systems and reduces the risk of account takeovers.
140
+
141
+ ### Regulatory Compliance
142
+ Decentralized identity can help meet KYC (Know Your Customer) and AML (Anti-Money Laundering) requirements while preserving user privacy.
143
+
144
+ ### Interoperability
145
+ Users can bring their identity and reputation from other applications, reducing friction and improving user experience.
146
+
147
+ ## Challenges and Considerations
148
+
149
+ ### User Experience
150
+ Decentralized identity requires users to understand new concepts like key management and certificate verification. Good wallet software and user interfaces are essential for adoption.
151
+
152
+ ### Recovery and Backup
153
+ Unlike centralized systems where you can reset your password, losing access to your identity keys can be permanent. Robust backup and recovery mechanisms are crucial.
154
+
155
+ ### Network Effects
156
+ The value of decentralized identity increases as more people and organizations participate. Early adoption requires overcoming the "chicken and egg" problem.
157
+
158
+ ### Scalability
159
+ As identity networks grow, efficient resolution and verification mechanisms become increasingly important to maintain performance.
160
+
161
+ ## The Future of Identity
162
+
163
+ Decentralized identity represents a fundamental shift toward user sovereignty and privacy. As the technology matures and adoption grows, we can expect to see:
164
+
165
+ - **Seamless Integration** with everyday applications and services
166
+ - **Enhanced Privacy Protection** through advanced cryptographic techniques
167
+ - **Global Interoperability** across different identity systems and networks
168
+ - **Reduced Identity Fraud** through cryptographic verification
169
+ - **New Business Models** that respect user privacy and data ownership
170
+
171
+ By understanding these concepts, developers can build applications that respect user privacy, enhance security, and contribute to a more open and decentralized internet.
172
+
173
+ ## Related Concepts
174
+
175
+ - [Identity Certificates](./identity-certificates.md) - How cryptographic certificates enable trust
176
+ - [Digital Signatures](./signatures.md) - Cryptographic foundations of identity verification
177
+ - [Trust Model](./trust-model.md) - Security assumptions in decentralized systems
178
+ - [Key Management](./key-management.md) - Managing cryptographic keys securely
179
+
180
+ ## Further Reading
181
+
182
+ - [Identity Management Tutorial](../tutorials/identity-management.md) - Hands-on implementation guide
183
+ - [AuthFetch Tutorial](../tutorials/authfetch-tutorial.md) - Authenticated communication using identity
184
+ - [Security Best Practices](../guides/security-best-practices.md) - Secure identity implementation patterns
@@ -0,0 +1,217 @@
1
+ # Transaction Fees
2
+
3
+ Understanding Bitcoin transaction fees and how they work in the BSV TypeScript SDK.
4
+
5
+ ## What are Transaction Fees?
6
+
7
+ Transaction fees are payments to miners for including transactions in blocks:
8
+
9
+ ```typescript
10
+ import { Transaction } from '@bsv/sdk'
11
+
12
+ // Calculate transaction fee
13
+ const tx = new Transaction()
14
+ const feeRequired = tx.getFee()
15
+
16
+ // Set custom fee rate
17
+ const customFee = tx.getFee(feePerKB)
18
+ ```
19
+
20
+ ## Fee Calculation
21
+
22
+ Fees are calculated based on transaction size:
23
+ - **Fee Rate**: Satoshis per kilobyte (sat/kB)
24
+ - **Transaction Size**: Total bytes in serialized transaction
25
+ - **Total Fee**: Size × Fee Rate
26
+
27
+ ## SDK Fee Handling
28
+
29
+ ### Automatic Fee Calculation
30
+ The SDK calculates fees automatically:
31
+ ```typescript
32
+ // Wallet handles fees automatically
33
+ const wallet = new WalletClient()
34
+ const action = await wallet.createAction({
35
+ outputs: [{
36
+ satoshis: 1000,
37
+ lockingScript: script
38
+ }]
39
+ })
40
+ // Fee calculated and deducted automatically
41
+ ```
42
+
43
+ ### Manual Fee Control
44
+ For advanced use cases:
45
+ ```typescript
46
+ // Calculate fee manually
47
+ const tx = new Transaction()
48
+ tx.addInput(/* input */)
49
+ tx.addOutput(/* output */)
50
+
51
+ const estimatedSize = tx.getSerializedSize()
52
+ const feeRequired = estimatedSize * feePerByte
53
+ ```
54
+
55
+ ## Fee Rates
56
+
57
+ ### Network Fee Rates
58
+ BSV typically uses low, predictable fees:
59
+ - **Standard Rate**: ~0.5 sat/byte
60
+ - **Priority Rate**: ~1.0 sat/byte
61
+ - **Economy Rate**: ~0.1 sat/byte
62
+
63
+ ### Dynamic Fee Estimation
64
+ ```typescript
65
+ // Get current network fee rates
66
+ const feeRates = await chainTracker.getFeeRates()
67
+ const recommendedFee = feeRates.standard
68
+ ```
69
+
70
+ ## Fee Components
71
+
72
+ ### Input Costs
73
+ Each input adds to transaction size:
74
+ - Previous transaction hash (32 bytes)
75
+ - Output index (4 bytes)
76
+ - Unlocking script (variable)
77
+ - Sequence number (4 bytes)
78
+
79
+ ### Output Costs
80
+ Each output adds to transaction size:
81
+ - Value (8 bytes)
82
+ - Locking script length (1-9 bytes)
83
+ - Locking script (variable)
84
+
85
+ ### Base Transaction
86
+ Fixed overhead for every transaction:
87
+ - Version (4 bytes)
88
+ - Input count (1-9 bytes)
89
+ - Output count (1-9 bytes)
90
+ - Lock time (4 bytes)
91
+
92
+ ## Fee Optimization
93
+
94
+ ### UTXO Selection
95
+ Choose UTXOs efficiently:
96
+ ```typescript
97
+ // Prefer fewer, larger UTXOs to reduce fees
98
+ const utxos = await wallet.getUTXOs()
99
+ const selected = selectOptimalUTXOs(utxos, targetAmount)
100
+ ```
101
+
102
+ ### Output Consolidation
103
+ Combine multiple payments:
104
+ ```typescript
105
+ // Batch multiple outputs in one transaction
106
+ const outputs = [
107
+ { satoshis: 1000, lockingScript: script1 },
108
+ { satoshis: 2000, lockingScript: script2 },
109
+ { satoshis: 1500, lockingScript: script3 }
110
+ ]
111
+ ```
112
+
113
+ ### Script Efficiency
114
+ Use efficient script templates:
115
+ ```typescript
116
+ // P2PKH is more efficient than complex scripts
117
+ const p2pkh = new P2PKH()
118
+ const efficientScript = p2pkh.lock(publicKeyHash)
119
+ ```
120
+
121
+ ## Fee Estimation
122
+
123
+ ### Size Estimation
124
+ Estimate transaction size before creation:
125
+ ```typescript
126
+ // Estimate size for fee calculation
127
+ const estimatedInputs = 2
128
+ const estimatedOutputs = 3
129
+ const estimatedSize = estimateTransactionSize(estimatedInputs, estimatedOutputs)
130
+ const estimatedFee = estimatedSize * feeRate
131
+ ```
132
+
133
+ ### Template-Based Estimation
134
+ ```typescript
135
+ // Use script templates for accurate estimation
136
+ const template = new P2PKH()
137
+ const scriptSize = template.estimateLength([publicKeyHash])
138
+ ```
139
+
140
+ ## Error Handling
141
+
142
+ Common fee-related issues:
143
+ - Insufficient funds for fees
144
+ - Fee rate too low for network
145
+ - Transaction size miscalculation
146
+
147
+ ```typescript
148
+ try {
149
+ const action = await wallet.createAction({
150
+ outputs: outputs
151
+ })
152
+ } catch (error) {
153
+ if (error.message.includes('Insufficient funds')) {
154
+ // Handle insufficient balance for fees
155
+ console.log('Not enough funds to cover transaction and fees')
156
+ }
157
+ }
158
+ ```
159
+
160
+ ## Best Practices
161
+
162
+ ### Fee Management
163
+ - Always account for fees in balance calculations
164
+ - Use appropriate fee rates for urgency
165
+ - Monitor network conditions for fee adjustments
166
+ - Implement fee estimation before transaction creation
167
+
168
+ ### Cost Optimization
169
+ - Batch transactions when possible
170
+ - Use efficient script templates
171
+ - Optimize UTXO selection
172
+ - Consider transaction timing
173
+
174
+ ### User Experience
175
+ - Display estimated fees to users
176
+ - Provide fee rate options (economy, standard, priority)
177
+ - Handle insufficient fund errors gracefully
178
+ - Show fee breakdown for transparency
179
+
180
+ ## Wallet Integration
181
+
182
+ Most applications rely on wallets for fee handling:
183
+ ```typescript
184
+ // Wallet manages fees automatically
185
+ const wallet = new WalletClient()
186
+
187
+ // Fees are calculated and deducted automatically
188
+ const result = await wallet.createAction({
189
+ description: 'Payment with automatic fees',
190
+ outputs: [/* outputs */]
191
+ })
192
+ ```
193
+
194
+ ## Advanced Fee Strategies
195
+
196
+ ### Replace-by-Fee (RBF)
197
+ Increase fees for faster confirmation:
198
+ ```typescript
199
+ // Create transaction with RBF enabled
200
+ const tx = new Transaction()
201
+ tx.setRBF(true) // Enable replace-by-fee
202
+ ```
203
+
204
+ ### Child-Pays-for-Parent (CPFP)
205
+ Use dependent transactions to increase effective fee rate:
206
+ ```typescript
207
+ // Create child transaction with higher fee
208
+ const childTx = new Transaction()
209
+ childTx.addInput(/* from parent transaction */)
210
+ // Higher fee rate pulls parent transaction along
211
+ ```
212
+
213
+ ## Next Steps
214
+
215
+ - Understand [Transaction Structure](./transaction-structure.md) for size calculation
216
+ - Learn about [Wallet Integration](./wallet-integration.md) for automatic fee handling
217
+ - Explore [Script Templates](./script-templates.md) for efficient fee optimization