1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
|
<script lang="ts">
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";
import {
last,
invoice,
request,
ndef,
passwordPrompt,
selectSigner,
password,
paymentSignal,
pin,
theme as themeStore,
fiat,
rate as rateStore,
} from "$lib/store";
import { page } from "$app/stores";
import { browser } from "$app/environment";
import LoadingSplash from "$comp/LoadingSplash.svelte";
import AppHeader from "$comp/AppHeader.svelte";
import Nostr from "$comp/Nostr.svelte";
import Password from "$comp/Password.svelte";
import { s, f, toFiat, success, getCookie, warning, post } from "$lib/utils";
import { t, locale, loading } from "$lib/translations";
import { goto, invalidate, afterNavigate, preloadData } from "$app/navigation";
let { data, children } = $props();
let user = $derived(data.user);
let subject = $derived(data.subject);
let token = $derived(data.token);
let theme = $derived(data.theme);
$effect(() => {
$themeStore = theme;
});
$effect(() => {
theme = $themeStore;
});
afterNavigate(() => {
document.cookie = `pathname=${$page.url.pathname}; path=/; max-age=86400`;
if (user) {
preloadData(`/${user.username}`);
preloadData(`/${user.username}/receive`);
preloadData("/payments");
preloadData("/send");
if ($arkkey) arkSync("afterNavigate");
}
});
let arkSyncing = false;
let arkForwarding = false;
let arkSync = async (source = "unknown") => {
if (arkSyncing || arkSending) {
console.log(`[arkSync] SKIPPED (source: ${source}, syncing: ${arkSyncing}, sending: ${arkSending})`);
return;
}
console.log(`[arkSync] START (source: ${source})`);
arkSyncing = true;
try {
const aid = $arkaid || getCookie("aid") || user.id;
const result = await syncTransactions(aid);
console.log(`[arkSync] DONE (source: ${source}, received: ${result?.received || 0})`);
if (result?.forward && !arkForwarding) {
arkForwarding = true;
try {
const { serverArkAddress, amount, iid } = result.forward;
const txid = await sendArk(serverArkAddress, amount);
await post("/post/ark/vault-send", { hash: txid, amount, aid });
await post("/post/ark/receive", { amount, hash: txid, iid });
} catch (e) {
console.error("Ark custodial forward failed:", e);
} finally {
arkForwarding = false;
}
} else 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");
} catch (e) {
console.error("Ark sync failed:", e);
} finally {
arkSyncing = false;
}
};
let arkInitializedKey: string | undefined;
let arkRefreshTimer: ReturnType<typeof setInterval> | undefined;
let aspStopFunc: (() => void) | undefined;
const initArk = async () => {
const key = $arkkey;
if (!key || arkInitializedKey === key) return;
arkInitializedKey = key;
const wallet = await getWallet();
if (wallet) {
localStorage.setItem("arkkey:uid", user.id);
// 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));
// Periodically recover expired VTXOs
if (arkRefreshTimer) clearInterval(arkRefreshTimer);
arkRefreshTimer = setInterval(() => {
refresh().catch((e) => console.error("Ark periodic refresh failed:", e));
}, 60_000);
}
};
$effect(() => {
if (browser && user && $arkkey) initArk();
});
$effect(() => {
if ($paymentSignal && $arkkey) arkSync("paymentSignal");
});
onMount(async () => {
if (browser) {
checkSocket();
$pin = getCookie("pin");
if (user) {
const storedUid = localStorage.getItem("arkkey:uid");
if (storedUid && storedUid !== user.id) {
$arkkey = "";
$arkaid = "";
localStorage.removeItem("arkkey:uid");
}
}
// if (window.NDEFReader) {
// try {
// $ndef = new NDEFReader();
// await $ndef.scan();
//
// $ndef.addEventListener("readingerror", (e) => {
// console.log("nfc error", e);
// });
//
// $ndef.addEventListener("reading", ({ message, serialNumber }) => {
// console.log("MESSAGE", message);
//
// const record = message.records[0];
//
// if (record.recordType === "url") {
// const textDecoder = new TextDecoder();
// const url = textDecoder.decode(record.data);
// console.log("URL:", url);
//
// // Navigate to the URL or use it however you want
// goto(`/send/${encodeURIComponent(url)}`);
// } else {
// console.error("Unsupported record type:", record.recordType);
// }
// });
// } catch (error) {
// console.log("Argh! " + error);
// }
// }
}
});
let checkTimer,
counter = 0;
let checkSocket = () => {
counter++;
let lost = socket?.readyState !== 1 || !$last || Date.now() - ($last as number) > 30000;
if (lost) connect(token);
if (counter > 5) {
send("heartbeat", token);
counter = 0;
}
checkTimer = setTimeout(checkSocket, 1000);
};
onDestroy(() => {
if (browser) {
close();
clearTimeout(checkTimer);
if (arkRefreshTimer) clearInterval(arkRefreshTimer);
aspStopFunc?.();
}
});
</script>
{#if browser && user && $passwordPrompt}
<Password {user} />
{/if}
{#if browser}
<Nostr />
{/if}
<svelte:head>
{#if subject}
<title>coinos - {subject.username}</title>
<meta name="lightning" content={`lnurlp:${subject.username}@coinos.io`} />
{:else}
<title>coinos</title>
{/if}
{#if subject?.profile}
<meta name="og:image" content={`/api/public/${subject.profile}.webp`} />
{:else}
<meta property="og:image" content="/images/logo.webp" />
{/if}
</svelte:head>
<SvelteToast options={{ reversed: true, intro: { y: 192 } }} />
<main class="pb-4 min-h-dvh" data-theme={theme}>
<AppHeader {user} {subject} />
{#if !$loading}
{@render children?.()}
{/if}
</main>
|