From 4a278d29e6811d87a3e8f34839827b29feb9f410 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Thu, 30 Oct 2025 22:44:05 -0700 Subject: [PATCH] use reverse swap addition to lightning mode --- package-lock.json | 717 ++++++++++++++++++++++- package.json | 2 + src/components/wallet/CashuWallet.tsx | 43 +- src/components/wallet/PaymentCard.tsx | 131 ++++- src/components/wallet/WalletModals.tsx | 10 +- src/hooks/cashu/useWalletTransactions.ts | 217 ++++++- src/hooks/useReverseSwap.ts | 444 ++++++++++++++ src/lib/bitcoin.ts | 29 + 8 files changed, 1577 insertions(+), 16 deletions(-) create mode 100644 src/hooks/useReverseSwap.ts diff --git a/package-lock.json b/package-lock.json index 5b36471..af62aa5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -45,7 +45,9 @@ "@tanstack/react-query": "^5.56.2", "@unhead/addons": "^2.0.10", "@unhead/react": "^2.0.10", + "@vulpemventures/secp256k1-zkp": "^3.2.1", "bitcoinjs-lib": "^7.0.0", + "boltz-core": "^3.0.0", "buffer": "^6.0.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -231,6 +233,12 @@ "@noble/curves": "^1.7.0" } }, + "node_modules/@boltz/bitcoin-ops": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@boltz/bitcoin-ops/-/bitcoin-ops-2.0.0.tgz", + "integrity": "sha512-AM7vFNwSD7B4XI6yeRKccWbbD/lvwoFr8U3pqhzryBQo4uMkYe5V3/kMVnml4SNuxzyqdIFu4ur3TId02sC33A==", + "license": "MIT" + }, "node_modules/@cashu/cashu-ts": { "version": "2.7.2", "resolved": "https://registry.npmjs.org/@cashu/cashu-ts/-/cashu-ts-2.7.2.tgz", @@ -1459,6 +1467,12 @@ "react": "^18.0.0" } }, + "node_modules/@openzeppelin/contracts": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-5.4.0.tgz", + "integrity": "sha512-eCYgWnLg6WO+X52I16TZt8uEjbtdkgLC0SUX/xnAksjjrQI4Xfn4iBRoI5j55dmlOhDv1Y7BoR3cU7e3WWhC6A==", + "license": "MIT" + }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", @@ -4152,6 +4166,18 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@vulpemventures/secp256k1-zkp": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@vulpemventures/secp256k1-zkp/-/secp256k1-zkp-3.2.1.tgz", + "integrity": "sha512-2U4nuNbXuUgMmxhuoILbRMoD2DE7KND3udk5cYilIS1MHvMtje9ywUm/zsI0g7d7x8g2A57xri+wvqCC/fCnJg==", + "license": "MIT", + "dependencies": { + "long": "^5.2.3" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/@webbtc/webln-types": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@webbtc/webln-types/-/webln-types-3.0.0.tgz", @@ -4374,6 +4400,21 @@ "postcss": "^8.1.0" } }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -4449,6 +4490,83 @@ "node": ">=18.0.0" } }, + "node_modules/bip32": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/bip32/-/bip32-4.0.0.tgz", + "integrity": "sha512-aOGy88DDlVUhspIXJN+dVEtclhIsfAUppD43V0j40cPTld3pv/0X/MlrZSZ6jowIaQQzFwP8M6rFU2z2mVYjDQ==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "@scure/base": "^1.1.1", + "typeforce": "^1.11.5", + "wif": "^2.0.6" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/bip32/node_modules/@scure/base": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", + "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/bip32/node_modules/base-x": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-3.0.11.tgz", + "integrity": "sha512-xz7wQ8xDhdyP7tQxwdteLYeFfS68tSMNCZ/Y37WJ4bhGfKPpqEIlmIyueQHqOyoPhE6xNUqjzRr8ra0eF9VRvA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/bip32/node_modules/bs58": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-4.0.1.tgz", + "integrity": "sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw==", + "license": "MIT", + "dependencies": { + "base-x": "^3.0.2" + } + }, + "node_modules/bip32/node_modules/bs58check": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bs58check/-/bs58check-2.1.2.tgz", + "integrity": "sha512-0TS1jicxdU09dwJMNZtVAfzPi6Q6QeN0pM1Fkzrjn+XYHvzMKPU3pHVpva+769iNVSfIYWf7LJ6WR+BuuMf8cA==", + "license": "MIT", + "dependencies": { + "bs58": "^4.0.0", + "create-hash": "^1.1.0", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/bip32/node_modules/wif": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/wif/-/wif-2.0.6.tgz", + "integrity": "sha512-HIanZn1zmduSF+BQhkE+YXIbEiH0xPr1012QbFEGB0xsKqJii0/SqJjyn8dFv6y36kOznMgMB+LGcbZTJ1xACQ==", + "license": "MIT", + "dependencies": { + "bs58check": "<3.0.0" + } + }, + "node_modules/bip65": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bip65/-/bip65-1.0.3.tgz", + "integrity": "sha512-RQ1nc7xtnLa5XltnCqkoR2zmhuz498RjMJwrLKQzOE049D1HUqnYfon7cVSbwS5UGm0/EQlC2CH+NY3MyITA4Q==", + "license": "ISC", + "engines": { + "node": ">=4.5.0" + } + }, + "node_modules/bip66": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/bip66/-/bip66-2.0.0.tgz", + "integrity": "sha512-kBG+hSpgvZBrkIm9dt5T1Hd/7xGCPEX2npoxAWZfsK1FvjgaxySEh2WizjyIstWXriKo9K9uJ4u0OnsyLDUPXQ==", + "license": "MIT" + }, "node_modules/bitcoinjs-lib": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/bitcoinjs-lib/-/bitcoinjs-lib-7.0.0.tgz", @@ -4467,6 +4585,96 @@ "node": ">=18.0.0" } }, + "node_modules/bn.js": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.2.tgz", + "integrity": "sha512-v2YAxEmKaBLahNwE1mjp4WON6huMNeuDvagFZW+ASCuA/ku0bXR9hSMw0XpiqMoA3+rmnyck/tPRSFQkoC9Cuw==", + "license": "MIT" + }, + "node_modules/boltz-core": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/boltz-core/-/boltz-core-3.0.0.tgz", + "integrity": "sha512-L0jzUnTIb/vir9k6yVlCkV8I29ZeBK7LWq3rrDcp/KP7bB0VvKR5JTceua8g2KBCBM5HOMVDEuPW3c9/82/Nmg==", + "license": "AGPL-3.0", + "dependencies": { + "@boltz/bitcoin-ops": "^2.0.0", + "@openzeppelin/contracts": "^5.2.0", + "@vulpemventures/secp256k1-zkp": "^3.2.1", + "bip32": "^4.0.0", + "bip65": "^1.0.3", + "bip66": "^2.0.0", + "bitcoinjs-lib": "^6.1.7", + "bn.js": "^5.2.1", + "ecpair": "^3.0.0", + "varuint-bitcoin": "^2.0.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "liquidjs-lib": "^6.0.2-liquid.37" + } + }, + "node_modules/boltz-core/node_modules/base-x": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-4.0.1.tgz", + "integrity": "sha512-uAZ8x6r6S3aUM9rbHGVOIsR15U/ZSc82b3ymnCPsT45Gk1DDvhDPdIgB5MrhirZWt+5K0EEPQH985kNqZgNPFw==", + "license": "MIT" + }, + "node_modules/boltz-core/node_modules/bip174": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bip174/-/bip174-2.1.1.tgz", + "integrity": "sha512-mdFV5+/v0XyNYXjBS6CQPLo9ekCx4gtKZFnJm5PMto7Fs9hTTDpkkzOB7/FtluRI6JbUUAu+snTYfJRgHLZbZQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/boltz-core/node_modules/bitcoinjs-lib": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/bitcoinjs-lib/-/bitcoinjs-lib-6.1.7.tgz", + "integrity": "sha512-tlf/r2DGMbF7ky1MgUqXHzypYHakkEnm0SZP23CJKIqNY/5uNAnMbFhMJdhjrL/7anfb/U8+AlpdjPWjPnAalg==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "bech32": "^2.0.0", + "bip174": "^2.1.1", + "bs58check": "^3.0.1", + "typeforce": "^1.11.3", + "varuint-bitcoin": "^1.1.2" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/boltz-core/node_modules/bitcoinjs-lib/node_modules/varuint-bitcoin": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/varuint-bitcoin/-/varuint-bitcoin-1.1.2.tgz", + "integrity": "sha512-4EVb+w4rx+YfVM32HQX42AbbT7/1f5zwAYhIujKXKk8NQK+JfRVl3pqT3hjNn/L+RstigmGGKVwHA/P0wgITZw==", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.1" + } + }, + "node_modules/boltz-core/node_modules/bs58": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-5.0.0.tgz", + "integrity": "sha512-r+ihvQJvahgYT50JD05dyJNKlmmSlMoOGwn1lCcEzanPglg7TxYjioQUYehQ9mAR/+hOSd2jRc/Z2y5UxBymvQ==", + "license": "MIT", + "dependencies": { + "base-x": "^4.0.0" + } + }, + "node_modules/boltz-core/node_modules/bs58check": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/bs58check/-/bs58check-3.0.1.tgz", + "integrity": "sha512-hjuuJvoWEybo7Hn/0xOrczQKKEKD63WguEjlhLExYs2wUBcebDC1jDNK17eEAD2lYfw82d5ASC1d7K3SWszjaQ==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "bs58": "^5.0.0" + } + }, "node_modules/brace-expansion": { "version": "1.1.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", @@ -4578,6 +4786,53 @@ "node": ">=8" } }, + "node_modules/call-bind": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz", + "integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.0", + "es-define-property": "^1.0.0", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -4710,6 +4965,20 @@ "node": ">= 6" } }, + "node_modules/cipher-base": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.7.tgz", + "integrity": "sha512-Mz9QMT5fJe7bKI7MH31UilT5cEK5EHHRCccw/YRFsRY47AuNgaV6HY3rscp0/I4Q+tTW/5zoqpSeRRI54TkDWA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.4", + "safe-buffer": "^5.2.1", + "to-buffer": "^1.2.2" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/class-variance-authority": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", @@ -4877,6 +5146,25 @@ "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", "license": "MIT" }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "license": "MIT", + "dependencies": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -5134,6 +5422,23 @@ "dev": true, "license": "MIT" }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -5193,6 +5498,20 @@ "csstype": "^3.0.2" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/eastasianwidth": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", @@ -5292,6 +5611,24 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-html-parser": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/es-html-parser/-/es-html-parser-0.2.0.tgz", @@ -5306,6 +5643,18 @@ "dev": true, "license": "MIT" }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.25.11", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.11.tgz", @@ -5752,6 +6101,21 @@ "dev": true, "license": "ISC" }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/foreground-child": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", @@ -5802,7 +6166,6 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -5817,6 +6180,30 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/get-nonce": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", @@ -5826,6 +6213,19 @@ "node": ">=6" } }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/glob": { "version": "10.4.5", "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", @@ -5899,6 +6299,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graphemer": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", @@ -5916,11 +6328,64 @@ "node": ">=8" } }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hash-base": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.1.2.tgz", + "integrity": "sha512-Bb33KbowVTIj5s7Ked1OsqHUeCpz//tPwR+E2zJgJKo9Z5XolZ9b6bdUgjmYlwnWhoOQKoTd1TYToZGn5mAYOg==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.4", + "readable-stream": "^2.3.8", + "safe-buffer": "^5.2.1", + "to-buffer": "^1.2.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/hasown": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dev": true, "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -6062,6 +6527,12 @@ "node": ">=8" } }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, "node_modules/input-otp": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/input-otp/-/input-otp-1.4.2.tgz", @@ -6094,6 +6565,18 @@ "node": ">=8" } }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-core-module": { "version": "2.16.1", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", @@ -6159,6 +6642,27 @@ "dev": true, "license": "MIT" }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -6357,6 +6861,12 @@ "dev": true, "license": "MIT" }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", @@ -6425,6 +6935,26 @@ "url": "https://github.com/sponsors/sxzz" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "license": "MIT", + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -6946,6 +7476,15 @@ "node": ">=10.13.0" } }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/postcss": { "version": "8.5.6", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", @@ -7178,6 +7717,12 @@ "dev": true, "license": "MIT" }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, "node_modules/prop-types": { "version": "15.8.1", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", @@ -7471,6 +8016,27 @@ "pify": "^2.3.0" } }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", @@ -7600,6 +8166,19 @@ "node": ">=0.10.0" } }, + "node_modules/ripemd160": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.3.tgz", + "integrity": "sha512-5Di9UC0+8h1L6ZD2d7awM7E/T4uA1fJRlx6zk/NvdCCVEoAnFqvHmCuNeIKoCeIixBX/q8uM+6ycDvF8woqosA==", + "license": "MIT", + "dependencies": { + "hash-base": "^3.1.2", + "inherits": "^2.0.4" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/rollup": { "version": "4.52.5", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.5.tgz", @@ -7673,6 +8252,26 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -7721,6 +8320,43 @@ "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", "license": "ISC" }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/sha.js": { + "version": "2.4.12", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.12.tgz", + "integrity": "sha512-8LzC5+bvI45BjpfXU8V5fdU2mfeKiQe1D1gIMn7XUlF3OTUrpdJpPPH4EMAnF0DsHHdSZqCdSss5qCmJKuiO3w==", + "license": "(MIT AND BSD-3-Clause)", + "dependencies": { + "inherits": "^2.0.4", + "safe-buffer": "^5.2.1", + "to-buffer": "^1.2.0" + }, + "bin": { + "sha.js": "bin.js" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -7788,6 +8424,21 @@ "dev": true, "license": "MIT" }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, "node_modules/string-width": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", @@ -8175,6 +8826,26 @@ "dev": true, "license": "MIT" }, + "node_modules/to-buffer": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/to-buffer/-/to-buffer-1.2.2.tgz", + "integrity": "sha512-db0E3UJjcFhpDhAF4tLo03oli3pwl3dbnzXOUIlRKrp+ldk/VUxzpWYZENsw2SZiuBjHAk7DfB0VU7NKdpb6sw==", + "license": "MIT", + "dependencies": { + "isarray": "^2.0.5", + "safe-buffer": "^5.2.1", + "typed-array-buffer": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/to-buffer/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -8253,6 +8924,26 @@ "node": ">= 0.8.0" } }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typeforce": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/typeforce/-/typeforce-1.18.0.tgz", + "integrity": "sha512-7uc1O8h1M1g0rArakJdf0uLRSSgFcYexrVoKo+bzJd32gd4gDy2L/Z+8/FjPnU9ydY3pEnVPtr9FyscYY60K1g==", + "license": "MIT" + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -8455,7 +9146,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true, "license": "MIT" }, "node_modules/valibot": { @@ -8790,6 +9480,27 @@ "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", "license": "ISC" }, + "node_modules/which-typed-array": { + "version": "1.1.19", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.19.tgz", + "integrity": "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", diff --git a/package.json b/package.json index c8337c5..e8f1493 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,9 @@ "@tanstack/react-query": "^5.56.2", "@unhead/addons": "^2.0.10", "@unhead/react": "^2.0.10", + "@vulpemventures/secp256k1-zkp": "^3.2.1", "bitcoinjs-lib": "^7.0.0", + "boltz-core": "^3.0.0", "buffer": "^6.0.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/src/components/wallet/CashuWallet.tsx b/src/components/wallet/CashuWallet.tsx index d256659..56602d6 100644 --- a/src/components/wallet/CashuWallet.tsx +++ b/src/components/wallet/CashuWallet.tsx @@ -18,7 +18,8 @@ import { QRModal } from '@/components/ui/qr-modal'; import { WalletHeader } from './WalletHeader'; import { TransactionCard } from './PaymentCard'; import { WalletModals } from './WalletModals'; -import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/ui/drawer'; +import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer'; +import * as VisuallyHidden from '@radix-ui/react-visually-hidden'; import { TransactionHistory } from './TransactionHistory'; import { ScrollArea } from '@/components/ui/scroll-area'; import { ChevronUp, Send, Download, ScanLine } from 'lucide-react'; @@ -132,6 +133,11 @@ export function CashuWallet() { setDecodedInvoiceAmount, pendingInvoice, setPendingInvoice, + pendingBitcoinSwapAddress, + setPendingBitcoinSwapAddress, + bitcoinSwapAmount, + setBitcoinSwapAmount, + swapStatus, sentToken, setSentToken, sentTokenQRCode, @@ -211,6 +217,9 @@ export function CashuWallet() { setPendingLightningAddress(null); setDecodedInvoiceAmount(null); setPendingInvoice(null); + // Reset reverse swap state + setPendingBitcoinSwapAddress(null); + setBitcoinSwapAmount(''); // Reset Bitcoin state setBitcoinAmount(''); setBitcoinRecipient(''); @@ -345,6 +354,17 @@ export function CashuWallet() { // eslint-disable-next-line react-hooks/exhaustive-deps }, [showQRScanner, startScanning, stopScanning, setModalOpen]); + // Handle focus management when drawers open to prevent aria-hidden warnings + useEffect(() => { + if (showSendModal || showReceiveModal || showHistoryModal) { + // Blur any currently focused element to allow drawer's focus trap to work + const activeElement = document.activeElement as HTMLElement; + if (activeElement && activeElement.blur) { + activeElement.blur(); + } + } + }, [showSendModal, showReceiveModal, showHistoryModal]); + // ============================================================================ // EFFECTS - Cleanup // ============================================================================ @@ -617,6 +637,11 @@ export function CashuWallet() { Send + + + Send tokens, Lightning payments, or Bitcoin + +
handleSendMax(setBitcoinAmount)} + // Reverse swap props + pendingBitcoinSwapAddress={pendingBitcoinSwapAddress} + setPendingBitcoinSwapAddress={setPendingBitcoinSwapAddress} + bitcoinSwapAmount={bitcoinSwapAmount} + setBitcoinSwapAmount={setBitcoinSwapAmount} + swapStatus={swapStatus} />
@@ -686,6 +717,11 @@ export function CashuWallet() { Receive + + + Receive tokens, Lightning invoices, or Bitcoin + +
Transactions + + + View your transaction history + + void; + // Reverse swap props (Lightning mode) + pendingBitcoinSwapAddress?: string | null; + setPendingBitcoinSwapAddress?: (value: string | null) => void; + bitcoinSwapAmount?: string; + setBitcoinSwapAmount?: (value: string) => void; + swapStatus?: string | null; } export function TransactionCard({ @@ -103,12 +109,19 @@ export function TransactionCard({ hasNsecAccess, bitcoinMaxAmount, onSendMax, + pendingBitcoinSwapAddress, + setPendingBitcoinSwapAddress, + bitcoinSwapAmount, + setBitcoinSwapAmount, + swapStatus, }: TransactionCardProps) { // Slider state for confirmation const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]); const [addressSliderValue, setAddressSliderValue] = useState([0]); const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]); + const [swapSliderValue, setSwapSliderValue] = useState([0]); const [sendMaxEnabled, setSendMaxEnabled] = useState(false); + const [swapAmountError, setSwapAmountError] = useState(null); // Handle slider value changes and auto-submit at 100% const handleInvoiceSliderChange = (value: number[]) => { @@ -132,6 +145,13 @@ export function TransactionCard({ } }; + const handleSwapSliderChange = (value: number[]) => { + setSwapSliderValue(value); + if (value[0] === 100) { + onSend(); + } + }; + const handleSendMaxToggle = () => { const newState = !sendMaxEnabled; setSendMaxEnabled(newState); @@ -148,6 +168,8 @@ export function TransactionCard({ setAddressSliderValue([0]); } else if (sliderId === 'bitcoin' && bitcoinSliderValue[0] !== 100) { setBitcoinSliderValue([0]); + } else if (sliderId === 'swap' && swapSliderValue[0] !== 100) { + setSwapSliderValue([0]); } }; @@ -171,11 +193,36 @@ export function TransactionCard({ } }, [pendingBitcoinRecipient]); + useEffect(() => { + if (!pendingBitcoinSwapAddress) { + setSwapSliderValue([0]); + setSwapAmountError(null); + } + }, [pendingBitcoinSwapAddress]); + + // Validate swap amount when it changes + useEffect(() => { + if (pendingBitcoinSwapAddress && bitcoinSwapAmount) { + const amount = parseInt(bitcoinSwapAmount); + if (isNaN(amount) || amount <= 0) { + setSwapAmountError('Please enter a valid amount'); + } else if (amount < 25_000) { + setSwapAmountError('Minimum amount is 25,000 sats'); + } else if (amount > 25_000_000) { + setSwapAmountError('Maximum amount is 25,000,000 sats'); + } else { + setSwapAmountError(null); + } + } else { + setSwapAmountError(null); + } + }, [bitcoinSwapAmount, pendingBitcoinSwapAddress]); + return (
{/* Title */}
-

+

{operation === 'send' ? ( mode === 'tokens' ? 'Generate Cashu token to send' @@ -234,7 +281,24 @@ export function TransactionCard({
- ) : 'Pay invoices or addresses' + ) : pendingBitcoinSwapAddress ? ( +
+ + Reverse Swap to:{' '} + {truncateAddress(pendingBitcoinSwapAddress)} + + +
+ ) : 'Pay invoices, addresses, or Bitcoin addresses' ) : ( mode === 'tokens' ? 'Enter Cashu token to redeem' @@ -242,7 +306,7 @@ export function TransactionCard({ ? 'Receive Bitcoin on-chain' : 'Deposit funds with Lightning' )} -

+
{/* Content */} @@ -402,6 +466,63 @@ export function TransactionCard({
+ ) : pendingBitcoinSwapAddress ? ( + // Reverse Swap Amount Input with Slider +
+
+ { + setBitcoinSwapAmount?.(e.target.value); + }} + onKeyDown={(e) => { + if (e.key === 'Enter' && bitcoinSwapAmount && !swapAmountError && activeMintUrl && !isLoading) { + onSend(); + } + }} + disabled={!activeMintUrl || isLoading} + className={`w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield] ${ + swapAmountError ? 'border-destructive' : '' + }`} + /> + {swapAmountError && ( +

{swapAmountError}

+ )} + {!swapAmountError && bitcoinSwapAmount && ( +

+ Amount must be between 25,000 and 25,000,000 sats +

+ )} + {swapStatus && ( +

{swapStatus}

+ )} +
+
+
+
handleSliderMouseUp('swap')} + onMouseLeave={() => handleSliderMouseUp('swap')} + onTouchEnd={() => handleSliderMouseUp('swap')} + > + +
+
+ + {swapSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'} + +
+
+
+
) : pendingLightningAddress ? ( // Lightning Address Amount Input with Slider
@@ -443,10 +564,10 @@ export function TransactionCard({
) : ( - // Lightning Invoice/Address Input + // Lightning Invoice/Address/Bitcoin Address Input
{ const value = e.target.value; diff --git a/src/components/wallet/WalletModals.tsx b/src/components/wallet/WalletModals.tsx index 477fcce..cbb300d 100644 --- a/src/components/wallet/WalletModals.tsx +++ b/src/components/wallet/WalletModals.tsx @@ -5,7 +5,8 @@ import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft, Loader2, Clipboard } from 'lucide-react'; import { QRModal } from '@/components/ui/qr-modal'; -import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import * as VisuallyHidden from '@radix-ui/react-visually-hidden'; import { nip19 } from 'nostr-tools'; import { useToast } from '@/hooks/useToast'; import { UTXO } from '@/lib/bitcoin'; @@ -496,7 +497,12 @@ export function WalletModals({ {/* Header */} - + Scan QR Code + + + Position the QR code within the camera view to scan + + {/* Camera container with square aspect ratio */} diff --git a/src/hooks/cashu/useWalletTransactions.ts b/src/hooks/cashu/useWalletTransactions.ts index 577d358..94cc974 100644 --- a/src/hooks/cashu/useWalletTransactions.ts +++ b/src/hooks/cashu/useWalletTransactions.ts @@ -1,6 +1,9 @@ import { useState, useCallback, useRef, useEffect } from 'react'; import { isUnknownMintError, extractMintUrlFromError } from './walletUtils'; import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder'; +import { isValidBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin'; +import { createReverseSwap, type SwapStatusUpdate } from '@/hooks/useReverseSwap'; +import { nip19 } from 'nostr-tools'; import type { Manager } from 'coco-cashu-core'; import type { Token } from '@cashu/cashu-ts'; import { useToast } from '@/hooks/useToast'; @@ -42,6 +45,12 @@ export function useWalletTransactions({ >(null); const [decodedInvoiceAmount, setDecodedInvoiceAmount] = useState(null); const [pendingInvoice, setPendingInvoice] = useState(null); + + // Reverse swap state (Lightning -> Bitcoin) + const [pendingBitcoinSwapAddress, setPendingBitcoinSwapAddress] = useState(null); + const [bitcoinSwapAmount, setBitcoinSwapAmount] = useState(''); + const [swapStatus, setSwapStatus] = useState(null); + const [reverseSwapClose, setReverseSwapClose] = useState<(() => void) | null>(null); // Transaction output state const [sentToken, setSentToken] = useState(null); @@ -225,14 +234,35 @@ export function useWalletTransactions({ // Handle send (token or Lightning) const handleSend = useCallback(async () => { - if (!coco) return; + console.log('[handleSend] Called with state:', { + hasCoco: !!coco, + sendAmount, + lightningInvoice, + lightningAddressInput, + pendingLightningAddress, + pendingBitcoinSwapAddress, + bitcoinSwapAmount, + activeMintUrl, + mode: 'lightning' // We're in Lightning mode when this is called + }); - if (!sendAmount && !lightningInvoice && !lightningAddressInput && !pendingLightningAddress) { + if (!coco) { + console.log('[handleSend] No coco instance'); + return; + } + + // Check for reverse swap first (this takes priority in Lightning mode) + if (pendingBitcoinSwapAddress && bitcoinSwapAmount) { + console.log('[handleSend] Reverse swap detected:', { pendingBitcoinSwapAddress, bitcoinSwapAmount }); + // Don't return early - continue to reverse swap logic below + } else if (!sendAmount && !lightningInvoice && !lightningAddressInput && !pendingLightningAddress && !pendingBitcoinSwapAddress) { + console.log('[handleSend] No input provided - returning early'); return; } // Send Cashu token mode if (sendAmount && activeMintUrl) { + console.log('[handleSend] Handling token send mode'); try { const amount = parseInt(sendAmount); if (isNaN(amount) || amount <= 0) { @@ -257,8 +287,142 @@ export function useWalletTransactions({ } } else if (activeMintUrl) { // Lightning mode - // Step 1: Check if we have a pending Lightning address awaiting amount - if (pendingLightningAddress) { + console.log('[handleSend] Entering Lightning mode branch, activeMintUrl:', activeMintUrl); + // Step 1: Check if we have a pending Bitcoin swap address awaiting amount + if (pendingBitcoinSwapAddress) { + console.log('[handleSend] Found pendingBitcoinSwapAddress:', pendingBitcoinSwapAddress); + // Step 2: User entered amount, now initiate reverse swap + if (!bitcoinSwapAmount) { + console.log('[handleSend] Reverse swap pending but no amount provided'); + return; + } + + console.log('[handleSend] Starting reverse swap with:', { + address: pendingBitcoinSwapAddress, + amount: bitcoinSwapAmount, + activeMintUrl + }); + + try { + const amount = parseInt(bitcoinSwapAmount); + if (isNaN(amount) || amount <= 0) { + toast({ + variant: 'destructive', + title: 'Invalid Amount', + description: 'Please enter a valid amount', + }); + return; + } + + // Validate reverse swap amount limits (25,000 - 25,000,000 sats) + if (amount < 25_000 || amount > 25_000_000) { + toast({ + variant: 'destructive', + title: 'Invalid Amount', + description: 'Reverse swap amount must be between 25,000 and 25,000,000 sats', + }); + return; + } + + // Determine destination address (could be Bitcoin address or npub) + let destinationAddress = pendingBitcoinSwapAddress; + try { + // Try to decode as npub first + const decoded = nip19.decode(pendingBitcoinSwapAddress); + if (decoded.type === 'npub') { + destinationAddress = npubToBitcoinAddress(pendingBitcoinSwapAddress); + } + } catch { + // Not an npub, assume it's already a Bitcoin address + } + + // Initiate reverse swap + console.log('[handleSend] Creating reverse swap...'); + setSwapStatus('Creating reverse swap...'); + const swapResult = await createReverseSwap({ + invoiceAmount: amount, + destinationAddress, + onStatusUpdate: (update: SwapStatusUpdate) => { + switch (update.status) { + case 'swap.created': + setSwapStatus('Waiting for invoice payment...'); + break; + case 'transaction.mempool': + setSwapStatus('Swap transaction sent to blockchain...'); + break; + case 'invoice.settled': + case 'transaction.confirmed': + setSwapStatus('Swap completed!'); + break; + } + }, + onSuccess: () => { + const displayAddress = destinationAddress.length > 26 + ? destinationAddress.slice(0, 12) + '...' + destinationAddress.slice(-12) + : destinationAddress; + toast({ + title: 'Reverse Swap Completed', + description: `Successfully swapped ${amount} sats to Bitcoin address ${displayAddress}!`, + }); + setSwapStatus(null); + setPendingBitcoinSwapAddress(null); + setBitcoinSwapAmount(''); + if (reverseSwapClose) { + reverseSwapClose(); + setReverseSwapClose(null); + } + }, + onError: (error: Error) => { + toast({ + variant: 'destructive', + title: 'Reverse Swap Failed', + description: error.message, + }); + setSwapStatus(null); + setPendingBitcoinSwapAddress(null); + setBitcoinSwapAmount(''); + if (reverseSwapClose) { + reverseSwapClose(); + setReverseSwapClose(null); + } + }, + }); + + // Store close function for cleanup + setReverseSwapClose(() => swapResult.close); + + // Pay the Lightning invoice from the swap using the active mint + console.log('[handleSend] Paying Lightning invoice:', swapResult.invoice); + setSwapStatus('Paying Lightning invoice...'); + const meltQuote = await coco.quotes.createMeltQuote( + activeMintUrl, + swapResult.invoice + ); + console.log('[handleSend] Melt quote created, paying...'); + await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote); + console.log('[handleSend] Invoice paid successfully'); + + toast({ + title: 'Invoice Paid', + description: `Lightning invoice paid. Swap in progress...`, + }); + } catch (err) { + console.error('Reverse swap error:', err); + toast({ + variant: 'destructive', + title: 'Reverse Swap Failed', + description: err instanceof Error ? err.message : 'Unknown error', + }); + setSwapStatus(null); + setPendingBitcoinSwapAddress(null); + setBitcoinSwapAmount(''); + if (reverseSwapClose) { + reverseSwapClose(); + setReverseSwapClose(null); + } + } + } else if (pendingLightningAddress) { + console.log('[handleSend] Handling Lightning address payment'); // Step 2: User entered amount, now resolve address and pay if (!lightningAddressAmount) return; @@ -302,10 +466,34 @@ export function useWalletTransactions({ }); } } else { - // Step 1: Check if input is a Lightning address or invoice + // Step 1: Check if input is a Bitcoin address, Lightning address, or invoice const input = lightningInvoice.trim() || lightningAddressInput.trim(); if (!input) return; + // Check if it's a Bitcoin address (for reverse swap) + if (isValidBitcoinAddress(input)) { + setPendingBitcoinSwapAddress(input); + setLightningInvoice(''); + setLightningAddressInput(''); + return; + } + + // Check if it's an npub (can be converted to Bitcoin address) + try { + const decoded = nip19.decode(input); + if (decoded.type === 'npub') { + const bitcoinAddr = npubToBitcoinAddress(input); + if (bitcoinAddr) { + setPendingBitcoinSwapAddress(input); // Store npub, will convert later + setLightningInvoice(''); + setLightningAddressInput(''); + return; + } + } + } catch { + // Not an npub, continue to check other formats + } + // Check if it's a Lightning address (contains @) if (input.includes('@')) { setPendingLightningAddress(input); @@ -350,11 +538,15 @@ export function useWalletTransactions({ lightningAddressInput, lightningAddressAmount, pendingLightningAddress, + pendingBitcoinSwapAddress, + bitcoinSwapAmount, activeMintUrl, toast, getEncodedToken, generateSentTokenQRCode, getLightningInvoice, + reverseSwapClose, + npubToBitcoinAddress, ]); // Handle confirmed invoice payment @@ -491,6 +683,15 @@ export function useWalletTransactions({ }; }, []); + // Cleanup reverse swap WebSocket on unmount + useEffect(() => { + return () => { + if (reverseSwapClose) { + reverseSwapClose(); + } + }; + }, [reverseSwapClose]); + return { // Receive state tokenInput, @@ -512,6 +713,12 @@ export function useWalletTransactions({ setDecodedInvoiceAmount, pendingInvoice, setPendingInvoice, + // Reverse swap state + pendingBitcoinSwapAddress, + setPendingBitcoinSwapAddress, + bitcoinSwapAmount, + setBitcoinSwapAmount, + swapStatus, // Transaction output state sentToken, setSentToken, diff --git a/src/hooks/useReverseSwap.ts b/src/hooks/useReverseSwap.ts new file mode 100644 index 0000000..2623920 --- /dev/null +++ b/src/hooks/useReverseSwap.ts @@ -0,0 +1,444 @@ +import zkpInit from '@vulpemventures/secp256k1-zkp'; +import { + Transaction, + address, + initEccLib, + networks, +} from 'bitcoinjs-lib'; +import { + Musig, + OutputType, + SwapTreeSerializer, + TaprootUtils, + constructClaimTransaction, + detectSwap, + targetFee, +} from 'boltz-core'; +import { ECPairFactory, type ECPairAPI, type ECPairInterface } from 'ecpair'; +import * as ecc from '@bitcoinerlab/secp256k1'; +import { Buffer } from 'buffer'; + +// Initialize ECC library +initEccLib(ecc); + +// Boltz API endpoints +const API_ENDPOINT = 'https://api.boltz.exchange'; +const WS_ENDPOINT = 'wss://api.boltz.exchange/v2/ws'; + +// Use mainnet by default +const network = networks.bitcoin; + +// Lazy initialization of ECPair factory +let ECPair: ECPairAPI | null = null; + +function getECPair(): ECPairAPI { + if (!ECPair) { + ECPair = ECPairFactory(ecc); + } + return ECPair; +} + +/** + * Generate random bytes using browser crypto API + */ +function randomBytes(length: number): Buffer { + const array = new Uint8Array(length); + if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) { + window.crypto.getRandomValues(array); + } else { + // Fallback for Node.js environments (shouldn't happen in browser, but just in case) + for (let i = 0; i < length; i++) { + array[i] = Math.floor(Math.random() * 256); + } + } + return Buffer.from(array); +} + +/** + * SHA256 hash using browser SubtleCrypto API + * + * Note: window.crypto.subtle requires a secure context (HTTPS or localhost). + * It will be undefined if the page is served over HTTP. + */ +async function sha256(data: Buffer): Promise { + if (typeof window !== 'undefined' && window.crypto && window.crypto.subtle) { + // Convert Buffer to Uint8Array for SubtleCrypto + const uint8Array = new Uint8Array(data); + const hashBuffer = await window.crypto.subtle.digest('SHA-256', uint8Array); + return Buffer.from(hashBuffer); + } + // window.crypto.subtle unavailable - likely due to: + // 1. Page served over HTTP (not HTTPS/localhost) + // 2. Very old browser without support + // 3. Test environment without crypto API + throw new Error( + 'SHA256 not available: window.crypto.subtle requires HTTPS or localhost. ' + + 'Please serve the application over HTTPS or use localhost for development.' + ); +} + +/** + * Swap status update from WebSocket + */ +export interface SwapStatusUpdate { + status: 'swap.created' | 'transaction.mempool' | 'invoice.settled' | 'transaction.confirmed'; + transaction?: { + hex: string; + }; +} + +/** + * Reverse swap result + */ +export interface ReverseSwapResult { + /** Lightning invoice to pay */ + invoice: string; + /** Swap ID for tracking */ + swapId: string; + /** Function to close WebSocket connection */ + close: () => void; +} + +/** + * Options for creating a reverse swap + */ +export interface ReverseSwapOptions { + /** Amount in satoshis for the Lightning invoice */ + invoiceAmount: number; + /** Bitcoin address to receive the on-chain funds */ + destinationAddress: string; + /** Callback for swap status updates */ + onStatusUpdate?: (update: SwapStatusUpdate) => void; + /** Callback when swap is successfully completed */ + onSuccess?: () => void; + /** Callback for errors */ + onError?: (error: Error) => void; + /** Network to use (defaults to mainnet) */ + network?: typeof networks.bitcoin | typeof networks.regtest | typeof networks.testnet; +} + +/** + * Create a reverse swap (Lightning to on-chain Bitcoin) + * + * This function creates a reverse swap where the user pays a Lightning invoice, + * and receives Bitcoin on-chain at the specified address. + * + * @param options - Reverse swap configuration options + * @returns Promise resolving to swap result with invoice and tracking functions + * + * @example + * ```typescript + * const { invoice, swapId, close } = await createReverseSwap({ + * invoiceAmount: 100_000, + * destinationAddress: 'bc1q...', + * onStatusUpdate: (update) => { + * console.log('Swap status:', update.status); + * }, + * onSuccess: () => { + * console.log('Swap completed!'); + * } + * }); + * + * // Display invoice to user for payment + * console.log('Pay this invoice:', invoice); + * + * // Later, close the connection when done + * close(); + * ``` + */ +export async function createReverseSwap( + options: ReverseSwapOptions +): Promise { + const { + invoiceAmount, + destinationAddress, + onStatusUpdate, + onSuccess, + onError, + network: swapNetwork = network, + } = options; + + // Create a random preimage for the swap (must be 32 bytes) + const preimage = randomBytes(32); + const keys = getECPair().makeRandom(); + + // Hash the preimage + const preimageHash = await sha256(preimage); + + // Get public key as hex - match original code exactly + // keys.publicKey is a Buffer (or Uint8Array in browser), convert to hex string + // This should be a compressed public key (33 bytes = 66 hex chars) + const claimPublicKeyHex = Buffer.from(keys.publicKey).toString('hex'); + + // Validate length (compressed public key should be 33 bytes = 66 hex chars) + if (claimPublicKeyHex.length !== 66) { + throw new Error(`Invalid public key hex length: expected 66 chars (33 bytes), got ${claimPublicKeyHex.length}`); + } + + const requestBody = { + invoiceAmount, + to: 'BTC', + from: 'BTC', + claimPublicKey: claimPublicKeyHex, + preimageHash: preimageHash.toString('hex'), + }; + + console.log('[createReverseSwap] Request body:', { + ...requestBody, + claimPublicKeyLength: claimPublicKeyHex.length / 2, // Divide by 2 because hex is 2 chars per byte + preimageHashLength: requestBody.preimageHash.length / 2, + }); + + // Create the reverse swap via API + const createResponse = await fetch(`${API_ENDPOINT}/v2/swap/reverse`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }); + + if (!createResponse.ok) { + const errorText = await createResponse.text(); + console.error('[createReverseSwap] API error response:', errorText); + throw new Error(`Failed to create reverse swap: ${errorText}`); + } + + const createdResponse = await createResponse.json(); + + // Set up WebSocket connection for tracking swap progress + const webSocket = new WebSocket(WS_ENDPOINT); + + const close = () => { + if (webSocket.readyState === WebSocket.OPEN) { + webSocket.close(); + } + }; + + webSocket.onopen = () => { + webSocket.send( + JSON.stringify({ + op: 'subscribe', + channel: 'swap.update', + args: [createdResponse.id], + }) + ); + }; + + webSocket.onmessage = async (event) => { + try { + const msg = JSON.parse(event.data); + + if (msg.event !== 'update') { + return; + } + + const statusUpdate: SwapStatusUpdate = { + status: msg.args[0].status, + transaction: msg.args[0].transaction, + }; + + onStatusUpdate?.(statusUpdate); + + switch (msg.args[0].status) { + case 'swap.created': { + // Boltz is waiting for the invoice to be paid + break; + } + + case 'transaction.mempool': { + // Boltz sent an on-chain transaction, now we need to claim it + try { + await claimSwapTransaction( + createdResponse, + keys, + preimage, + destinationAddress, + msg.args[0].transaction.hex, + swapNetwork + ); + } catch (error) { + const err = error instanceof Error ? error : new Error(String(error)); + onError?.(err); + close(); + throw err; + } + break; + } + + case 'invoice.settled': + case 'transaction.confirmed': { + // Swap successful + onSuccess?.(); + close(); + break; + } + } + } catch (error) { + const err = error instanceof Error ? error : new Error(String(error)); + onError?.(err); + close(); + } + }; + + webSocket.onerror = (error) => { + onError?.(new Error('WebSocket error occurred')); + }; + + webSocket.onclose = () => { + // Connection closed + }; + + return { + invoice: createdResponse.invoice, + swapId: createdResponse.id, + close, + }; +} + +/** + * Claim the swap transaction after Boltz sends it to the mempool + */ +async function claimSwapTransaction( + createdResponse: { + id: string; + refundPublicKey: string; + swapTree: string; + }, + keys: ECPairInterface, + preimage: Buffer, + destinationAddress: string, + lockupTxHex: string, + swapNetwork: typeof networks.bitcoin | typeof networks.regtest | typeof networks.testnet +): Promise { + const boltzPublicKey = Buffer.from(createdResponse.refundPublicKey, 'hex'); + + // Create a musig signing session and tweak it with the Taptree of the swap scripts + const zkp = await zkpInit(); + // Convert keys.publicKey (Uint8Array) to Buffer for Musig + const keysPublicKeyBuffer = Buffer.from(keys.publicKey); + const musig = new Musig(zkp, keys, randomBytes(32), [ + boltzPublicKey, + keysPublicKeyBuffer, + ]); + + const tweakedKey = TaprootUtils.tweakMusig( + musig, + SwapTreeSerializer.deserializeSwapTree(createdResponse.swapTree).tree + ); + + // Parse the lockup transaction and find the output relevant for the swap + const lockupTx = Transaction.fromHex(lockupTxHex); + // Convert Transaction outputs to the format expected by detectSwap + // bitcoinjs-lib v7 uses bigint for values, but detectSwap expects number + const txOutputs = lockupTx.outs.map((out) => ({ + script: Buffer.from(out.script), + value: Number(out.value), // Convert bigint to number + })); + const swapOutput = detectSwap(tweakedKey, { outs: txOutputs }); + + if (swapOutput === undefined) { + throw new Error('No swap output found in lockup transaction'); + } + + // Create a claim transaction to be signed cooperatively via a key path spend + // swapOutput.value is guaranteed to be a number because we converted it above + // (detectSwap preserves the input type, and we passed { value: number }) + // TypeScript needs explicit assertion since detectSwap is generic + const swapValueForClaim: number = Number(swapOutput.value); + + // Convert txHash to Buffer + const txHashBuffer = Buffer.from(lockupTx.getHash()); + + // Convert address script to Buffer + const destinationScript = Buffer.from(address.toOutputScript(destinationAddress, swapNetwork)); + + const claimTx = targetFee(2, (fee) => + constructClaimTransaction( + [ + { + ...swapOutput, + value: swapValueForClaim, + keys, + preimage, + cooperative: true, + type: OutputType.Taproot, + txHash: txHashBuffer, + }, + ], + destinationScript, + fee + ) + ); + + // Get the partial signature from Boltz + const claimResponse = await fetch( + `${API_ENDPOINT}/v2/swap/reverse/${createdResponse.id}/claim`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + index: 0, + transaction: claimTx.toHex(), + preimage: preimage.toString('hex'), + pubNonce: Buffer.from(musig.getPublicNonce()).toString('hex'), + }), + } + ); + + if (!claimResponse.ok) { + const errorText = await claimResponse.text(); + throw new Error(`Failed to get claim signature: ${errorText}`); + } + + const boltzSig = await claimResponse.json(); + + // Aggregate the nonces + musig.aggregateNonces([ + [boltzPublicKey, Buffer.from(boltzSig.pubNonce, 'hex')], + ]); + + // Initialize the session to sign the claim transaction + // Use the already converted value for hashForWitnessV1 + musig.initializeSession( + claimTx.hashForWitnessV1( + 0, + [swapOutput.script], + [swapValueForClaim], + Transaction.SIGHASH_DEFAULT + ) + ); + + // Add the partial signature from Boltz + musig.addPartial( + boltzPublicKey, + Buffer.from(boltzSig.partialSignature, 'hex') + ); + + // Create our partial signature + musig.signPartial(); + + // Witness of the input to the aggregated signature + claimTx.ins[0].witness = [musig.aggregatePartials()]; + + // Broadcast the finalized transaction + const broadcastResponse = await fetch( + `${API_ENDPOINT}/v2/chain/BTC/transaction`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + hex: claimTx.toHex(), + }), + } + ); + + if (!broadcastResponse.ok) { + const errorText = await broadcastResponse.text(); + throw new Error(`Failed to broadcast transaction: ${errorText}`); + } +} diff --git a/src/lib/bitcoin.ts b/src/lib/bitcoin.ts index f608ff1..6c217a4 100644 --- a/src/lib/bitcoin.ts +++ b/src/lib/bitcoin.ts @@ -54,6 +54,35 @@ export function npubToBitcoinAddress(npub: string): string { } } +/** + * Check if a string looks like a Bitcoin address + * Supports P2PKH (starts with 1), P2SH (starts with 3), and P2TR/Taproot (starts with bc1) + */ +export function isValidBitcoinAddress(address: string): boolean { + if (!address || typeof address !== 'string') return false; + + const trimmed = address.trim(); + + // P2PKH addresses (legacy, starts with 1) + if (trimmed.startsWith('1') && trimmed.length >= 26 && trimmed.length <= 35) { + return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(trimmed); + } + + // P2SH addresses (starts with 3) + if (trimmed.startsWith('3') && trimmed.length >= 26 && trimmed.length <= 35) { + return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(trimmed); + } + + // P2TR/Taproot addresses (bech32, starts with bc1) + if (trimmed.startsWith('bc1')) { + // Taproot addresses are bc1p... (62 chars) or bc1q... (42 chars for P2WPKH) + // For reverse swaps, we're mostly concerned with bc1p (Taproot) + return /^bc1[a-z0-9]{39,59}$/i.test(trimmed); + } + + return false; +} + /** * Interface for UTXO (Unspent Transaction Output) */