@anywalletkit/wallet-btc 0.0.0-stage → 0.2.0

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
- # Temporary Holding Version
1
+ # @anywalletkit/wallet-btc
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Bitcoin accounts on [`@scure/btc-signer`](https://github.com/paulmillr/scure-btc-signer)
4
+ (audited by Cure53; pure `Uint8Array`, no `Buffer`, no Node shims):
5
+
6
+ | `addressType` | Path | Address | Standard |
7
+ |---|---|---|---|
8
+ | `p2wpkh` (default) | `m/84'/0'/0'/0/i` | `bc1q…` | BIP-84 native segwit |
9
+ | `p2tr` | `m/86'/0'/0'/0/i` | `bc1p…` | BIP-86 key-path taproot |
10
+
11
+ Test networks use coin type `1'` (`tb1…` / `bcrt1…`). Both paths are pinned by the
12
+ official BIP-84 / BIP-86 test vectors.
13
+
14
+ ```ts
15
+ import WalletManagerBtc from '@anywalletkit/wallet-btc'
16
+
17
+ const wallet = new WalletManagerBtc(seedPhrase, {
18
+ network: 'bitcoin',
19
+ addressType: 'p2wpkh', // or 'p2tr'
20
+ client: [
21
+ { type: 'blockbook-http', clientConfig: { url: 'https://btc1.trezor.io' } },
22
+ { type: 'esplora-http', clientConfig: { url: 'https://mempool.space/api' } }, // fails over in order
23
+ ],
24
+ maxFeeRate: 200, // sat/vB ceiling (default 500)
25
+ })
26
+ const account = await wallet.getAccount(0)
27
+
28
+ const preview = await account.describeTransaction({ to: 'bc1q…', value: 50_000n })
29
+ // { kind: 'btc-transfer', inputs, outputs: [{ role: 'recipient' | 'change' }], fee, feeRate, vsize, rbf, lockTime, warnings }
30
+
31
+ await account.transfer({ recipient: 'bc1q…', amount: 50_000n }) // sats
32
+ await account.sendTransaction({ to: 'bc1q…', value: 50_000n, feeRate: 12n }) // explicit sat/vB
33
+ const hex = await account.signTransaction({ to: 'bc1q…', value: 50_000n }) // sign only
34
+ const max = await account.getMaxSpendable() // sweep amount after fee
35
+ wallet.dispose()
36
+ ```
37
+
38
+ ## What a spend is
39
+
40
+ Coin selection is our own (`selectCoins`, `coinselect.ts`): effective-value
41
+ accumulation, largest first; inputs that cannot pay for themselves are skipped;
42
+ change below dust (294 sat p2wpkh / 330 sat p2tr) is folded into the fee; at most
43
+ `maxInputs` (200) inputs. Fees are `feeRate × vsize` with the standard segwit
44
+ weights, estimated with 72-byte signatures so the quote is never below the fee
45
+ actually paid.
46
+
47
+ Transactions signal replace-by-fee (`rbf`, default on) and set `nLockTime` to the
48
+ current tip (`antiFeeSniping`, default on when the transport can report the height).
49
+
50
+ ## Safety checks
51
+
52
+ Before signing **and** before broadcasting — also for caller-supplied raw hex —
53
+ every transaction is resolved into a `BtcTxDescription` and must pass:
54
+
55
+ - fee rate ≤ `maxFeeRate` (`UnsafeTransactionError('fee-rate-too-high')`);
56
+ - exactly one output equals the requested recipient + amount, every other output
57
+ is our own change (`'unexpected-output'`, `'recipient-mismatch'`, `'change-not-ours'`);
58
+ - `transactionMaxFee` / `transferMaxFee` absolute caps.
59
+
60
+ Warnings that do not block: `high-fee-rate`, `fee-over-10pct-of-amount`,
61
+ `dust-output`, `no-change`.
62
+
63
+ ## Message signing
64
+
65
+ `sign()` / `verify()` are BIP-137 for p2wpkh accounts (header `39 + recovery`,
66
+ base64 — the Electrum / Bitcoin Core encoding). Taproot accounts have no BIP-137
67
+ form; `sign()` throws `UnsupportedAddressTypeError` (BIP-322 is not implemented).
68
+
69
+ ## Transports
70
+
71
+ `blockbook-http` (Trezor Blockbook REST, QuickNode's add-on) and `esplora-http`
72
+ (mempool.space, blockstream.info). Requests time out after `timeoutMs` (15 s) and
73
+ responses are shape-checked (`NetworkError` otherwise). Pass your own object
74
+ implementing `BtcClient` for anything else.
75
+
76
+ ## Activity history
77
+
78
+ `createBtcHistory` is the chain's `HistorySource` (`@anywalletkit/core`) over Blockbook, reusing `BlockbookClient` (`getAddressPage`, `getTransactionDetails`).
79
+
80
+ ```ts
81
+ import { createBtcHistory } from '@anywalletkit/wallet-btc/history'
82
+
83
+ const history = createBtcHistory({ blockbookUrls: ['https://btc1.trezor.io', 'https://bitcoin.atomicwallet.io'] })
84
+ const page = await history.listActivity('bc1q3x8yszvcvjjxqragsh0l6j8rxnhk7pay9hnj5h', { limit: 25 })
85
+ const older = await history.listActivity(address, { cursor: page.cursor })
86
+ const one = await history.getTransaction(page.items[0].hash, address)
87
+ history.explorerTxUrl(one.hash) // https://mempool.space/tx/…
88
+ ```
89
+
90
+ | option | default | notes |
91
+ |---|---|---|
92
+ | `blockbookUrl` / `blockbookUrls` | — | Blockbook roots, tried in order (Cloudflare 403, 5xx, network → next). The Trezor instances (`btc1…5.trezor.io`) sit behind a Cloudflare challenge that blocks non-browser user agents; `bitcoin.atomicwallet.io` and `blockbook.btc.zelcore.io` answered on 2026-10-14. QuickNode's Blockbook add-on speaks the same API. |
93
+ | `network` | `bitcoin` | `testnet` / `regtest` CAIP-2 ids; mempool.space testnet links. |
94
+ | `pageSize` | the query `limit`, ≤ 100 | Rows per Blockbook page (its max is 1000). |
95
+ | `fetch`, `timeoutMs` | global, 15 000 | |
96
+
97
+ **Endpoint.** `GET /api/v2/address/{a}?details=txs&page=&pageSize=` — Blockbook returns transactions newest first with inputs and outputs (`hex` is dropped). The cursor is base64 JSON `{ v: 1, p, s }`: the next page and the page size the pagination started with (Blockbook clamps out-of-range pages to the last one, so paging stops at `totalPages`). `since` is applied client-side; unconfirmed rows are always kept.
98
+
99
+ **Mapping.** Inputs the address spent (`ownIn`) and outputs it received (`ownOut`) are summed. Spent inputs → a send: `from` = address, `to` = the first output that is not ours, `nativeValue` = what left to non-own outputs (change ignored, fee separate); every output ours → a consolidation to itself. No spent inputs → a receive: `from` = the first input address (`coinbase` when none), `nativeValue` = `ownOut`. `transfers` is that one native leg, `fee` = `fees`, `status` = `confirmed` once `confirmations ≥ 1` (else `pending`, no `block`), `block` = `blockHeight`, `raw` = the Blockbook transaction plus `ownIn` / `ownOut`.
100
+
101
+ Fixtures in `test/fixtures/history/` were captured on 2026-10-14 from `bitcoin.atomicwallet.io` for the test address (its 4 transactions: two receives, two sends with change) and `GET /api/v2/tx/{txid}` of one send. No protocol module recognizes Bitcoin transactions, so there is no recognizer cross-check.
@@ -0,0 +1,318 @@
1
+ // src/blockbook.ts
2
+ import { NetworkError as NetworkError2 } from "@anywalletkit/core";
3
+
4
+ // src/http.ts
5
+ import { NetworkError } from "@anywalletkit/core";
6
+ var DEFAULT_TIMEOUT_MS = 15e3;
7
+ async function fetchWithTimeout(fetchFn, url, init, timeoutMs, provider) {
8
+ const signal = typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(timeoutMs) : void 0;
9
+ try {
10
+ return await fetchFn(url, { ...init, ...signal ? { signal } : {} });
11
+ } catch (e) {
12
+ throw new NetworkError(`Request failed: ${url}`, { provider, cause: e });
13
+ }
14
+ }
15
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
16
+ var isHex64 = (v) => typeof v === "string" && /^[0-9a-fA-F]{64}$/.test(v);
17
+ var isIntString = (v) => typeof v === "string" && /^-?\d+$/.test(v);
18
+
19
+ // src/blockbook.ts
20
+ var MEMPOOL_SPACE_URL = "https://mempool.space";
21
+ function unconfirmedOutgoing(transactions, address) {
22
+ const pending = (transactions ?? []).filter((tx) => tx.blockHeight === -1);
23
+ const pendingIds = new Set(pending.map((t) => t.txid));
24
+ const byId = new Map(pending.map((t) => [t.txid, t]));
25
+ const trusted = /* @__PURE__ */ new Map();
26
+ const owned = (entries) => (entries ?? []).filter((e) => e.isAddress && e.addresses?.includes(address)).reduce((s, e) => s + BigInt(e.value ?? 0), 0n);
27
+ const isTrusted = (tx) => {
28
+ if (trusted.has(tx.txid)) return trusted.get(tx.txid);
29
+ trusted.set(tx.txid, false);
30
+ const vins = tx.vin ?? [];
31
+ const ours = vins.filter((v) => v.isAddress && v.addresses?.includes(address));
32
+ const ok = vins.length > 0 && ours.length === vins.length && ours.every((v) => !v.txid || !pendingIds.has(v.txid) || isTrusted(byId.get(v.txid)));
33
+ trusted.set(tx.txid, ok);
34
+ return ok;
35
+ };
36
+ const consumed = /* @__PURE__ */ new Set();
37
+ for (const tx of pending) for (const v of tx.vin ?? []) if (v.txid && pendingIds.has(v.txid)) consumed.add(`${v.txid}:${v.vout}`);
38
+ return pending.reduce((total, tx) => {
39
+ const spent = owned((tx.vin ?? []).filter((v) => !v.txid || !pendingIds.has(v.txid)));
40
+ const change = isTrusted(tx) ? owned((tx.vout ?? []).filter((o) => !consumed.has(`${tx.txid}:${o.n}`))) : 0n;
41
+ return total + (spent - change);
42
+ }, 0n);
43
+ }
44
+ var BlockbookClient = class _BlockbookClient {
45
+ base;
46
+ fetchFn;
47
+ timeoutMs;
48
+ constructor(config, fetchFn = globalThis.fetch, timeoutMs = DEFAULT_TIMEOUT_MS) {
49
+ this.base = config.url.replace(/\/+$/, "").replace(/\/api$/, "");
50
+ this.fetchFn = fetchFn;
51
+ this.timeoutMs = timeoutMs;
52
+ }
53
+ async connect() {
54
+ }
55
+ async close() {
56
+ }
57
+ async get(path, check) {
58
+ const url = `${this.base}/api${path}`;
59
+ const res = await fetchWithTimeout(this.fetchFn, url, void 0, this.timeoutMs, this.base);
60
+ if (!res.ok) throw new NetworkError2(`Blockbook request failed: ${res.status} ${res.statusText} (${url})`, { provider: this.base });
61
+ let body;
62
+ try {
63
+ body = await res.json();
64
+ } catch (e) {
65
+ throw new NetworkError2(`Blockbook returned non-JSON for ${url}`, { provider: this.base, cause: e });
66
+ }
67
+ if (!check(body)) throw new NetworkError2(`Blockbook returned an unexpected shape for ${url}`, { provider: this.base });
68
+ return body;
69
+ }
70
+ async getBalance(address) {
71
+ const data = await this.get(`/v2/address/${address}?details=txs`, (v) => isRecord(v) && isIntString(v.balance) && isIntString(v.unconfirmedBalance) && (v.transactions === void 0 || Array.isArray(v.transactions)));
72
+ return { confirmed: BigInt(data.balance), unconfirmed: BigInt(data.unconfirmedBalance), unconfirmedOutgoing: unconfirmedOutgoing(data.transactions, address) };
73
+ }
74
+ async listUnspent(address) {
75
+ const data = await this.get(`/v2/utxo/${address}`, (v) => Array.isArray(v) && v.every((u) => isRecord(u) && typeof u.txid === "string" && typeof u.vout === "number" && isIntString(u.value)));
76
+ return data.map((u) => ({ txid: u.txid, vout: u.vout, value: BigInt(u.value), height: u.height ?? -1 }));
77
+ }
78
+ async getHistory(address) {
79
+ const items = [];
80
+ for (let page = 1; ; page++) {
81
+ const data = await this.get(`/v2/address/${address}?details=txslight&pageSize=1000&page=${page}`, (v) => isRecord(v) && (v.transactions === void 0 || Array.isArray(v.transactions)));
82
+ for (const tx of data.transactions ?? []) items.push({ txid: tx.txid, height: tx.blockHeight });
83
+ if (page >= (data.totalPages ?? 1)) break;
84
+ }
85
+ return items;
86
+ }
87
+ /** One page of the address's transactions, newest first, with inputs / outputs (what the activity history reads). */
88
+ async getAddressPage(address, page = 1, pageSize = 25) {
89
+ const data = await this.get(`/v2/address/${address}?details=txs&page=${page}&pageSize=${pageSize}`, (v) => isRecord(v) && (v.transactions === void 0 || Array.isArray(v.transactions) && v.transactions.every(_BlockbookClient.isTx)));
90
+ const out = { ...data };
91
+ for (const tx of out.transactions ?? []) delete tx.hex;
92
+ return out;
93
+ }
94
+ /** A transaction with its inputs / outputs; undefined when Blockbook does not know it. */
95
+ async getTransactionDetails(txid) {
96
+ try {
97
+ const tx = await this.get(`/v2/tx/${txid}`, (v) => _BlockbookClient.isTx(v));
98
+ const out = { ...tx };
99
+ delete out.hex;
100
+ return out;
101
+ } catch (e) {
102
+ if (e instanceof NetworkError2 && /\b(400|404)\b/.test(e.message)) return void 0;
103
+ throw e;
104
+ }
105
+ }
106
+ static isTx(v) {
107
+ return isRecord(v) && typeof v.txid === "string" && typeof v.blockHeight === "number" && typeof v.confirmations === "number";
108
+ }
109
+ async getTransactionInfo(txid) {
110
+ try {
111
+ return await this.get(`/v2/tx/${txid}`, _BlockbookClient.isTx);
112
+ } catch (e) {
113
+ if (e instanceof NetworkError2 && /\b(400|404)\b/.test(e.message)) return void 0;
114
+ throw e;
115
+ }
116
+ }
117
+ async getTransaction(txid) {
118
+ const data = await this.get(`/v2/tx/${txid}`, _BlockbookClient.isTx);
119
+ if (typeof data.hex !== "string" || !data.hex) throw new NetworkError2(`Transaction ${txid} has no hex data`, { provider: this.base });
120
+ return data.hex;
121
+ }
122
+ async broadcast(rawTx) {
123
+ const data = await this.get(`/v2/sendtx/${rawTx}`, (v) => isRecord(v));
124
+ if (data.error) throw new Error(typeof data.error === "string" ? data.error : data.error.message ?? "broadcast failed");
125
+ if (!data.result) throw new NetworkError2("Blockbook returned no txid", { provider: this.base });
126
+ return data.result;
127
+ }
128
+ /** sat/vB. Blockbook reports BTC/kB (×1e5 → sat/vB); falls back to mempool.space when it has no estimate. */
129
+ async estimateFee(blocks) {
130
+ try {
131
+ const data = await this.get(`/v1/estimatefee/${blocks}`, (v) => typeof v === "string" || isRecord(v));
132
+ const rate = Number(typeof data === "string" ? data : data.result);
133
+ if (rate > 0) return Math.max(rate * 1e5, 1);
134
+ } catch {
135
+ }
136
+ const res = await fetchWithTimeout(this.fetchFn, `${MEMPOOL_SPACE_URL}/api/v1/fees/recommended`, void 0, this.timeoutMs, MEMPOOL_SPACE_URL);
137
+ if (!res.ok) throw new NetworkError2("Fee estimation request failed", { provider: MEMPOOL_SPACE_URL });
138
+ const d = await res.json();
139
+ const satPerVb = blocks <= 1 ? d.fastestFee : blocks <= 3 ? d.halfHourFee : blocks <= 6 ? d.hourFee : d.economyFee;
140
+ if (!satPerVb || satPerVb <= 0) throw new NetworkError2("Fee estimation is unavailable", { provider: MEMPOOL_SPACE_URL });
141
+ return satPerVb;
142
+ }
143
+ async getBlockHeight() {
144
+ const data = await this.get("/v2", (v) => isRecord(v));
145
+ const h = data.blockbook?.bestHeight;
146
+ if (typeof h !== "number" || h <= 0) throw new NetworkError2("Blockbook did not report a block height", { provider: this.base });
147
+ return h;
148
+ }
149
+ };
150
+
151
+ // src/types.ts
152
+ var CAIP2_GENESIS = {
153
+ bitcoin: "bip122:000000000019d6689c085ae165831e93",
154
+ testnet: "bip122:000000000933ea01ad0ee984209779ba",
155
+ regtest: "bip122:0f9188f13cb7b2c71f2a335e3a4fc328"
156
+ };
157
+
158
+ // src/history.ts
159
+ var HistoryUnavailableError = class extends Error {
160
+ chain;
161
+ reason;
162
+ attempts;
163
+ constructor(chain, reason, attempts = []) {
164
+ super(`History unavailable for ${chain}: ${reason}`);
165
+ this.name = "HistoryUnavailableError";
166
+ this.chain = chain;
167
+ this.reason = reason;
168
+ this.attempts = attempts;
169
+ }
170
+ };
171
+ var DEFAULT_LIMIT = 25;
172
+ var MAX_PAGE_SIZE = 100;
173
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
174
+ function b64encode(s) {
175
+ let out = "";
176
+ for (let i = 0; i < s.length; i += 3) {
177
+ const c = [s.charCodeAt(i), s.charCodeAt(i + 1), s.charCodeAt(i + 2)];
178
+ const n = c[0] << 16 | (c[1] || 0) << 8 | (c[2] || 0);
179
+ out += B64[n >> 18 & 63] + B64[n >> 12 & 63] + (Number.isNaN(c[1]) ? "=" : B64[n >> 6 & 63]) + (Number.isNaN(c[2]) ? "=" : B64[n & 63]);
180
+ }
181
+ return out;
182
+ }
183
+ function b64decode(s) {
184
+ const clean = s.replace(/[^A-Za-z0-9+/]/g, "");
185
+ let out = "";
186
+ for (let i = 0; i < clean.length; i += 4) {
187
+ const c = [0, 1, 2, 3].map((k) => i + k < clean.length ? B64.indexOf(clean[i + k]) : -1);
188
+ if (c[0] < 0 || c[1] < 0) throw new Error("bad base64");
189
+ const n = c[0] << 18 | c[1] << 12 | (c[2] < 0 ? 0 : c[2]) << 6 | (c[3] < 0 ? 0 : c[3]);
190
+ out += String.fromCharCode(n >> 16 & 255);
191
+ if (c[2] >= 0) out += String.fromCharCode(n >> 8 & 255);
192
+ if (c[3] >= 0) out += String.fromCharCode(n & 255);
193
+ }
194
+ return out;
195
+ }
196
+ function encodeCursor(c) {
197
+ return b64encode(JSON.stringify(c));
198
+ }
199
+ function decodeCursor(s) {
200
+ let parsed;
201
+ try {
202
+ parsed = JSON.parse(b64decode(s));
203
+ } catch {
204
+ throw new Error("@anywalletkit/wallet-btc: malformed history cursor");
205
+ }
206
+ const c = parsed;
207
+ if (!c || c.v !== 1 || !Number.isInteger(c.p) || c.p < 1 || !Number.isInteger(c.s) || c.s < 1) throw new Error("@anywalletkit/wallet-btc: malformed history cursor");
208
+ return { v: 1, p: c.p, s: c.s };
209
+ }
210
+ var big = (v) => typeof v === "string" && /^-?\d+$/.test(v) ? BigInt(v) : typeof v === "number" ? BigInt(Math.trunc(v)) : 0n;
211
+ function mapBlockbookTx(chain, address, tx) {
212
+ const owns = (e) => e.isAddress !== false && (e.addresses ?? []).includes(address);
213
+ let ownIn = 0n, ownOut = 0n, sentToOthers = 0n;
214
+ for (const vin of tx.vin ?? []) if (owns(vin)) ownIn += big(vin.value);
215
+ for (const vout of tx.vout ?? []) {
216
+ if (owns(vout)) ownOut += big(vout.value);
217
+ else sentToOthers += big(vout.value);
218
+ }
219
+ const firstInput = (tx.vin ?? []).find((v) => v.isAddress !== false && v.addresses?.[0])?.addresses?.[0];
220
+ const firstOtherOutput = (tx.vout ?? []).find((v) => v.isAddress !== false && !owns(v) && v.addresses?.[0])?.addresses?.[0];
221
+ const transfers = [];
222
+ let from, to, nativeValue;
223
+ if (ownIn > 0n) {
224
+ from = address;
225
+ to = firstOtherOutput ?? address;
226
+ nativeValue = firstOtherOutput ? sentToOthers : ownOut;
227
+ if (nativeValue > 0n) transfers.push({ token: null, from: address, to, amount: nativeValue });
228
+ } else {
229
+ from = firstInput ?? "coinbase";
230
+ to = address;
231
+ nativeValue = ownOut;
232
+ if (nativeValue > 0n) transfers.push({ token: null, from, to: address, amount: nativeValue });
233
+ }
234
+ const confirmed = tx.confirmations > 0 && tx.blockHeight > 0;
235
+ const out = {
236
+ chain,
237
+ hash: tx.txid,
238
+ time: tx.blockTime ?? 0,
239
+ status: confirmed ? "confirmed" : "pending",
240
+ address,
241
+ from,
242
+ to,
243
+ nativeValue,
244
+ transfers,
245
+ raw: { tx, ownIn, ownOut }
246
+ };
247
+ if (tx.fees !== void 0) out.fee = big(tx.fees);
248
+ if (confirmed) out.block = BigInt(tx.blockHeight);
249
+ return out;
250
+ }
251
+ function btcExplorerTxUrl(hash, network = "bitcoin") {
252
+ return `https://mempool.space/${network === "testnet" ? "testnet/" : ""}tx/${hash}`;
253
+ }
254
+ function createBtcHistory(options = {}) {
255
+ const network = options.network ?? "bitcoin";
256
+ const chain = CAIP2_GENESIS[network];
257
+ const urls = [...options.blockbookUrls ?? [], ...options.blockbookUrl ? [options.blockbookUrl] : []];
258
+ if (urls.length === 0) throw new Error("@anywalletkit/wallet-btc: createBtcHistory needs blockbookUrl or blockbookUrls");
259
+ const fetchFn = options.fetch ?? globalThis.fetch;
260
+ if (typeof fetchFn !== "function") throw new Error("@anywalletkit/wallet-btc: no global fetch; pass `fetch` in the options");
261
+ const clients = urls.map((url) => ({ url, client: new BlockbookClient({ url }, fetchFn, options.timeoutMs ?? DEFAULT_TIMEOUT_MS) }));
262
+ async function failover(run) {
263
+ const attempts = [];
264
+ for (const { url, client } of clients) {
265
+ try {
266
+ return await run(client);
267
+ } catch (e) {
268
+ attempts.push(`${url}: ${e instanceof Error ? e.message : String(e)}`);
269
+ }
270
+ }
271
+ throw new HistoryUnavailableError(chain, attempts[attempts.length - 1] ?? "every Blockbook failed", attempts);
272
+ }
273
+ return {
274
+ chain,
275
+ async listActivity(address, query = {}) {
276
+ const cursor = query.cursor ? decodeCursor(query.cursor) : void 0;
277
+ const pageSize = cursor?.s ?? Math.min(MAX_PAGE_SIZE, Math.max(1, Math.floor(options.pageSize ?? query.limit ?? DEFAULT_LIMIT)));
278
+ const pageNo = cursor?.p ?? 1;
279
+ const data = await failover((c) => c.getAddressPage(address, pageNo, pageSize));
280
+ let items = (data.transactions ?? []).map((tx) => mapBlockbookTx(chain, address, tx));
281
+ items.sort((a, b) => (b.block === void 0 ? 1 : a.block === void 0 ? -1 : Number(b.block - a.block)) || b.time - a.time);
282
+ const totalPages = data.totalPages ?? 1;
283
+ let more = pageNo < totalPages;
284
+ if (query.since !== void 0) {
285
+ const since = query.since;
286
+ if (items.some((t) => t.status === "confirmed" && t.time < since)) more = false;
287
+ items = items.filter((t) => t.status !== "confirmed" || t.time >= since);
288
+ }
289
+ const page = { items, page: pageNo, totalPages };
290
+ if (more) page.cursor = encodeCursor({ v: 1, p: pageNo + 1, s: pageSize });
291
+ return page;
292
+ },
293
+ async getTransaction(hash, address) {
294
+ const tx = await failover((c) => c.getTransactionDetails(hash));
295
+ return tx ? mapBlockbookTx(chain, address, tx) : void 0;
296
+ },
297
+ explorerTxUrl(hash) {
298
+ return btcExplorerTxUrl(hash, network);
299
+ }
300
+ };
301
+ }
302
+
303
+ export {
304
+ CAIP2_GENESIS,
305
+ DEFAULT_TIMEOUT_MS,
306
+ fetchWithTimeout,
307
+ isRecord,
308
+ isHex64,
309
+ unconfirmedOutgoing,
310
+ BlockbookClient,
311
+ HistoryUnavailableError,
312
+ encodeCursor,
313
+ decodeCursor,
314
+ mapBlockbookTx,
315
+ btcExplorerTxUrl,
316
+ createBtcHistory
317
+ };
318
+ //# sourceMappingURL=chunk-KAAQYL5X.js.map