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
|
import { EventSource } from "eventsource";
if (!globalThis.EventSource) globalThis.EventSource = EventSource;
import config from "$config";
import { SingleKey, Wallet, Ramps, RestArkProvider, VtxoManager } from "@arkade-os/sdk";
import { l, warn } from "$lib/logging";
let wallet: any;
const getWallet = async () => {
if (wallet) return wallet;
const { arkPrivateKey, arkServerUrl, esploraUrl } = config.ark;
const identity = SingleKey.fromHex(arkPrivateKey);
wallet = await Wallet.create({ identity, arkServerUrl, esploraUrl });
return wallet;
};
let refreshing = false;
let lastRefresh = 0;
const REFRESH_COOLDOWN = 30_000;
const failedBoardingOutpoints = new Set<string>();
const withTimeout = <T>(promise: Promise<T>, ms: number, label: string) =>
Promise.race([
promise,
new Promise<T>((_, reject) => setTimeout(() => reject(new Error(`${label} timed out`)), ms)),
]);
export const refreshArkWallet = async (force = false) => {
const now = Date.now();
if (refreshing || (!force && now - lastRefresh < REFRESH_COOLDOWN)) return;
try {
refreshing = true;
lastRefresh = now;
const w = await getWallet();
const balance = await w.getBalance();
l(
"ark wallet check — available:",
balance.available,
"recoverable:",
balance.recoverable,
"boarding:",
balance.boarding.confirmed,
);
const manager = new VtxoManager(w);
// Recover swept/expired VTXOs
if (balance.recoverable > 0) {
try {
const txid = await withTimeout(manager.recoverVtxos(), 60_000, "ark recovery");
l("ark recovered swept vtxos, txid:", txid);
} catch (e: any) {
warn("ark vtxo recovery failed:", e.message);
}
}
// Renew VTXOs approaching expiry (SDK default: 3 days)
try {
const expiring = await manager.getExpiringVtxos();
if (expiring.length > 0) {
l("ark renewing", expiring.length, "expiring vtxos");
const txid = await withTimeout(manager.renewVtxos(), 60_000, "ark renewal");
l("ark renewed vtxos, txid:", txid);
}
} catch (e: any) {
warn("ark vtxo renewal failed:", e.message);
}
// Onboard confirmed boarding UTXOs
const boardingUtxos = await w.getBoardingUtxos();
const confirmed = boardingUtxos.filter((u: any) => u.status?.confirmed);
if (confirmed.length > 0) {
const provider = new RestArkProvider(config.ark.arkServerUrl);
const info = await provider.getInfo();
const ramps = new Ramps(w);
// Try each boarding UTXO, freshest first, skipping known failures
const outpointKey = (u: any) => `${u.txid}:${u.vout}`;
const sorted = [...confirmed]
.filter((u: any) => !failedBoardingOutpoints.has(outpointKey(u)))
.sort((a: any, b: any) => (b.status?.block_height || 0) - (a.status?.block_height || 0));
for (const utxo of sorted) {
try {
const txid = await withTimeout(
ramps.onboard(info.fees, [utxo], undefined, () => {}),
60_000,
"ark onboard",
);
l("ark onboarded boarding utxo:", utxo.value, "sats, txid:", txid);
failedBoardingOutpoints.clear();
break;
} catch (e: any) {
failedBoardingOutpoints.add(outpointKey(utxo));
warn("ark onboard failed:", utxo.value, "sats:", e.message);
}
}
}
} catch (e: any) {
warn("ark wallet refresh failed:", e.message);
} finally {
refreshing = false;
}
};
// Initial check after 30s startup delay; ongoing checks triggered by ZMQ blocks
setTimeout(refreshArkWallet, 30_000);
export const sendArk = async (address: string, amount: number) => {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Ark send timed out")), 60000),
);
const send = async () => {
const w = await getWallet();
try {
return await w.sendBitcoin({ address, amount });
} catch (e: any) {
if (/insufficient funds/i.test(e.message)) {
l("ark send got insufficient funds, refreshing wallet and retrying");
await refreshArkWallet(true);
return w.sendBitcoin({ address, amount });
}
throw e;
}
};
return Promise.race([send(), timeout]);
};
export const getArkAddress = async () => {
const w = await getWallet();
return w.getAddress();
};
export const getArkBalance = async () => {
const w = await getWallet();
return w.getBalance();
};
export const verifyArkVtxo = async (hash: string) => {
const { bech32m } = await import("@scure/base");
const serverAddr = await getArkAddress();
const decoded = bech32m.decode(serverAddr, 1023);
const words = new Uint8Array(bech32m.fromWords(decoded.words));
const vtxoHex = Buffer.from(words.slice(33, 65)).toString("hex");
const r = await fetch(
`${config.ark.arkServerUrl}/v1/indexer/vtxos?scripts=5120${vtxoHex}&spendable_only=true`,
);
const { vtxos } = await r.json();
return vtxos?.some((v: any) => v.outpoint?.txid === hash) ?? false;
};
|