aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/components/AmountField.svelte2
-rw-r--r--src/components/Lnurlp.svelte4
-rw-r--r--src/components/Lnurlw.svelte5
-rw-r--r--src/lib/ark.ts119
-rw-r--r--src/routes/(app)/+layout.svelte31
-rw-r--r--src/routes/(app)/account/[id]/+page.svelte5
-rw-r--r--src/routes/(app)/pay/[username]/[...amount]/+page.server.ts21
-rw-r--r--src/routes/(app)/payment/[id]/+page.svelte2
-rw-r--r--src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.server.ts6
-rw-r--r--src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.svelte30
-rw-r--r--src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.svelte9
11 files changed, 202 insertions, 32 deletions
diff --git a/src/components/AmountField.svelte b/src/components/AmountField.svelte
index 810e36f1..dc88089c 100644
--- a/src/components/AmountField.svelte
+++ b/src/components/AmountField.svelte
@@ -52,7 +52,7 @@
<div class="fixed bg-base-100/90 inset-0 overflow-y-auto h-full w-full z-50 max-w-lg mx-auto">
<div class="relative p-5 border shadow-lg rounded-md bg-base-100 space-y-5">
<h1 class="text-center text-2xl font-semibold">{label}</h1>
- <Numpad bind:amount {currency} {rate} bind:submit={done} bind:element={numpad} />
+ <Numpad bind:amount {currency} {rate} {locale} bind:submit={done} bind:element={numpad} />
<button bind:this={done} type="button" onclick={set} class="btn">Ok</button>
</div>
diff --git a/src/components/Lnurlp.svelte b/src/components/Lnurlp.svelte
index cde26d86..757a2540 100644
--- a/src/components/Lnurlp.svelte
+++ b/src/components/Lnurlp.svelte
@@ -6,9 +6,11 @@
import Numpad from "$comp/Numpad.svelte";
import Spinner from "$comp/Spinner.svelte";
import { pin } from "$lib/store";
+ import { loc } from "$lib/utils";
let { data, form, send = $bindable(), comment = $bindable() } = $props();
let currency = $derived(data.user.currency);
+ let locale = $derived(loc(data.user));
let minSendable = $derived(data.minSendable);
let maxSendable = $derived(data.maxSendable);
let commentAllowed = $derived(data.commentAllowed);
@@ -39,7 +41,7 @@
<div class="text-red-600 text-center mb-5">{form.error}</div>
{/if}
- <Numpad bind:amount {rate} {currency} bind:submit={send} />
+ <Numpad bind:amount {rate} {currency} {locale} bind:submit={send} />
<form action="?/pay" method="POST" use:enhance onsubmit={submit}>
<input name="amount" value={amount} type="hidden" />
diff --git a/src/components/Lnurlw.svelte b/src/components/Lnurlw.svelte
index a743bba5..0cc6f824 100644
--- a/src/components/Lnurlw.svelte
+++ b/src/components/Lnurlw.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import { tick } from "svelte";
import handler from "$lib/handler";
- import { sats, f, s, focus } from "$lib/utils";
+ import { sats, f, s, focus, loc } from "$lib/utils";
import { t } from "$lib/translations";
import { enhance } from "$app/forms";
import Numpad from "$comp/Numpad.svelte";
@@ -11,6 +11,7 @@
let { data, form } = $props();
let currency = $derived(data.user.currency);
+ let locale = $derived(loc(data.user));
let username = $derived(data.user.username);
let defaultDescription = $derived(data.defaultDescription);
let minWithdrawable = $derived(data.minWithdrawable);
@@ -56,7 +57,7 @@
{/if}
</div>
{:else}
- <Numpad bind:amount {currency} {rate} />
+ <Numpad bind:amount {currency} {rate} {locale} />
{/if}
<form use:enhance={handler(toggle)} action="?/withdraw" method="POST" class="space-y-5">
diff --git a/src/lib/ark.ts b/src/lib/ark.ts
index 82d1ccce..6685f3ab 100644
--- a/src/lib/ark.ts
+++ b/src/lib/ark.ts
@@ -36,6 +36,90 @@ export const getWallet = async () => {
return walletInstance;
};
+const toHex = (bytes: Uint8Array) =>
+ Array.from(bytes)
+ .map((b) => b.toString(16).padStart(2, "0"))
+ .join("");
+
+export const subscribeToAsp = (onEvent: () => void) => {
+ let es: EventSource | null = null;
+ let subId: string | null = null;
+ let stopped = false;
+ let watchdog: ReturnType<typeof setInterval> | undefined;
+
+ const connect = async () => {
+ if (stopped) return;
+ es?.close();
+
+ const wallet = await getWallet();
+ if (!wallet) return;
+
+ const script = toHex(wallet.offchainTapscript.pkScript);
+
+ const res = await fetch(`${arkServerUrl}/v1/indexer/script/subscribe`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ scripts: [script] }),
+ });
+
+ if (!res.ok) throw new Error(`ASP subscribe failed: ${res.statusText}`);
+ ({ subscriptionId: subId } = await res.json());
+
+ es = new EventSource(
+ `${arkServerUrl}/v1/indexer/script/subscription/${subId}`,
+ );
+
+ es.onmessage = (event) => {
+ try {
+ const data = JSON.parse(event.data);
+ console.log("[ark] SSE event:", data);
+ if (
+ data.event?.newVtxos?.length > 0 ||
+ data.event?.spentVtxos?.length > 0
+ ) {
+ onEvent();
+ }
+ } catch (e) {
+ console.error("[ark] SSE parse error:", e);
+ }
+ };
+
+ es.onerror = () => {
+ // Native EventSource auto-reconnects on transient errors.
+ // If the subscription expired server-side, the watchdog below
+ // will detect CLOSED state and fully re-subscribe.
+ };
+
+ console.log("[ark] SSE subscribed", subId);
+ };
+
+ connect().catch((e) => {
+ console.error("[ark] SSE initial connect failed:", e);
+ });
+
+ // Watchdog: detect CLOSED state (server rejected reconnect) and re-subscribe
+ watchdog = setInterval(() => {
+ if (stopped) return;
+ if (!es || es.readyState === EventSource.CLOSED) {
+ console.warn("[ark] SSE dead, re-subscribing...");
+ connect().catch((e) => console.error("[ark] SSE reconnect failed:", e));
+ }
+ }, 30_000);
+
+ return () => {
+ stopped = true;
+ if (watchdog) clearInterval(watchdog);
+ es?.close();
+ if (subId) {
+ fetch(`${arkServerUrl}/v1/indexer/script/unsubscribe`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ subscriptionId: subId }),
+ }).catch(() => {});
+ }
+ };
+};
+
export const getAddress = async (): Promise<string> => {
const wallet = await getWallet();
return wallet.getAddress();
@@ -155,26 +239,41 @@ export const sendArk = async (address: string, amount: number) => {
}
const freshBalance = await wallet.getBalance();
+ const preSendTotal = (freshBalance.available || 0) + (freshBalance.preconfirmed || 0);
if (freshBalance.available < amount) {
throw new Error(`Insufficient funds: ${freshBalance.available} available, need ${amount}`);
}
+
let txid;
+ let sendWallet = wallet;
try {
txid = await withTimeout(wallet.sendBitcoin({ address, amount }), 45_000, "Ark send");
} catch (e: any) {
- if (e?.message?.includes("VTXO_ALREADY_REGISTERED")) {
- await wallet.settle();
- const vtxos = await wallet.getVtxos({ spendableOnly: false });
+ if (e?.message?.includes("VTXO_ALREADY_REGISTERED") || e?.message?.includes("VTXO_ALREADY_SPENT")) {
+ console.log("ark send: stale VTXOs, recreating wallet and retrying");
+ walletInstance = undefined;
+ walletKey = undefined;
+ sendWallet = await getWallet();
+ if (!sendWallet) throw new Error("Ark wallet not available after refresh");
+ const vtxos = await sendWallet.getVtxos({ spendableOnly: false });
if (vtxos?.length) addProcessedVtxos(vtxos.map(vtxoKey));
- txid = await withTimeout(wallet.sendBitcoin({ address, amount }), 45_000, "Ark send retry");
+ txid = await withTimeout(sendWallet.sendBitcoin({ address, amount }), 45_000, "Ark send retry");
} else {
throw e;
}
}
+ // Verify the send actually changed the balance
+ const postBalance = await sendWallet.getBalance();
+ const postSendTotal = (postBalance.available || 0) + (postBalance.preconfirmed || 0);
+ console.log("ark send: pre-balance", preSendTotal, "post-balance", postSendTotal, "amount", amount, "txid", txid);
+ if (postSendTotal >= preSendTotal) {
+ throw new Error("Send failed: balance unchanged after sendBitcoin");
+ }
+
// Mark post-send VTXOs as processed so notifyIncomingFunds
// ignores change VTXOs from this send
- const vtxos = await wallet.getVtxos({ spendableOnly: false });
+ const vtxos = await sendWallet.getVtxos({ spendableOnly: false });
if (vtxos?.length) addProcessedVtxos(vtxos.map(vtxoKey));
return txid;
@@ -193,17 +292,17 @@ export const sendArkViaForward = async ({
serverArkAddress: string;
amount: number;
aid: string;
- forward: string;
+ forward?: string;
user: any;
}) => {
const txid = await sendArk(serverArkAddress, amount);
await post("/post/ark/vault-send", { hash: txid, amount, aid });
- const inv = await post("/post/invoice", {
- invoice: { type: "ark", amount, forward, aid },
- user,
- });
+ const invoice: any = { type: "ark", amount, aid };
+ if (forward) invoice.forward = forward;
+
+ const inv = await post("/post/invoice", { invoice, user });
return post("/post/ark/receive", { amount, hash: txid, iid: inv.id });
};
diff --git a/src/routes/(app)/+layout.svelte b/src/routes/(app)/+layout.svelte
index 0c88ff19..3fc8f9cf 100644
--- a/src/routes/(app)/+layout.svelte
+++ b/src/routes/(app)/+layout.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { getWallet, syncTransactions, settle, refresh, arkkey, arkaid, sendArk, arkSending } from "$lib/ark";
+ import { getWallet, subscribeToAsp, syncTransactions, settle, refresh, arkkey, arkaid, sendArk, arkSending } from "$lib/ark";
import { SvelteToast } from "@zerodevx/svelte-toast";
import { onDestroy, onMount } from "svelte";
import { close, connect, send, socket } from "$lib/socket";
@@ -102,6 +102,7 @@
let arkInitializedKey: string | undefined;
let arkRefreshTimer: ReturnType<typeof setInterval> | undefined;
+ let aspStopFunc: (() => void) | undefined;
const initArk = async () => {
const key = $arkkey;
@@ -111,7 +112,32 @@
const wallet = await getWallet();
if (wallet) {
localStorage.setItem("arkkey:uid", user.id);
- wallet.notifyIncomingFunds(() => arkSync("notifyIncomingFunds"));
+
+ // Subscribe directly to ASP event stream (bypasses SDK's fragile wrapper)
+ aspStopFunc?.();
+ aspStopFunc = subscribeToAsp(async () => {
+ // Retry arkSync with backoff — indexer needs time to process the new VTXO
+ for (const delay of [1000, 3000, 8000]) {
+ await new Promise((r) => setTimeout(r, delay));
+ const aid = $arkaid || getCookie("aid") || user.id;
+ const result = await syncTransactions(aid);
+ console.log(`[arkSync] SSE retry (delay: ${delay}ms, received: ${result?.received || 0})`);
+ if (result?.received > 0) {
+ const paidPayment = result.payments?.find((p: any) => p.iid && p.amount > 0);
+ if (paidPayment) {
+ goto(`/invoice/${paidPayment.iid}`);
+ } else if ($fiat && $rateStore && user?.currency) {
+ success(`Received ${f(toFiat(result.received, $rateStore as number), user.currency)}!`);
+ } else {
+ success(`Received ${s(result.received)}!`);
+ }
+ invalidate("app:payments");
+ return;
+ }
+ }
+ invalidate("app:payments");
+ });
+
arkSync("initArk");
refresh().catch((e) => console.error("Ark refresh failed:", e));
settle().catch((e) => console.error("Ark settle failed:", e));
@@ -200,6 +226,7 @@
close();
clearTimeout(checkTimer);
if (arkRefreshTimer) clearInterval(arkRefreshTimer);
+ aspStopFunc?.();
}
});
</script>
diff --git a/src/routes/(app)/account/[id]/+page.svelte b/src/routes/(app)/account/[id]/+page.svelte
index 065b85c6..62c4beea 100644
--- a/src/routes/(app)/account/[id]/+page.svelte
+++ b/src/routes/(app)/account/[id]/+page.svelte
@@ -5,7 +5,7 @@
import Toggle from "$comp/Toggle.svelte";
import WalletPass from "$comp/WalletPass.svelte";
import { goto } from "$app/navigation";
- import { copy, fail, focus, post } from "$lib/utils";
+ import { copy, fail, focus, loc, post } from "$lib/utils";
import { importing } from "$lib/store";
import { enhance } from "$app/forms";
import { t } from "$lib/translations";
@@ -33,6 +33,7 @@
let name = $state(data.account.name || displayType);
let currency = $state(data.account.currency || data.user.currency);
let userCurrency = $derived(data.user.currency);
+ let locale = $derived(loc(data.user));
let currencyChanged = $derived(currency !== userCurrency);
let updateUserCurrency = $state(false);
@@ -325,6 +326,7 @@
<Numpad
bind:amount={threshold}
{currency}
+ {locale}
bind:rate
bind:submit={doneReserve}
bind:element={thresholdEl}
@@ -341,6 +343,7 @@
<Numpad
bind:amount={reserve}
{currency}
+ {locale}
bind:rate
bind:submit={doneReserve}
bind:element={reserveEl}
diff --git a/src/routes/(app)/pay/[username]/[...amount]/+page.server.ts b/src/routes/(app)/pay/[username]/[...amount]/+page.server.ts
index f1e5a073..ca0f382d 100644
--- a/src/routes/(app)/pay/[username]/[...amount]/+page.server.ts
+++ b/src/routes/(app)/pay/[username]/[...amount]/+page.server.ts
@@ -7,7 +7,26 @@ export async function load({ cookies, params, parent }) {
const { user } = await parent();
const rates = await getRates();
- if (user?.username === username) redirect(307, `/${username}/receive`);
+ if (user?.username === username) {
+ // Allow vault→custodial self-payment: redirect to send/ark with server address
+ const aid = cookies.get("aid");
+ if (aid && aid !== user.id) {
+ const account = await get(`/account/${aid}`, auth(cookies));
+ if (account?.type === "ark") {
+ const serverAddr = await get("/ark/address");
+ let [amt, cur] = params.amount.split("/");
+ if (amt) {
+ if (cur) {
+ const r = rates[cur.toUpperCase()];
+ if (r) amt = String(Math.round((Number(amt) * sats) / r));
+ }
+ redirect(307, `/send/ark/${serverAddr}/${amt}`);
+ }
+ redirect(307, `/send/ark/${serverAddr}`);
+ }
+ }
+ redirect(307, `/${username}/receive`);
+ }
const subject = await get(`/users/${username}`);
let [amount, currency] = params.amount.split("/");
diff --git a/src/routes/(app)/payment/[id]/+page.svelte b/src/routes/(app)/payment/[id]/+page.svelte
index 84a728a0..af729233 100644
--- a/src/routes/(app)/payment/[id]/+page.svelte
+++ b/src/routes/(app)/payment/[id]/+page.svelte
@@ -144,7 +144,7 @@
<div>
<span class="text-lg text-secondary">{$t("payments.date")}</span>
<div>
- {format(new Date(created), "MMM d, yyyy", { locale })}{format(new Date(created), "h:mmaaa", { locale })}
+ {format(new Date(created), "MMM d, yyyy", { locale })} {format(new Date(created), "h:mmaaa", { locale })}
</div>
</div>
diff --git a/src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.server.ts b/src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.server.ts
index 10a6a737..9fa754d6 100644
--- a/src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.server.ts
+++ b/src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.server.ts
@@ -26,12 +26,18 @@ export async function load({ params: { address, amount }, cookies, parent }) {
}
const rate = rates[user.currency];
+ const serverArkAddress = account.type === "ark" ? await get("/ark/address") : null;
+
+ // Check if destination is the user's own vault address (custodial ark invoice)
+ const isCustodialForward = account.type === "ark" && address === account.arkAddress;
return {
account,
amount,
address,
rate,
+ serverArkAddress,
+ isCustodialForward,
};
}
diff --git a/src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.svelte b/src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.svelte
index 02f1c4fb..744886ae 100644
--- a/src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.svelte
+++ b/src/routes/(app)/send/ark/[address]/[amount]/[...feeRate]/+page.svelte
@@ -2,12 +2,12 @@
import { t } from "$lib/translations";
import { enhance } from "$app/forms";
import Spinner from "$comp/Spinner.svelte";
- import { focus, s, post } from "$lib/utils";
+ import { focus, loc, s, post } from "$lib/utils";
import { pin } from "$lib/store";
import { goto, invalidate } from "$app/navigation";
import { rate } from "$lib/store";
import { applyAction } from "$app/forms";
- import { sendArk } from "$lib/ark";
+ import { sendArk, sendArkViaForward } from "$lib/ark";
import Amount from "$comp/Amount.svelte";
@@ -23,13 +23,24 @@
submitting = true;
error = "";
try {
- const txid = await sendArk(address, parseInt(amount));
+ let p;
- const p = await post("/post/ark/vault-send", {
- hash: txid,
- amount: parseInt(amount),
- aid: account.id,
- });
+ if (data.serverArkAddress && (address === data.serverArkAddress || data.isCustodialForward)) {
+ // Vault→custodial: send to server and credit custodial account
+ p = await sendArkViaForward({
+ serverArkAddress: data.serverArkAddress,
+ amount: parseInt(amount),
+ aid: account.id,
+ user: data.user,
+ });
+ } else {
+ const txid = await sendArk(address, parseInt(amount));
+ p = await post("/post/ark/vault-send", {
+ hash: txid,
+ amount: parseInt(amount),
+ aid: account.id,
+ });
+ }
goto(`/sent/${p.id}`, { invalidateAll: true });
} catch (e: any) {
@@ -65,6 +76,7 @@
let balance = $derived(data.user.balance);
let currency = $derived(data.user.currency);
+ let locale = $derived(loc(data.user));
let submitting = $state(false),
submit = $state();
</script>
@@ -81,7 +93,7 @@
{#if !error}
<div class="text-xl text-secondary break-all">{address}</div>
- <Amount {amount} rate={$rate} {currency} />
+ <Amount {amount} rate={$rate} {currency} {locale} />
<form method="POST" use:enhance={handler}>
<input name="pin" value={$pin} type="hidden" />
diff --git a/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.svelte b/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.svelte
index 967c47af..4cb22155 100644
--- a/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.svelte
+++ b/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.svelte
@@ -6,7 +6,7 @@
import Spinner from "$comp/Spinner.svelte";
import WalletPass from "$comp/WalletPass.svelte";
import { page } from "$app/stores";
- import { toFiat, f, focus, s, sat, closest, network } from "$lib/utils";
+ import { toFiat, f, focus, loc, s, sat, closest, network } from "$lib/utils";
import { pin } from "$lib/store";
import { goto, invalidate } from "$app/navigation";
import { rate } from "$lib/store";
@@ -198,6 +198,7 @@
let balance = $derived(data.user.balance);
let currency = $derived(data.user.currency);
+ let locale = $derived(loc(data.user));
let submitting = $state(),
submit: any = $state(),
showSettings = $state();
@@ -231,7 +232,7 @@
<div class="text-xl text-secondary break-all">{address}</div>
{/if}
- <Amount amount={subtract ? amount - fee - ourfee : amount} rate={$rate} {currency} />
+ <Amount amount={subtract ? amount - fee - ourfee : amount} rate={$rate} {currency} {locale} />
{#if fees}
<div class="text-center">
@@ -245,7 +246,7 @@
</option>
{/each}
</select>
- <Amount amount={fee} rate={$rate} {currency} />
+ <Amount amount={fee} rate={$rate} {currency} {locale} />
</div>
</div>
@@ -253,7 +254,7 @@
<div class="text-center">
<h2 class="text-secondary text-lg">{$t("payments.platformFee")}</h2>
- <Amount amount={ourfee} rate={$rate} {currency} />
+ <Amount amount={ourfee} rate={$rate} {currency} {locale} />
</div>
{/if}
{/if}