aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/bip21.ts
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2024-11-26 13:08:08 -0800
committerAdam Soltys <[email protected]>2024-11-26 13:20:53 -0800
commit9b3e117eafbba224b86dd7f8b3c56a0370f72d5b (patch)
treea670c3ae954d5075c851126c2aca7a1a45d1b41d /src/lib/bip21.ts
parent2761363d694d3f24600abbe656769f64d7a67605 (diff)
downloadcoinos-ui-9b3e117eafbba224b86dd7f8b3c56a0370f72d5b.tar.gz
coinos-ui-9b3e117eafbba224b86dd7f8b3c56a0370f72d5b.zip
bip21 and socket fixes
Diffstat (limited to 'src/lib/bip21.ts')
-rw-r--r--src/lib/bip21.ts48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/lib/bip21.ts b/src/lib/bip21.ts
new file mode 100644
index 00000000..2642afab
--- /dev/null
+++ b/src/lib/bip21.ts
@@ -0,0 +1,48 @@
+export function decode(uri, allowedSchemes = ["bitcoin", "liquidnetwork"]) {
+ // Determine the scheme from the URI
+ const split = uri.indexOf(":");
+ if (split === -1) {
+ throw new Error("Invalid URI: Missing scheme");
+ }
+
+ const urnScheme = uri.slice(0, split).toLowerCase();
+ if (!allowedSchemes.includes(urnScheme)) {
+ throw new Error(`Invalid scheme: ${urnScheme}`);
+ }
+
+ // Extract address and query string
+ const queryStart = uri.indexOf("?");
+ const address = uri.slice(
+ split + 1,
+ queryStart === -1 ? undefined : queryStart,
+ );
+ const query = queryStart === -1 ? "" : uri.slice(queryStart + 1);
+ const options = Object.fromEntries(new URLSearchParams(query));
+
+ const n = Number(options?.amount);
+ if (!Number.isFinite(n)) throw new Error("Invalid amount");
+ if (n < 0) throw new Error("Invalid amount");
+
+ return { scheme: urnScheme, address, options };
+}
+
+export function encode(
+ address,
+ options = { amount: "" },
+ urnScheme = "bitcoin",
+) {
+ if (!address || typeof address !== "string") {
+ throw new TypeError("Invalid address");
+ }
+
+ if (!["bitcoin", "liquidnetwork"].includes(urnScheme)) {
+ throw new Error(`Unsupported scheme: ${urnScheme}`);
+ }
+
+ const n = Number(options?.amount);
+ if (!Number.isFinite(n)) throw new Error("Invalid amount");
+ if (n < 0) throw new Error("Invalid amount");
+
+ const query = new URLSearchParams(options).toString();
+ return `${urnScheme}:${address}${query ? `?${query}` : ""}`;
+}