aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/app.html18
-rw-r--r--src/components/About.svelte14
-rw-r--r--src/components/Account.svelte58
-rw-r--r--src/components/AppHeader.svelte60
-rw-r--r--src/components/Avatar.svelte16
-rw-r--r--src/components/Balance.svelte22
-rw-r--r--src/components/Event.svelte12
-rw-r--r--src/components/Footer.svelte5
-rw-r--r--src/components/Invoice.svelte4
-rw-r--r--src/components/Items.svelte246
-rw-r--r--src/components/LandingHeader.svelte16
-rw-r--r--src/components/LandingHero.svelte2
-rw-r--r--src/components/Lnurlp.svelte17
-rw-r--r--src/components/Lnurlw.svelte19
-rw-r--r--src/components/LocationsMap.svelte206
-rw-r--r--src/components/Mnemonic.svelte16
-rw-r--r--src/components/Numpad.svelte17
-rw-r--r--src/components/Pinpad.svelte5
-rw-r--r--src/components/Request.svelte39
-rw-r--r--src/components/WalletPass.svelte65
-rw-r--r--src/lib/english.js2048
-rw-r--r--src/lib/handler.ts13
-rw-r--r--src/lib/invoice.js32
-rw-r--r--src/lib/invoice.ts38
-rw-r--r--src/lib/locales.ts14
-rw-r--r--src/lib/nostr.js177
-rw-r--r--src/lib/nostr.ts177
-rw-r--r--src/lib/parse.ts82
-rw-r--r--src/lib/punks.js66
-rw-r--r--src/lib/punks.ts66
-rw-r--r--src/lib/samples.ts (renamed from src/lib/samples.js)47
-rw-r--r--src/lib/socket.js88
-rw-r--r--src/lib/socket.ts100
-rw-r--r--src/lib/store.js58
-rw-r--r--src/lib/store.ts62
-rw-r--r--src/lib/ticket.js31
-rw-r--r--src/lib/ticket.ts31
-rw-r--r--src/lib/tickets.js52
-rw-r--r--src/lib/tickets.ts52
-rw-r--r--src/lib/translations/index.js19
-rw-r--r--src/lib/translations/lang.json2
-rw-r--r--src/lib/types.ts23
-rw-r--r--src/lib/upload.js18
-rw-r--r--src/lib/upload.ts18
-rw-r--r--src/lib/utils.js333
-rw-r--r--src/lib/utils.ts364
-rw-r--r--src/locales/de.json85
-rw-r--r--src/locales/el.json85
-rw-r--r--src/locales/en.json100
-rw-r--r--src/locales/es.json85
-rw-r--r--src/locales/fa.json85
-rw-r--r--src/locales/fr.json85
-rw-r--r--src/locales/guided_translation.py8
-rw-r--r--src/locales/ja.json97
-rw-r--r--src/locales/pt.json87
-rw-r--r--src/locales/ru.json88
-rw-r--r--src/locales/zh.json111
-rw-r--r--src/routes/(app)/+layout.server.js49
-rw-r--r--src/routes/(app)/+layout.server.ts59
-rw-r--r--src/routes/(app)/+layout.svelte65
-rw-r--r--src/routes/(app)/[username]/(profile)/+layout.server.js26
-rw-r--r--src/routes/(app)/[username]/(profile)/+layout.server.ts16
-rw-r--r--src/routes/(app)/[username]/(profile)/+layout.svelte333
-rw-r--r--src/routes/(app)/[username]/(profile)/+page.server.js11
-rw-r--r--src/routes/(app)/[username]/(profile)/+page.server.ts16
-rw-r--r--src/routes/(app)/[username]/(profile)/+page.svelte336
-rw-r--r--src/routes/(app)/[username]/(profile)/event/[id]/+page.server.js12
-rw-r--r--src/routes/(app)/[username]/(profile)/event/[id]/+page.server.ts12
-rw-r--r--src/routes/(app)/[username]/(profile)/followers/+page.server.js8
-rw-r--r--src/routes/(app)/[username]/(profile)/followers/+page.svelte28
-rw-r--r--src/routes/(app)/[username]/(profile)/follows/+page.server.js8
-rw-r--r--src/routes/(app)/[username]/(profile)/follows/+page.svelte60
-rw-r--r--src/routes/(app)/[username]/+layout.server.js18
-rw-r--r--src/routes/(app)/[username]/+layout.server.ts24
-rw-r--r--src/routes/(app)/[username]/+layout.svelte50
-rw-r--r--src/routes/(app)/[username]/address/+page.server.js10
-rw-r--r--src/routes/(app)/[username]/card/[serial]/+page.server.js16
-rw-r--r--src/routes/(app)/[username]/card/[serial]/+page.svelte36
-rw-r--r--src/routes/(app)/[username]/customers/+page.svelte0
-rw-r--r--src/routes/(app)/[username]/funds/+page.server.js0
-rw-r--r--src/routes/(app)/[username]/funds/+page.svelte52
-rw-r--r--src/routes/(app)/[username]/generate/+server.js11
-rw-r--r--src/routes/(app)/[username]/invoice/+server.js7
-rw-r--r--src/routes/(app)/[username]/invoice/[id]/+layout.server.js38
-rw-r--r--src/routes/(app)/[username]/invoice/[id]/+layout.svelte1
-rw-r--r--src/routes/(app)/[username]/invoice/[id]/+page.svelte298
-rw-r--r--src/routes/(app)/[username]/invoice/[id]/tip/+page.server.js12
-rw-r--r--src/routes/(app)/[username]/items/[id]/+page.server.js21
-rw-r--r--src/routes/(app)/[username]/items/create/+page.server.js16
-rw-r--r--src/routes/(app)/[username]/map/+page.server.js12
-rw-r--r--src/routes/(app)/[username]/map/+page.svelte8
-rw-r--r--src/routes/(app)/[username]/messages/+page.server.js33
-rw-r--r--src/routes/(app)/[username]/messages/[recipient]/+page.server.js23
-rw-r--r--src/routes/(app)/[username]/payments/[...page]/+page.server.js26
-rw-r--r--src/routes/(app)/[username]/payments/[...page]/+server.js18
-rw-r--r--src/routes/(app)/[username]/receive/+page.server.js8
-rw-r--r--src/routes/(app)/[username]/receive/+page.svelte272
-rw-r--r--src/routes/(app)/[username]/receive/[...param]/+page.server.js15
-rw-r--r--src/routes/(app)/[username]/receive/[...param]/+page.svelte52
-rw-r--r--src/routes/(app)/[username]/reset/+server.js10
-rw-r--r--src/routes/(app)/[username]/settings/[...tab]/+page.server.js34
-rw-r--r--src/routes/(app)/[username]/shopify.js/+server.ts (renamed from src/routes/(app)/[username]/shopify.js/+server.js)16
-rw-r--r--src/routes/(app)/[username]/verify/[code]/+page.server.js14
-rw-r--r--src/routes/(app)/account/+server.ts12
-rw-r--r--src/routes/(app)/account/[id]/+page.server.ts24
-rw-r--r--src/routes/(app)/account/[id]/+page.svelte125
-rw-r--r--src/routes/(app)/account/cash/+page.svelte37
-rw-r--r--src/routes/(app)/account/import/+page.svelte55
-rw-r--r--src/routes/(app)/account/mints/+page.svelte1
-rw-r--r--src/routes/(app)/account/pass/+page.svelte158
-rw-r--r--src/routes/(app)/account/savings/+page.svelte33
-rw-r--r--src/routes/(app)/account/seed/+page.svelte76
-rw-r--r--src/routes/(app)/account/setup/+page.svelte33
-rw-r--r--src/routes/(app)/admin/+layout.server.js11
-rw-r--r--src/routes/(app)/admin/+layout.server.ts11
-rw-r--r--src/routes/(app)/admin/+page.server.js12
-rw-r--r--src/routes/(app)/admin/+page.server.ts12
-rw-r--r--src/routes/(app)/admin/+page.svelte2
-rw-r--r--src/routes/(app)/buy/+page.server.js28
-rw-r--r--src/routes/(app)/buy/+page.svelte138
-rw-r--r--src/routes/(app)/disable2fa/+server.js13
-rw-r--r--src/routes/(app)/disable2fa/+server.ts13
-rw-r--r--src/routes/(app)/ecash/[id]/[...version]/+layout.server.ts11
-rw-r--r--src/routes/(app)/ecash/[id]/[...version]/+layout.svelte56
-rw-r--r--src/routes/(app)/ecash/[id]/[...version]/+page.server.ts21
-rw-r--r--src/routes/(app)/ecash/[id]/[...version]/+page.svelte86
-rw-r--r--src/routes/(app)/ecash/[id]/[...version]/swap/+page.server.ts3
-rw-r--r--src/routes/(app)/ecash/[id]/[...version]/swap/+page.svelte7
-rw-r--r--src/routes/(app)/enable2fa/+server.js8
-rw-r--r--src/routes/(app)/enable2fa/+server.ts8
-rw-r--r--src/routes/(app)/events/+server.ts12
-rw-r--r--src/routes/(app)/forgot/+page.server.js14
-rw-r--r--src/routes/(app)/forgot/+page.server.ts14
-rw-r--r--src/routes/(app)/fund/[id]/+page.server.js23
-rw-r--r--src/routes/(app)/fund/[id]/+page.server.ts23
-rw-r--r--src/routes/(app)/fund/[id]/sweep/+page.server.js13
-rw-r--r--src/routes/(app)/fund/[id]/sweep/+page.server.ts13
-rw-r--r--src/routes/(app)/fund/[id]/sweep/+page.svelte2
-rw-r--r--src/routes/(app)/fund/[id]/withdraw/+page.server.js20
-rw-r--r--src/routes/(app)/fund/[id]/withdraw/+page.server.ts20
-rw-r--r--src/routes/(app)/fund/[id]/withdraw/+page.svelte2
-rw-r--r--src/routes/(app)/fund/[id]/withdraw/+server.ts (renamed from src/routes/(app)/events/+server.js)4
-rw-r--r--src/routes/(app)/generate/+page.svelte (renamed from src/routes/(app)/[username]/generate/+page.svelte)2
-rw-r--r--src/routes/(app)/generate/+server.ts12
-rw-r--r--src/routes/(app)/invoice/+page.server.ts29
-rw-r--r--src/routes/(app)/invoice/+page.svelte (renamed from src/routes/(app)/[username]/address/+page.svelte)0
-rw-r--r--src/routes/(app)/invoice/+server.ts7
-rw-r--r--src/routes/(app)/invoice/[id]/+layout.server.ts40
-rw-r--r--src/routes/(app)/invoice/[id]/[email protected]115
-rw-r--r--src/routes/(app)/invoice/[id]/+page.server.ts (renamed from src/routes/(app)/[username]/invoice/[id]/+page.server.js)2
-rw-r--r--src/routes/(app)/invoice/[id]/+page.svelte334
-rw-r--r--src/routes/(app)/invoice/[id]/memo/+page.server.ts (renamed from src/routes/(app)/[username]/invoice/[id]/memo/+page.server.js)9
-rw-r--r--src/routes/(app)/invoice/[id]/memo/+page.svelte (renamed from src/routes/(app)/[username]/invoice/[id]/memo/+page.svelte)2
-rw-r--r--src/routes/(app)/invoice/[id]/paid/+page.svelte (renamed from src/routes/(app)/[username]/invoice/[id]/paid/+page.svelte)2
-rw-r--r--src/routes/(app)/invoice/[id]/tip/+page.server.ts15
-rw-r--r--src/routes/(app)/invoice/[id]/tip/+page.svelte (renamed from src/routes/(app)/[username]/invoice/[id]/tip/+page.svelte)24
-rw-r--r--src/routes/(app)/invoice/sent/+page.svelte (renamed from src/routes/(app)/[username]/invoice/sent/+page.svelte)0
-rw-r--r--src/routes/(app)/items/[id]/+page.server.ts21
-rw-r--r--src/routes/(app)/items/[id]/+page.svelte (renamed from src/routes/(app)/[username]/items/[id]/+page.svelte)0
-rw-r--r--src/routes/(app)/items/create/+page.server.ts16
-rw-r--r--src/routes/(app)/items/create/+page.svelte (renamed from src/routes/(app)/[username]/items/create/+page.svelte)0
-rw-r--r--src/routes/(app)/ln/[lnurl]/+page.server.js75
-rw-r--r--src/routes/(app)/ln/[lnurl]/+page.server.ts81
-rw-r--r--src/routes/(app)/ln/withdrawal/sent/+page.svelte2
-rw-r--r--src/routes/(app)/locations/+server.js15
-rw-r--r--src/routes/(app)/locations/+server.ts15
-rw-r--r--src/routes/(app)/login/+page.server.js29
-rw-r--r--src/routes/(app)/login/+page.svelte188
-rw-r--r--src/routes/(app)/logout/+page.server.js14
-rw-r--r--src/routes/(app)/logout/+page.server.ts15
-rw-r--r--src/routes/(app)/messages/+page.server.ts44
-rw-r--r--src/routes/(app)/messages/+page.svelte (renamed from src/routes/(app)/[username]/messages/+page.svelte)2
-rw-r--r--src/routes/(app)/messages/[recipient]/+page.server.ts25
-rw-r--r--src/routes/(app)/messages/[recipient]/+page.svelte (renamed from src/routes/(app)/[username]/messages/[recipient]/+page.svelte)6
-rw-r--r--src/routes/(app)/otpsecret/+server.js17
-rw-r--r--src/routes/(app)/otpsecret/+server.ts17
-rw-r--r--src/routes/(app)/password/+server.ts (renamed from src/routes/(app)/password/+server.js)4
-rw-r--r--src/routes/(app)/pay/[username]/[...amount]/+page.server.ts54
-rw-r--r--src/routes/(app)/pay/[username]/[...amount]/+page.svelte (renamed from src/routes/(app)/send/user/[username]/[...amount]/+page.svelte)37
-rw-r--r--src/routes/(app)/payment/[id]/+page.server.js7
-rw-r--r--src/routes/(app)/payment/[id]/+page.server.ts7
-rw-r--r--src/routes/(app)/payment/[id]/+page.svelte93
-rw-r--r--src/routes/(app)/payment/[id]/bump/+server.js12
-rw-r--r--src/routes/(app)/payment/[id]/bump/+server.ts12
-rw-r--r--src/routes/(app)/payment/[id]/plain/+page.server.ts (renamed from src/routes/(app)/payment/[id]/plain/+page.server.js)4
-rw-r--r--src/routes/(app)/payment/[id]/print/+server.ts (renamed from src/routes/(app)/payment/[id]/print/+server.js)4
-rw-r--r--src/routes/(app)/payments/[...page]/+page.server.ts31
-rw-r--r--src/routes/(app)/payments/[...page]/+page.svelte (renamed from src/routes/(app)/[username]/payments/[...page]/+page.svelte)151
-rw-r--r--src/routes/(app)/payments/[...page]/+server.ts19
-rw-r--r--src/routes/(app)/pin/+server.ts (renamed from src/routes/(app)/pin/+server.js)4
-rw-r--r--src/routes/(app)/qr/[text]/+page.server.js8
-rw-r--r--src/routes/(app)/qr/[text]/+page.server.ts8
-rw-r--r--src/routes/(app)/qr/[text]/+page.svelte25
-rw-r--r--src/routes/(app)/qr/create/+page.svelte60
-rw-r--r--src/routes/(app)/receive/[...token]/+page.server.ts17
-rw-r--r--src/routes/(app)/receive/[...token]/+page.svelte90
-rw-r--r--src/routes/(app)/redeem/[redeemcode]/+page.server.js17
-rw-r--r--src/routes/(app)/redeem/[redeemcode]/+page.svelte4
-rw-r--r--src/routes/(app)/register/+page.server.js41
-rw-r--r--src/routes/(app)/register/+page.svelte315
-rw-r--r--src/routes/(app)/reset/+server.ts (renamed from src/routes/(app)/fund/[id]/withdraw/+server.js)3
-rw-r--r--src/routes/(app)/reset/[code]/+page.server.js30
-rw-r--r--src/routes/(app)/reset/[code]/+page.server.ts30
-rw-r--r--src/routes/(app)/scan/[email protected]3
-rw-r--r--src/routes/(app)/scan/+page.svelte37
-rw-r--r--src/routes/(app)/send/+layout.svelte2
-rw-r--r--src/routes/(app)/send/[...text]/+page.server.js98
-rw-r--r--src/routes/(app)/send/[...text]/+page.server.ts19
-rw-r--r--src/routes/(app)/send/[...text]/+page.svelte56
-rw-r--r--src/routes/(app)/send/bitcoin/[address]/+layout.server.ts23
-rw-r--r--src/routes/(app)/send/bitcoin/[address]/+page.server.ts7
-rw-r--r--src/routes/(app)/send/bitcoin/[address]/+page.svelte10
-rw-r--r--src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.server.js35
-rw-r--r--src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.server.ts49
-rw-r--r--src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.svelte110
-rw-r--r--src/routes/(app)/send/ecash/+page.server.ts18
-rw-r--r--src/routes/(app)/send/ecash/+page.svelte73
-rw-r--r--src/routes/(app)/send/fund/[name]/[...amount]/+page.server.js17
-rw-r--r--src/routes/(app)/send/fund/[name]/[...amount]/+page.server.ts17
-rw-r--r--src/routes/(app)/send/invoice/[id]/+page.server.js35
-rw-r--r--src/routes/(app)/send/invoice/[id]/+page.server.ts39
-rw-r--r--src/routes/(app)/send/invoice/[id]/+page.svelte25
-rw-r--r--src/routes/(app)/send/lightning/[payreq]/+page.server.js24
-rw-r--r--src/routes/(app)/send/lightning/[payreq]/+page.server.ts29
-rw-r--r--src/routes/(app)/send/lightning/[payreq]/+page.svelte75
-rw-r--r--src/routes/(app)/send/user/[username]/[...amount]/+page.server.js50
-rw-r--r--src/routes/(app)/sent/+page.server.js6
-rw-r--r--src/routes/(app)/sent/[id]/+page.server.ts7
-rw-r--r--src/routes/(app)/sent/[id]/+page.svelte (renamed from src/routes/(app)/sent/+page.svelte)12
-rw-r--r--src/routes/(app)/settings/[...tab]/+page.server.ts36
-rw-r--r--src/routes/(app)/settings/[...tab]/+page.svelte (renamed from src/routes/(app)/[username]/settings/[...tab]/+page.svelte)27
-rw-r--r--src/routes/(app)/settings/[...tab]/_account.svelte (renamed from src/routes/(app)/[username]/settings/[...tab]/_account.svelte)0
-rw-r--r--src/routes/(app)/settings/[...tab]/_pos.svelte (renamed from src/routes/(app)/[username]/settings/[...tab]/_pos.svelte)82
-rw-r--r--src/routes/(app)/settings/[...tab]/_security.svelte (renamed from src/routes/(app)/[username]/settings/[...tab]/_security.svelte)0
-rw-r--r--src/routes/(app)/settings/[...tab]/_shopify.svelte (renamed from src/routes/(app)/[username]/settings/[...tab]/_shopify.svelte)0
-rw-r--r--src/routes/(app)/subscription/+server.ts8
-rw-r--r--src/routes/(app)/subscription/delete/+server.ts8
-rw-r--r--src/routes/(app)/verify/[code]/+page.server.ts14
-rw-r--r--src/routes/(app)/verify/[code]/+page.svelte (renamed from src/routes/(app)/[username]/verify/[code]/+page.svelte)0
-rw-r--r--src/routes/(app)/withdraw/+server.js10
-rw-r--r--src/routes/(app)/withdraw/+server.ts10
-rw-r--r--src/routes/(static)/+layout.server.js16
-rw-r--r--src/routes/(static)/+layout.server.ts14
-rw-r--r--src/routes/(static)/+layout.svelte2
-rw-r--r--src/routes/(static)/docs/+page.server.js4
-rw-r--r--src/routes/(static)/docs/+page.server.ts4
-rw-r--r--src/routes/(static)/login/+page.server.ts25
-rw-r--r--src/routes/(static)/login/+page.svelte172
-rw-r--r--src/routes/(static)/privacy/+page.svelte16
-rw-r--r--src/routes/(static)/register/+page.server.ts41
-rw-r--r--src/routes/(static)/register/+page.svelte292
-rw-r--r--src/routes/(static)/removal/+page.svelte9
-rw-r--r--src/routes/(static)/support/+page.svelte (renamed from src/routes/(app)/support/+page.svelte)31
-rw-r--r--src/routes/(static)/support/+server.ts (renamed from src/routes/(app)/support/+server.js)4
-rw-r--r--src/routes/+error.svelte37
-rw-r--r--src/routes/+layout.js14
-rw-r--r--src/routes/+layout.server.js45
-rw-r--r--src/routes/+layout.server.ts47
-rw-r--r--src/routes/+layout.svelte11
-rw-r--r--src/routes/+layout.ts14
-rw-r--r--src/routes/+page.server.js4
-rw-r--r--src/routes/+page.server.ts3
-rw-r--r--src/routes/+page.svelte15
-rw-r--r--src/routes/about/+server.ts (renamed from src/routes/about/+server.js)2
-rw-r--r--src/routes/map/+page.server.js11
-rw-r--r--src/routes/map/+page.server.ts11
-rw-r--r--src/routes/map/+page.svelte12
-rw-r--r--src/routes/start/+server.js11
-rw-r--r--src/routes/start/+server.ts10
-rw-r--r--src/service-worker.js37
270 files changed, 6868 insertions, 6507 deletions
diff --git a/src/app.html b/src/app.html
index 9d7e2fdb..5903f2ff 100644
--- a/src/app.html
+++ b/src/app.html
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
@@ -7,12 +7,22 @@
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
- <meta name="description" content="The easiest raysway to get started with bitcoin" />
+ <meta
+ name="description"
+ content="The easiest raysway to get started with bitcoin"
+ />
<meta name="keywords" content="open source bitcoin lightning web wallet" />
+ <meta name="theme-color" content="#fff" />
+ <meta name="apple-mobile-web-app-capable" content="yes" />
+ <meta
+ name="apple-mobile-web-app-status-bar-style"
+ content="black-translucent"
+ />
+ <link rel="apple-touch-icon" href="/images/icon-160.png" />
<link rel="manifest" href="/manifest.webmanifest" />
%sveltekit.head%
</head>
- <body>
- <div>%sveltekit.body%</div>
+ <body data-sveltekit-preload-data="hover">
+ <div style="display: contents">%sveltekit.body%</div>
</body>
</html>
diff --git a/src/components/About.svelte b/src/components/About.svelte
index 0087e350..01ff4c7c 100644
--- a/src/components/About.svelte
+++ b/src/components/About.svelte
@@ -90,6 +90,18 @@
>
{@html $t("about.locations.description")}
</p>
- <LocationsMap {locations} />
+ <!-- <LocationsMap {locations} /> -->
+
+ <a href="/map">
+ <div class="relative">
+ <img src="/map.png" class="mx-auto" />
+
+ <button
+ class="bg-black text-white border border-4 rounded-full px-6 py-2 font-bold hover:bg-secondary absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 text-2xl"
+ >
+ {$t("about.locations.viewMap")}
+ </button>
+ </div>
+ </a>
</div>
{/if}
diff --git a/src/components/Account.svelte b/src/components/Account.svelte
new file mode 100644
index 00000000..96aa1964
--- /dev/null
+++ b/src/components/Account.svelte
@@ -0,0 +1,58 @@
+<script>
+ import Icon from "$comp/Icon.svelte";
+ import Balance from "$comp/Balance.svelte";
+ import { t } from "$lib/translations";
+
+ export let user, rate, account, last;
+ let { name, seed, balance, id } = account;
+ $: type = seed ? "Savings" : "Cash";
+
+ $: refresh(account);
+ let refresh = (a) => ({ seed, balance, id } = a);
+
+ let setAccount = () => (document.cookie = `aid=${id}; path=/; max-age=86400`);
+</script>
+
+<a
+ href={`/payments`}
+ class="block space-y-2 border-black py-4"
+ class:border-b-8={!last}
+ on:click={setAccount}
+>
+ <div class="flex">
+ <Balance {balance} {user} {rate} />
+ <a href={`/payments`} class="contents" on:click={setAccount}>
+ <button class="ml-auto flex gap-1 mb-auto pb-4 pl-4">
+ <Icon icon="clock" style="w-8 my-auto" />
+ </button>
+ </a>
+ <a href={`/account/${id}`} class="contents">
+ <button class="flex gap-1 mb-auto pb-4 pl-4">
+ <Icon icon="settings" style="w-8 my-auto" />
+ </button>
+ </a>
+ </div>
+
+ <div class="flex justify-center w-full text-xl gap-2">
+ <a href={`/invoice`} class="contents" on:click={setAccount}>
+ <button class="py-5 px-6 hover:opacity-80 flex grow rounded-2xl">
+ <div class="mx-auto flex gap-2">
+ <Icon icon="receive" style="w-8" />
+ <div class="my-auto">{$t("user.dashboard.receive")}</div>
+ </div>
+ </button>
+ </a>
+
+ <a href={`/send`} class="contents grow" on:click={setAccount}>
+ <button
+ type="button"
+ class="py-5 px-6 hover:opacity-80 flex grow rounded-2xl"
+ >
+ <div class="mx-auto flex gap-1">
+ <Icon icon="send" style="w-8" />
+ <div class="my-auto">{$t("user.dashboard.send")}</div>
+ </div>
+ </button>
+ </a>
+ </div>
+</a>
diff --git a/src/components/AppHeader.svelte b/src/components/AppHeader.svelte
index 731f0260..9dd37d7e 100644
--- a/src/components/AppHeader.svelte
+++ b/src/components/AppHeader.svelte
@@ -7,11 +7,9 @@
import { loading, t } from "$lib/translations";
import { page } from "$app/stores";
- export let data;
+ export let user, subject;
- let { subject, user } = data;
- $: update(data);
- let update = (data) => ({ subject, user } = data);
+ $: if (!subject) subject = user;
let menuButtons;
$: if (user)
@@ -19,15 +17,15 @@
{
key: "nav.settings",
icon: "settings",
- href: `/${user.username}/settings`,
+ href: `/settings`,
},
{ key: "nav.support", icon: "support", href: `/support` },
- { key: "nav.map", icon: "map", href: `/${user.username}/map` },
- {
- key: "nav.messages",
- icon: "message",
- href: `/${user.username}/messages`,
- },
+ { key: "nav.map", icon: "map", href: `/map` },
+ // {
+ // key: "nav.messages",
+ // icon: "message",
+ // href: `/messages`,
+ // },
{ key: "nav.merch", icon: "shop", href: `https://coinosmerch.com` },
{ key: "nav.signOut", icon: "logout", href: `/logout` },
];
@@ -38,8 +36,10 @@
$banner?.id && $banner.id === subject.id
? `url(${$banner.src})`
: subject?.banner
- ? `url(/api/public/${subject.banner}.webp)`
- : undefined;
+ ? subject.banner.includes(":")
+ ? `url(${subject.banner})`
+ : `url(/api/public/${subject.banner}.webp)`
+ : undefined;
$: $page && (showMenu = false);
</script>
@@ -51,7 +51,7 @@
>
<nav class="flex justify-end items-center space-x-4 p-5">
{#if user}
- <a href={`/${user.username}`}>
+ <a href={`/${user.username}`} data-sveltekit-preload-code="eager">
<button
class="bg-white p-2 rounded-full w-12 h-12 sm:w-16 sm:h-16 drop-shadow-xl border border-black/10 {$page
.url.pathname === `/${user.username}`
@@ -62,17 +62,18 @@
</a>
<a href={`/${user.username}/receive`}>
<button
- class="bg-white p-2 rounded-full w-12 h-12 sm:w-16 sm:h-16 drop-shadow-xl border border-black/10 {$page
- .url.pathname === `/${user.username}/receive`
+ class="bg-white p-2 rounded-full w-12 h-12 sm:w-16 sm:h-16 drop-shadow-xl border border-black/10 {$page.url.pathname.includes(
+ 'invoice',
+ )
? 'opacity-100'
: 'opacity-70 hover:opacity-80'}"
- ><Icon icon="numpad" style="mx-auto w-6 sm:w-8" />
+ ><Icon icon="receive" style="mx-auto w-6 sm:w-8" />
</button>
</a>
- <a href={`/${user.username}/payments`}>
+ <a href={`/payments`} data-sveltekit-preload-code="eager">
<button
class="bg-white p-2 rounded-full w-12 h-12 sm:w-16 sm:h-16 drop-shadow-xl border border-black/10 {$page
- .url.pathname === `/${user.username}/payments`
+ .url.pathname === `/payments`
? 'opacity-100'
: 'opacity-70 hover:opacity-80'} relative"
><Icon icon="clock" style="mx-auto w-6 sm:w-8" />
@@ -90,7 +91,7 @@
{/if}
</button>
</a>
- <a href={`/send`}>
+ <a href={`/send`} data-sveltekit-preload-code="eager">
<button
class="bg-white p-2 rounded-full w-12 h-12 sm:w-16 sm:h-16 drop-shadow-xl border border-black/10 {$page
.url.pathname === `/send`
@@ -103,8 +104,7 @@
<OutClick on:outclick={() => (showMenu = false)}>
<button
class="bg-white p-2 rounded-full w-12 h-12 sm:w-16 sm:h-16 drop-shadow-xl border border-black/10 {$page
- .url.pathname === `/${user.username}` ||
- $page.url.pathname === `/${user.username}/settings` ||
+ .url.pathname === `/settings` ||
$page.url.pathname === `/support`
? 'opacity-100'
: `opacity-70 hover:opacity-80 ${
@@ -122,7 +122,7 @@
<ul class="space-y-5 w-48">
{#each menuButtons as { href, icon, key }}
<li>
- <a {href} data-sveltekit-prefetch="off">
+ <a {href} data-sveltekit-preload-code="eager">
<button
class="flex justify-center items-center font-semibold hover:opacity-80"
><Icon {icon} style="mr-2 w-6 sm:w-8" /> {$t(key)}
@@ -132,7 +132,7 @@
{/each}
</ul>
<hr class="my-4" />
- <a href="/"
+ <a href="/?stay=true"
><img src="/images/logo.svg" alt="Coinos" class="w-32" /></a
>
</div>
@@ -146,11 +146,13 @@
</a>
{/if}
</nav>
- <div
- class="absolute md:w-[64px] md:mx-auto lg:left-[154px] xl:left-[194px] left-[calc(50vw-64px)] -bottom-[64px] z-30"
- >
- <Avatar user={subject} />
- </div>
+ {#if subject}
+ <div
+ class="absolute md:w-[64px] md:mx-auto lg:left-[154px] xl:left-[194px] left-[calc(50vw-64px)] -bottom-[64px] z-30"
+ >
+ <Avatar user={subject} />
+ </div>
+ {/if}
</header>
{/if}
diff --git a/src/components/Avatar.svelte b/src/components/Avatar.svelte
index 227200d7..e91285da 100644
--- a/src/components/Avatar.svelte
+++ b/src/components/Avatar.svelte
@@ -8,14 +8,15 @@
export let disabled = false;
$: s = size.toString();
- $: link = user.anon ? `/${user.pubkey}` : `/${user.username}`;
+ $: link = user?.anon ? `/${user.pubkey}` : `/${user.username}`;
- $: src =
- ($avatar?.id && $avatar.id === user.id && $avatar.src) ||
- "/api/public/" +
- (user.profile
- ? user.profile + ".webp"
- : "punks/" + punk(user.pubkey || user.id || "aa"));
+ let base = "/api/public";
+ $: profile = user?.profile ? `${base}/${user.profile}.webp` : user?.picture;
+ $: fallback = `${base}/punks/` + punk(user.pubkey || user.id || "aa");
+ $: tmp = $avatar?.id && $avatar.id === user.id && $avatar.src;
+ $: src = tmp || profile || fallback;
+
+ let handle = () => (src = fallback);
</script>
<a href={link} class:pointer-events-none={disabled}>
@@ -26,6 +27,7 @@
{src}
class="w-full h-full object-cover object-center overflow-hidden"
alt={user.username}
+ on:error={handle}
/>
</div>
</a>
diff --git a/src/components/Balance.svelte b/src/components/Balance.svelte
index 4d5ac6bd..0cc27068 100644
--- a/src/components/Balance.svelte
+++ b/src/components/Balance.svelte
@@ -6,33 +6,33 @@
import { t } from "$lib/translations";
let show;
- export let user, rate;
+ export let user, rate, balance;
</script>
{#if show && user.haspin && $pin?.length !== 6}
<Pin cancel={() => (show = false)} />
{/if}
-<div class="space-y-2">
+<div>
{#if user.haspin && !$pin}
<button
- class="flex gap-2 text-xl rounded-2xl border py-5 px-6 hover:opacity-80 bg-black text-white font-bold"
- on:click={() => (show = true)}
- >
- <Icon icon="eye" style="w-8 invert my-auto" />
- <div class="my-auto">{$t("user.showBalance")}</div></button
+ on:click|preventDefault={() => (show = true)}
+ class="flex gap-2 text-xl"
>
+ <Icon icon="eye-off" style="w-8 my-auto" />
+ <div class="my-auto">{$t("user.showBalance")}</div>
+ </button>
{:else}
- <div class="text-5xl font-bold tabular-nums">
+ <div class="text-4xl font-bold tabular-nums">
{#if isNaN(rate)}
<div class="text-gray-200">&mdash;</div>
{:else}
- {f((user.balance * rate) / sats, user.currency)}
+ {f((balance * rate) / sats, user.currency)}
{/if}
</div>
- <div class="text-secondary text-2xl">
- ⚡️{s(user.balance)}
+ <div class="text-secondary text-xl">
+ ⚡️{s(balance)}
</div>
{/if}
</div>
diff --git a/src/components/Event.svelte b/src/components/Event.svelte
index d3a6c0af..640b9e68 100644
--- a/src/components/Event.svelte
+++ b/src/components/Event.svelte
@@ -14,12 +14,12 @@
return diff > d
? Math.round(diff / d) + "d"
: diff > h
- ? Math.round(diff / h) + "h"
- : diff > m
- ? Math.round(diff / m) + "m"
- : diff > 2
- ? diff + "s"
- : "now";
+ ? Math.round(diff / h) + "h"
+ : diff > m
+ ? Math.round(diff / m) + "m"
+ : diff > 2
+ ? diff + "s"
+ : "now";
};
let w;
diff --git a/src/components/Footer.svelte b/src/components/Footer.svelte
index d70c013c..ca711d7f 100644
--- a/src/components/Footer.svelte
+++ b/src/components/Footer.svelte
@@ -4,7 +4,10 @@
import { t } from "$lib/translations";
const followLinks = [
- { url: "https://twitter.com/coinoswallet", titleID: "twitter" },
+ {
+ url: "nostr:nprofile1qqst4qyeqenw7zm0fwjsty68h6cnys5jre2xd8ngqpjv5a2j26s78fspz4mhxue69uhhyetvv9ujucm0d9hx7uewd9hsgwx239",
+ titleID: "nostr",
+ },
{ url: "https://t.me/coinoswallet", titleID: "telegram" },
{ url: "https://linktr.ee/coinos.io", titleID: "linktree" },
];
diff --git a/src/components/Invoice.svelte b/src/components/Invoice.svelte
index ba436649..3298dfe5 100644
--- a/src/components/Invoice.svelte
+++ b/src/components/Invoice.svelte
@@ -19,7 +19,7 @@
<b
>{f(
($invoice.amount * $invoice.rate) / sats,
- $invoice.currency
+ $invoice.currency,
)}</b
>
{sat($invoice.amount)}
@@ -27,7 +27,7 @@
</div>
</div>
<div class="mx-auto my-auto flex gap-2">
- <a href={`/${invoice.user.username}/invoice/${$invoice.id}/tip`}>
+ <a href={`/invoice/${$invoice.id}/tip`}>
<button
class="rounded-full border py-2 px-4 font-bold hover:opacity-80 w-32"
>
diff --git a/src/components/Items.svelte b/src/components/Items.svelte
new file mode 100644
index 00000000..2916721d
--- /dev/null
+++ b/src/components/Items.svelte
@@ -0,0 +1,246 @@
+<script>
+ import { t } from "$lib/translations";
+ import { btc, f, sat, post } from "$lib/utils";
+ import { browser } from "$app/environment";
+ import { goto, invalidate } from "$app/navigation";
+ import { fade } from "svelte/transition";
+ import { cubicIn } from "svelte/easing";
+ import { flip } from "svelte/animate";
+ import {
+ dndzone,
+ SHADOW_ITEM_MARKER_PROPERTY_NAME,
+ SOURCES,
+ TRIGGERS,
+ } from "svelte-dnd-action";
+ import DeleteItem from "$comp/DeleteItem.svelte";
+ import Icon from "$comp/Icon.svelte";
+
+ export let subject, user, items, rate, currency, total;
+
+ let flipDurationMs = 200;
+ let dropTargetStyle = {};
+
+ let dragDisabled =
+ subject?.id !== user?.id || (browser && window.innerWidth < 768);
+
+ let deleting;
+ let del = (item) => {
+ deleting = item;
+ };
+
+ function handleConsider(e) {
+ const {
+ items: newItems,
+ info: { source, trigger },
+ } = e.detail;
+ items = newItems;
+ if (source === SOURCES.KEYBOARD && trigger === TRIGGERS.DRAG_STOPPED)
+ reset();
+ }
+
+ async function handleFinalize(e) {
+ const {
+ items: newItems,
+ info: { source },
+ } = e.detail;
+ items = newItems;
+ if (source === SOURCES.POINTER) reset();
+
+ if (subject?.id === user?.id) {
+ await post("/api/items/sort", { items });
+ invalidate("app:items");
+ }
+ }
+
+ function startDrag(e) {
+ e.preventDefault();
+ dragDisabled = false;
+ }
+
+ function handleKeyDown(e) {
+ if ((e.key === "Enter" || e.key === " ") && dragDisabled)
+ dragDisabled = false;
+ }
+
+ $: if (total > 0 && browser) {
+ let payButton = document.querySelector("#payButton");
+ if (payButton) payButton.addEventListener("click", checkout);
+ }
+
+ let checkout = async () => {
+ let invoice = {
+ type: "lightning",
+ amount: btc(total, rate),
+ currency,
+ items: items.filter((i) => i.quantity > 0),
+ prompt: subject.prompt,
+ memoPrompt: subject.memoPrompt,
+ rate,
+ };
+
+ let { id } = await post(`/invoice`, {
+ invoice,
+ user: { username: subject.username },
+ });
+
+ if (invoice.memoPrompt) {
+ return goto(`/invoice/${id}/memo`);
+ }
+ goto(`/invoice/${id}`);
+ };
+
+ let reset = () =>
+ (dragDisabled =
+ user?.username !== subject?.username || window.innerWidth < 768);
+</script>
+
+<svelte:window on:resize={reset} />
+
+{#if deleting}
+ <DeleteItem bind:item={deleting} />
+{/if}
+
+{#if items.length}
+ <h2 class="text-2xl font-bold">Select items</h2>
+{/if}
+<div
+ class="grid sm:grid-cols-2 gap-4 pb-20"
+ use:dndzone={{ items, flipDurationMs, dropTargetStyle, dragDisabled }}
+ on:consider={handleConsider}
+ on:finalize={handleFinalize}
+>
+ {#each items as i (i.id)}
+ <button
+ type="button"
+ class="w-full text-center cursor-pointer hover:opacity-80 mb-auto"
+ on:click={() => i.quantity++}
+ >
+ <div class="relative w-full h-64 overflow-hidden rounded-xl">
+ {#if i[SHADOW_ITEM_MARKER_PROPERTY_NAME]}
+ <div
+ in:fade={{ duration: 200, easing: cubicIn }}
+ class="custom-shadow-item"
+ />
+ {:else if i.image}
+ <img
+ src={`/api/public/${i.image}.webp`}
+ alt={i.name}
+ class="mx-auto object-cover h-full w-full"
+ />
+ {:else}
+ <div
+ class="bg-gradient-to-r from-primary to-gradient mb-4 cursor-pointer hover:opacity-80 w-full h-full"
+ alt="Banner"
+ />
+ {/if}
+ {#if user?.username === subject.username}
+ <div class="flex gap-2 justify-center absolute top-2 right-2">
+ <button type="button" on:click|stopPropagation={() => {}}>
+ <a href={`/items/${i.id}`}>
+ <button
+ class="bg-black rounded-full w-12 h-12 bg-opacity-40 hover:bg-opacity-100"
+ >
+ <Icon icon="edit" style="w-8 mx-auto invert" />
+ </button>
+ </a>
+ </button>
+ <button
+ class="bg-black rounded-full w-12 h-12 bg-opacity-40 hover:bg-opacity-100"
+ on:click|stopPropagation={() => del(i)}
+ >
+ <Icon icon="trash" style="w-8 mx-auto invert" />
+ </button>
+ <button
+ type="button"
+ on:click|stopPropagation={() => {}}
+ class="sm:hidden"
+ on:mousedown={startDrag}
+ on:touchstart={startDrag}
+ on:keydown={handleKeyDown}
+ >
+ <a href={`/items/${i.id}`}>
+ <button
+ class="bg-black rounded-full w-12 h-12 bg-opacity-40 hover:bg-opacity-100"
+ >
+ <Icon icon="move" style="w-8 mx-auto invert" />
+ </button>
+ </a>
+ </button>
+ </div>
+ {/if}
+ </div>
+ <div class="bg-white rounded-xl py-2">
+ <div class="flex text-left gap-2">
+ <div class="overflow-hidden space-y-1">
+ <div class="text-2xl break-words">{i.name}</div>
+ <div class="flex gap-2">
+ <div class="font-semibold text-lg">
+ {f(i.price, currency)}
+ </div>
+ <div class="text-secondary my-auto">
+ {sat(btc(i.price, rate))}
+ </div>
+ </div>
+ </div>
+ <div class="flex gap-1 ml-auto mb-auto justify-around tabular-nums">
+ {#if i.quantity}
+ <button
+ type="button"
+ on:click|stopPropagation={() => i.quantity > 0 && i.quantity--}
+ >
+ <Icon icon="minus" style="w-10 min-w-10" />
+ </button>
+ {/if}
+ <div class="text-2xl my-auto text-center">
+ {#if i.quantity}{i.quantity}{:else}&mdash;{/if}
+ </div>
+ {#if i.quantity}
+ <button
+ type="button"
+ on:click|stopPropagation={() => i.quantity++}
+ >
+ <Icon icon="plus" style="w-10 min-w-10" />
+ </button>
+ {/if}
+ </div>
+ </div>
+ </div>
+ </button>
+ {/each}
+</div>
+
+<div
+ class="fixed inset-x-0 mx-auto flex bottom-16"
+ class:static={!items.length}
+>
+ {#if total > 0}
+ <button
+ class="rounded-2xl py-5 px-6 font-bold hover:bg-neutral-700 flex bg-black text-white mx-auto"
+ on:click={checkout}
+ >
+ <div class="mx-auto flex">
+ <div class="my-auto text-2xl">
+ {$t("user.dashboard.checkout")}
+ {f(total, currency)}
+ <span class="text-base">
+ {sat(btc(total, rate), currency)}
+ </span>
+ </div>
+ </div>
+ </button>
+ {/if}
+</div>
+
+<style>
+ .custom-shadow-item {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ visibility: visible;
+ background: #333;
+ opacity: 0.5;
+ margin: 0;
+ }
+</style>
diff --git a/src/components/LandingHeader.svelte b/src/components/LandingHeader.svelte
index d1094a1d..72913999 100644
--- a/src/components/LandingHeader.svelte
+++ b/src/components/LandingHeader.svelte
@@ -19,22 +19,22 @@
</script>
<header
- class="w-full lg:w-5/6 py-5 mx-auto fixed md:sticky z-10 top-0 bg-white/90"
+ class="w-full lg:w-5/6 py-5 mx-auto fixed sticky z-10 top-0 bg-white/90"
bind:this={header}
>
- <nav class="block xl:flex flex-wrap justify-between items-center">
+ <nav class="block lg:flex justify-between items-center">
<div
- class="flex justify-start md:justify-center items-center md:space-x-10"
+ class="flex justify-start lg:justify-center items-center lg:space-x-10"
>
<a href="/" on:click={() => scroll(header)}>
- <Icon icon="logo" style="hidden md:block mb-5 xl:mb-0" />
- <Icon icon="logo" style="block md:hidden ml-5 w-48" />
+ <Icon icon="logo" style="hidden lg:block mb-5 xl:mb-0" />
+ <Icon icon="logo" style="block lg:hidden ml-5 w-48" />
</a>
</div>
<!-- desktop nav -->
<div
- class="hidden space-x-10 md:flex flex-wrap justify-center items-center font-bold"
+ class="hidden space-x-10 lg:flex justify-center items-center font-bold"
>
{#if $page.url.pathname === "/"}
<button class="hover:opacity-80" on:click={() => scroll(howItWorks)}
@@ -76,13 +76,13 @@
<!-- mobile nav -->
<button
- class="block md:hidden absolute top-[34.5px] right-10 z"
+ class="block lg:hidden absolute top-[34.5px] right-10 z"
on:click={() => (showMobileMenu = !showMobileMenu)}
><Icon icon={!showMobileMenu ? "menu" : "close"} />
</button>
<div
- class="container w-full px-10 md:hidden absolute top-0 {showMobileMenu
+ class="container w-full px-10 lg:hidden absolute top-0 {showMobileMenu
? 'right-0'
: 'right-[-100%]'} transition-all ease-in-out duration-300 h-[100vh] w-full bg-white"
>
diff --git a/src/components/LandingHero.svelte b/src/components/LandingHero.svelte
index 43223499..154944fa 100644
--- a/src/components/LandingHero.svelte
+++ b/src/components/LandingHero.svelte
@@ -1,4 +1,5 @@
<script>
+ import { focus } from "$lib/utils";
import { goto } from "$app/navigation";
import Icon from "$comp/Icon.svelte";
import Image from "$comp/Image.svelte";
@@ -29,6 +30,7 @@
<div class="flex justify-center">
<a href="/register">
<button
+ use:focus
class="bg-black text-white border rounded-full px-6 py-2 font-bold hover:opacity-80"
>
{$t("nav.startInSeconds")}
diff --git a/src/components/Lnurlp.svelte b/src/components/Lnurlp.svelte
index 6785061a..5f075607 100644
--- a/src/components/Lnurlp.svelte
+++ b/src/components/Lnurlp.svelte
@@ -5,9 +5,10 @@
import Spinner from "$comp/Spinner.svelte";
import { pin } from "$lib/store";
- export let data, form, send;
+ export let data, form, send, comment;
let { currency } = data.user;
- let { minSendable, maxSendable, callback, metadata, rates } = data;
+ let { minSendable, maxSendable, commentAllowed, callback, metadata, rates } =
+ data;
$: rate = rates[currency];
@@ -16,7 +17,7 @@
let submit = () => (loading = true);
</script>
-<div class="container px-4 mt-20 max-w-xl mx-auto">
+<div class="container px-4 mt-20 max-w-xl mx-auto space-y-2">
<div class="text-center mb-8">
{#each JSON.parse(metadata) as m}
<div>
@@ -45,6 +46,16 @@
<input name="callback" value={callback} type="hidden" />
<input name="pin" value={$pin} type="hidden" />
+ {#if commentAllowed}
+ <textarea
+ name="comment"
+ placeholder={$t("payments.message")}
+ class="w-full p-4 border rounded-xl h-32 text-xl"
+ bind:value={comment}
+ autocapitalize="none"
+ />
+ {/if}
+
<div class="flex w-full">
<button
bind:this={send}
diff --git a/src/components/Lnurlw.svelte b/src/components/Lnurlw.svelte
index b83e648f..2062c849 100644
--- a/src/components/Lnurlw.svelte
+++ b/src/components/Lnurlw.svelte
@@ -1,4 +1,5 @@
<script>
+ import { sats, f, s } from "$lib/utils";
import { t } from "$lib/translations";
import { enhance } from "$app/forms";
import Numpad from "$comp/Numpad.svelte";
@@ -18,10 +19,11 @@
} = data;
$: rate = rates[currency];
- let amount = Math.round(maxWithdrawable / 1000),
+ let amount = Math.round(minWithdrawable / 1000),
loading;
let submit = () => (loading = true);
+ $: amountFiat = parseFloat(((amount * rate) / sats).toFixed(2));
</script>
<div class="container px-4 mt-20 max-w-xl mx-auto">
@@ -39,7 +41,20 @@
</div>
{/if}
- <Numpad bind:amount {currency} bind:rate />
+ {#if minWithdrawable === maxWithdrawable}
+ <div class="text-center font-bold text-2xl mb-4">
+ <div>
+ {f(amountFiat, currency)}
+ </div>
+ <div>
+ <span class="text-secondary font-normal text-xl"
+ >⚡️{`${s(amount)}`}</span
+ >
+ </div>
+ </div>
+ {:else}
+ <Numpad bind:amount {currency} bind:rate />
+ {/if}
<form action="?/withdraw" method="POST" use:enhance on:submit={submit}>
<input name="amount" value={amount} type="hidden" />
diff --git a/src/components/LocationsMap.svelte b/src/components/LocationsMap.svelte
index b41b1a73..4c3532b3 100644
--- a/src/components/LocationsMap.svelte
+++ b/src/components/LocationsMap.svelte
@@ -3,7 +3,7 @@
import { browser } from "$app/environment";
import Icon from "$comp/Icon.svelte";
import Popup from "$comp/Popup.svelte";
- import { shuffleArray } from "$lib/utils";
+ import { back } from "$lib/utils";
import "maplibre-gl/dist/maplibre-gl.css";
@@ -11,6 +11,8 @@
let map;
let mapContainer, mapWrapper;
let markers = [];
+ let search;
+ let clearSearch = (e) => (search = "");
let currentIndex = -1;
let timeout;
@@ -47,13 +49,32 @@
}
};
+ $: list = search
+ ? markers.filter((m) =>
+ m.tags.name.toLowerCase().includes(search.toLowerCase()),
+ )
+ : inview;
+
+ let scroll = () => {
+ const el = document.querySelector(".selected");
+ if (el)
+ el.scrollIntoView({
+ behavior: "smooth",
+ block: "nearest",
+ inline: "nearest",
+ });
+ };
+
+ let selected;
function select(m) {
+ selected = m;
stopFlying();
currentIndex = inview.indexOf(m);
- flyToMarker(m);
+ flyToMarker(m, 500);
}
- async function flyToMarker(marker) {
+ async function flyToMarker(marker, duration = 1500) {
+ if (!marker) return;
map.flyTo({
zoom: 12,
center: marker.getLngLat(),
@@ -61,24 +82,25 @@
easing: function (t) {
return 1 - Math.pow(1 - t, 3);
},
- duration: 3000,
+ duration,
});
- await new Promise((r) => setTimeout(r, 3000));
+ await new Promise((r) => setTimeout(r, duration));
marker.getElement().click();
- await new Promise((r) => setTimeout(r, 1500));
+ updateLabelVisibility();
+ await new Promise((r) => setTimeout(r, 2500));
if (!timeout) return;
-
- map.flyTo({
- zoom: 10.5,
- center: marker.getLngLat(),
- essential: true,
- easing: function (t) {
- return 1 - Math.pow(1 - t, 3);
- },
- duration: 1500,
- });
+ //
+ // map.flyTo({
+ // zoom: 10.5,
+ // center: marker.getLngLat(),
+ // essential: true,
+ // easing: function (t) {
+ // return 1 - Math.pow(1 - t, 3);
+ // },
+ // duration: 1000,
+ // });
}
let toggle = () => {
@@ -86,6 +108,9 @@
else startFlying();
};
+ let toggleList = () => (showList = !showList);
+ let showList;
+
let currentPopup;
function startFlying() {
currentIndex++;
@@ -94,10 +119,31 @@
if (currentIndex >= inview.length) currentIndex = 0;
flyToMarker(inview[currentIndex]);
- timeout = setTimeout(startFlying, 6000);
+ timeout = setTimeout(startFlying, 4000);
+ }
+
+ function debounce(func, delay) {
+ let timeout;
+ let immediate = true;
+
+ return function (...args) {
+ const context = this;
+
+ if (immediate) {
+ func.apply(context, args);
+ immediate = false;
+ }
+
+ clearTimeout(timeout);
+
+ timeout = setTimeout(() => {
+ immediate = true;
+ }, delay);
+ };
}
function stopFlying() {
+ updateLabelVisibility();
if (!timeout) return;
timeout = clearTimeout(timeout);
@@ -106,12 +152,12 @@
}
map.jumpTo({ center: map.getCenter(), zoom: map.getZoom() });
- map.off("moveend"); // Remove moveend listener if set
+ map.off("moveend");
}
let inview = [];
- function updateLabelVisibility() {
+ let updateLabelVisibility = debounce(() => {
inview = [];
if (!map) return;
let zoom = map.getZoom();
@@ -127,9 +173,9 @@
}
inview = inview.sort((a, b) => a.tags.name.localeCompare(b.tags.name));
- shuffleArray(inview);
- }
+ }, 200);
+ let locationMarkers = {};
let popups = {};
let counter = 0;
@@ -155,12 +201,12 @@
let popupContainer = document.createElement("div");
- let popup = new Popup({
+ new Popup({
target: popupContainer,
props: { tags },
});
- let marker = new maplibre.Marker({ color: "#F7931A" })
+ let marker = new maplibre.Marker({ color: "#F7931A", scale: 0.65 })
.setLngLat([lon, lat])
.setPopup(new maplibre.Popup().setDOMContent(popupContainer))
.addTo(map);
@@ -171,29 +217,23 @@
let p = marker.getPopup();
popups[marker.id] = p;
p.setDOMContent(popupContainer);
+ setTimeout(() => {
+ selected = marker;
+ setTimeout(scroll, 10);
+ }, 50);
p.on("close", () => {
+ selected = undefined;
delete popups[marker.id];
});
});
marker.tags = tags;
+ locationMarkers[location.id] = marker;
markers.push(marker);
});
updateLabelVisibility();
-
- let observer = new IntersectionObserver(
- (entries, observer) => {
- entries.forEach((entry) => {
- if (entry.isIntersecting) startFlying();
- else stopFlying();
- });
- },
- { threshold: 0.5 }
- );
-
- observer.observe(mapContainer);
});
map.on("mousedown", stopFlying);
@@ -214,45 +254,69 @@
onDestroy(() => map && map.remove());
</script>
-<div class="container mx-auto p-2 space-y-5">
- <div class="flex w-full h-[60vh]" id="map" bind:this={mapWrapper}>
- <div
- id="map-container"
- class="mx-auto h-full w-full z-0"
- bind:this={mapContainer}
- />
- <div class="relative">
- <div class="flex absolute flex top-2 right-2 gap-2">
- <button
- class="rounded-full border-2 border-black bg-white w-10 h-10"
- on:click={toggle}
- >
- {#if timeout}
- <Icon icon="pause" style="w-4 m-auto" />
- {:else}
- <Icon icon="play" style="w-4 m-auto" />
- {/if}
- </button>
- <button
- class="rounded-full border-2 border-black bg-white w-10 h-10"
- on:click={full}
- >
- <Icon icon="full" style="w-4 m-auto" />
- </button>
+<div class="w-screen h-dvh flex" id="map" bind:this={mapWrapper}>
+ <div
+ id="map-container"
+ class="mx-auto h-full w-full z-0"
+ bind:this={mapContainer}
+ />
+ <div class="absolute flex top-2 left-2 gap-2">
+ <button
+ class="rounded-full border-2 border-black bg-white w-10 h-10"
+ on:click={back}
+ >
+ <Icon icon="arrow-left" style="w-4 m-auto" />
+ </button>
+ </div>
+ <div class="relative">
+ {#if !showList}
+ <div
+ class="space-y-1 text-sm w-[300px] max-w-[calc(100vw*0.5)] h-[300px] max-h-[calc(100vh*0.4)] overflow-y-scroll p-4 bg-opacity-90 bg-primary absolute right-4 bottom-8 rounded-2xl shadow text-ellipsis overflow-x-hidden"
+ >
+ <div class="relative mb-4 sticky top-0 bg-primary z-10">
+ <input bind:value={search} class="w-full" />
+ <div class="flex gap-1 absolute right-6 top-3">
+ {#if search}
+ <button on:click={clearSearch}>
+ <Icon icon="close" style="w-8" />
+ </button>
+ {:else}
+ <Icon icon="search" style="w-8" />
+ {/if}
+ </div>
+ </div>
+
+ {#each list as marker, i}
+ <button
+ on:click={() => select(marker)}
+ class:font-bold={selected === marker}
+ class:selected={selected === marker}
+ class="block whitespace-nowrap text-ellipsis text-left w-full overflow-hidden"
+ >
+ {marker.tags.name}
+ </button>
+ {/each}
</div>
+ {/if}
+ <div class="absolute flex top-2 right-2 gap-2">
+ <button
+ class="rounded-full border-2 border-black bg-white w-10 h-10"
+ on:click={toggleList}
+ >
+ <Icon icon="list" style="w-4 m-auto" />
+ </button>
+ <button
+ class="rounded-full border-2 border-black bg-white w-10 h-10"
+ on:click={toggle}
+ >
+ {#if timeout}
+ <Icon icon="pause" style="w-4 m-auto" />
+ {:else}
+ <Icon icon="play" style="w-4 m-auto" />
+ {/if}
+ </button>
</div>
</div>
-
- <!-- <div class="hidden lg:grid grid-cols-3 justify-items-center"> -->
- <!-- {#each inview as m} -->
- <!-- <button -->
- <!-- on:click={() => select(m)} -->
- <!-- class="text-left" -->
- <!-- class:font-bold={m.id === inview[currentIndex]?.id} -->
- <!-- id={`marker-${m.id}`}>{m.tags.name}</button -->
- <!-- > -->
- <!-- {/each} -->
- <!-- </div> -->
</div>
<style>
diff --git a/src/components/Mnemonic.svelte b/src/components/Mnemonic.svelte
new file mode 100644
index 00000000..41e81d9a
--- /dev/null
+++ b/src/components/Mnemonic.svelte
@@ -0,0 +1,16 @@
+<script>
+ export let mnemonic;
+</script>
+
+<div class="flex w-full border p-4 rounded-2xl h-full">
+ <div
+ class="text-secondary grid grid-flow-col grid-rows-6 sm:grid-rows-none grid-cols-2 sm:grid-cols-3 sm:grid-flow-row gap-x-8 gap-y-2 justify-center whitespace-nowrap m-auto"
+ >
+ {#each mnemonic.split(" ") as w, i}
+ <div>
+ <span class="select-none text-black">{i + 1}.</span>
+ <span>{@html w === "-" ? "&mdash;" : w}</span>
+ </div>
+ {/each}
+ </div>
+</div>
diff --git a/src/components/Numpad.svelte b/src/components/Numpad.svelte
index 9119999f..5b9aaa01 100644
--- a/src/components/Numpad.svelte
+++ b/src/components/Numpad.svelte
@@ -1,7 +1,7 @@
<script>
import Left from "$comp/Left.svelte";
import Icon from "$comp/Icon.svelte";
- import { f, s, focus, post, warning, sat, sats } from "$lib/utils";
+ import { f, s, focus, warning, sat, sats } from "$lib/utils";
import { t } from "$lib/translations";
export let amount,
@@ -183,8 +183,8 @@
e.key === "Enter" && (e.preventDefault() || submit.click());
</script>
-<div class="flex justify-center items-center mb-3 px-3">
- <div class="space-y-5">
+<div class="flex justify-center items-center">
+ <div class="space-y-5 w-full">
<div class="text-center">
<div
class="text-5xl md:text-6xl font-semibold tracking-widest flex justify-center"
@@ -206,11 +206,11 @@
</div>
<div class="mt-2">
<span class="text-secondary mr-1"
- >{fiat ? sat(amount) : f(amountFiat, currency)}</span
+ >{fiat ? "⚡️" + s(amount) : f(amountFiat, currency)}</span
>
<button
type="button"
- on:click={() => {
+ on:click|preventDefault|stopPropagation={() => {
if (fiat) {
amount = parseInt((amountFiat / (rate / sats)).toFixed(0));
} else {
@@ -225,13 +225,13 @@
</div>
</div>
- <div class="grid grid-cols-3 gap-2 w-[300px] mx-auto">
+ <div class="grid grid-cols-3 gap-2 w-full mx-auto">
{#each numPad as value}
{#if value === arrow}
<button
type="button"
class="bg-primary rounded-xl py-4 px-8 font-semibold active:bg-black active:text-white flex justify-center items-center hover:opacity-80"
- on:click={() => handleInput(value)}
+ on:click|preventDefault|stopPropagation={() => handleInput(value)}
>
<Left />
</button>
@@ -239,7 +239,8 @@
<button
type="button"
class="bg-primary rounded-xl py-4 px-8 font-semibold active:bg-black active:text-white hover:opacity-80"
- on:click={() => handleInput(value)}>{value}</button
+ on:click|preventDefault|stopPropagation={() => handleInput(value)}
+ >{value}</button
>
{/if}
{/each}
diff --git a/src/components/Pinpad.svelte b/src/components/Pinpad.svelte
index 337b53d4..585a7942 100644
--- a/src/components/Pinpad.svelte
+++ b/src/components/Pinpad.svelte
@@ -73,7 +73,7 @@
<button
type="button"
class="bg-primary rounded-xl py-4 px-8 font-semibold active:bg-black active:text-white flex justify-center items-center hover:opacity-80"
- on:click={() => handleInput(value)}
+ on:click|stopPropagation|preventDefault={() => handleInput(value)}
>
<Left />
</button>
@@ -81,7 +81,8 @@
<button
type="button"
class="bg-primary rounded-xl py-4 px-8 font-semibold active:bg-black active:text-white hover:opacity-80"
- on:click={() => handleInput(value)}>{value}</button
+ on:click|stopPropagation|preventDefault={() => handleInput(value)}
+ >{value}</button
>
{/if}
{/each}
diff --git a/src/components/Request.svelte b/src/components/Request.svelte
deleted file mode 100644
index c085f9e2..00000000
--- a/src/components/Request.svelte
+++ /dev/null
@@ -1,39 +0,0 @@
-<script>
- import { t } from "$lib/translations";
- import { fly } from "svelte/transition";
-
- import Avatar from "$comp/Avatar.svelte";
- import Icon from "$comp/Icon.svelte";
-
- import { request, requestRedirect } from "$lib/store";
- import { page } from "$app/stores";
-
- export let user;
-
- $requestRedirect = $page.url.pathname;
-</script>
-
-{#if $request}
- <div class="fixed bottom-0 border-t w-full p-4 bg-white z-50" in:fly>
- <div class="flex flex-wrap md:flex-nowrap max-w-xl mx-auto gap-2">
- <div class="my-auto mx-auto">
- <div class="flex">
- <Avatar user={$request.requester} size={12} />
- <h1 class="my-auto">
- <b>{$request.requester.username}</b>
- {$t("payments.readyToPay")}
- </h1>
- </div>
- </div>
- <div class="mx-auto my-auto flex gap-2">
- <a href={`/${user.username}/receive/${$request.id}`}>
- <button
- class="rounded-full border py-2 px-4 font-bold hover:opacity-80 w-32"
- >
- {$t("payments.invoice")}
- </button>
- </a>
- </div>
- </div>
- </div>
-{/if}
diff --git a/src/components/WalletPass.svelte b/src/components/WalletPass.svelte
new file mode 100644
index 00000000..75c94f34
--- /dev/null
+++ b/src/components/WalletPass.svelte
@@ -0,0 +1,65 @@
+<script>
+ import { focus } from "$lib/utils";
+ import { t } from "$lib/translations";
+ import Icon from "$comp/Icon.svelte";
+ export let cancel, password, submit;
+ let revealPassword;
+</script>
+
+<div
+ class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-20"
+>
+ <div
+ class="relative top-1/3 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white space-y-5"
+ >
+ <h1 class="text-center text-2xl font-semibold">
+ {$t("payments.enterWalletPass")}
+ </h1>
+ <form on:submit|preventDefault={submit}>
+ <div class="relative mb-5">
+ {#if revealPassword}
+ <input
+ name="password"
+ type="text"
+ required
+ bind:value={password}
+ autocapitalize="none"
+ use:focus
+ />
+ {:else}
+ <input
+ name="password"
+ type="password"
+ required
+ bind:value={password}
+ autocapitalize="none"
+ use:focus
+ />
+ {/if}
+ <button
+ type="button"
+ on:click={() => (revealPassword = !revealPassword)}
+ class="absolute right-5 top-1/2"
+ >
+ <Icon icon={revealPassword ? "eye" : "eye-off"} />
+ </button>
+ </div>
+ <div class="w-full flex justify-center gap-2">
+ <button
+ type="button"
+ class="border rounded-2xl font-semibold mx-auto py-5 px-6 hover:opacity-80 mx-auto grow"
+ on:click={cancel}
+ on:keydown={cancel}
+ >
+ <div class="my-auto">Cancel</div>
+ </button>
+ <button
+ type="submit"
+ class="border rounded-2xl font-semibold mx-auto py-5 px-6 hover:opacity-80 mx-auto grow"
+ >
+ <div class="my-auto">Submit</div>
+ </button>
+ </div>
+ </form>
+ </div>
+</div>
diff --git a/src/lib/english.js b/src/lib/english.js
deleted file mode 100644
index 52a0da82..00000000
--- a/src/lib/english.js
+++ /dev/null
@@ -1,2048 +0,0 @@
-export default `abandon
-ability
-able
-about
-above
-absent
-absorb
-abstract
-absurd
-abuse
-access
-accident
-account
-accuse
-achieve
-acid
-acoustic
-acquire
-across
-act
-action
-actor
-actress
-actual
-adapt
-add
-addict
-address
-adjust
-admit
-adult
-advance
-advice
-aerobic
-affair
-afford
-afraid
-again
-age
-agent
-agree
-ahead
-aim
-air
-airport
-aisle
-alarm
-album
-alcohol
-alert
-alien
-all
-alley
-allow
-almost
-alone
-alpha
-already
-also
-alter
-always
-amateur
-amazing
-among
-amount
-amused
-analyst
-anchor
-ancient
-anger
-angle
-angry
-animal
-ankle
-announce
-annual
-another
-answer
-antenna
-antique
-anxiety
-any
-apart
-apology
-appear
-apple
-approve
-april
-arch
-arctic
-area
-arena
-argue
-arm
-armed
-armor
-army
-around
-arrange
-arrest
-arrive
-arrow
-art
-artefact
-artist
-artwork
-ask
-aspect
-assault
-asset
-assist
-assume
-asthma
-athlete
-atom
-attack
-attend
-attitude
-attract
-auction
-audit
-august
-aunt
-author
-auto
-autumn
-average
-avocado
-avoid
-awake
-aware
-away
-awesome
-awful
-awkward
-axis
-baby
-bachelor
-bacon
-badge
-bag
-balance
-balcony
-ball
-bamboo
-banana
-banner
-bar
-barely
-bargain
-barrel
-base
-basic
-basket
-battle
-beach
-bean
-beauty
-because
-become
-beef
-before
-begin
-behave
-behind
-believe
-below
-belt
-bench
-benefit
-best
-betray
-better
-between
-beyond
-bicycle
-bid
-bike
-bind
-biology
-bird
-birth
-bitter
-black
-blade
-blame
-blanket
-blast
-bleak
-bless
-blind
-blood
-blossom
-blouse
-blue
-blur
-blush
-board
-boat
-body
-boil
-bomb
-bone
-bonus
-book
-boost
-border
-boring
-borrow
-boss
-bottom
-bounce
-box
-boy
-bracket
-brain
-brand
-brass
-brave
-bread
-breeze
-brick
-bridge
-brief
-bright
-bring
-brisk
-broccoli
-broken
-bronze
-broom
-brother
-brown
-brush
-bubble
-buddy
-budget
-buffalo
-build
-bulb
-bulk
-bullet
-bundle
-bunker
-burden
-burger
-burst
-bus
-business
-busy
-butter
-buyer
-buzz
-cabbage
-cabin
-cable
-cactus
-cage
-cake
-call
-calm
-camera
-camp
-can
-canal
-cancel
-candy
-cannon
-canoe
-canvas
-canyon
-capable
-capital
-captain
-car
-carbon
-card
-cargo
-carpet
-carry
-cart
-case
-cash
-casino
-castle
-casual
-cat
-catalog
-catch
-category
-cattle
-caught
-cause
-caution
-cave
-ceiling
-celery
-cement
-census
-century
-cereal
-certain
-chair
-chalk
-champion
-change
-chaos
-chapter
-charge
-chase
-chat
-cheap
-check
-cheese
-chef
-cherry
-chest
-chicken
-chief
-child
-chimney
-choice
-choose
-chronic
-chuckle
-chunk
-churn
-cigar
-cinnamon
-circle
-citizen
-city
-civil
-claim
-clap
-clarify
-claw
-clay
-clean
-clerk
-clever
-click
-client
-cliff
-climb
-clinic
-clip
-clock
-clog
-close
-cloth
-cloud
-clown
-club
-clump
-cluster
-clutch
-coach
-coast
-coconut
-code
-coffee
-coil
-coin
-collect
-color
-column
-combine
-come
-comfort
-comic
-common
-company
-concert
-conduct
-confirm
-congress
-connect
-consider
-control
-convince
-cook
-cool
-copper
-copy
-coral
-core
-corn
-correct
-cost
-cotton
-couch
-country
-couple
-course
-cousin
-cover
-coyote
-crack
-cradle
-craft
-cram
-crane
-crash
-crater
-crawl
-crazy
-cream
-credit
-creek
-crew
-cricket
-crime
-crisp
-critic
-crop
-cross
-crouch
-crowd
-crucial
-cruel
-cruise
-crumble
-crunch
-crush
-cry
-crystal
-cube
-culture
-cup
-cupboard
-curious
-current
-curtain
-curve
-cushion
-custom
-cute
-cycle
-dad
-damage
-damp
-dance
-danger
-daring
-dash
-daughter
-dawn
-day
-deal
-debate
-debris
-decade
-december
-decide
-decline
-decorate
-decrease
-deer
-defense
-define
-defy
-degree
-delay
-deliver
-demand
-demise
-denial
-dentist
-deny
-depart
-depend
-deposit
-depth
-deputy
-derive
-describe
-desert
-design
-desk
-despair
-destroy
-detail
-detect
-develop
-device
-devote
-diagram
-dial
-diamond
-diary
-dice
-diesel
-diet
-differ
-digital
-dignity
-dilemma
-dinner
-dinosaur
-direct
-dirt
-disagree
-discover
-disease
-dish
-dismiss
-disorder
-display
-distance
-divert
-divide
-divorce
-dizzy
-doctor
-document
-dog
-doll
-dolphin
-domain
-donate
-donkey
-donor
-door
-dose
-double
-dove
-draft
-dragon
-drama
-drastic
-draw
-dream
-dress
-drift
-drill
-drink
-drip
-drive
-drop
-drum
-dry
-duck
-dumb
-dune
-during
-dust
-dutch
-duty
-dwarf
-dynamic
-eager
-eagle
-early
-earn
-earth
-easily
-east
-easy
-echo
-ecology
-economy
-edge
-edit
-educate
-effort
-egg
-eight
-either
-elbow
-elder
-electric
-elegant
-element
-elephant
-elevator
-elite
-else
-embark
-embody
-embrace
-emerge
-emotion
-employ
-empower
-empty
-enable
-enact
-end
-endless
-endorse
-enemy
-energy
-enforce
-engage
-engine
-enhance
-enjoy
-enlist
-enough
-enrich
-enroll
-ensure
-enter
-entire
-entry
-envelope
-episode
-equal
-equip
-era
-erase
-erode
-erosion
-error
-erupt
-escape
-essay
-essence
-estate
-eternal
-ethics
-evidence
-evil
-evoke
-evolve
-exact
-example
-excess
-exchange
-excite
-exclude
-excuse
-execute
-exercise
-exhaust
-exhibit
-exile
-exist
-exit
-exotic
-expand
-expect
-expire
-explain
-expose
-express
-extend
-extra
-eye
-eyebrow
-fabric
-face
-faculty
-fade
-faint
-faith
-fall
-false
-fame
-family
-famous
-fan
-fancy
-fantasy
-farm
-fashion
-fat
-fatal
-father
-fatigue
-fault
-favorite
-feature
-february
-federal
-fee
-feed
-feel
-female
-fence
-festival
-fetch
-fever
-few
-fiber
-fiction
-field
-figure
-file
-film
-filter
-final
-find
-fine
-finger
-finish
-fire
-firm
-first
-fiscal
-fish
-fit
-fitness
-fix
-flag
-flame
-flash
-flat
-flavor
-flee
-flight
-flip
-float
-flock
-floor
-flower
-fluid
-flush
-fly
-foam
-focus
-fog
-foil
-fold
-follow
-food
-foot
-force
-forest
-forget
-fork
-fortune
-forum
-forward
-fossil
-foster
-found
-fox
-fragile
-frame
-frequent
-fresh
-friend
-fringe
-frog
-front
-frost
-frown
-frozen
-fruit
-fuel
-fun
-funny
-furnace
-fury
-future
-gadget
-gain
-galaxy
-gallery
-game
-gap
-garage
-garbage
-garden
-garlic
-garment
-gas
-gasp
-gate
-gather
-gauge
-gaze
-general
-genius
-genre
-gentle
-genuine
-gesture
-ghost
-giant
-gift
-giggle
-ginger
-giraffe
-girl
-give
-glad
-glance
-glare
-glass
-glide
-glimpse
-globe
-gloom
-glory
-glove
-glow
-glue
-goat
-goddess
-gold
-good
-goose
-gorilla
-gospel
-gossip
-govern
-gown
-grab
-grace
-grain
-grant
-grape
-grass
-gravity
-great
-green
-grid
-grief
-grit
-grocery
-group
-grow
-grunt
-guard
-guess
-guide
-guilt
-guitar
-gun
-gym
-habit
-hair
-half
-hammer
-hamster
-hand
-happy
-harbor
-hard
-harsh
-harvest
-hat
-have
-hawk
-hazard
-head
-health
-heart
-heavy
-hedgehog
-height
-hello
-helmet
-help
-hen
-hero
-hidden
-high
-hill
-hint
-hip
-hire
-history
-hobby
-hockey
-hold
-hole
-holiday
-hollow
-home
-honey
-hood
-hope
-horn
-horror
-horse
-hospital
-host
-hotel
-hour
-hover
-hub
-huge
-human
-humble
-humor
-hundred
-hungry
-hunt
-hurdle
-hurry
-hurt
-husband
-hybrid
-ice
-icon
-idea
-identify
-idle
-ignore
-ill
-illegal
-illness
-image
-imitate
-immense
-immune
-impact
-impose
-improve
-impulse
-inch
-include
-income
-increase
-index
-indicate
-indoor
-industry
-infant
-inflict
-inform
-inhale
-inherit
-initial
-inject
-injury
-inmate
-inner
-innocent
-input
-inquiry
-insane
-insect
-inside
-inspire
-install
-intact
-interest
-into
-invest
-invite
-involve
-iron
-island
-isolate
-issue
-item
-ivory
-jacket
-jaguar
-jar
-jazz
-jealous
-jeans
-jelly
-jewel
-job
-join
-joke
-journey
-joy
-judge
-juice
-jump
-jungle
-junior
-junk
-just
-kangaroo
-keen
-keep
-ketchup
-key
-kick
-kid
-kidney
-kind
-kingdom
-kiss
-kit
-kitchen
-kite
-kitten
-kiwi
-knee
-knife
-knock
-know
-lab
-label
-labor
-ladder
-lady
-lake
-lamp
-language
-laptop
-large
-later
-latin
-laugh
-laundry
-lava
-law
-lawn
-lawsuit
-layer
-lazy
-leader
-leaf
-learn
-leave
-lecture
-left
-leg
-legal
-legend
-leisure
-lemon
-lend
-length
-lens
-leopard
-lesson
-letter
-level
-liar
-liberty
-library
-license
-life
-lift
-light
-like
-limb
-limit
-link
-lion
-liquid
-list
-little
-live
-lizard
-load
-loan
-lobster
-local
-lock
-logic
-lonely
-long
-loop
-lottery
-loud
-lounge
-love
-loyal
-lucky
-luggage
-lumber
-lunar
-lunch
-luxury
-lyrics
-machine
-mad
-magic
-magnet
-maid
-mail
-main
-major
-make
-mammal
-man
-manage
-mandate
-mango
-mansion
-manual
-maple
-marble
-march
-margin
-marine
-market
-marriage
-mask
-mass
-master
-match
-material
-math
-matrix
-matter
-maximum
-maze
-meadow
-mean
-measure
-meat
-mechanic
-medal
-media
-melody
-melt
-member
-memory
-mention
-menu
-mercy
-merge
-merit
-merry
-mesh
-message
-metal
-method
-middle
-midnight
-milk
-million
-mimic
-mind
-minimum
-minor
-minute
-miracle
-mirror
-misery
-miss
-mistake
-mix
-mixed
-mixture
-mobile
-model
-modify
-mom
-moment
-monitor
-monkey
-monster
-month
-moon
-moral
-more
-morning
-mosquito
-mother
-motion
-motor
-mountain
-mouse
-move
-movie
-much
-muffin
-mule
-multiply
-muscle
-museum
-mushroom
-music
-must
-mutual
-myself
-mystery
-myth
-naive
-name
-napkin
-narrow
-nasty
-nation
-nature
-near
-neck
-need
-negative
-neglect
-neither
-nephew
-nerve
-nest
-net
-network
-neutral
-never
-news
-next
-nice
-night
-noble
-noise
-nominee
-noodle
-normal
-north
-nose
-notable
-note
-nothing
-notice
-novel
-now
-nuclear
-number
-nurse
-nut
-oak
-obey
-object
-oblige
-obscure
-observe
-obtain
-obvious
-occur
-ocean
-october
-odor
-off
-offer
-office
-often
-oil
-okay
-old
-olive
-olympic
-omit
-once
-one
-onion
-online
-only
-open
-opera
-opinion
-oppose
-option
-orange
-orbit
-orchard
-order
-ordinary
-organ
-orient
-original
-orphan
-ostrich
-other
-outdoor
-outer
-output
-outside
-oval
-oven
-over
-own
-owner
-oxygen
-oyster
-ozone
-pact
-paddle
-page
-pair
-palace
-palm
-panda
-panel
-panic
-panther
-paper
-parade
-parent
-park
-parrot
-party
-pass
-patch
-path
-patient
-patrol
-pattern
-pause
-pave
-payment
-peace
-peanut
-pear
-peasant
-pelican
-pen
-penalty
-pencil
-people
-pepper
-perfect
-permit
-person
-pet
-phone
-photo
-phrase
-physical
-piano
-picnic
-picture
-piece
-pig
-pigeon
-pill
-pilot
-pink
-pioneer
-pipe
-pistol
-pitch
-pizza
-place
-planet
-plastic
-plate
-play
-please
-pledge
-pluck
-plug
-plunge
-poem
-poet
-point
-polar
-pole
-police
-pond
-pony
-pool
-popular
-portion
-position
-possible
-post
-potato
-pottery
-poverty
-powder
-power
-practice
-praise
-predict
-prefer
-prepare
-present
-pretty
-prevent
-price
-pride
-primary
-print
-priority
-prison
-private
-prize
-problem
-process
-produce
-profit
-program
-project
-promote
-proof
-property
-prosper
-protect
-proud
-provide
-public
-pudding
-pull
-pulp
-pulse
-pumpkin
-punch
-pupil
-puppy
-purchase
-purity
-purpose
-purse
-push
-put
-puzzle
-pyramid
-quality
-quantum
-quarter
-question
-quick
-quit
-quiz
-quote
-rabbit
-raccoon
-race
-rack
-radar
-radio
-rail
-rain
-raise
-rally
-ramp
-ranch
-random
-range
-rapid
-rare
-rate
-rather
-raven
-raw
-razor
-ready
-real
-reason
-rebel
-rebuild
-recall
-receive
-recipe
-record
-recycle
-reduce
-reflect
-reform
-refuse
-region
-regret
-regular
-reject
-relax
-release
-relief
-rely
-remain
-remember
-remind
-remove
-render
-renew
-rent
-reopen
-repair
-repeat
-replace
-report
-require
-rescue
-resemble
-resist
-resource
-response
-result
-retire
-retreat
-return
-reunion
-reveal
-review
-reward
-rhythm
-rib
-ribbon
-rice
-rich
-ride
-ridge
-rifle
-right
-rigid
-ring
-riot
-ripple
-risk
-ritual
-rival
-river
-road
-roast
-robot
-robust
-rocket
-romance
-roof
-rookie
-room
-rose
-rotate
-rough
-round
-route
-royal
-rubber
-rude
-rug
-rule
-run
-runway
-rural
-sad
-saddle
-sadness
-safe
-sail
-salad
-salmon
-salon
-salt
-salute
-same
-sample
-sand
-satisfy
-satoshi
-sauce
-sausage
-save
-say
-scale
-scan
-scare
-scatter
-scene
-scheme
-school
-science
-scissors
-scorpion
-scout
-scrap
-screen
-script
-scrub
-sea
-search
-season
-seat
-second
-secret
-section
-security
-seed
-seek
-segment
-select
-sell
-seminar
-senior
-sense
-sentence
-series
-service
-session
-settle
-setup
-seven
-shadow
-shaft
-shallow
-share
-shed
-shell
-sheriff
-shield
-shift
-shine
-ship
-shiver
-shock
-shoe
-shoot
-shop
-short
-shoulder
-shove
-shrimp
-shrug
-shuffle
-shy
-sibling
-sick
-side
-siege
-sight
-sign
-silent
-silk
-silly
-silver
-similar
-simple
-since
-sing
-siren
-sister
-situate
-six
-size
-skate
-sketch
-ski
-skill
-skin
-skirt
-skull
-slab
-slam
-sleep
-slender
-slice
-slide
-slight
-slim
-slogan
-slot
-slow
-slush
-small
-smart
-smile
-smoke
-smooth
-snack
-snake
-snap
-sniff
-snow
-soap
-soccer
-social
-sock
-soda
-soft
-solar
-soldier
-solid
-solution
-solve
-someone
-song
-soon
-sorry
-sort
-soul
-sound
-soup
-source
-south
-space
-spare
-spatial
-spawn
-speak
-special
-speed
-spell
-spend
-sphere
-spice
-spider
-spike
-spin
-spirit
-split
-spoil
-sponsor
-spoon
-sport
-spot
-spray
-spread
-spring
-spy
-square
-squeeze
-squirrel
-stable
-stadium
-staff
-stage
-stairs
-stamp
-stand
-start
-state
-stay
-steak
-steel
-stem
-step
-stereo
-stick
-still
-sting
-stock
-stomach
-stone
-stool
-story
-stove
-strategy
-street
-strike
-strong
-struggle
-student
-stuff
-stumble
-style
-subject
-submit
-subway
-success
-such
-sudden
-suffer
-sugar
-suggest
-suit
-summer
-sun
-sunny
-sunset
-super
-supply
-supreme
-sure
-surface
-surge
-surprise
-surround
-survey
-suspect
-sustain
-swallow
-swamp
-swap
-swarm
-swear
-sweet
-swift
-swim
-swing
-switch
-sword
-symbol
-symptom
-syrup
-system
-table
-tackle
-tag
-tail
-talent
-talk
-tank
-tape
-target
-task
-taste
-tattoo
-taxi
-teach
-team
-tell
-ten
-tenant
-tennis
-tent
-term
-test
-text
-thank
-that
-theme
-then
-theory
-there
-they
-thing
-this
-thought
-three
-thrive
-throw
-thumb
-thunder
-ticket
-tide
-tiger
-tilt
-timber
-time
-tiny
-tip
-tired
-tissue
-title
-toast
-tobacco
-today
-toddler
-toe
-together
-toilet
-token
-tomato
-tomorrow
-tone
-tongue
-tonight
-tool
-tooth
-top
-topic
-topple
-torch
-tornado
-tortoise
-toss
-total
-tourist
-toward
-tower
-town
-toy
-track
-trade
-traffic
-tragic
-train
-transfer
-trap
-trash
-travel
-tray
-treat
-tree
-trend
-trial
-tribe
-trick
-trigger
-trim
-trip
-trophy
-trouble
-truck
-true
-truly
-trumpet
-trust
-truth
-try
-tube
-tuition
-tumble
-tuna
-tunnel
-turkey
-turn
-turtle
-twelve
-twenty
-twice
-twin
-twist
-two
-type
-typical
-ugly
-umbrella
-unable
-unaware
-uncle
-uncover
-under
-undo
-unfair
-unfold
-unhappy
-uniform
-unique
-unit
-universe
-unknown
-unlock
-until
-unusual
-unveil
-update
-upgrade
-uphold
-upon
-upper
-upset
-urban
-urge
-usage
-use
-used
-useful
-useless
-usual
-utility
-vacant
-vacuum
-vague
-valid
-valley
-valve
-van
-vanish
-vapor
-various
-vast
-vault
-vehicle
-velvet
-vendor
-venture
-venue
-verb
-verify
-version
-very
-vessel
-veteran
-viable
-vibrant
-vicious
-victory
-video
-view
-village
-vintage
-violin
-virtual
-virus
-visa
-visit
-visual
-vital
-vivid
-vocal
-voice
-void
-volcano
-volume
-vote
-voyage
-wage
-wagon
-wait
-walk
-wall
-walnut
-want
-warfare
-warm
-warrior
-wash
-wasp
-waste
-water
-wave
-way
-wealth
-weapon
-wear
-weasel
-weather
-web
-wedding
-weekend
-weird
-welcome
-west
-wet
-whale
-what
-wheat
-wheel
-when
-where
-whip
-whisper
-wide
-width
-wife
-wild
-will
-win
-window
-wine
-wing
-wink
-winner
-winter
-wire
-wisdom
-wise
-wish
-witness
-wolf
-woman
-wonder
-wood
-wool
-word
-work
-world
-worry
-worth
-wrap
-wreck
-wrestle
-wrist
-write
-wrong
-yard
-year
-yellow
-you
-young
-youth
-zebra
-zero
-zone
-zoo`.split("\n");
diff --git a/src/lib/handler.ts b/src/lib/handler.ts
new file mode 100644
index 00000000..baca442d
--- /dev/null
+++ b/src/lib/handler.ts
@@ -0,0 +1,13 @@
+import { goto } from "$app/navigation";
+import { applyAction } from "$app/forms";
+
+export default (toggle) => () => {
+ toggle();
+ return async ({ result }) => {
+ if (result.type === "redirect") {
+ goto(result.location);
+ } else {
+ await applyAction(result);
+ }
+ };
+};
diff --git a/src/lib/invoice.js b/src/lib/invoice.js
deleted file mode 100644
index d2d3d13d..00000000
--- a/src/lib/invoice.js
+++ /dev/null
@@ -1,32 +0,0 @@
-import { auth, get, post } from "$lib/utils";
-import { redirect } from "@sveltejs/kit";
-
-export default async ({ cookies, request, url }) => {
- let form = await request.formData();
-
- let rates = await get("/rates");
- let amount = parseInt(form.get("amount"));
-
- let invoice = {
- amount,
- items: JSON.parse(form.get("items")),
- memo: form.get("memo"),
- memoPrompt: form.get("memoPrompt"),
- tip: parseInt(form.get("tip")) || 0,
- type: form.get("type"),
- prompt: form.get("prompt") === "true",
- rate: parseFloat(form.get("rate")) || rates[form.get("currency")],
- };
-
- let user = { username: form.get("username"), currency: form.get("currency") };
-
- invoice = await post("/invoice", { invoice, user }, auth(cookies));
- let { id } = invoice;
-
- if (invoice.prompt && invoice.tip === null)
- redirect(307, `/${user.username}/invoice/${id}/tip`);
-
- if (invoice.memoPrompt && !invoice.memo) {
- redirect(307, `/${user.username}/invoice/${id}/memo`);
- } else redirect(307, `/${user.username}/invoice/${id}`);
-};
diff --git a/src/lib/invoice.ts b/src/lib/invoice.ts
new file mode 100644
index 00000000..a48e02a4
--- /dev/null
+++ b/src/lib/invoice.ts
@@ -0,0 +1,38 @@
+import { auth, get, post } from "$lib/utils";
+import { redirect } from "@sveltejs/kit";
+
+export default async ({ cookies, request }) => {
+ const form = await request.formData();
+ const aid = form.get("aid") || cookies.get("aid");
+
+ const rates = await get("/rates");
+ const amount = parseInt(form.get("amount"));
+
+ let invoice = {
+ aid,
+ amount,
+ items: JSON.parse(form.get("items")),
+ memo: form.get("memo"),
+ memoPrompt: form.get("memoPrompt"),
+ tip: parseInt(form.get("tip")) || 0,
+ type: form.get("type"),
+ prompt: form.get("prompt") === "true",
+ rate: parseFloat(form.get("rate")) || rates[form.get("currency")],
+ id: undefined,
+ };
+
+ const user = {
+ username: form.get("username"),
+ currency: form.get("currency"),
+ };
+
+ invoice = await post("/invoice", { invoice, user }, auth(cookies));
+ const { id } = invoice;
+
+ if (invoice.prompt && invoice.tip === null)
+ redirect(307, `/invoice/${id}/tip`);
+
+ if (invoice.memoPrompt && !invoice.memo) {
+ redirect(307, `/invoice/${id}/memo`);
+ } else redirect(307, `/invoice/${id}`);
+};
diff --git a/src/lib/locales.ts b/src/lib/locales.ts
new file mode 100644
index 00000000..29c47a77
--- /dev/null
+++ b/src/lib/locales.ts
@@ -0,0 +1,14 @@
+import {
+ de,
+ el,
+ enUS as en,
+ es,
+ faIR as fa,
+ fr,
+ ja,
+ pt,
+ ru,
+ zhCN as zh,
+} from "date-fns/locale/index.js";
+
+export default { de, el, en, es, fa, fr, ja, pt, ru, zh };
diff --git a/src/lib/nostr.js b/src/lib/nostr.js
deleted file mode 100644
index 5209418a..00000000
--- a/src/lib/nostr.js
+++ /dev/null
@@ -1,177 +0,0 @@
-import { browser } from "$app/environment";
-import { hexToUint8Array } from "uint8array-extras";
-import { get } from "svelte/store";
-import { Buffer } from "buffer";
-import { fail, wait, post, stretch } from "$lib/utils";
-import {
- decrypted,
- password as pw,
- passwordPrompt,
- pin,
- loginRedirect,
-} from "$lib/store";
-import { goto, invalidate } from "$app/navigation";
-import {
- getPublicKey,
- finalizeEvent,
- getEventHash,
- nip04,
- nip19,
-} from "nostr-tools";
-
-import {
- encrypt as nip49encrypt,
- decrypt as nip49decrypt,
-} from "nostr-tools/nip49";
-
-import { mnemonicToEntropy, entropyToMnemonic } from "@scure/bip39";
-import wordlist from "$lib/english";
-import { bech32m } from "@scure/base";
-
-import { generateSeedWords, privateKeyFromSeedWords } from "nostr-tools/nip06";
-const { encode, decode, toWords, fromWords } = bech32m;
-
-export let generate = async (user) => {
- if (!get(pin)?.length === 6) return;
-
- let salt = crypto.getRandomValues(new Uint8Array(16));
- let mnemonic = generateSeedWords();
- let sk = privateKeyFromSeedWords(mnemonic);
-
- let bytes = new Uint8Array(
- await crypto.subtle.encrypt(
- { name: "AES-GCM", iv: new Uint8Array(16) },
- await stretch(await getPassword(), salt),
- Uint8Array.from(Buffer.from(mnemonicToEntropy(mnemonic, wordlist), "hex"))
- )
- );
-
- user.pubkey = getPublicKey(sk);
- user.cipher = encode("en", toWords(bytes), 180);
- user.salt = Buffer.from(salt).toString("hex");
-};
-
-export let encrypt = async ({ message, recipient, user }) => {
- let sk = await getPrivateKey(user);
- return nip04.encrypt(sk, recipient, message);
-};
-
-export let decrypt = async ({ event, user }) => {
- let cache = get(decrypted);
- try {
- let { content, pubkey, id } = event;
- if (cache[id]) return cache[id];
- if (pubkey === user.pubkey) pubkey = event.tags[0][1];
-
- let message = await nip04.decrypt(
- await getPrivateKey(user),
- pubkey,
- content
- );
-
- cache[id] = Buffer.from(message).toString("utf8");
- decrypted.set(cache);
-
- return cache[id];
- } catch (e) {
- // console.log(e);
- }
-};
-
-function typedArrayToBuffer(array) {
- return array.buffer.slice(
- array.byteOffset,
- array.byteLength + array.byteOffset
- );
-}
-
-export let getPrivateKey = async (user) => {
- let k;
- if (browser) {
- k = localStorage.getItem("nsec");
- if (k) {
- return nip19.decode(k).data;
- }
- }
-
- let { nsec, username, salt } = user;
-
- if (nsec) {
- k = nip49decrypt(nsec, await getPassword());
- } else k = hexToUint8Array(privateKeyFromSeedWords(await getMnemonic(user)));
-
- localStorage.setItem("nsec", nip19.nsecEncode(k));
- return k;
-};
-
-export let getMnemonic = async (user) => {
- let { cipher, username, salt } = user;
- let mnemonic, key, seed, entropy, child, privkey;
-
- entropy = new Uint8Array(
- await crypto.subtle.decrypt(
- { name: "AES-GCM", iv: new Uint8Array(16) },
- await stretch(await getPassword(), Buffer.from(salt, "hex")),
- Uint8Array.from(fromWords(decode(cipher, 180).words))
- )
- );
-
- return entropyToMnemonic(entropy, wordlist);
-};
-
-export let getNsec = async (user) => {
- return nip19.nsecEncode(await getPrivateKey(user));
-};
-
-export let setNsec = async (user, nsec) => {
- let { data: sk } = nip19.decode(nsec);
- user.pubkey = getPublicKey(sk);
- user.nsec = await encryptNsec(nsec);
-};
-
-export let encryptNsec = async (nsec) => {
- let { type, data } = nip19.decode(nsec);
- if (type === "nsec" && data.length === 32) {
- return nip49encrypt(data, await getPassword());
- } else {
- fail("invalid nsec");
- }
-};
-
-export let sign = async ({ event, user }) => {
- event = finalizeEvent(event, await getPrivateKey(user));
-};
-
-export let send = (event) => {
- return post("/events", { event });
-};
-
-let getPassword = async () => {
- if (!get(pw)) passwordPrompt.set(true);
- await wait(() => !!get(pw));
- return get(pw);
-};
-
-export let reEncryptEntropy = async (user, newPassword) => {
- let { cipher, username, salt } = user;
-
- let mnemonic, key, seed, entropy, child, privkey;
- entropy = Buffer.from(
- await crypto.subtle.decrypt(
- { name: "AES-GCM", iv: new Uint8Array(16) },
- await stretch(await getPassword(), Buffer.from(salt, "hex")),
- Uint8Array.from(fromWords(decode(cipher, 180).words))
- ),
- "hex"
- ).toString("hex");
-
- let bytes = new Uint8Array(
- await crypto.subtle.encrypt(
- { name: "AES-GCM", iv: new Uint8Array(16) },
- await stretch(newPassword, Buffer.from(salt, "hex")),
- Uint8Array.from(Buffer.from(entropy, "hex"))
- )
- );
-
- return encode("en", toWords(bytes), 180);
-};
diff --git a/src/lib/nostr.ts b/src/lib/nostr.ts
new file mode 100644
index 00000000..f45dc811
--- /dev/null
+++ b/src/lib/nostr.ts
@@ -0,0 +1,177 @@
+import { browser } from "$app/environment";
+import { hexToUint8Array } from "uint8array-extras";
+import { get } from "svelte/store";
+import { Buffer } from "buffer";
+import { wait, post, stretch } from "$lib/utils";
+import { decrypted, password as pw, passwordPrompt, pin } from "$lib/store";
+import {
+ getPublicKey,
+ finalizeEvent,
+ nip04,
+ nip19,
+ type EventTemplate,
+} from "nostr-tools";
+
+import {
+ encrypt as nip49encrypt,
+ decrypt as nip49decrypt,
+} from "nostr-tools/nip49";
+
+import { mnemonicToEntropy, entropyToMnemonic } from "@scure/bip39";
+import { bech32m } from "@scure/base";
+import { wordlist } from "@scure/bip39/wordlists/english";
+
+import { generateSeedWords, privateKeyFromSeedWords } from "nostr-tools/nip06";
+
+type User = {
+ [key: string]: any;
+};
+
+type EncryptParams = {
+ message: string;
+ recipient: string;
+ user: User;
+};
+
+const { encode, decode, toWords, fromWords } = bech32m;
+
+export const generate = async (user: any) => {
+ const p = get(pin);
+ if (p && p.length !== 6) return;
+
+ const salt = crypto.getRandomValues(new Uint8Array(16));
+ const mnemonic = generateSeedWords();
+ const sk = privateKeyFromSeedWords(mnemonic);
+
+ const bytes = new Uint8Array(
+ await crypto.subtle.encrypt(
+ { name: "AES-GCM", iv: new Uint8Array(16) },
+ await stretch(await getPassword(), salt),
+ mnemonicToEntropy(mnemonic, wordlist),
+ ),
+ );
+
+ user.pubkey = getPublicKey(hexToUint8Array(sk));
+ user.cipher = encode("en", toWords(bytes), 180);
+ user.salt = Buffer.from(salt).toString("hex");
+};
+
+export const encrypt = async ({ message, recipient, user }: EncryptParams) => {
+ const sk = await getPrivateKey(user);
+ return nip04.encrypt(sk, recipient, message);
+};
+
+export const decrypt = async ({ event, user }) => {
+ const cache = get(decrypted);
+ try {
+ let { content, pubkey, id } = event;
+ if (cache[id]) return cache[id];
+ if (pubkey === user.pubkey) pubkey = event.tags[0][1];
+
+ const message = await nip04.decrypt(
+ await getPrivateKey(user),
+ pubkey,
+ content,
+ );
+
+ cache[id] = Buffer.from(message).toString("utf8");
+ decrypted.set(cache);
+
+ return cache[id];
+ } catch (e) {
+ // console.log(e);
+ }
+};
+
+export const getPrivateKey = async (user: User): Promise<Uint8Array> => {
+ let k;
+ if (browser) {
+ k = localStorage.getItem("nsec");
+ if (k) {
+ return nip19.decode(k).data as Uint8Array;
+ }
+ }
+
+ const { nsec } = user;
+
+ if (nsec) {
+ k = nip49decrypt(nsec, await getPassword());
+ } else k = hexToUint8Array(privateKeyFromSeedWords(await getMnemonic(user)));
+
+ localStorage.setItem("nsec", nip19.nsecEncode(k));
+ return k;
+};
+
+export const getMnemonic = async (user: User) => {
+ const { cipher, salt } = user;
+ let entropy;
+
+ entropy = new Uint8Array(
+ await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv: new Uint8Array(16) },
+ await stretch(await getPassword(), Buffer.from(salt, "hex")),
+ Uint8Array.from(fromWords(decode(cipher, 180).words)),
+ ),
+ );
+
+ return entropyToMnemonic(entropy, wordlist);
+};
+
+const decodeNsec = (nsec: string): Uint8Array => {
+ const { type, data } = nip19.decode(nsec);
+ if (type === "nsec" && data instanceof Uint8Array) return data;
+ throw new Error("invalid nsec");
+};
+
+export const getNsec = async (user: User) => {
+ return nip19.nsecEncode(await getPrivateKey(user));
+};
+
+export const setNsec = async (user: User, nsec: string) => {
+ user.pubkey = getPublicKey(decodeNsec(nsec));
+ user.nsec = await encryptNsec(nsec);
+};
+
+export const encryptNsec = async (nsec: string) => {
+ const d = decodeNsec(nsec);
+ return nip49encrypt(d, await getPassword());
+};
+
+type SignParams = {
+ event: EventTemplate;
+ user: User;
+};
+
+export const sign = async ({ event, user }: SignParams) => {
+ event = finalizeEvent(event, await getPrivateKey(user));
+};
+
+export const send = (event: EventTemplate) => {
+ return post("/events", { event });
+};
+
+const getPassword = async (): Promise<string> => {
+ if (!get(pw)) passwordPrompt.set(true);
+ await wait(() => !!get(pw));
+ return get(pw) || "";
+};
+
+export const reEncryptEntropy = async (user: User, newPassword: string) => {
+ const { cipher, salt } = user;
+
+ const entropy = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv: new Uint8Array(16) },
+ await stretch(await getPassword(), hexToUint8Array(salt)),
+ Uint8Array.from(fromWords(decode(cipher, 180).words)),
+ );
+
+ const bytes = new Uint8Array(
+ await crypto.subtle.encrypt(
+ { name: "AES-GCM", iv: new Uint8Array(16) },
+ await stretch(newPassword, hexToUint8Array(salt)),
+ entropy,
+ ),
+ );
+
+ return encode("en", toWords(bytes), 180);
+};
diff --git a/src/lib/parse.ts b/src/lib/parse.ts
new file mode 100644
index 00000000..aeb823e3
--- /dev/null
+++ b/src/lib/parse.ts
@@ -0,0 +1,82 @@
+import { PUBLIC_DOMAIN } from "$env/static/public";
+import { get, isLiquid, post } from "$lib/utils";
+import { redirect } from "@sveltejs/kit";
+import bip21 from "bip21";
+import { validate } from "bitcoin-address-validation";
+
+export default async (s, host) => {
+ if (!s) return;
+ let t = s;
+
+ if (t.startsWith("http")) redirect(307, t);
+ if (t.startsWith(host)) redirect(307, `http://${t}`);
+
+ let amount;
+ let user;
+
+ t = t.trim();
+ if (t.toLowerCase().startsWith("bitcoin:"))
+ ({
+ address: t,
+ options: { amount },
+ } = bip21.decode(t));
+
+ if (t.startsWith("lightning:")) t = t.replace("lightning:", "");
+ if (t.endsWith(`@${PUBLIC_DOMAIN}`)) t = t.split("@")[0];
+ if (t.includes("@") && t.includes(".")) {
+ try {
+ t = await get(`/encode?address=${t}`);
+ } catch (e) {}
+ }
+
+ if (t.includes("/fund")) redirect(307, t.substring(t.indexOf("/fund")));
+
+ // lightning
+ if (t.toLowerCase().startsWith("lightning:"))
+ t = t.toLowerCase().replace("lightning:", "");
+ if (t.toLowerCase().startsWith("lnurl")) redirect(307, `/ln/${t}`);
+ if (t.includes(":")) t = t.split(":")[1];
+
+ if (t.toLowerCase().startsWith("ln")) {
+ try {
+ await get(`/invoice/${t}`);
+ } catch (e) {
+ redirect(307, `/send/lightning/${t}`);
+ }
+ }
+
+ // bitcoin
+ if (validate(t) || isLiquid(t)) {
+ let r = `/send/bitcoin/${t}`;
+ if (amount) r += `/${amount}`;
+ redirect(307, r);
+ }
+
+ if (t.startsWith("cashu")) {
+ const { id } = await post("/cash", { token: t });
+ redirect(307, `/ecash/${id}`);
+ }
+
+ // user
+ try {
+ user = await get(`/users/${t.split("/")[0]}`);
+ if (user.anon) user = null;
+ } catch (e) {}
+
+ if (user) redirect(307, `/pay/${t}`);
+
+ let fund;
+ try {
+ fund = await get(`/fund/${t}`);
+ } catch (e) {}
+
+ if (fund) redirect(307, `/send/fund/${t}`);
+
+ // invoice
+ let invoice;
+ try {
+ invoice = await get(`/invoice/${t}`);
+ } catch (e) {}
+
+ if (invoice) redirect(307, `/send/invoice/${invoice.id}`);
+};
diff --git a/src/lib/punks.js b/src/lib/punks.js
deleted file mode 100644
index e5551062..00000000
--- a/src/lib/punks.js
+++ /dev/null
@@ -1,66 +0,0 @@
-export default [
- "6e1f1626a9308abd0b7732fecbc7d49366ced46dead63ef3603fb0f4ec7aa53d",
- "96ea95735b61c48c6f465db8ca0246a62539f34c3a977be6338770d92461da89",
- "8c18c036b257d7b9c5a970a786efa04c320f3cf5afa73fa310a6603744d1ee3a",
- "a7a6187e54e83acdb893d456c8b4ad6877e4738ea9e0d47c9b2070bf2c98a35f",
- "836d72150b6f3033b6220d15ac9d49457d81041a700d12898bd3b8e737b4d265",
- "e3d1c40538a8aed282a430647e3ff16ff94b64b8ed0a7cf427e8b0e2780a9b2a",
- "2155224ef35cfb4bbdb06d982b42bb9b93d97b2bc691c22c804e1759a0a04882",
- "5f6549ad9dd15dd57c204b1a9b60c68c376e77d7d114cfa13219e6a1a71f901f",
- "ba8dd5a7070aee7102d4f8bc83ac497091e2e473a0f448a1c513569167dd0791",
- "4f07e1da3685a858970a9f39300564971e97257f5d37b55a6d9882014aecc421",
- "01aa9348244c4b65de3df758d49c98076e17a109aef04bc211abc77cf42dc51d",
- "080574eb9e0613926e0e5d9b667c132e12965a1b1d47218a0b290a2d55c55d2f",
- "08ce4840184f63a779bcd1f91bbcb56a2e8cba75c3ba2dbd290a559a57e4238e",
- "27caa38c14a85ad64b4c4469a34e61a3965a1cbc4cad9a85707da374301c830d",
- "eccc90741370ba4acc70bc65f4ccc38fddb1327d977c366156018974bc52fe4a",
- "3759946d9e875ac2fc5c51ed850686193bb1e0716219e42efd52f3965993b275",
- "db5fe28b8ddb9ae5e4f5e0e757ee60bc938bffbdfdd38de807939e212d3c5066",
- "3f8f861e663accee51e68b987705ce647a7446b7f118abc94c632e158acbb44f",
- "43bab95a047112dca6705506f916a97252363a20da4a4c0a5ab7b676e11083fc",
- "d3018e45c66dd485697f738ad191af98267e6255d562496dd06b1a662e0c7a88",
- "0ec2e8d07e053d686140857493ece653cde52764a60aa1d25651d81811d44a3d",
- "4595bb092682af7177799464364c047fbfa7ede767336734949bce5d085fce15",
- "6524936709e0719f9e28bf1caac91f86f323d1a79f10ab65a03fa9ea2e6b3270",
- "8ba4736edc68da8e5b21c23af4de1f9131f47778c2a5b2a970a799223a9380b3",
- "2aaba839e8546a8cb6d04a81ff5be83ac4e700ca4491607a16ebd60dc4995750",
- "5f88f7f579ce50d7bcf60d6e9556f77acf361ba54caf3eb61dc4f2ca9c94c6a2",
- "d1ca262272613d7386fecce7f1ad268188940b59ea83fdd1f8d7ab85771e3f43",
- "5211890e4128d8d730802cc75ee105867e8878581d5e72ffc98a0d60027a5398",
- "c1dececcbd7b623bfaa726392512e6ea110db93a0649dd01bf9e559318514f7c",
- "43ce93c9835e983403a01329918d184832c5516e1b0ea4e0878b4c4def042777",
- "c84724a398bda8d20436fb0663d059c196628fa71192bb720fa5adf6137bed9b",
- "f307620a90a36045fa550316d61be4755c1f6c7f3fc81c95fc4d590ac568b2c4",
- "78ae0118856a1f17c13f292628fcf3dccc150c7278578caaceb9f35ca8bc9f55",
- "9d9a9a40c490f05d7dbafde8bf60d68aab7dcb79a7976eef62d1448a4549816b",
- "f6017bec50563dbbb24b979214ae225f96b01dea5b090b174038ff2842a1c6b1",
- "6dbec748ea87e959390b0df429c005fccffe9e672864f555c14c7a407b940870",
- "11701e76233395ebdba8d1d50334d1a0cc3a158f3452260c9a7b9a067b78d753",
- "7354f3829dd05c838aa16d66b00316f7994797927a4d3b594c8af04a2b4ae86a",
- "14d254333c6240fbdacbbbe261f7ae15be2e83bffcf084f4f59f459bae0a4571",
- "7849ac0f31056265efb0110038f86e61effe17b7db836377d88433b73312e65a",
- "9018be885177c675baf9b36978428d841ca30a9185e11de1a31238a08e3ec1af",
- "777c5715de7423597fea6c03c496ea46414f0508cd96e119261f002965beb805",
- "b742b7509a97c2b346ea762f0510e8475b30dc988417f0f146ae00a800c6dd56",
- "7af3029a826e6dfba23ad502901a3632ef4ee047bd45d618b1f106717b0af7ea",
- "82390020b2bca461204cc49b20ee6fec1b93dad476726f377785d04040a4d6c3",
- "6bc2990699be7f610c9f6a49bc7a19b034040727bc3de63fee89a1573fe00673",
- "50c7c2e8e8c7f4aabffb195187a1ac1105f5712859f02d491d794ba2d8498e08",
- "5d1d3769cd141603ce907df5dca159e389ca4d75338eddbe1b7db1c0766cbfd6",
- "4d8ad7a761d068b7ef9b058fb4ba924b276e7a45a3ad47a79b767e08e821e038",
- "d5b5b2167602f7277cdac76cfda8bdad0befcb8ff12df495dfabf40c91d1120c",
- "6f2618272bb0164247e9b0f40b19f020c1c9253510dc658a3cc078d079ef01bf",
- "fd502d5007bfc62a91eb7a34c1ae23b9de4a20cf5e1bbd86dadc421d7083099c",
- "914813583b901044970b9c7d6dcdfde4344339325f5988d0dd681d377f1243fb",
- "85cb7cf0245613d08b3027f879f58a6db645bf0db107242beb856b340ee49ee8",
- "d6dbb18d5df5e92c8c74ee59aa86d19dff25a5d0f9d030e84285a686f86804d7",
- "65309f82cd9f9926a578d09e1ad13909f68a06d02b853760731a4225f7aecef4",
- "433519d13f2b64fe82a90cd054797d4779507fea93c1054bd51c35ba846a0f7f",
- "62a55d4d6e4b6f992a1c1840f041585c957affcdbf875202cf9e1db9def05aeb",
- "e19eb1eeabdeffa04ccd792eb09776690cf2121887b26a7c5d20d66e3e8fd0fb",
- "a80951fc593035abb2dda045a2076d29a30f5cc470e0a20db39c3ec588ed61d8",
- "4f1b39906714266a7a1936bfa8e08c5d891285dd2b188b4bcd4afb0107671004",
- "f46310b2e60727af071d09e759814f52f933688a0ff0995c7da373b381e70005",
- "2cc94821f56d21918ba4f2770d97f280e06fd99f4199167e2f4ddc780f404c8a",
- "698a2ca7a09e88fa6594801da037f4dbce6ae841d1d33736aebcf8f6fe104e01",
-];
diff --git a/src/lib/punks.ts b/src/lib/punks.ts
new file mode 100644
index 00000000..8b7b53df
--- /dev/null
+++ b/src/lib/punks.ts
@@ -0,0 +1,66 @@
+export default [
+ "6e1f1626a9308abd0b7732fecbc7d49366ced46dead63ef3603fb0f4ec7aa53d",
+ "96ea95735b61c48c6f465db8ca0246a62539f34c3a977be6338770d92461da89",
+ "8c18c036b257d7b9c5a970a786efa04c320f3cf5afa73fa310a6603744d1ee3a",
+ "a7a6187e54e83acdb893d456c8b4ad6877e4738ea9e0d47c9b2070bf2c98a35f",
+ "836d72150b6f3033b6220d15ac9d49457d81041a700d12898bd3b8e737b4d265",
+ "e3d1c40538a8aed282a430647e3ff16ff94b64b8ed0a7cf427e8b0e2780a9b2a",
+ "2155224ef35cfb4bbdb06d982b42bb9b93d97b2bc691c22c804e1759a0a04882",
+ "5f6549ad9dd15dd57c204b1a9b60c68c376e77d7d114cfa13219e6a1a71f901f",
+ "ba8dd5a7070aee7102d4f8bc83ac497091e2e473a0f448a1c513569167dd0791",
+ "4f07e1da3685a858970a9f39300564971e97257f5d37b55a6d9882014aecc421",
+ "01aa9348244c4b65de3df758d49c98076e17a109aef04bc211abc77cf42dc51d",
+ "080574eb9e0613926e0e5d9b667c132e12965a1b1d47218a0b290a2d55c55d2f",
+ "08ce4840184f63a779bcd1f91bbcb56a2e8cba75c3ba2dbd290a559a57e4238e",
+ "27caa38c14a85ad64b4c4469a34e61a3965a1cbc4cad9a85707da374301c830d",
+ "eccc90741370ba4acc70bc65f4ccc38fddb1327d977c366156018974bc52fe4a",
+ "3759946d9e875ac2fc5c51ed850686193bb1e0716219e42efd52f3965993b275",
+ "db5fe28b8ddb9ae5e4f5e0e757ee60bc938bffbdfdd38de807939e212d3c5066",
+ "3f8f861e663accee51e68b987705ce647a7446b7f118abc94c632e158acbb44f",
+ "43bab95a047112dca6705506f916a97252363a20da4a4c0a5ab7b676e11083fc",
+ "d3018e45c66dd485697f738ad191af98267e6255d562496dd06b1a662e0c7a88",
+ "0ec2e8d07e053d686140857493ece653cde52764a60aa1d25651d81811d44a3d",
+ "4595bb092682af7177799464364c047fbfa7ede767336734949bce5d085fce15",
+ "6524936709e0719f9e28bf1caac91f86f323d1a79f10ab65a03fa9ea2e6b3270",
+ "8ba4736edc68da8e5b21c23af4de1f9131f47778c2a5b2a970a799223a9380b3",
+ "2aaba839e8546a8cb6d04a81ff5be83ac4e700ca4491607a16ebd60dc4995750",
+ "5f88f7f579ce50d7bcf60d6e9556f77acf361ba54caf3eb61dc4f2ca9c94c6a2",
+ "d1ca262272613d7386fecce7f1ad268188940b59ea83fdd1f8d7ab85771e3f43",
+ "5211890e4128d8d730802cc75ee105867e8878581d5e72ffc98a0d60027a5398",
+ "c1dececcbd7b623bfaa726392512e6ea110db93a0649dd01bf9e559318514f7c",
+ "43ce93c9835e983403a01329918d184832c5516e1b0ea4e0878b4c4def042777",
+ "c84724a398bda8d20436fb0663d059c196628fa71192bb720fa5adf6137bed9b",
+ "f307620a90a36045fa550316d61be4755c1f6c7f3fc81c95fc4d590ac568b2c4",
+ "78ae0118856a1f17c13f292628fcf3dccc150c7278578caaceb9f35ca8bc9f55",
+ "9d9a9a40c490f05d7dbafde8bf60d68aab7dcb79a7976eef62d1448a4549816b",
+ "f6017bec50563dbbb24b979214ae225f96b01dea5b090b174038ff2842a1c6b1",
+ "6dbec748ea87e959390b0df429c005fccffe9e672864f555c14c7a407b940870",
+ "11701e76233395ebdba8d1d50334d1a0cc3a158f3452260c9a7b9a067b78d753",
+ "7354f3829dd05c838aa16d66b00316f7994797927a4d3b594c8af04a2b4ae86a",
+ "14d254333c6240fbdacbbbe261f7ae15be2e83bffcf084f4f59f459bae0a4571",
+ "7849ac0f31056265efb0110038f86e61effe17b7db836377d88433b73312e65a",
+ "9018be885177c675baf9b36978428d841ca30a9185e11de1a31238a08e3ec1af",
+ "777c5715de7423597fea6c03c496ea46414f0508cd96e119261f002965beb805",
+ "b742b7509a97c2b346ea762f0510e8475b30dc988417f0f146ae00a800c6dd56",
+ "7af3029a826e6dfba23ad502901a3632ef4ee047bd45d618b1f106717b0af7ea",
+ "82390020b2bca461204cc49b20ee6fec1b93dad476726f377785d04040a4d6c3",
+ "6bc2990699be7f610c9f6a49bc7a19b034040727bc3de63fee89a1573fe00673",
+ "50c7c2e8e8c7f4aabffb195187a1ac1105f5712859f02d491d794ba2d8498e08",
+ "5d1d3769cd141603ce907df5dca159e389ca4d75338eddbe1b7db1c0766cbfd6",
+ "4d8ad7a761d068b7ef9b058fb4ba924b276e7a45a3ad47a79b767e08e821e038",
+ "d5b5b2167602f7277cdac76cfda8bdad0befcb8ff12df495dfabf40c91d1120c",
+ "6f2618272bb0164247e9b0f40b19f020c1c9253510dc658a3cc078d079ef01bf",
+ "fd502d5007bfc62a91eb7a34c1ae23b9de4a20cf5e1bbd86dadc421d7083099c",
+ "914813583b901044970b9c7d6dcdfde4344339325f5988d0dd681d377f1243fb",
+ "85cb7cf0245613d08b3027f879f58a6db645bf0db107242beb856b340ee49ee8",
+ "d6dbb18d5df5e92c8c74ee59aa86d19dff25a5d0f9d030e84285a686f86804d7",
+ "65309f82cd9f9926a578d09e1ad13909f68a06d02b853760731a4225f7aecef4",
+ "433519d13f2b64fe82a90cd054797d4779507fea93c1054bd51c35ba846a0f7f",
+ "62a55d4d6e4b6f992a1c1840f041585c957affcdbf875202cf9e1db9def05aeb",
+ "e19eb1eeabdeffa04ccd792eb09776690cf2121887b26a7c5d20d66e3e8fd0fb",
+ "a80951fc593035abb2dda045a2076d29a30f5cc470e0a20db39c3ec588ed61d8",
+ "4f1b39906714266a7a1936bfa8e08c5d891285dd2b188b4bcd4afb0107671004",
+ "f46310b2e60727af071d09e759814f52f933688a0ff0995c7da373b381e70005",
+ "2cc94821f56d21918ba4f2770d97f280e06fd99f4199167e2f4ddc780f404c8a",
+ "698a2ca7a09e88fa6594801da037f4dbce6ae841d1d33736aebcf8f6fe104e01",
+];
diff --git a/src/lib/samples.js b/src/lib/samples.ts
index 85a85ef8..469ddad9 100644
--- a/src/lib/samples.js
+++ b/src/lib/samples.ts
@@ -1,61 +1,48 @@
import { PUBLIC_DOMAIN, PUBLIC_COINOS_URL } from "$env/static/public";
-let api = PUBLIC_DOMAIN.includes("localhost")
- ? `${PUBLIC_COINOS_URL}`
- : `https://${PUBLIC_DOMAIN}/api`;
+const api = PUBLIC_DOMAIN.includes("localhost")
+ ? `${PUBLIC_COINOS_URL}`
+ : `https://${PUBLIC_DOMAIN}/api`;
export default {
- register: `curl "${api}/register" -H "content-type: application/json" -d '{
+ register: `curl "${api}/register" -H "content-type: application/json" -d '{
"user": {
"username": "demo",
"password": "hunter2"
}
}'`,
- login: `curl "${api}/login" -H "content-type: application/json" -d '{
+ login: `curl "${api}/login" -H "content-type: application/json" -d '{
"username": "demo",
"password": "hunter2"
}'`,
- payments: `curl "${api}/payments"
+ payments: `curl "${api}/payments"
-H "content-type: application/json"
-H "Authorization: Bearer $token"
`,
- lightning: `curl "${api}/payments"
+ lightning: `curl "${api}/payments"
-H "content-type: application/json"
-H "Authorization: Bearer $token"
-d '{
"payreq": "lnbc1pj94d8fsp5n77k340ps4m9jn7kp8he8yynpddvurv6mcsrrqpnq5l2jxdxzlwqpp5m96pqhc5nrlk8cqsu9ufdxxa43sarp8vwf9egvm2pg9nl0zu9r8qdq2vdhkjmn0wvxqztgcqpjrzjqwhmav82kntsppmkp8jp4vg4h9nns78tsy8mg7ve4lq5txrkp0h56zlarvqqdtcqqsqqqqqqqqqqp6cq9q9qyysgqzxlypywzphyujm3ga5j5csfcmqvlnae0fgnvymkaaw94eeg7py5rqzysyjkr3ev2snq63qpsc69vf54adkd0szvmvwt5cuadjnuy95sq4xfa40"
}'`,
- bitcoin: `curl "${api}/bitcoin/send"
+ bitcoin: `curl "${api}/bitcoin/send"
-H "content-type: application/json"
-H "Authorization: Bearer $token"
-d '{
"amount": 5000,
"address": "bc1q3unh97w4rmelflrm2hvdwz37d8kray3vn4d5ca"
}'`,
- internal: `HASH=$(curl "${api}/invoice"
- -H "content-type: application/json"
- -H "Authorization: Bearer $token"
- -d '{
- "invoice": {
- "amount": 1000,
- "type": "lightning"
- },
- "user": {
- "username": "alice"
- }
- }' | jq -r '.hash');
-
- curl "${api}/payments"
+ internal: `curl "${api}/send"
-H "content-type: application/json"
-H "Authorization: Bearer $token"
-d '{
"amount": 5000,
- "hash": $HASH
+ "username": "alice"
}'`,
- rates: `curl "${api}/rates"
+ rates: `curl "${api}/rates"
-H "content-type: application/json"
}'`,
- lightningInvoice: `curl "${api}/invoice"
+ lightningInvoice: `curl "${api}/invoice"
-H "content-type: application/json"
-H "Authorization: Bearer $token"
-d '{
@@ -64,7 +51,7 @@ export default {
"type": "lightning"
}
}'`,
- bitcoinAddress: `curl "${api}/invoice"
+ bitcoinAddress: `curl "${api}/invoice"
-H "content-type: application/json"
-H "Authorization: Bearer $token"
-d '{
@@ -73,7 +60,7 @@ export default {
"type": "bitcoin"
}
}'`,
- webhook: `curl "${api}/invoice"
+ webhook: `curl "${api}/invoice"
-H "content-type: application/json"
-H "Authorization: Bearer $token"
-d '{
@@ -83,9 +70,9 @@ export default {
"secret": "webhooksecret"
}
}'`,
- fetchInvoice: `curl "${api}/invoice/bc1qmhfk9stzffhd9umzmld92vff7zg3mdlh7rvvaj"
+ fetchInvoice: `curl "${api}/invoice/bc1qmhfk9stzffhd9umzmld92vff7zg3mdlh7rvvaj"
-H "content-type: application/json"'`,
- invoiceResponse: `{
+ invoiceResponse: `{
"amount":3141
"tip":0
"type":"bitcoin"
@@ -98,5 +85,5 @@ export default {
"received":0
"created":1677537428134
}`,
- socketAuth: `echo '{"type":"login","data":{"username":"user","password":"password"}}' | websocat -n https://coinos.io/ws`,
+ socketAuth: `echo '{"type":"login","data":{"username":"user","password":"password"}}' | websocat -n https://coinos.io/ws`,
};
diff --git a/src/lib/socket.js b/src/lib/socket.js
deleted file mode 100644
index f6a6893b..00000000
--- a/src/lib/socket.js
+++ /dev/null
@@ -1,88 +0,0 @@
-import { get } from "svelte/store";
-import { event, invoice, request, newPayment, last } from "$lib/store";
-import { success, sat } from "$lib/utils";
-import { PUBLIC_SOCKET } from "$env/static/public";
-import { invalidate } from "$app/navigation";
-import { browser } from "$app/environment";
-
-let socket, token;
-
-export const auth = () => token && send("login", token);
-
-export const send = (type, data) => {
- socket?.readyState === 1 && socket.send(JSON.stringify({ type, data }));
- return true;
-};
-
-export const messages = (data) => ({
- id() {
- last.set(Date.now());
- },
- invoice() {
- invoice.set(data);
- },
- event() {
- event.set(data);
- },
-
- request() {
- request.set(data);
- invalidate("app:invoice");
- },
-
- async payment() {
- let { amount, confirmed } = data;
- invalidate("app:user");
- invalidate("app:invoice");
- invalidate("app:payments");
-
- if (amount > 0) {
- success(`${confirmed ? "Received" : "Detected"} ${sat(amount)}!`);
- }
- },
-
- connected: auth,
-});
-
-const initialReconnectDelay = 1000;
-const maxReconnectDelay = 16000;
-
-let currentReconnectDelay = initialReconnectDelay;
-
-export function connect(t) {
- token = t;
-
- if (socket) return auth();
-
- socket = new WebSocket(PUBLIC_SOCKET);
- socket.addEventListener("open", onWebsocketOpen);
- socket.addEventListener("close", onWebsocketClose);
- socket.addEventListener("message", onWebsocketMessage);
-}
-
-export function close() {
- if (socket) socket.close();
-}
-
-function onWebsocketMessage(msg) {
- let { type, data } = JSON.parse(msg.data);
- messages(data)[type] && messages(data)[type]();
-}
-
-function onWebsocketOpen() {
- currentReconnectDelay = initialReconnectDelay;
-}
-
-function onWebsocketClose() {
- socket = null;
- setTimeout(() => {
- reconnectToWebsocket();
- }, currentReconnectDelay + Math.floor(Math.random() * 3000));
-}
-
-function reconnectToWebsocket() {
- if (currentReconnectDelay < maxReconnectDelay) {
- currentReconnectDelay *= 2;
- }
- connect(token);
-}
diff --git a/src/lib/socket.ts b/src/lib/socket.ts
new file mode 100644
index 00000000..02d441bf
--- /dev/null
+++ b/src/lib/socket.ts
@@ -0,0 +1,100 @@
+import { invalidate } from "$app/navigation";
+import { navigating } from "$app/stores";
+import { PUBLIC_SOCKET } from "$env/static/public";
+import { event, invoice, last, request } from "$lib/store";
+import { sat, sleep, success, wait } from "$lib/utils";
+import { get } from "svelte/store";
+
+let socket;
+let token;
+
+export const auth = () => token && send("login", token);
+
+export const send = async (type, data) => {
+ try {
+ await wait(() => socket && socket.readyState === 1, 1000, 10);
+ } catch (e: any) {
+ if (e.message === "timeout") reconnectToWebsocket();
+ }
+
+ await wait(() => socket.readyState === 1, 1000, 10);
+ socket.send(JSON.stringify({ type, data }));
+};
+
+export const messages = (data) => ({
+ id() {
+ last.set(Date.now());
+ },
+ invoice() {
+ invoice.set(data);
+ },
+ event() {
+ event.set(data);
+ },
+
+ request() {
+ request.set(data);
+ invalidate("app:invoice");
+ },
+
+ async payment() {
+ const { amount, confirmed } = data;
+ invalidate("app:user");
+ invalidate("app:invoice");
+ invalidate("app:payments");
+
+ if (amount > 0) {
+ success(`${confirmed ? "Received" : "Detected"} ${sat(amount)}!`);
+ }
+ },
+
+ connected: auth,
+});
+
+const initialReconnectDelay = 1000;
+const maxReconnectDelay = 16000;
+
+let currentReconnectDelay = initialReconnectDelay;
+
+export function connect(t) {
+ token = t;
+
+ if (socket) return auth();
+
+ socket = new WebSocket(PUBLIC_SOCKET);
+ socket.addEventListener("open", onWebsocketOpen);
+ socket.addEventListener("close", onWebsocketClose);
+ socket.addEventListener("message", onWebsocketMessage);
+}
+
+export function close() {
+ if (socket) socket.close();
+}
+
+async function onWebsocketMessage(msg) {
+ const { type, data } = JSON.parse(msg.data);
+ if (get(navigating)) await sleep(2000);
+
+ if (messages(data)[type]) messages(data)[type]();
+}
+
+function onWebsocketOpen() {
+ currentReconnectDelay = initialReconnectDelay;
+}
+
+function onWebsocketClose() {
+ socket = null;
+ setTimeout(
+ () => {
+ reconnectToWebsocket();
+ },
+ currentReconnectDelay + Math.floor(Math.random() * 3000),
+ );
+}
+
+function reconnectToWebsocket() {
+ if (currentReconnectDelay < maxReconnectDelay) {
+ currentReconnectDelay *= 2;
+ }
+ connect(token);
+}
diff --git a/src/lib/store.js b/src/lib/store.js
deleted file mode 100644
index 6245fb76..00000000
--- a/src/lib/store.js
+++ /dev/null
@@ -1,58 +0,0 @@
-import { get, writable } from "svelte/store";
-import { browser } from "$app/environment";
-
-let persistSession = (key, defaultValue) => {
- let s = writable(
- browser &&
- sessionStorage.getItem(key) &&
- sessionStorage.getItem(key) !== "undefined"
- ? JSON.parse(sessionStorage.getItem(key))
- : defaultValue
- );
-
- s.subscribe((v) => {
- browser && sessionStorage.setItem(key, JSON.stringify(v));
- });
-
- return s;
-};
-
-let persistLocal = (key, defaultValue) => {
- let s = writable(
- browser &&
- localStorage.getItem(key) &&
- localStorage.getItem(key) !== "undefined"
- ? JSON.parse(localStorage.getItem(key))
- : defaultValue
- );
-
- s.subscribe((v) => {
- try {
- browser && localStorage.setItem(key, JSON.stringify(v));
- } catch (e) {
- console.log("problem setting key", v);
- console.log(e);
- }
- });
-
- return s;
-};
-
-export let avatar = writable();
-export let banner = writable();
-export let event = writable();
-export let events = writable({});
-export let invoice = writable();
-export let last = writable();
-export let loginRedirect = writable();
-export let decrypted = persistLocal("decrypted", {});
-export let newPayment = persistLocal("newPayment");
-export let password = writable();
-export let passwordPrompt = writable();
-export let pin = persistLocal("pin");
-export let rate = writable();
-export let request = writable();
-export let requestRedirect = writable();
-export let token = persistSession("token");
-export let ndef = writable();
-export let showQr = persistLocal("showQr");
diff --git a/src/lib/store.ts b/src/lib/store.ts
new file mode 100644
index 00000000..3156d0e2
--- /dev/null
+++ b/src/lib/store.ts
@@ -0,0 +1,62 @@
+import { writable } from "svelte/store";
+import { browser } from "$app/environment";
+
+const persistSession = (key, defaultValue = undefined) => {
+ const s = writable(
+ browser &&
+ sessionStorage.getItem(key) &&
+ sessionStorage.getItem(key) !== "undefined"
+ ? JSON.parse(sessionStorage.getItem(key) || "")
+ : defaultValue,
+ );
+
+ s.subscribe((v) => {
+ browser && sessionStorage.setItem(key, JSON.stringify(v));
+ });
+
+ return s;
+};
+
+const persistLocal = (key, defaultValue: any = undefined) => {
+ const s = writable(
+ browser &&
+ localStorage.getItem(key) &&
+ localStorage.getItem(key) !== "undefined"
+ ? JSON.parse(localStorage.getItem(key) || "")
+ : defaultValue,
+ );
+
+ s.subscribe((v) => {
+ try {
+ browser && localStorage.setItem(key, JSON.stringify(v));
+ } catch (e) {
+ console.log("problem setting key", v);
+ console.log(e);
+ }
+ });
+
+ return s;
+};
+
+export const account = writable();
+export const amountPrompt = persistLocal("amountPrompt");
+export const avatar = writable();
+export const banner = writable();
+export const event = writable();
+export const events = writable({});
+export const installPrompt = writable();
+export const invoice = writable();
+export const last = writable();
+export const loginRedirect = writable();
+export const decrypted = persistLocal("decrypted", {});
+export const mnemonic = persistSession("mnemonic");
+export const newPayment = persistLocal("newPayment");
+export const password = writable<string | undefined>();
+export const passwordPrompt = writable();
+export const pin = persistLocal("pin");
+export const rate = writable();
+export const request = writable();
+export const requestRedirect = writable();
+export const token = persistSession("token");
+export const ndef = writable();
+export const showQr = persistLocal("showQr", true);
diff --git a/src/lib/ticket.js b/src/lib/ticket.js
deleted file mode 100644
index 73ef7716..00000000
--- a/src/lib/ticket.js
+++ /dev/null
@@ -1,31 +0,0 @@
-import { auth, get, post } from "$lib/utils";
-import { env } from "$env/dynamic/private";
-import tickets from "$lib/tickets";
-
-export const createTicket = async (cookies, username) => {
- let { ticket } = await get("/ticket");
-
- let { address } = await post(
- `/${username}/invoice`,
- { invoice: { network: "liquid" }, user: { username } },
- auth(cookies)
- );
-
- let { asset } = await post(
- "/assets",
- {
- address,
- name: `Launch Party Ticket ${ticket}`,
- ticker: "LPT",
- precision: 0,
- asset_amount: "1",
- token_amount: 0,
- domain: "coinos.io",
- filename: tickets[ticket],
- },
- { authorization: `Bearer ${env.LAUNCH}` }
- );
-
- await post("/ticket", { asset }, { authorization: `Bearer ${env.LAUNCH}` });
- return asset;
-};
diff --git a/src/lib/ticket.ts b/src/lib/ticket.ts
new file mode 100644
index 00000000..0d93f390
--- /dev/null
+++ b/src/lib/ticket.ts
@@ -0,0 +1,31 @@
+import { auth, get, post } from "$lib/utils";
+import { env } from "$env/dynamic/private";
+import tickets from "$lib/tickets";
+
+export const createTicket = async (cookies, username) => {
+ const { ticket } = await get("/ticket");
+
+ const { address } = await post(
+ `/${username}/invoice`,
+ { invoice: { network: "liquid" }, user: { username } },
+ auth(cookies),
+ );
+
+ const { asset } = await post(
+ "/assets",
+ {
+ address,
+ name: `Launch Party Ticket ${ticket}`,
+ ticker: "LPT",
+ precision: 0,
+ asset_amount: "1",
+ token_amount: 0,
+ domain: "coinos.io",
+ filename: tickets[ticket],
+ },
+ { authorization: `Bearer ${env.LAUNCH}` },
+ );
+
+ await post("/ticket", { asset }, { authorization: `Bearer ${env.LAUNCH}` });
+ return asset;
+};
diff --git a/src/lib/tickets.js b/src/lib/tickets.js
deleted file mode 100644
index 1f8cbdac..00000000
--- a/src/lib/tickets.js
+++ /dev/null
@@ -1,52 +0,0 @@
-export default [
- "QmPbFkiXNuaQyfwD4W9GcXP7qWaNd6wFd9KCnJir5mes1J",
- "QmPVjvbaMxSJRpDxMLYTdUWQbknej1vYLckBQ2pAgxZgJN",
- "QmVasycSFzCYhyXrcvTE7mN3d6W78RFnrhzg5cRF6Dp6Zq",
- "QmTmnhjpTBjZdeHwXgT9Dftc3uWMW73qsZpZ5ECrTyiKKZ",
- "QmWDBiyVPyFkzUrEdvy7DSJe1rBQpene1m6quKAtyjBP6a",
- "QmcxxzQZwgG7SE9QbHNvoTiCi6Dhs9rrz9roqvxm2JQA88",
- "Qmd9ThEpXLLHimEzRUWEFrAGLSw5PAHzn2SmwfCnjNLwWt",
- "Qmc7pWw1yxc2ARBWitDMYiyPkWK61NsXXU8oYAQwNAvcx1",
- "QmX9Hgw1rMFUgBBuq8QfZZDzLjN5xCED19fwFdDeDDqwmr",
- "QmconCAyNyaagqKvvfKCbG7Eu8c6vCtkv2ivvxMoFN9YwA",
- "QmWbFmvViy5gx4JdD5sw5YJETet4ZQcXtYgijYnrsnSZ3a",
- "QmP6QiiJwoqkduZMqdd5e5htHZ4aYHCsvEu7WEEUknKYa5",
- "QmefHk8hvBUHsuKugntok5u75Q8i886cnPwsj4LZZB6uWg",
- "QmdrSDK5ByYHxc88hfDu8hQgK5XYFpXSfPorUXdyTbE437",
- "QmZ6ZycjRzYpsjnLm1Lfgk1fXXDdhcYRkyfmqYJZVGwADy",
- "QmSkBxS5yLPjB2VPs89oQRZANsoyodK6s8s52E8GKXr2zt",
- "QmSn8TCPwq3UZ1Z4eyko76CvQo2H2Hyef1NGboDQN22m5i",
- "QmP6CTH5zrKMzZwtjy7VaK9NXiq4Gw53kmuRjUbJjeovoe",
- "QmdwT4yvz9Xf8g3t6irKRoh3Wa7MwRQrcUJckQxyQe1Bc5",
- "QmcwuHH3bD5JExqjDvKqRQ3V5xEVGqs94qPNVDzaCqJa5a",
- "QmRfVduHwn8sXwSoyfgZpxSi8L7EjP4LMp6fmijo9VApDp",
- "Qmc4TGj1Ahbg9HJ9WDXDm2bXsNkT4zRDp8Wdw9wqqdEwuH",
- "QmY8uQiHMWA8ztf2wAurNFW7eiTHQEUiLTQ2vGceMwVqz3",
- "QmXiXbaD12F4mkbUSQcKhWshkPU4oi29cUawZGnPk86VVU",
- "QmZaiAGjvBZBw4suz33s9JQNzY2Kshean2mQQPCa6gKMQe",
- "Qme8bDSdzX7tanPYf672xXW8vPdkLkeSLqLzHJqidRXsYJ",
- "QmRJirjuUKgh2AMyBF4jNquaXHFPBtDJf3gKFC614hX7qu",
- "QmdRoSKSgabcrpekNBPB6T47RBtJnCETYE8ry2a3P37MUe",
- "QmXoqArruHSghrUGW35vVQHPknBG5Cj939iWWHHXU3B616",
- "QmYCxtDuoHLMAFhNpifUsLU9ptAeFKwyxSiSEJhDQLMZtN",
- "QmQZQBw8wgzUsrmVDEejdePK23AEJbk9aUracvxLPyHz2x",
- "QmSsbu7U3i62AQKuYqfisRo5E6nqdMZfHRKWYJgouaXDxD",
- "QmaP4adVQuWyqtN4QCXeYXj4nr19Je4EqsaTG1zM9ywqFS",
- "QmPPsvgfXsiN3wNqdAwHAhQVpw6SZWNpry9Na6R2Xb7zXY",
- "QmR7z6wQmcfZUvRsVK83GRRboyvwZEDQujLwumMY33nAit",
- "QmQXgkgorDLPUyQpFbW8aLUW6jioQjUKamtXw5UuNCttDg",
- "QmcwYBeXt1BPfdSrtSrXFpWctRZ7RDHvmKTttC5hPPTSzG",
- "QmTUexZnw3xPy3YVdUsqJALwTvy2qFax5b3QpJVMvTCJQb",
- "QmNLkYXFUvctpfeeDTZxruZE2f834EUnYMM6JJUeTcUB4J",
- "QmT7544UaTPgKFYMCpPE4unXphNGX71BLZBPKLkxAijSmj",
- "QmTpVR4dqX1QV4fae5pZ1ACtRcANHwEWCLwpMXFmwE95Sm",
- "Qmdfyps5fW8d8wstXMfpvpei2DTmaADBWgmxLT7e7uan4P",
- "QmUSK8byipYoG3H97QpmPrHw9vYrvHygyhkiM81XmaKyxS",
- "QmQUGRvp96LTw5i8Ly9f5LoMvUpeQHCLGNqC88KV74wEHK",
- "Qma693TFLh9Z1MeBFzhPHi6Yk4tmTcZY2jogwJ8cPkU2B4",
- "QmNu8FyMpmkFdbCXGRVG8mKJtMvvCoLP8LNzFsxBQwxQeS",
- "QmWZHE87PKujL1MGLuFgP3D12o5GQxYbvbeTRgr12f1XMu",
- "QmcZJn8gPGd3poS9yuiNJh6iP4cn9uy5fnypky71r4sSSw",
- "QmTwrAF4E9ucpdnrUZFj6EfrQamGv7Qyn7ceSx1DUQYceC",
- "QmexssxU5iTXypgNqrmrQwMDJnTNxyZUxor5wDLnwb5TZp",
-];
diff --git a/src/lib/tickets.ts b/src/lib/tickets.ts
new file mode 100644
index 00000000..f37fad78
--- /dev/null
+++ b/src/lib/tickets.ts
@@ -0,0 +1,52 @@
+export default [
+ "QmPbFkiXNuaQyfwD4W9GcXP7qWaNd6wFd9KCnJir5mes1J",
+ "QmPVjvbaMxSJRpDxMLYTdUWQbknej1vYLckBQ2pAgxZgJN",
+ "QmVasycSFzCYhyXrcvTE7mN3d6W78RFnrhzg5cRF6Dp6Zq",
+ "QmTmnhjpTBjZdeHwXgT9Dftc3uWMW73qsZpZ5ECrTyiKKZ",
+ "QmWDBiyVPyFkzUrEdvy7DSJe1rBQpene1m6quKAtyjBP6a",
+ "QmcxxzQZwgG7SE9QbHNvoTiCi6Dhs9rrz9roqvxm2JQA88",
+ "Qmd9ThEpXLLHimEzRUWEFrAGLSw5PAHzn2SmwfCnjNLwWt",
+ "Qmc7pWw1yxc2ARBWitDMYiyPkWK61NsXXU8oYAQwNAvcx1",
+ "QmX9Hgw1rMFUgBBuq8QfZZDzLjN5xCED19fwFdDeDDqwmr",
+ "QmconCAyNyaagqKvvfKCbG7Eu8c6vCtkv2ivvxMoFN9YwA",
+ "QmWbFmvViy5gx4JdD5sw5YJETet4ZQcXtYgijYnrsnSZ3a",
+ "QmP6QiiJwoqkduZMqdd5e5htHZ4aYHCsvEu7WEEUknKYa5",
+ "QmefHk8hvBUHsuKugntok5u75Q8i886cnPwsj4LZZB6uWg",
+ "QmdrSDK5ByYHxc88hfDu8hQgK5XYFpXSfPorUXdyTbE437",
+ "QmZ6ZycjRzYpsjnLm1Lfgk1fXXDdhcYRkyfmqYJZVGwADy",
+ "QmSkBxS5yLPjB2VPs89oQRZANsoyodK6s8s52E8GKXr2zt",
+ "QmSn8TCPwq3UZ1Z4eyko76CvQo2H2Hyef1NGboDQN22m5i",
+ "QmP6CTH5zrKMzZwtjy7VaK9NXiq4Gw53kmuRjUbJjeovoe",
+ "QmdwT4yvz9Xf8g3t6irKRoh3Wa7MwRQrcUJckQxyQe1Bc5",
+ "QmcwuHH3bD5JExqjDvKqRQ3V5xEVGqs94qPNVDzaCqJa5a",
+ "QmRfVduHwn8sXwSoyfgZpxSi8L7EjP4LMp6fmijo9VApDp",
+ "Qmc4TGj1Ahbg9HJ9WDXDm2bXsNkT4zRDp8Wdw9wqqdEwuH",
+ "QmY8uQiHMWA8ztf2wAurNFW7eiTHQEUiLTQ2vGceMwVqz3",
+ "QmXiXbaD12F4mkbUSQcKhWshkPU4oi29cUawZGnPk86VVU",
+ "QmZaiAGjvBZBw4suz33s9JQNzY2Kshean2mQQPCa6gKMQe",
+ "Qme8bDSdzX7tanPYf672xXW8vPdkLkeSLqLzHJqidRXsYJ",
+ "QmRJirjuUKgh2AMyBF4jNquaXHFPBtDJf3gKFC614hX7qu",
+ "QmdRoSKSgabcrpekNBPB6T47RBtJnCETYE8ry2a3P37MUe",
+ "QmXoqArruHSghrUGW35vVQHPknBG5Cj939iWWHHXU3B616",
+ "QmYCxtDuoHLMAFhNpifUsLU9ptAeFKwyxSiSEJhDQLMZtN",
+ "QmQZQBw8wgzUsrmVDEejdePK23AEJbk9aUracvxLPyHz2x",
+ "QmSsbu7U3i62AQKuYqfisRo5E6nqdMZfHRKWYJgouaXDxD",
+ "QmaP4adVQuWyqtN4QCXeYXj4nr19Je4EqsaTG1zM9ywqFS",
+ "QmPPsvgfXsiN3wNqdAwHAhQVpw6SZWNpry9Na6R2Xb7zXY",
+ "QmR7z6wQmcfZUvRsVK83GRRboyvwZEDQujLwumMY33nAit",
+ "QmQXgkgorDLPUyQpFbW8aLUW6jioQjUKamtXw5UuNCttDg",
+ "QmcwYBeXt1BPfdSrtSrXFpWctRZ7RDHvmKTttC5hPPTSzG",
+ "QmTUexZnw3xPy3YVdUsqJALwTvy2qFax5b3QpJVMvTCJQb",
+ "QmNLkYXFUvctpfeeDTZxruZE2f834EUnYMM6JJUeTcUB4J",
+ "QmT7544UaTPgKFYMCpPE4unXphNGX71BLZBPKLkxAijSmj",
+ "QmTpVR4dqX1QV4fae5pZ1ACtRcANHwEWCLwpMXFmwE95Sm",
+ "Qmdfyps5fW8d8wstXMfpvpei2DTmaADBWgmxLT7e7uan4P",
+ "QmUSK8byipYoG3H97QpmPrHw9vYrvHygyhkiM81XmaKyxS",
+ "QmQUGRvp96LTw5i8Ly9f5LoMvUpeQHCLGNqC88KV74wEHK",
+ "Qma693TFLh9Z1MeBFzhPHi6Yk4tmTcZY2jogwJ8cPkU2B4",
+ "QmNu8FyMpmkFdbCXGRVG8mKJtMvvCoLP8LNzFsxBQwxQeS",
+ "QmWZHE87PKujL1MGLuFgP3D12o5GQxYbvbeTRgr12f1XMu",
+ "QmcZJn8gPGd3poS9yuiNJh6iP4cn9uy5fnypky71r4sSSw",
+ "QmTwrAF4E9ucpdnrUZFj6EfrQamGv7Qyn7ceSx1DUQYceC",
+ "QmexssxU5iTXypgNqrmrQwMDJnTNxyZUxor5wDLnwb5TZp",
+];
diff --git a/src/lib/translations/index.js b/src/lib/translations/index.js
index f8fbd9c2..cd7c20dd 100644
--- a/src/lib/translations/index.js
+++ b/src/lib/translations/index.js
@@ -1,28 +1,9 @@
import i18n from "sveltekit-i18n";
-import lang from "./lang.json";
-
-// setup loaders & translations from lang.json data
-function createLocaleLoader(localeCode) {
- return {
- locale: localeCode,
- key: "",
- loader: async () =>
- (await import(`../../locales/${localeCode}.json`)).default,
- };
-}
-
-const availableLocales = Object.keys(lang);
-const trans = {};
-for (let i = 0; i < availableLocales.length; i++) {
- trans[availableLocales[i]] = { lang };
-}
-const loaders = availableLocales.map(createLocaleLoader);
export const defaultLocale = "en";
const config = {
fallbackLocale: "en",
- translations: trans,
loaders: [
{
locale: "en",
diff --git a/src/lib/translations/lang.json b/src/lib/translations/lang.json
index c301a550..8c302ce9 100644
--- a/src/lib/translations/lang.json
+++ b/src/lib/translations/lang.json
@@ -6,7 +6,7 @@
"ja": "日本語",
"ru": "Русский",
"pt": "Português",
- "zh": "中国人",
+ "zh": "中文",
"fa": "فارسی ",
"el": "Ελληνικά"
}
diff --git a/src/lib/types.ts b/src/lib/types.ts
new file mode 100644
index 00000000..19277ec1
--- /dev/null
+++ b/src/lib/types.ts
@@ -0,0 +1,23 @@
+export interface Message {
+ author: User;
+ created_at: number;
+ recipient: User;
+}
+
+export interface Note {
+ created_at: number;
+ seen: number;
+}
+
+export interface User {
+ id: string;
+}
+
+export interface Invoice {
+ aid: string;
+ id?: string;
+ memoPrompt?: boolean;
+ memo?: string;
+ rate: number;
+ type?: string;
+}
diff --git a/src/lib/upload.js b/src/lib/upload.js
deleted file mode 100644
index 31c235c6..00000000
--- a/src/lib/upload.js
+++ /dev/null
@@ -1,18 +0,0 @@
-export const upload = async (file, type, progress) => {
- let url = `/api/upload/${type}`;
- let formData = new FormData();
- formData.append("file", file);
-
- return new Promise((resolve, reject) => {
- let ajax = new XMLHttpRequest();
- ajax.addEventListener("load", () => {
- if (ajax.readyState === ajax.DONE) {
- if (ajax.status === 200) resolve(ajax.response);
- else reject(new Error(`Upload failed: ${ajax.response}`));
- }
- });
- ajax.upload.addEventListener("progress", progress, false);
- ajax.open("POST", url);
- ajax.send(formData);
- });
-};
diff --git a/src/lib/upload.ts b/src/lib/upload.ts
new file mode 100644
index 00000000..6d9d4230
--- /dev/null
+++ b/src/lib/upload.ts
@@ -0,0 +1,18 @@
+export const upload = async (file, type, progress) => {
+ const url = `/api/upload/${type}`;
+ const formData = new FormData();
+ formData.append("file", file);
+
+ return new Promise((resolve, reject) => {
+ const ajax = new XMLHttpRequest();
+ ajax.addEventListener("load", () => {
+ if (ajax.readyState === ajax.DONE) {
+ if (ajax.status === 200) resolve(ajax.response);
+ else reject(new Error(`Upload failed: ${ajax.response}`));
+ }
+ });
+ ajax.upload.addEventListener("progress", progress, false);
+ ajax.open("POST", url);
+ ajax.send(formData);
+ });
+};
diff --git a/src/lib/utils.js b/src/lib/utils.js
deleted file mode 100644
index 6902c928..00000000
--- a/src/lib/utils.js
+++ /dev/null
@@ -1,333 +0,0 @@
-import { browser } from "$app/environment";
-import { toast } from "@zerodevx/svelte-toast";
-import { goto } from "$app/navigation";
-import { PUBLIC_COINOS_URL } from "$env/static/public";
-import { page } from "$app/stores";
-import { get as getStore } from "svelte/store";
-
-export function scroll(section) {
- if (getStore(page).url.pathname !== "/") goto("/");
- setTimeout(() => section.scrollIntoView({ behavior: "smooth" }), 500);
-}
-
-let base = browser ? "" : PUBLIC_COINOS_URL;
-
-export let punk = (k) =>
- Math.floor((parseInt(k.slice(-2), 16) / 256) * 64) + 1 + ".webp";
-
-export let g = (url, fetch, headers) =>
- fetch(base + url, { headers })
- .then((r) => r.text())
- .then((body) => {
- try {
- return JSON.parse(body);
- } catch (e) {
- throw new Error(body);
- }
- });
-
-export let get = (url, headers = {}) => {
- return fetch(base + url, { headers })
- .then(async (r) => {
- if (r.ok) return r.text();
- throw new Error(await r.text());
- })
- .then((body) => {
- try {
- return JSON.parse(body);
- } catch (e) {
- return body;
- }
- });
-};
-
-export let post = async (url, body, headers) => {
- headers = {
- "content-type": "application/json",
- accept: "application/json",
- ...headers,
- };
-
- let response = await fetch(base + url, {
- method: "POST",
- body: JSON.stringify(body),
- headers,
- })
- .then(async (r) => {
- if (r.ok) return r.text();
- let text = await r.text();
-
- let message;
- try {
- ({ message } = JSON.parse(text));
- } catch (e) {}
-
- if (message) throw new Error(message);
- throw new Error(text);
- })
- .then((body) => {
- try {
- body = JSON.parse(body);
- } catch (e) {
- throw new Error(body);
- }
-
- if (body.error instanceof Error) throw body.error;
- if (body instanceof Error) throw body;
- if (body.name === "Error") throw new Error(body.message);
-
- return body;
- });
-
- return response;
-};
-
-export let copy = (text) => {
- navigator.clipboard.writeText(text);
- success("Copied!");
-};
-
-export let copyNoNewlines = (text) => {
- let stripped = text.replace(/\n/g, " ").replace(/\s+/g, " ");
- navigator.clipboard.writeText(stripped);
- success("Copied!");
-};
-
-export function reverseFormat(val, locale) {
- let parts = new Intl.NumberFormat(locale).formatToParts(1111.1);
- let group = parts.find((part) => part.type === "group").value;
- let decimal = parts.find((part) => part.type === "decimal").value;
- let reversedVal = val.replace(new RegExp("\\" + group, "g"), "");
- reversedVal = reversedVal.replace(new RegExp("\\" + decimal, "g"), ".");
- return Number.isNaN(reversedVal) ? 0 : +reversedVal;
-}
-
-export let protectedRoutes = [/customers/, /settings/, /payments/];
-
-let recent = [];
-export let success = (m, clear = true) => {
- if (recent.includes(m)) return;
- recent.push(m);
- setTimeout(() => (recent = []), 5000);
- if (clear) toast.pop();
- toast.push(m, {
- theme: {
- "--toastBarBackground": "#F5F7FA",
- },
- });
-};
-
-export let warning = (m, clear = true) => {
- if (clear) toast.pop();
- toast.push(m, {
- theme: {
- "--toastBarBackground": "#FFCE22",
- },
- });
-};
-export let fail = (m, clear = true) => {
- if (clear) toast.pop();
- toast.push(m, {
- theme: {
- "--toastBarBackground": "#E93535",
- },
- });
-};
-export let info = (m) => {
- toast.pop();
- toast.push(m, {
- theme: {
- "--toastBarBackground": "white",
- },
- });
-};
-
-export let login = async (user, cookies, ip) => {
- let maxAge = 380 * 24 * 60 * 60;
-
- let res = await fetch(base + "/login", {
- method: "POST",
- body: JSON.stringify(user),
- headers: {
- "content-type": "application/json",
- accept: "application/json",
- "cf-connecting-ip": ip,
- },
- });
- if (res.status === 401) {
- let text = await res.text();
- if (text.startsWith("2fa")) throw new Error("2fa");
- }
-
- let { user: u, token } = await res.json();
- if (!token) throw new Error("Login failed");
-
- let expires = new Date();
- expires.setSeconds(expires.getSeconds() + maxAge);
-
- let opts = { path: "/", expires };
- if (u.language) cookies.set("lang", u.language, opts);
- cookies.set("username", user.username, opts);
- cookies.set("token", token, opts);
-};
-
-export let auth = (cookies) => ({
- authorization: `Bearer ${cookies.get("token")}`,
-});
-
-export let btc = (fiat, rate) => Math.round((fiat * sats) / rate);
-export let fiat = (amount, rate) => (amount * rate) / sats;
-export let fd = async (req) => {
- let obj = Object.fromEntries(await req.formData());
- for (let k in obj)
- (obj[k] === "undefined" && (obj[k] = undefined)) ||
- (obj[k] === "false" && (obj[k] = false));
- return obj;
-};
-
-export let f = (s, currency) =>
- new Intl.NumberFormat("en-US", {
- style: "currency",
- currency,
- })
- .format(s)
- .replace("CA", "");
-
-export let s = (s) =>
- new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(s);
-
-export let sat = (s) => {
- s = Math.abs(s);
- let p = Math.floor(Math.log(s) / Math.LN10 + 0.000000001);
- let d = Math.floor((p + 1) / 3);
-
- return (
- "⚡️" +
- (parseInt(s) > 0
- ? new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(
- s / Math.pow(1000, d)
- ) + ["", "K", "M", "G", "T", "P", "E", "Z"][d]
- : 0
- ).toString()
- );
-};
-
-export let sats = 100000000;
-
-export let back = () =>
- browser && (history.length ? history.go(-1) : goto("/"));
-
-export let focus = (el) =>
- browser && screen.width > 1280 && setTimeout(() => el.focus(), 1);
-
-export let select = (el) =>
- browser && screen.width > 1280 && setTimeout(() => el.select(), 1);
-
-export let sleep = (n) => new Promise((r) => setTimeout(r, n));
-export let wait = async (f, n = 100, s = 300) => {
- let i = 0;
- while (!(await f()) && i < s) (await sleep(n)) && i++;
- if (i >= s) throw new Error("timeout");
- return f();
-};
-
-export let stretch = async (password, salt) =>
- crypto.subtle.deriveKey(
- {
- name: "PBKDF2",
- salt,
- iterations: 100000,
- hash: "SHA-256",
- },
- await crypto.subtle.importKey(
- "raw",
- new TextEncoder().encode(password),
- { name: "PBKDF2" },
- false,
- ["deriveBits", "deriveKey"]
- ),
- { name: "AES-GCM", length: 256 },
- true,
- ["encrypt", "decrypt"]
- );
-
-function get_bigrams(string) {
- var s = string.toLowerCase();
- var v = s.split("");
- for (var i = 0; i < v.length; i++) {
- v[i] = s.slice(i, i + 2);
- }
- return v;
-}
-
-export function ss(str1, str2) {
- if (str1.length > 0 && str2.length > 0) {
- var pairs1 = get_bigrams(str1);
- var pairs2 = get_bigrams(str2);
- var union = pairs1.length + pairs2.length;
- var hits = 0;
- for (var x = 0; x < pairs1.length; x++) {
- for (var y = 0; y < pairs2.length; y++) {
- if (pairs1[x] == pairs2[y]) hit_count++;
- }
- }
- if (hits > 0) return (2.0 * hits) / union;
- }
-
- return 0.0;
-}
-
-export let types = {
- bitcoin: "bitcoin",
- liquid: "liquid",
- lightning: "lightning",
- internal: "internal",
- fund: "fund",
-};
-
-export let ease = (t) =>
- t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
-
-export function shuffleArray(array) {
- for (let i = array.length - 1; i > 0; i--) {
- const j = Math.floor(Math.random() * (i + 1));
- [array[i], array[j]] = [array[j], array[i]];
- }
-}
-
-export let closest = (a, n) =>
- a.reduce((prev, curr) =>
- Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev
- );
-
-export let isLiquid = (text) =>
- text.startsWith("Az") ||
- text.startsWith("lq1") ||
- text.startsWith("VJL") ||
- text.startsWith("VT") ||
- text.startsWith("XR") ||
- text.startsWith("XC") ||
- ((text.startsWith("H") || text.startsWith("G") || text.startsWith("Q")) &&
- text.length === 34) ||
- (text.startsWith("ert1q") && text.length === 43) ||
- (text.startsWith("ex1q") && text.length === 42) ||
- text.startsWith("el1qq") ||
- text.startsWith("lq1qq");
-
-export function getCookie(name) {
- let nameEQ = name + "=";
- let ca = document.cookie.split(";");
- for (let i = 0; i < ca.length; i++) {
- let c = ca[i];
- while (c.charAt(0) === " ") c = c.substring(1);
- if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
- }
- return null;
-}
-
-export function setCookie(name, value, seconds) {
- const now = new Date();
- now.setTime(now.getTime() + seconds * 1000);
- const expires = "expires=" + now.toUTCString();
- document.cookie = name + "=" + value + ";" + expires + ";path=/";
-}
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
new file mode 100644
index 00000000..b27ce5f1
--- /dev/null
+++ b/src/lib/utils.ts
@@ -0,0 +1,364 @@
+import { browser } from "$app/environment";
+import { goto } from "$app/navigation";
+import { page } from "$app/stores";
+import { PUBLIC_COINOS_NETWORK, PUBLIC_COINOS_URL } from "$env/static/public";
+import { toast } from "@zerodevx/svelte-toast";
+import { get as getStore } from "svelte/store";
+
+export function scroll(section: any) {
+ if (getStore(page).url.pathname !== "/") goto("/");
+ setTimeout(() => section.scrollIntoView({ behavior: "smooth" }), 500);
+}
+
+const base = browser ? "" : PUBLIC_COINOS_URL;
+
+export const punk = (k: string) =>
+ `${Math.floor((parseInt(k.slice(-2), 16) / 256) * 64) + 1}.webp`;
+
+export const g = (url: string, fetch: any, headers: object) =>
+ fetch(base + url, { headers })
+ .then((r: Response) => r.text())
+ .then((body: string) => {
+ try {
+ return JSON.parse(body);
+ } catch (e) {
+ throw new Error(body);
+ }
+ });
+
+export const get = (url: string, headers = {}) => {
+ return fetch(base + url, { headers })
+ .then(async (r) => {
+ if (r.ok) return r.text();
+ throw new Error(await r.text());
+ })
+ .then((body) => {
+ try {
+ return JSON.parse(body);
+ } catch (e) {
+ return body;
+ }
+ });
+};
+
+export const post = async (
+ url: string,
+ body: object,
+ headers: HeadersInit | undefined = undefined,
+) => {
+ headers = {
+ "content-type": "application/json",
+ accept: "application/json",
+ ...headers,
+ };
+
+ const response = await fetch(base + url, {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers,
+ })
+ .then(async (r) => {
+ if (r.ok) return r.text();
+ const text = await r.text();
+
+ let message;
+ try {
+ ({ message } = JSON.parse(text));
+ } catch (e) {}
+
+ if (message) throw new Error(message);
+ throw new Error(text);
+ })
+ .then((body) => {
+ let json;
+ try {
+ json = JSON.parse(body);
+ } catch (e) {
+ throw new Error(body);
+ }
+
+ if (json.error instanceof Error) throw json.error;
+ if (json instanceof Error) throw body;
+ if (json.name === "Error") throw new Error(json.message);
+
+ return json;
+ });
+
+ return response;
+};
+
+export const copy = (text: string) => {
+ navigator.clipboard.writeText(text);
+ success("Copied!");
+};
+
+export const copyNoNewlines = (text: string) => {
+ const stripped = text.replace(/\n/g, " ").replace(/\s+/g, " ");
+ navigator.clipboard.writeText(stripped);
+ success("Copied!");
+};
+
+export function reverseFormat(val: string, locale: string): number {
+ const parts = new Intl.NumberFormat(locale).formatToParts(1111.1);
+ const group = parts.find((part) => part.type === "group")?.value;
+ const decimal = parts.find((part) => part.type === "decimal")?.value;
+ let reversedVal = val.replace(new RegExp(`\\${group}`, "g"), "");
+ reversedVal = reversedVal.replace(new RegExp(`\\${decimal}`, "g"), ".");
+ return Number.isNaN(reversedVal) ? 0 : +reversedVal;
+}
+
+export const protectedRoutes: RegExp[] = [/customers/, /settings/, /payments/];
+
+let recent: string[] = [];
+export const success = (m: string, clear = true) => {
+ if (recent.includes(m)) return;
+ recent.push(m);
+ setTimeout(() => (recent = []), 5000);
+ if (clear) toast.pop();
+ toast.push(m, {
+ theme: {
+ "--toastBarBackground": "#F5F7FA",
+ },
+ });
+};
+
+export const warning = (m: string, clear = true) => {
+ if (clear) toast.pop();
+ toast.push(m, {
+ theme: {
+ "--toastBarBackground": "#FFCE22",
+ },
+ });
+};
+
+export const fail = (m: string, clear = true) => {
+ if (clear) toast.pop();
+ toast.push(m, {
+ theme: {
+ "--toastBarBackground": "#E93535",
+ },
+ });
+};
+
+export const info = (m: string) => {
+ toast.pop();
+ toast.push(m, {
+ theme: {
+ "--toastBarBackground": "white",
+ },
+ });
+};
+
+export const login = async (
+ user: { username: string; password: string },
+ cookies: any,
+ ip: string,
+) => {
+ const maxAge = 380 * 24 * 60 * 60;
+
+ const res = await fetch(`${base}/login`, {
+ method: "POST",
+ body: JSON.stringify(user),
+ headers: {
+ "content-type": "application/json",
+ accept: "application/json",
+ "cf-connecting-ip": ip,
+ },
+ });
+ if (res.status === 401) {
+ const text = await res.text();
+ if (text.startsWith("2fa")) throw new Error("2fa");
+ }
+
+ const { user: u, token } = await res.json();
+ if (!token) throw new Error("Login failed");
+
+ const expires = new Date();
+ expires.setSeconds(expires.getSeconds() + maxAge);
+
+ const opts = { path: "/", expires };
+ if (u.language) cookies.set("lang", u.language, opts);
+ cookies.set("username", user.username, opts);
+ cookies.set("token", token, opts);
+};
+
+export const auth = (cookies: any) => ({
+ authorization: `Bearer ${cookies.get("token")}`,
+});
+
+export const btc = (fiat: number, rate: number): number =>
+ Math.round((fiat * sats) / rate);
+
+export const fiat = (amount: number, rate: number): number =>
+ (amount * rate) / sats;
+
+export const fd = async (req: Request): Promise<any> => {
+ const obj: Record<string, any> = Object.fromEntries(await req.formData());
+ for (const k in obj)
+ (obj[k] === "undefined" && (obj[k] = undefined)) ||
+ (obj[k] === "false" && (obj[k] = false));
+ return obj;
+};
+
+export const f = (s: number, currency: string): string => {
+ try {
+ return new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency,
+ })
+ .format(s)
+ .replace("CA", "");
+ } catch (e) {
+ return "";
+ }
+};
+
+export const s = (s: number): string =>
+ new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(s);
+
+export const sat = (s: number): string => `⚡️${si(Math.abs(s)).toString()}`;
+
+export const si = (s: number) => {
+ if (s < 1000) return s.toString(); // Return the original number if it's less than 1000
+
+ const units = ["", "K", "M", "G", "T", "P", "E", "Z"];
+ const d = Math.floor(Math.log10(s) / 3); // Calculate the unit index
+ const scaled = s / 1000 ** d; // Scale the number to the correct unit
+
+ return (
+ new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(
+ scaled,
+ ) + units[d]
+ );
+};
+
+export const sats = 100000000;
+
+export const back = (): any =>
+ browser && (history.length ? history.go(-1) : goto("/"));
+
+export const focus = (el: HTMLElement): any =>
+ browser && screen.width > 1280 && setTimeout(() => el.focus(), 1);
+
+export const select = (el: HTMLInputElement): any =>
+ browser && screen.width > 1280 && setTimeout(() => el.select(), 1);
+
+export const sleep = (n: number): Promise<void> =>
+ new Promise((r) => setTimeout(r, n));
+
+export const wait = async (
+ f: () => boolean | Promise<boolean>,
+ n = 100,
+ s = 300,
+): Promise<boolean> => {
+ let i = 0;
+ while (!(await f()) && i < s) {
+ await sleep(n);
+ i++;
+ }
+ if (i >= s) throw new Error("timeout");
+ return f();
+};
+
+export const stretch = async (password: string, salt: Uint8Array) =>
+ crypto.subtle.deriveKey(
+ {
+ name: "PBKDF2",
+ salt,
+ iterations: 100000,
+ hash: "SHA-256",
+ },
+ await crypto.subtle.importKey(
+ "raw",
+ new TextEncoder().encode(password),
+ { name: "PBKDF2" },
+ false,
+ ["deriveBits", "deriveKey"],
+ ),
+ { name: "AES-GCM", length: 256 },
+ true,
+ ["encrypt", "decrypt"],
+ );
+
+export const types = {
+ bitcoin: "bitcoin",
+ liquid: "liquid",
+ lightning: "lightning",
+ internal: "internal",
+ fund: "fund",
+ ecash: "ecash",
+ reconcile: "reconcile",
+};
+
+export const ease = (t: number): number =>
+ t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
+
+export function shuffleArray<T>(array: T[]): void {
+ for (let i = array.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [array[i], array[j]] = [array[j], array[i]];
+ }
+}
+
+export const closest = (a: number[], n: number): number =>
+ a.reduce((prev, curr) =>
+ Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev,
+ );
+
+export const isLiquid = (text: string): boolean =>
+ text.startsWith("Az") ||
+ text.startsWith("lq1") ||
+ text.startsWith("VJL") ||
+ text.startsWith("VT") ||
+ text.startsWith("XR") ||
+ text.startsWith("XC") ||
+ ((text.startsWith("H") || text.startsWith("G") || text.startsWith("Q")) &&
+ text.length === 34) ||
+ (text.startsWith("ert1q") && text.length === 43) ||
+ (text.startsWith("ex1q") && text.length === 42) ||
+ text.startsWith("el1qq") ||
+ text.startsWith("lq1qq");
+
+export function getCookie(name: string): string | null {
+ const nameEQ = `${name}=`;
+ const ca = document.cookie.split(";");
+ for (let i = 0; i < ca.length; i++) {
+ let c = ca[i];
+ while (c.charAt(0) === " ") c = c.substring(1);
+ if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
+ }
+ return null;
+}
+
+export function setCookie(name: string, value: string, seconds: number): void {
+ const now = new Date();
+ now.setTime(now.getTime() + seconds * 1000);
+ const expires = `expires=${now.toUTCString()}`;
+ document.cookie = `${name}=${value};${expires};path=/`;
+}
+
+export const network = {
+ bitcoin: {
+ bech32: "bc",
+ pubKeyHash: 0x00,
+ scriptHash: 0x05,
+ wif: 0x80,
+ },
+ regtest: {
+ bech32: "bcrt",
+ pubKeyHash: 0x6f,
+ scriptHash: 0xc4,
+ wif: 0xef,
+ },
+}[PUBLIC_COINOS_NETWORK];
+
+export const versions = {
+ bitcoin: {
+ private: 0x0488ade4,
+ public: 0x0488b21e,
+ },
+ regtest: {
+ private: 0x04358394,
+ public: 0x043587cf,
+ },
+}[PUBLIC_COINOS_NETWORK];
diff --git a/src/locales/de.json b/src/locales/de.json
index a8e6213b..195f56f4 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -20,7 +20,8 @@
},
"locations": {
"header": "Standorte",
- "description": "Hier finden Sie einige Unternehmen, welche bereits Zahlungen mit Bitcoin über Coinos akzeptieren. Wir hoffen, dass Ihr Unternehmen das nächste sein wird!"
+ "description": "Hier finden Sie einige Unternehmen, welche bereits Zahlungen mit Bitcoin über Coinos akzeptieren. Wir hoffen, dass Ihr Unternehmen das nächste sein wird!",
+ "viewMap": "Karte anzeigen"
}
},
"error": {
@@ -78,7 +79,8 @@
"twitter": "Twitter",
"news": "Neuigkeiten",
"linktree": "Linktree",
- "documentation": "Dokumentation"
+ "documentation": "Dokumentation",
+ "nostr": "Nostr"
},
"howItWorks": {
"header": "So funktioniert's",
@@ -149,7 +151,9 @@
"forgot": "Passwort vergessen?",
"reset": "Passwort zurücksetzen",
"submit": "Einreichen",
- "newPassword": "Neues Kennwort"
+ "newPassword": "Neues Kennwort",
+ "createAccount": "Benutzerkonto erstellen",
+ "signUp": "Melden Sie sich an"
},
"nav": {
"profile": "Profil",
@@ -198,11 +202,14 @@
"withdraw": "Senden",
"deposit": "Einzahlung",
"voucher": "Beleg",
- "checkout": "Kasse"
+ "checkout": "Kasse",
+ "payNow": "Zahlen Sie jetzt",
+ "setup": "Selbstverwahrung einrichten"
},
"receive": {
"lessThan1BTCWarning": "Bitte geben Sie einen Betrag unter 1 Bitcoin ein.",
- "showQR": "QR-Code zeigen"
+ "showQR": "QR-Code zeigen",
+ "hideQR": "QR verstecken"
},
"send": {
"contacts": "Kontakte",
@@ -289,7 +296,10 @@
"memoPromptPlaceholder": "z.B. Bitte geben Sie für die Bestellung Ihren Namen ein",
"rememberFor": "Denken Sie daran",
"import": "Schlüssel importieren",
- "seconds": "Sekunden"
+ "seconds": "Sekunden",
+ "pushNotifications": "Push-Benachrichtigungen",
+ "pushNotificationsDesc": "Erhalten Sie Zahlungsinformationen auf Ihrem Gerät",
+ "pushNotificationsDisabled": "Sie haben die Benachrichtigungsberechtigung auf diesem Gerät verweigert. Überprüfen Sie Ihre Browser-Einstellungen, wenn Sie das rückgängig machen möchten."
},
"support": {
"header": "Support",
@@ -311,7 +321,11 @@
"notes": "Anmerkungen",
"pay": "Zahlen",
"details": "Einzelheiten",
- "noMessages": "Sie haben noch keine Nachrichten gesendet oder empfangen"
+ "noMessages": "Sie haben noch keine Nachrichten gesendet oder empfangen",
+ "install": "App installieren",
+ "moreDetails": "Links und Details",
+ "url": "Öffentliche URL",
+ "nwc": "Nostr-Wallet verbinden"
},
"payments": {
"header": "Transaktionen",
@@ -385,7 +399,36 @@
"tips": "Tipps",
"options": "Optionen",
"bump": "Bump-Gebühr",
- "for": "für"
+ "for": "für",
+ "legacyVersion": "Ältere Version",
+ "newVersion": "Neue Version",
+ "income": "Einkommen",
+ "subtotal": "Zwischensumme",
+ "expenditure": "Ausgaben",
+ "spent": "Bereits ausgegeben",
+ "mint": "Minze",
+ "ecash": "E-Cash",
+ "memo": "Hinweise",
+ "voucherText": "Geben Sie einen ecash- oder lnurlw-Code ein",
+ "createEcash": "E-Cash erstellen",
+ "voucher": "Zahlungscode",
+ "copy": "Kopie",
+ "setAmount": "Betrag festlegen",
+ "redeemVoucher": "Ecash oder LNURLw",
+ "swap": "Tauschen",
+ "shareLink": "Link teilen",
+ "showText": "Text anzeigen",
+ "showQr": "QR anzeigen",
+ "copyPr": "Lohnanforderung kopieren",
+ "amountPrompt": "Immer nach dem Betrag fragen",
+ "enterWalletPass": "Wallet-Passwort",
+ "failedToRoute": "Die Weiterleitung der Zahlung ist fehlgeschlagen. Der Empfänger ist möglicherweise nicht erreichbar. Versuchen Sie, einen kleineren Betrag zu senden oder die maximale Gebührenreserve zu erhöhen.",
+ "ok": "Ok",
+ "cancel": "Abbrechen",
+ "message": "Nachricht",
+ "fundingAmount": "Förderbetrag",
+ "ecashDesc": "Ecash-Tokens werden mit etwas Bitcoin finanziert. Sie können wieder in Münzen eingelöst oder in andere Brieftaschen geladen werden. Verwenden Sie sie, um Bitcoin an jemanden zu geben, der möglicherweise noch keine Brieftasche hat, indem Sie sie einfach die Zeichenkette texten oder die URL teilen. Mehr erfahren",
+ "maxFeeDesc": "Setzt eine Obergrenze der Netzleitgebühr. Wenn zu niedrig gesetzt, kann die Zahlung scheitern. Sie können es höher setzen und versuchen wieder. Wir debitieren den vollen Betrag, während wir versuchen, die Zahlung, aber Gutschrift zurück jeden ungenutzten Teil."
},
"items": {
"add": "Artikel hinzufügen",
@@ -394,5 +437,31 @@
"price": "Preis",
"submit": "Einreichen",
"image": "Bild"
+ },
+ "accounts": {
+ "back": "Zurück",
+ "next": "Nächste",
+ "seedPhrase": "Seed-Phrase",
+ "save": "Speichern",
+ "copy": "Kopie",
+ "revealMnemonic": "Seed-Phrase anzeigen",
+ "regenerate": "Regenerieren",
+ "deleteAccount": "Konto löschen",
+ "addAccount": "Konto hinzufügen",
+ "create": "Erstellen",
+ "import": "Import",
+ "accountSetup": "Kontoeinrichtung",
+ "enterSeed": "Geben Sie eine Seed-Phrase ein",
+ "passwordMismatch": "Passwörter stimmen nicht überein",
+ "generateSeed": "Generieren Sie eine neue Seed-Phrase in Ihrem Browser",
+ "accountPassword": "Kontokennwort",
+ "importSeed": "Geben Sie eine vorhandene Seed-Phrase ein",
+ "passwordWarning": "Wenn Sie dieses Passwort verlieren, können Sie weder Geld vom Konto abheben noch Ihre Seed-Phrase wiederherstellen. Wir können es nicht für Sie wiederherstellen.",
+ "savings": "Ersparnisse",
+ "password": "Passwort",
+ "confirmPassword": "Passwort bestätigen",
+ "finish": "Beenden",
+ "showQR": "QR anzeigen",
+ "revealNwc": "NWC enthüllen"
}
}
diff --git a/src/locales/el.json b/src/locales/el.json
index 86b0ea57..f04192d7 100644
--- a/src/locales/el.json
+++ b/src/locales/el.json
@@ -20,7 +20,8 @@
},
"locations": {
"header": "Τοποθεσίες",
- "description": "Ακολουθούν ορισμένες επιχειρήσεις που δέχονται bitcoin με Coinos. Ελπίζουμε ότι η δική σας θα είναι η επόμενη!"
+ "description": "Ακολουθούν ορισμένες επιχειρήσεις που δέχονται bitcoin με Coinos. Ελπίζουμε ότι η δική σας θα είναι η επόμενη!",
+ "viewMap": "Προβολή χάρτη"
}
},
"error": {
@@ -77,7 +78,8 @@
"support": "Υποστήριξη",
"telegram": "Telegram",
"twitter": "Twitter",
- "documentation": "Τεκμηρίωση"
+ "documentation": "Τεκμηρίωση",
+ "nostr": "Nostr"
},
"howItWorks": {
"header": "Πως δουλεύει",
@@ -148,7 +150,9 @@
"forgot": "Ξεχάσατε τον κωδικό?",
"reset": "ΕΠΑΝΑΦΟΡΑ ΚΩΔΙΚΟΥ",
"submit": "υποβάλλουν",
- "newPassword": "Νέος Κωδικός"
+ "newPassword": "Νέος Κωδικός",
+ "createAccount": "Δημιουργία λογαριασμού",
+ "signUp": "Εγγραφείτε"
},
"nav": {
"profile": "Προφίλ",
@@ -200,11 +204,14 @@
"deposit": "Κατάθεση",
"voucher": "Κουπόν",
"fetchingRate": "ποσοστό ανάκτησης...",
- "checkout": "Ολοκλήρωση αγοράς"
+ "checkout": "Ολοκλήρωση αγοράς",
+ "payNow": "Πλήρωσε τώρα",
+ "setup": "Ρύθμιση αυτοεπιμέλειας"
},
"receive": {
"lessThan1BTCWarning": "Παρακαλώ εισάγετε ένα ποσό μικρότερο από 1 bitcoin ",
- "showQR": "Εμφάνιση Q"
+ "showQR": "Εμφάνιση Q",
+ "hideQR": "Απόκρυψη QR"
},
"send": {
"contacts": "Επαφές",
@@ -290,7 +297,10 @@
"memoPromptPlaceholder": "π.χ. Εισαγάγετε το όνομά σας για την παραγγελία",
"rememberFor": "Θυμηθείτε για",
"import": "Κλειδί εισαγωγής",
- "seconds": "δευτερόλεπτα"
+ "seconds": "δευτερόλεπτα",
+ "pushNotifications": "Πιέστε τις κοινοποιήσεις",
+ "pushNotificationsDesc": "Λήψη ειδοποιήσεων πληρωμής στη συσκευή σας",
+ "pushNotificationsDisabled": "Αρνήθηκες την άδεια ειδοποίησης της συσκευής. Ελέγξτε τις ρυθμίσεις του περιηγητή σας αν θέλετε να το αναιρέσετε αυτό."
},
"support": {
"header": "Υποστήριξη",
@@ -305,7 +315,11 @@
"welcome": "Καλως ΗΡΘΑΤΕ! Το υπόλοιπο του λογαριασμού σας είναι κενό. Μπορείτε να ξεκινήσετε κάνοντας μια κατάθεση ή ζητώντας από κάποιον να σας πληρώσει.",
"showBalance": "Εμφάνιση υπολοίπου",
"details": "Λεπτομέριες",
- "noMessages": "Δεν έχετε στείλει ή λάβει ακόμη μηνύματα"
+ "noMessages": "Δεν έχετε στείλει ή λάβει ακόμη μηνύματα",
+ "install": "Εγκαταστήστε την εφαρμογή",
+ "moreDetails": "Σύνδεσμοι και λεπτομέρειες",
+ "url": "Δημόσια διεύθυνση URL",
+ "nwc": "Σύνδεση πορτοφολιού Nostr"
},
"payments": {
"amount": "Ποσό",
@@ -376,7 +390,36 @@
"tips": "Συμβουλές",
"options": "επιλογές",
"bump": "Χρέωση πρόσκρουσης",
- "for": "Για"
+ "for": "Για",
+ "legacyVersion": "Παλιότερη έκδοση",
+ "newVersion": "Νέα έκδοση",
+ "income": "Εισόδημα",
+ "subtotal": "Υποσύνολο",
+ "expenditure": "Δαπάνη",
+ "spent": "Ήδη ξοδευμένο",
+ "mint": "Μέντα",
+ "ecash": "Ecash",
+ "memo": "Σημειώσεις",
+ "voucherText": "Εισαγάγετε έναν κωδικό ecash ή lnurlw",
+ "createEcash": "Δημιουργία μετρητά",
+ "voucher": "Κωδικός πληρωμής",
+ "copy": "Αντίγραφο",
+ "setAmount": "Ορίστε το ποσό",
+ "redeemVoucher": "Ecash ή LNURLw",
+ "swap": "Ανταλαγή",
+ "shareLink": "Κοινή χρήση συνδέσμου",
+ "showText": "Εμφάνιση κειμένου",
+ "showQr": "Εμφάνιση QR",
+ "copyPr": "Αντιγραφή αιτήματος πληρωμής",
+ "amountPrompt": "Πάντα προτροπή για ποσό",
+ "enterWalletPass": "Κωδικός πρόσβασης πορτοφολιού",
+ "failedToRoute": "Η δρομολόγηση της πληρωμής απέτυχε, ο παραλήπτης ενδέχεται να μην είναι προσβάσιμος. Δοκιμάστε να στείλετε ένα μικρότερο ποσό ή να αυξήσετε το μέγιστο απόθεμα χρέωσης.",
+ "ok": "Εντάξει",
+ "cancel": "Ακύρωση",
+ "message": "Μήνυμα",
+ "fundingAmount": "Ποσό χρηματοδότησης",
+ "ecashDesc": "Τα κουπόνια εκash χρηματοδοτούνται με κάποια ποσότητα bitcoin. Μπορούν να εξαγοραστούν σε νομίσματα ή να φορτωθούν σε άλλα πορτοφόλια. Χρησιμοποιήστε τα για να δώσετε το bitcoin σε κάποιον που μπορεί να μην έχει ακόμα πορτοφόλι στέλνοντάς τους απλά το συμβολοσειρά token ή μοιράζοντας το URL. Μάθετε περισσότερα",
+ "maxFeeDesc": "Ορίζει ένα ανώτατο όριο στο τέλος δρομολόγησης δικτύου. Εάν τεθεί πολύ χαμηλά η πληρωμή μπορεί να αποτύχει. Μπορείς να το βάλεις ψηλότερα και να προσπαθήσεις ξανά. Χρεώνουμε όλο το ποσό, ενώ επιχειρούμε την πληρωμή, αλλά να πιστώσετε πίσω κάθε αχρησιμοποίητη μερίδα."
},
"items": {
"add": "Πρόσθεσε είδος",
@@ -385,5 +428,31 @@
"price": "Τιμή",
"submit": "υποβάλλουν",
"image": "Εικόνα"
+ },
+ "accounts": {
+ "back": "Πίσω",
+ "next": "Επόμενος",
+ "seedPhrase": "Φράση σπόρων",
+ "save": "Εκτός",
+ "copy": "Αντίγραφο",
+ "revealMnemonic": "Αποκαλύψτε τη φράση σπόρων",
+ "regenerate": "Αναγεννηθείς",
+ "deleteAccount": "Διαγραφή λογαριασμού",
+ "addAccount": "Προσθήκη λογαριασμού",
+ "create": "Δημιουργώ",
+ "import": "Εισαγωγή",
+ "accountSetup": "Ρύθμιση λογαριασμού",
+ "enterSeed": "Εισαγάγετε μια αρχική φράση",
+ "passwordMismatch": "Οι κωδικοί πρόσβασης δεν ταιριάζουν",
+ "generateSeed": "Δημιουργήστε μια νέα αρχική φράση στο πρόγραμμα περιήγησής σας",
+ "accountPassword": "Κωδικός πρόσβασης λογαριασμού",
+ "importSeed": "Εισαγάγετε μια υπάρχουσα αρχική φράση",
+ "passwordWarning": "Εάν χάσετε αυτόν τον κωδικό πρόσβασης, δεν θα μπορείτε να κάνετε ανάληψη χρημάτων από τον λογαριασμό ή να επαναφέρετε τη φράση αρχικής σας. Δεν μπορούμε να σας το ανακτήσουμε.",
+ "savings": "Οικονομίες",
+ "password": "Σύνθημα",
+ "confirmPassword": "Επιβεβαίωση κωδικού πρόσβασης",
+ "finish": "Φινίρισμα",
+ "showQR": "Εμφάνιση QR",
+ "revealNwc": "Αποκαλύψτε το NWC"
}
}
diff --git a/src/locales/en.json b/src/locales/en.json
index fda23d7e..64fa3d51 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -1,4 +1,30 @@
{
+ "accounts": {
+ "showQR": "Show QR",
+ "revealNwc": "Reveal NWC",
+ "finish": "Finish",
+ "back": "Back",
+ "next": "Next",
+ "seedPhrase": "Seed phrase",
+ "save": "Save",
+ "copy": "Copy",
+ "revealMnemonic": "Reveal seed phrase",
+ "regenerate": "Regenerate",
+ "deleteAccount": "Delete account",
+ "addAccount": "Add account",
+ "create": "Create",
+ "import": "Import",
+ "accountSetup": "Account setup",
+ "enterSeed": "Enter a seed phrase",
+ "passwordMismatch": "Passwords don't match",
+ "generateSeed": "Generate a new seed phrase",
+ "accountPassword": "Account password",
+ "importSeed": "Enter an existing seed phrase",
+ "passwordWarning": "If you lose this password you won't be able to withdraw funds from the account or restore your seed phrase. We can't recover it for you.",
+ "savings": "Savings",
+ "password": "Password",
+ "confirmPassword": "Confirm password"
+ },
"404": {
"404": "404",
"pageNotFound": "Page not found."
@@ -19,8 +45,9 @@
}
},
"locations": {
+ "viewMap": "View map",
"header": "Locations",
- "description": "Here are some businesses that are accepting bitcoin with Coinos. We hope that yours will be next!"
+ "description": "Over 500 businesses worldwide are accepting bitcoin with Coinos. We hope that yours will be next!"
}
},
"error": {
@@ -61,6 +88,7 @@
"support": "Support",
"telegram": "Telegram",
"twitter": "Twitter",
+ "nostr": "Nostr",
"documentation": "Documentation"
},
"howItWorks": {
@@ -131,7 +159,9 @@
"haveAccount": "Already have an account?",
"noAccount": "Don't have an account?",
"register": "Register",
+ "createAccount": "Create account",
"signIn": "Sign In",
+ "signUp": "Sign Up",
"failed": "Login failed"
},
"nav": {
@@ -140,7 +170,7 @@
"messages": "Messages",
"funds": "Funds",
"map": "Map",
- "merch": "Swag",
+ "merch": "Shop",
"profile": "Profile",
"startInSeconds": "Start in Seconds",
"account": "Account",
@@ -155,9 +185,12 @@
"subheader": "Latest Updates"
},
"user": {
- "details": "Details",
- "noMessages": "You have not sent or received any messages yet",
+ "url": "Public URL",
+ "install": "Install app",
+ "moreDetails": "Profile details",
+ "noMessages": "You have not sent or received any messages",
"profilePage": "Profile page",
+ "nwc": "Nostr wallet connect",
"nostrPubkey": "Nostr pubkey",
"requestPayment": "Request Payment",
"welcome": "Welcome! Your account balance is empty. You can start by making a deposit or by asking someone to pay you.",
@@ -180,6 +213,8 @@
"this": "This",
"lightningAddress": "Lightning address",
"dashboard": {
+ "setup": "Setup self-custody",
+ "payNow": "Pay now",
"checkout": "Checkout",
"go": "Go",
"dashboard": "Dashboard",
@@ -194,7 +229,8 @@
},
"receive": {
"lessThan1BTCWarning": "Please enter an amount less than 1 bitcoin.",
- "showQR": "Show QR"
+ "showQR": "Show QR",
+ "hideQR": "Hide QR"
},
"send": {
"makeQR": "QR",
@@ -219,7 +255,10 @@
"thresholdDesc": "When your balance exceeds this amount, a withdrawal will be triggered",
"autoWithdraw": "Autowithdrawal",
"autoWithdrawDescription": "Enable withdrawals to an external address when your balance reaches a given threshold",
- "notifications": "Payment notifications",
+ "notifications": "Email notifications",
+ "pushNotifications": "Push notifications",
+ "pushNotificationsDesc": "Get payment notifications on your device",
+ "pushNotificationsDisabled": "You've denied notification permission on this device. Check your browser settings if you want to undo that.",
"notificationsDesc": "Receive an email whenever a payment lands in your account",
"seedPhrase": "Seed phrase",
"nostrKeys": "Nostr key",
@@ -291,26 +330,54 @@
}
},
"payments": {
+ "ok": "Ok",
+ "cancel": "Cancel",
+ "failedToRoute": "Failed to route payment, recipient may not be reachable. Try sending a smaller amount or increasing the max fee reserve.",
+ "message": "Message",
+ "enterWalletPass": "Wallet password",
+ "legacyVersion": "Legacy version",
+ "newVersion": "New version",
+ "income": "Income",
+ "subtotal": "Subtotal",
+ "expenditure": "Expenditure",
+ "spent": "Already spent",
+ "mint": "Mint",
+ "ecash": "Ecash",
+ "memo": "Notes",
+ "voucherText": "Enter an ecash token or lnurlw code",
+ "createEcash": "Mint ecash",
"tips": "Tips",
"options": "options",
"bump": "Bump fee",
"networkFee": "Network fee",
"platformFee": "Platform fee",
"fastest": "Fastest",
+ "fundingAmount": "Funding amount",
"fast": "Fast",
+ "ecashDesc": "Ecash tokens get funded with an amount of bitcoin. They can be redeemed into a coinos account or loaded into other wallets. You can use them to give bitcoin to someone who may not have a wallet yet. Learn more at",
+ "ecashToken": "Ecash token",
"medium": "Medium",
+ "maxFeeDesc": "Set an upper limit on the network routing fee. If set too low the payment may fail. You can set it higher and try again. We debit the full amount while attempting the payment but credit back any unused portion.",
"slow": "Slow",
"create": "Create",
"fund": "Fund",
"addFunds": "Add Funds",
"takeFunds": "Take Funds",
"show": "Show",
+ "showText": "Show text",
+ "showQr": "Show QR",
"hide": "Hide",
+ "voucher": "Payment code",
"qr": "QR",
- "copyLink": "Copy Link",
- "copyText": "Copy Text",
+ "copy": "Copy",
+ "amountPrompt": "Prompt for amount",
+ "shareLink": "Share link",
+ "copyLink": "Copy link",
+ "copyText": "Copy text",
"openLink": "Open wallet",
+ "setAmount": "Set amount",
"moreOptions": "More options",
+ "redeemVoucher": "Ecash",
"total": "Total",
"gainLoss": "Gain/Loss",
"presentValue": "Present Value",
@@ -319,7 +386,7 @@
"id": "Transaction ID",
"details": "Transaction Details",
"header": "Payments",
- "preimage": "Proof of payment",
+ "preimage": "Lightning preimage",
"maxfee": "Max routing fee",
"type": "Type",
"time": "Time",
@@ -352,13 +419,14 @@
"tapAnywhere": "Tap anywhere to continue",
"from": "from",
"redeem": "Redeem",
+ "swap": "Swap",
"redeemed": "Redeemed",
"redeemedBy": "Redeemed by",
"sendMessage": "Write a message...",
"fundsClaimed": "Funds claimed!",
"print": "Print",
"onlyLbtc": "We only support",
- "dontDeposit": "don't deposit other assets yet"
+ "dontDeposit": "don't deposit other assets"
},
"items": {
"add": "Add item",
@@ -367,5 +435,17 @@
"price": "Price",
"submit": "Submit",
"image": "Image"
+ },
+ "lang": {
+ "en": "English",
+ "es": "Español",
+ "fr": "Français",
+ "de": "Deutsch",
+ "ja": "日本語",
+ "ru": "Русский",
+ "pt": "Português",
+ "zh": "中文",
+ "fa": "فارسی ",
+ "el": "Ελληνικά"
}
}
diff --git a/src/locales/es.json b/src/locales/es.json
index 0bf78d84..9fe6b480 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -20,7 +20,8 @@
},
"locations": {
"header": "Ubicaciones",
- "description": "Aquí hay algunos negocios que aceptan bitcoin con Coinos. ¡Esperamos que el tuyo sea el siguiente!"
+ "description": "Aquí hay algunos negocios que aceptan bitcoin con Coinos. ¡Esperamos que el tuyo sea el siguiente!",
+ "viewMap": "Ver mapa"
}
},
"error": {
@@ -61,7 +62,8 @@
"support": "Soporte",
"telegram": "Telegram",
"twitter": "Twitter",
- "documentation": "Documentación"
+ "documentation": "Documentación",
+ "nostr": "Nostálgico"
},
"howItWorks": {
"header": "Cómo Funciona",
@@ -132,7 +134,9 @@
"noAccount": "¿No tienes una cuenta?",
"register": "Registrarse",
"signIn": "Iniciar Sesión",
- "failed": "Inicio de sesión fallido"
+ "failed": "Inicio de sesión fallido",
+ "createAccount": "Crear una cuenta",
+ "signUp": "Inscribirse"
},
"nav": {
"about": "Acerca de",
@@ -188,11 +192,14 @@
"voucher": "Vale",
"go": "Ir",
"dashboard": "Panel",
- "checkout": "Verificar"
+ "checkout": "Verificar",
+ "payNow": "Pagar ahora",
+ "setup": "Configurar la autocustodia"
},
"receive": {
"lessThan1BTCWarning": "Por favor, introduzca una cantidad menor a 1 bitcoin.",
- "showQR": "Mostrar QR"
+ "showQR": "Mostrar QR",
+ "hideQR": "Ocultar QR"
},
"send": {
"makeQR": "QR",
@@ -278,7 +285,10 @@
"memoPromptPlaceholder": "p.ej. Por favor ingrese su nombre para el pedido",
"rememberFor": "Recuerda por",
"import": "Importar clave",
- "seconds": "segundos"
+ "seconds": "segundos",
+ "pushNotifications": "Notificaciones de empuje",
+ "pushNotificationsDesc": "Obtenga notificaciones de pago en su dispositivo",
+ "pushNotificationsDisabled": "Has negado el permiso de notificación en este dispositivo. Compruebe la configuración de su navegador si desea deshacerlo."
},
"support": {
"header": "Soporte",
@@ -288,7 +298,11 @@
"send": "Enviar"
},
"details": "Detalles",
- "noMessages": "Aún no has enviado ni recibido ningún mensaje"
+ "noMessages": "Aún no has enviado ni recibido ningún mensaje",
+ "install": "Instalar aplicación",
+ "moreDetails": "Enlaces y detalles",
+ "url": "URL pública",
+ "nwc": "Conexión de billetera Nostr"
},
"payments": {
"networkFee": "Tarifa de Red",
@@ -358,7 +372,36 @@
"tips": "Consejos",
"options": "opciones",
"bump": "Tarifa adicional",
- "for": "para"
+ "for": "para",
+ "legacyVersion": "Versión heredada",
+ "newVersion": "Nueva versión",
+ "income": "Ingreso",
+ "subtotal": "Total parcial",
+ "expenditure": "Gasto",
+ "spent": "Ya gastado",
+ "mint": "Menta",
+ "ecash": "Efectivo electrónico",
+ "memo": "Notas",
+ "voucherText": "Ingresa un código de ecash o lnurlw",
+ "createEcash": "Crear ecash",
+ "voucher": "Código de pago",
+ "copy": "Copiar",
+ "setAmount": "Monto establecido",
+ "redeemVoucher": "Efectivo electrónico o LNURLw",
+ "swap": "Intercambio",
+ "shareLink": "Compartir enlace",
+ "showText": "Mostrar texto",
+ "showQr": "Mostrar código QR",
+ "copyPr": "Copiar solicitud de pago",
+ "amountPrompt": "Siempre solicite la cantidad",
+ "enterWalletPass": "Contraseña de la billetera",
+ "failedToRoute": "No se pudo enviar el pago; es posible que no se pueda contactar al destinatario. Intente enviar un monto menor o aumentar la reserva de tarifa máxima.",
+ "ok": "Ok",
+ "cancel": "Cancelar",
+ "message": "Mensaje",
+ "fundingAmount": "Cuantía de financiación",
+ "ecashDesc": "Los tokens de Ecash se cargan con una cantidad de Bitcoin. Se pueden canjear de nuevo en Coinos o cargar en otras billeteras. Úsalos para regalar Bitcoin a alguien que aún no tenga una billetera, simplemente enviándole el token por mensaje de texto o compartiendo el enlace. Aprende más en",
+ "maxFeeDesc": "Establece un límite superior en la tasa de enrutamiento de la red. Si se establece demasiado bajo el pago puede fallar. Puedes ponerlo más alto e intentarlo de nuevo. Debitamos toda la cantidad mientras intentamos el pago pero acreditamos cualquier parte no utilizada."
},
"items": {
"add": "Añadir artículo",
@@ -367,5 +410,31 @@
"price": "Precio",
"submit": "Entregar",
"image": "Imagen"
+ },
+ "accounts": {
+ "back": "Atrás",
+ "next": "Próximo",
+ "seedPhrase": "Frase semilla",
+ "save": "Ahorrar",
+ "copy": "Copiar",
+ "revealMnemonic": "Revelar frase semilla",
+ "regenerate": "Regenerado",
+ "deleteAccount": "Eliminar cuenta",
+ "addAccount": "Agregar cuenta",
+ "create": "Crear",
+ "import": "Importar",
+ "accountSetup": "Configuración de cuenta",
+ "enterSeed": "Introduzca una frase inicial",
+ "passwordMismatch": "Las contraseñas no coinciden",
+ "generateSeed": "Genera una nueva frase semilla en tu navegador",
+ "accountPassword": "Contraseña de la cuenta",
+ "importSeed": "Introduzca una frase semilla existente",
+ "passwordWarning": "Si pierde esta contraseña, no podrá retirar fondos de la cuenta ni recuperar su frase inicial. No podemos recuperarla por usted.",
+ "savings": "Ahorros",
+ "password": "Contraseña",
+ "confirmPassword": "Confirmar Contraseña",
+ "finish": "Finalizar",
+ "showQR": "Mostrar código QR",
+ "revealNwc": "Revelar NWC"
}
}
diff --git a/src/locales/fa.json b/src/locales/fa.json
index cd8b0ba3..1a3776cd 100644
--- a/src/locales/fa.json
+++ b/src/locales/fa.json
@@ -20,7 +20,8 @@
},
"locations": {
"header": "مکان ها",
- "description": "در اینجا چند کسب و کار وجود دارد که بیت کوین را با کوینوس می پذیرند. امیدواریم مال بعدی شما باشد!"
+ "description": "در اینجا چند کسب و کار وجود دارد که بیت کوین را با کوینوس می پذیرند. امیدواریم مال بعدی شما باشد!",
+ "viewMap": "مشاهده نقشه"
}
},
"error": {
@@ -61,7 +62,8 @@
"support": "حمایت کردن",
"telegram": "تلگرام",
"twitter": "توییتر",
- "documentation": "مستندات"
+ "documentation": "مستندات",
+ "nostr": "Nostr"
},
"howItWorks": {
"header": "چگونه کار می کند",
@@ -132,7 +134,9 @@
"noAccount": "حساب کاربری ندارید؟",
"register": "ثبت نام",
"signIn": "ورود",
- "failed": "ورود ناموفق بود"
+ "failed": "ورود ناموفق بود",
+ "createAccount": "ایجاد حساب کاربری",
+ "signUp": "ثبت نام کنید"
},
"nav": {
"about": "در باره",
@@ -188,11 +192,14 @@
"withdraw": "ارسال",
"deposit": "سپرده",
"voucher": "کوپن",
- "checkout": "وارسی"
+ "checkout": "وارسی",
+ "payNow": "الان پرداخت کن",
+ "setup": "خود سرپرستی را تنظیم کنید"
},
"receive": {
"lessThan1BTCWarning": "لطفا مقدار کمتر از 1 بیت کوین را وارد کنید.",
- "showQR": "نمایش QR"
+ "showQR": "نمایش QR",
+ "hideQR": "Hide QR"
},
"send": {
"makeQR": "QR",
@@ -278,7 +285,10 @@
"memoPromptPlaceholder": "به عنوان مثال، لطفا نام خود را برای سفارش وارد کنید",
"rememberFor": "به خاطر داشته باشید برای",
"import": "کلید واردات",
- "seconds": "ثانیه"
+ "seconds": "ثانیه",
+ "pushNotifications": "اعلان های Push",
+ "pushNotificationsDesc": "اعلان های پرداخت را در دستگاه خود دریافت کنید",
+ "pushNotificationsDisabled": "شما اجازه اطلاع رسانی در این دستگاه را رد کرده اید. تنظیمات مرورگر خود را بررسی کنید اگر می خواهید آن را خنثی کنید."
},
"support": {
"header": "حمایت کردن",
@@ -288,7 +298,11 @@
"send": "ارسال"
},
"details": "جزئیات",
- "noMessages": "شما هنوز هیچ پیامی ارسال یا دریافت نکرده اید"
+ "noMessages": "شما هنوز هیچ پیامی ارسال یا دریافت نکرده اید",
+ "install": "برنامه را نصب کنید",
+ "moreDetails": "لینک ها و جزئیات",
+ "url": "URL عمومی",
+ "nwc": "اتصال کیف پول Nostr"
},
"payments": {
"networkFee": "هزینه شبکه",
@@ -358,7 +372,36 @@
"tips": "نکات",
"options": "گزینه ها",
"bump": "هزینه دست انداز",
- "for": "برای"
+ "for": "برای",
+ "legacyVersion": "نسخه میراث",
+ "newVersion": "نسخه جدید",
+ "income": "درآمد",
+ "subtotal": "جمع فرعی",
+ "expenditure": "مخارج",
+ "spent": "قبلاً خرج شده است",
+ "mint": "نعناع",
+ "ecash": "پول نقد",
+ "memo": "یادداشت ها",
+ "voucherText": "کد ecash یا lnurlw را وارد کنید",
+ "createEcash": "پول نقد ایجاد کنید",
+ "voucher": "کد پرداخت",
+ "copy": "کپی کنید",
+ "setAmount": "مقدار را تنظیم کنید",
+ "redeemVoucher": "Ecash یا LNURLw",
+ "swap": "تعویض کنید",
+ "shareLink": "لینک را به اشتراک بگذارید",
+ "showText": "نمایش متن",
+ "showQr": "نمایش QR",
+ "copyPr": "کپی درخواست پرداخت",
+ "amountPrompt": "همیشه مقدار را درخواست کنید",
+ "enterWalletPass": "رمز کیف پول",
+ "failedToRoute": "مسیر پرداخت انجام نشد، ممکن است گیرنده قابل دسترسی نباشد. سعی کنید مبلغ کمتری ارسال کنید یا حداکثر ذخیره هزینه را افزایش دهید.",
+ "ok": "Ok",
+ "cancel": "لغو",
+ "message": "پیام",
+ "fundingAmount": "بودجه",
+ "ecashDesc": "توکن های Ecash با مقداری بیت کوین تامین می شوند. آنها می توانند به سکه ها بازگردانده شوند یا به کیف پول های دیگر بارگیری شوند. از آنها برای دادن بیت کوین به کسی که ممکن است کیف پول نداشته باشد استفاده کنید اما به سادگی آنها را به رشته توکن یا به اشتراک گذاری URL ارسال کنید. بیشتر بدانید",
+ "maxFeeDesc": "محدودیت بالایی در هزینه مسیریابی شبکه ایجاد می کند. اگر پرداخت خیلی کم باشد ممکن است شکست بخورد. می توانید آن را بالاتر تنظیم کنید و دوباره امتحان کنید. ما در هنگام تلاش برای پرداخت، مبلغ کامل را پرداخت می کنیم، اما به هر بخش بدون استفاده اعتبار می دهیم."
},
"items": {
"add": "این مورد را اضافه کنید",
@@ -367,5 +410,31 @@
"price": "قیمت",
"submit": "ارسال",
"image": "تصویر"
+ },
+ "accounts": {
+ "back": "برگشت",
+ "next": "بعدی",
+ "seedPhrase": "عبارت بذر",
+ "save": "ذخیره کنید",
+ "copy": "کپی کنید",
+ "revealMnemonic": "عبارت بذر را آشکار کنید",
+ "regenerate": "بازسازی کنید",
+ "deleteAccount": "حذف اکانت",
+ "addAccount": "اضافه کردن حساب",
+ "create": "ایجاد کنید",
+ "import": "واردات",
+ "accountSetup": "تنظیم حساب",
+ "enterSeed": "یک عبارت بذری وارد کنید",
+ "passwordMismatch": "گذرواژه ها مطابقت ندارند",
+ "generateSeed": "یک عبارت seed جدید در مرورگر خود ایجاد کنید",
+ "accountPassword": "رمز عبور حساب",
+ "importSeed": "عبارت seed موجود را وارد کنید",
+ "passwordWarning": "اگر این رمز عبور را گم کنید، نمی توانید وجوهی را از حساب برداشت کنید یا عبارت اولیه خود را بازیابی کنید. ما نمی توانیم آن را برای شما بازیابی کنیم.",
+ "savings": "پس انداز",
+ "password": "رمز عبور",
+ "confirmPassword": "رمز عبور را تایید کنید",
+ "finish": "پایان",
+ "showQR": "نمایش QR",
+ "revealNwc": "NWC را آشکار کنید"
}
}
diff --git a/src/locales/fr.json b/src/locales/fr.json
index a365128c..42cc0ae9 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -7,7 +7,8 @@
"header": "À Propos",
"locations": {
"header": "Établissements",
- "description": "Il y a des entreprises qui acceptent bitcoin utilisant le point de vente coinos. Si vous utilisez notre appli, s'il vous plait <a href=\"mailto:[email protected]\" class=\"underline underline-offset-4\">fais-le-nous savoir!</a>"
+ "description": "Il y a des entreprises qui acceptent bitcoin utilisant le point de vente coinos. Si vous utilisez notre appli, s'il vous plait <a href=\"mailto:[email protected]\" class=\"underline underline-offset-4\">fais-le-nous savoir!</a>",
+ "viewMap": "Voir la carte"
},
"team": {
"header": "L'Équipe",
@@ -61,7 +62,8 @@
"support": "Assistance",
"jobs": "Jobs",
"linktree": "Linktree",
- "documentation": "Documentation"
+ "documentation": "Documentation",
+ "nostr": "Noster"
},
"howItWorks": {
"header": "Comment cela Fonctionne",
@@ -114,7 +116,9 @@
"forgot": "Mot de passe oublié?",
"reset": "Reinitialiser le mot de passe",
"submit": "Soumettre",
- "newPassword": "Nouveau mot de passe"
+ "newPassword": "Nouveau mot de passe",
+ "createAccount": "Créer un compte",
+ "signUp": "S'inscrire"
},
"nav": {
"startInSeconds": "Commence en Secondes",
@@ -165,11 +169,14 @@
"receive": "Reçois un Paiement",
"deposit": "Déposer",
"voucher": "Bon",
- "checkout": "Vérifier"
+ "checkout": "Vérifier",
+ "payNow": "Payez maintenant",
+ "setup": "Mettre en place l'auto-garde"
},
"receive": {
"lessThan1BTCWarning": "S'il vous plaît utilisez moins d'un bitcoin.",
- "showQR": "Voire le QR code"
+ "showQR": "Voire le QR code",
+ "hideQR": "Masquer le QR"
},
"settings": {
"header": "Préférences",
@@ -247,7 +254,10 @@
"memoPromptPlaceholder": "par exemple. Veuillez entrer votre nom pour la commande",
"rememberFor": "Rappelez-vous pour",
"import": "Clé d'importation",
- "seconds": "secondes"
+ "seconds": "secondes",
+ "pushNotifications": "Notifications de poussée",
+ "pushNotificationsDesc": "Obtenez des notifications de paiement sur votre appareil",
+ "pushNotificationsDisabled": "Vous avez refusé l'autorisation de notification sur cet appareil. Vérifiez les paramètres de votre navigateur si vous voulez annuler cela."
},
"support": {
"header": "Assistance",
@@ -284,7 +294,11 @@
"profilePage": "Page de profil",
"nostrPubkey": "Clé publique nostr",
"details": "Détails",
- "noMessages": "Vous n'avez pas encore envoyé ou reçu de messages"
+ "noMessages": "Vous n'avez pas encore envoyé ou reçu de messages",
+ "install": "Installer l'application",
+ "moreDetails": "Liens et détails",
+ "url": "URL publique",
+ "nwc": "Connexion au portefeuille Nostr"
},
"news": {
"header": "Nouvelles",
@@ -358,7 +372,36 @@
"tips": "Conseils",
"options": "choix",
"bump": "Frais forfaitaires",
- "for": "pour"
+ "for": "pour",
+ "legacyVersion": "Version héritée",
+ "newVersion": "Nouvelle version",
+ "income": "Revenu",
+ "subtotal": "Total",
+ "expenditure": "Dépense",
+ "spent": "Déjà dépensé",
+ "mint": "Menthe",
+ "ecash": "Cash électronique",
+ "memo": "Remarques",
+ "voucherText": "Entrez un code ecash ou lnurlw",
+ "createEcash": "Créer de l'argent en espèces",
+ "voucher": "Code de paiement",
+ "copy": "Copie",
+ "setAmount": "Montant défini",
+ "redeemVoucher": "Ecash ou LNURLw",
+ "swap": "Échanger",
+ "shareLink": "Partager le lien",
+ "showText": "Afficher le texte",
+ "showQr": "Afficher le QR",
+ "copyPr": "Copie de la demande de paiement",
+ "amountPrompt": "Toujours demander le montant",
+ "enterWalletPass": "Mot de passe du portefeuille",
+ "failedToRoute": "Impossible d'acheminer le paiement, le destinataire n'est peut-être pas joignable. Essayez d'envoyer un montant inférieur ou d'augmenter la réserve de frais maximale.",
+ "ok": "Oui",
+ "cancel": "Annuler",
+ "message": "Message",
+ "fundingAmount": "Montant du financement",
+ "ecashDesc": "Ecash jetons obtenir financé avec une certaine quantité de Bitcoin. Ils peuvent être rachetés dans des pièces de monnaie ou chargés dans d'autres portefeuilles. Utilisez-les pour donner Bitcoin à quelqu'un qui peut ne pas avoir encore un portefeuille en texto simplement la chaîne de jeton ou le partage de l'URL. En savoir plus à",
+ "maxFeeDesc": "Définit une limite supérieure sur les frais de routage réseau. Si le paiement est trop bas, il peut échouer. Vous pouvez le placer plus haut et essayer à nouveau. Nous débitons le montant total tout en tentant le paiement, mais créditons toute partie inutilisée."
},
"items": {
"add": "Ajouter un item",
@@ -367,5 +410,31 @@
"price": "Prix",
"submit": "Soumettre",
"image": "Image"
+ },
+ "accounts": {
+ "back": "Dos",
+ "next": "Suivant",
+ "seedPhrase": "Phrase de départ",
+ "save": "Sauvegarder",
+ "copy": "Copie",
+ "revealMnemonic": "Révéler la phrase de départ",
+ "regenerate": "Régénérer",
+ "deleteAccount": "Supprimer le compte",
+ "addAccount": "Ajouter un compte",
+ "create": "Créer",
+ "import": "Importer",
+ "accountSetup": "Configuration du compte",
+ "enterSeed": "Entrez une phrase de départ",
+ "passwordMismatch": "Les mots de passe ne correspondent pas",
+ "generateSeed": "Générez une nouvelle phrase de départ dans votre navigateur",
+ "accountPassword": "Mot de passe du compte",
+ "importSeed": "Entrez une phrase de départ existante",
+ "passwordWarning": "Si vous perdez ce mot de passe, vous ne pourrez pas retirer de fonds du compte ni restaurer votre phrase de départ. Nous ne pouvons pas le récupérer pour vous.",
+ "savings": "Économies",
+ "password": "Mot de passe",
+ "confirmPassword": "Confirmez le mot de passe",
+ "finish": "Finition",
+ "showQR": "Afficher le QR",
+ "revealNwc": "Révéler le NWC"
}
}
diff --git a/src/locales/guided_translation.py b/src/locales/guided_translation.py
index 27342314..9a4a85ec 100644
--- a/src/locales/guided_translation.py
+++ b/src/locales/guided_translation.py
@@ -33,13 +33,15 @@ def localize_string(string_id, from_data, to_data, to_locale):
logging.debug("Translating string with id %s", string_id)
id_parts = string_id.split('.')
+ if id_parts[0] == "lang": return
+
# get original string
to_translate = from_data
for id_part in id_parts:
to_translate = to_translate[id_part]
# Google Translate API endpoint
- url = "https://translation.googleapis.com/language/translate/v2"
+ url = "http://127.0.0.1:5000/translate"
# Prepare data for POST request
data = {
@@ -53,12 +55,12 @@ def localize_string(string_id, from_data, to_data, to_locale):
headers = {"Content-Type": "application/json"}
# Make the request
- response = requests.post(url, headers=headers, params={'key': api_key}, json=data)
+ response = requests.post(url, headers=headers, json=data)
# Check if the request was successful
if response.status_code == 200:
# Parse the response and extract translation
- translated_text = response.json()['data']['translations'][0]['translatedText']
+ translated_text = response.json()['translatedText']
print("Translated text:", translated_text)
else:
print("Error while translating:", response.json())
diff --git a/src/locales/ja.json b/src/locales/ja.json
index b0725305..b82d2ebe 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -4,7 +4,7 @@
"pageNotFound": "ページが見つかりません。"
},
"about": {
- "header": "について",
+ "header": "About",
"team": {
"header": "チーム",
"adam": {
@@ -20,7 +20,8 @@
},
"locations": {
"header": "所在地",
- "description": "Coinosでビットコインを受け入れている企業をいくつか紹介します。次はあなたのものになることを願っています!"
+ "description": "Coinosでビットコインを受け入れている企業をいくつか紹介します。次はあなたのものになることを願っています!",
+ "viewMap": "地図を見る"
}
},
"error": {
@@ -61,7 +62,8 @@
"support": "サポート",
"telegram": "電報",
"twitter": "ツイッター",
- "documentation": "ドキュメンテーション"
+ "documentation": "ドキュメンテーション",
+ "nostr": "ノストル"
},
"howItWorks": {
"header": "使い方",
@@ -97,9 +99,9 @@
"pitch3": "影響を与えることができると思われる場合は、ぜひご連絡ください。履歴書を下記までお送りください"
},
"landing": {
- "header_before_icon": "の",
- "header_with_icon": "最も簡単な",
- "header_after_icon": "ビットコインを始める方法。",
+ "header_before_icon": "最も",
+ "header_with_icon": "簡単な",
+ "header_after_icon": "ビットコインの始め方。",
"subheader": "誰でも使える無料のウェブウォレットと支払いページ。",
"info1": {
"title": "ライトニングによる即時支払い",
@@ -132,10 +134,12 @@
"noAccount": "アカウントをお持ちでない場合は、",
"register": "登録する",
"signIn": "サインイン",
- "failed": "ログインに失敗しました"
+ "failed": "ログインに失敗しました",
+ "createAccount": "アカウントを作成する",
+ "signUp": "サインアップ"
},
"nav": {
- "about": "について",
+ "about": "About",
"docs": "ドキュメント",
"messages": "メッセージ",
"funds": "資金",
@@ -188,11 +192,14 @@
"withdraw": "送信",
"deposit": "デポジット",
"voucher": "バウチャー",
- "checkout": "チェックアウト"
+ "checkout": "チェックアウト",
+ "payNow": "今払う",
+ "setup": "自己管理の設定"
},
"receive": {
"lessThan1BTCWarning": "1 ビットコイン未満の金額を入力してください。",
- "showQR": "QRを表示"
+ "showQR": "QRを表示",
+ "hideQR": "QRを隠す"
},
"send": {
"makeQR": "QR",
@@ -231,7 +238,7 @@
"username": "ユーザー名",
"email": "Eメール",
"newPassword": "パスワードを変更する",
- "about": "について",
+ "about": "About",
"aboutPlaceholder": "あなたまたはあなたの会社の住所と営業時間についてのちょっとしたこと",
"emailNotifications": "電子メール通知",
"emailNotificationsDescription": "アカウントに変更が発生したとき、または他の人から支払いが送られたときに、電子メールで通知を受け取ります。",
@@ -278,7 +285,10 @@
"memoPromptPlaceholder": "例えばご注文のお名前を入力してください",
"rememberFor": "覚えておいてください",
"import": "インポートキー",
- "seconds": "秒"
+ "seconds": "秒",
+ "pushNotifications": "プッシュ通知",
+ "pushNotificationsDesc": "デバイスの支払い通知を取得します",
+ "pushNotificationsDisabled": "通知権限をこのデバイスに拒否しました。 それをやりたくない場合は、ブラウザの設定を確認してください."
},
"support": {
"header": "サポート",
@@ -288,7 +298,11 @@
"send": "送信"
},
"details": "詳細",
- "noMessages": "まだメッセージを送信または受信していません"
+ "noMessages": "まだメッセージを送信または受信していません",
+ "install": "アプリをインストールする",
+ "moreDetails": "リンクと詳細",
+ "url": "公開URL",
+ "nwc": "Nostrウォレットコネクト"
},
"payments": {
"networkFee": "ネットワーク料金",
@@ -358,7 +372,36 @@
"tips": "チップ",
"options": "オプション",
"bump": "バンプ料金",
- "for": "のために"
+ "for": "のために",
+ "legacyVersion": "レガシーバージョン",
+ "newVersion": "新バージョン",
+ "income": "所得",
+ "subtotal": "小計",
+ "expenditure": "支出",
+ "spent": "すでに使用済み",
+ "mint": "ミント",
+ "ecash": "イーキャッシュ",
+ "memo": "注記",
+ "voucherText": "ecashまたはlnurlwコードを入力してください",
+ "createEcash": "電子キャッシュを作成する",
+ "voucher": "支払いコード",
+ "copy": "コピー",
+ "setAmount": "金額を設定",
+ "redeemVoucher": "Ecash または LNURLw",
+ "swap": "スワップ",
+ "shareLink": "リンクを共有",
+ "showText": "テキストを表示",
+ "showQr": "QRコードを表示",
+ "copyPr": "支払い請求のコピー",
+ "amountPrompt": "常に金額の入力を求める",
+ "enterWalletPass": "ウォレットパスワード",
+ "failedToRoute": "支払いのルーティングに失敗しました。受取人に連絡が取れない可能性があります。送金金額を減らすか、最大手数料準備金を増やしてみてください。",
+ "ok": "お問い合わせ",
+ "cancel": "キャンセル",
+ "message": "メッセージ",
+ "fundingAmount": "資金調達額",
+ "ecashDesc": "Ecashトークンは、ビットコインのいくらかの金額で入金されます。 それらは、coinosに戻り、他の財布にロードすることができます。 ビットコインをトークン文字列をテキスト化したり、URLを共有することで、ウォレットがまだ持っていない可能性がある人に与えるために使用してください。 詳しくはこちら",
+ "maxFeeDesc": "ネットワークルーティング料金の上限を設定します。 支払いが少なすぎると失敗する可能性があります。 設定して、もう一度お試しください。 支払いを試みながら全額を差し引くが、未使用部分をクレジットバック."
},
"items": {
"add": "アイテムの追加",
@@ -367,5 +410,31 @@
"price": "価格",
"submit": "提出する",
"image": "画像"
+ },
+ "accounts": {
+ "back": "戻る",
+ "next": "次",
+ "seedPhrase": "シードフレーズ",
+ "save": "保存",
+ "copy": "コピー",
+ "revealMnemonic": "シードフレーズを表示",
+ "regenerate": "再生する",
+ "deleteAccount": "アカウントを削除",
+ "addAccount": "アカウントを追加",
+ "create": "作成する",
+ "import": "輸入",
+ "accountSetup": "アカウント設定",
+ "enterSeed": "シードフレーズを入力してください",
+ "passwordMismatch": "パスワードが一致しません",
+ "generateSeed": "ブラウザで新しいシードフレーズを生成する",
+ "accountPassword": "アカウントパスワード",
+ "importSeed": "既存のシードフレーズを入力してください",
+ "passwordWarning": "このパスワードを紛失した場合、アカウントから資金を引き出したり、シードフレーズを復元したりできなくなります。弊社では回復することはできません。",
+ "savings": "貯蓄",
+ "password": "パスワード",
+ "confirmPassword": "パスワードを認証する",
+ "finish": "仕上げる",
+ "showQR": "QRコードを表示",
+ "revealNwc": "NWCを公開"
}
}
diff --git a/src/locales/pt.json b/src/locales/pt.json
index 852b4023..b9248aa1 100644
--- a/src/locales/pt.json
+++ b/src/locales/pt.json
@@ -20,7 +20,8 @@
},
"locations": {
"header": "Locais",
- "description": "Aqui estão algumas empresas que estão aceitando bitcoin com a Coinos. Esperamos que o seu seja o próximo!"
+ "description": "Aqui estão algumas empresas que estão aceitando bitcoin com a Coinos. Esperamos que o seu seja o próximo!",
+ "viewMap": "Ver mapa"
}
},
"error": {
@@ -77,7 +78,8 @@
"support": "Suporte",
"telegram": "Telegram",
"twitter": "Twitter",
- "documentation": "Documentação"
+ "documentation": "Documentação",
+ "nostr": "Nostr"
},
"howItWorks": {
"header": "Como funciona",
@@ -148,7 +150,9 @@
"noAccount": "Não tem uma conta?",
"register": "Registre",
"signIn": "Entrar",
- "failed": "Falha no login"
+ "failed": "Falha no login",
+ "createAccount": "Criar uma conta",
+ "signUp": "Inscrever-se"
},
"nav": {
"about": "Sobre",
@@ -207,11 +211,14 @@
"withdraw": "Enviar",
"deposit": "Depósito",
"voucher": "Voucher",
- "checkout": "Confira"
+ "checkout": "Confira",
+ "payNow": "Pague agora",
+ "setup": "Configurar autocustódia"
},
"receive": {
"lessThan1BTCWarning": "Favor inserir uma quantidade inferior a 1 bitcoin.",
- "showQR": "Mostrar QR code"
+ "showQR": "Mostrar QR code",
+ "hideQR": "Ocultar QR"
},
"send": {
"contacts": "Contatos",
@@ -297,7 +304,10 @@
"memoPromptPlaceholder": "por exemplo. Por favor insira seu nome para o pedido",
"rememberFor": "Lembre-se por",
"import": "Chave de importação",
- "seconds": "segundos"
+ "seconds": "segundos",
+ "pushNotifications": "Notificações push",
+ "pushNotificationsDesc": "Obter notificações de pagamento no seu dispositivo",
+ "pushNotificationsDisabled": "Negou permissão de notificação neste dispositivo. Verifique as configurações do navegador se quiser desfazer isso."
},
"support": {
"header": "Suporte",
@@ -309,7 +319,11 @@
"profilePage": "Página de perfil",
"nostrPubkey": "Nostr pubkey",
"details": "Detalhes",
- "noMessages": "Você ainda não enviou ou recebeu nenhuma mensagem"
+ "noMessages": "Você ainda não enviou ou recebeu nenhuma mensagem",
+ "install": "Instalar aplicativo",
+ "moreDetails": "Links e detalhes",
+ "url": "URL pública",
+ "nwc": "Nostr carteira conectar"
},
"payments": {
"amount": "Quantidade",
@@ -380,7 +394,36 @@
"tips": "Pontas",
"options": "opções",
"bump": "Taxa de aumento",
- "for": "para"
+ "for": "para",
+ "legacyVersion": "Versão legada",
+ "newVersion": "Nova versão",
+ "income": "Renda",
+ "subtotal": "Subtotal",
+ "expenditure": "Despesa",
+ "spent": "Já gasto",
+ "mint": "Hortelã",
+ "ecash": "Dinheiro eletrônico",
+ "memo": "Notas",
+ "voucherText": "Insira um código ecash ou lnurlw",
+ "createEcash": "Criar ecash",
+ "voucher": "Código de pagamento",
+ "copy": "Cópia",
+ "setAmount": "Definir quantidade",
+ "redeemVoucher": "Ecash ou LNURLw",
+ "swap": "Trocar",
+ "shareLink": "Compartilhar link",
+ "showText": "Mostrar texto",
+ "showQr": "Mostrar QR",
+ "copyPr": "Copiar solicitação de pagamento",
+ "amountPrompt": "Sempre solicite o valor",
+ "enterWalletPass": "Senha da carteira",
+ "failedToRoute": "Falha ao encaminhar o pagamento, o destinatário pode não estar acessível. Tente enviar uma quantia menor ou aumentar a reserva de taxa máxima.",
+ "ok": "Ok",
+ "cancel": "Cancelar",
+ "message": "Mensagem",
+ "fundingAmount": "Montante de financiamento",
+ "ecashDesc": "Os tokens Ecash são financiados com alguma quantidade de bitcoin. Eles podem ser resgatados em coinos ou carregados em outras carteiras. Use-os para dar bitcoin a alguém que pode não ter uma carteira ainda, simplesmente enviando-lhes a string token ou compartilhando a URL. Saiba mais em",
+ "maxFeeDesc": "Define um limite superior na taxa de roteamento da rede. Se definido demasiado baixo o pagamento pode falhar. Você pode colocá-lo mais alto e tentar novamente. Nós debitamos o valor total ao tentar o pagamento, mas creditamos de volta qualquer parte não utilizada."
},
"items": {
"add": "Adicionar item",
@@ -389,5 +432,31 @@
"price": "Preço",
"submit": "Enviar",
"image": "Imagem"
+ },
+ "accounts": {
+ "back": "Voltar",
+ "next": "Próximo",
+ "seedPhrase": "Frase semente",
+ "save": "Salvar",
+ "copy": "Cópia",
+ "revealMnemonic": "Revelar frase semente",
+ "regenerate": "Regenerado",
+ "deleteAccount": "Excluir conta",
+ "addAccount": "Adicionar conta",
+ "create": "Criar",
+ "import": "Importar",
+ "accountSetup": "Configuração da conta",
+ "enterSeed": "Insira uma frase semente",
+ "passwordMismatch": "As senhas não correspondem",
+ "generateSeed": "Gere uma nova frase semente no seu navegador",
+ "accountPassword": "Senha da conta",
+ "importSeed": "Insira uma frase semente existente",
+ "passwordWarning": "Se você perder essa senha, não poderá sacar fundos da conta ou restaurar sua seed phrase. Não podemos recuperá-la para você.",
+ "savings": "Poupança",
+ "password": "Senha",
+ "confirmPassword": "Confirme sua senha",
+ "finish": "Terminar",
+ "showQR": "Mostrar QR",
+ "revealNwc": "Revelar NWC"
}
-} \ No newline at end of file
+}
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 5fb2f868..6aebb2e7 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -20,7 +20,8 @@
},
"locations": {
"header": "Локации",
- "description": "Вот некоторые компании, которые принимают биткойны через Coinos. Надеемся, что ваш будет следующим!"
+ "description": "Вот некоторые компании, которые принимают биткойны через Coinos. Надеемся, что ваш будет следующим!",
+ "viewMap": "Посмотреть карту"
}
},
"error": {
@@ -61,7 +62,8 @@
"support": "Поддерживать",
"telegram": "Телеграмма",
"twitter": "Твиттер",
- "documentation": "Документация"
+ "documentation": "Документация",
+ "nostr": "Ностр"
},
"howItWorks": {
"header": "Как это работает",
@@ -113,7 +115,8 @@
"info3": {
"title": "Брендируйте это по-своему!",
"description": "Настройте внешний вид страницы своего профиля или оставьте ее по умолчанию — это полностью зависит от вас."
- }
+ },
+ "header_before_icon": "The"
},
"login": {
"forgot": "Забыли пароль?",
@@ -131,7 +134,9 @@
"noAccount": "У вас нет учетной записи?",
"register": "регистр",
"signIn": "Войти",
- "failed": "Ошибка входа"
+ "failed": "Ошибка входа",
+ "createAccount": "Зарегистрироваться",
+ "signUp": "Зарегистрироваться"
},
"nav": {
"about": "О",
@@ -187,11 +192,14 @@
"withdraw": "Отправлять",
"deposit": "Депозит",
"voucher": "Ваучер",
- "checkout": "Проверить"
+ "checkout": "Проверить",
+ "payNow": "Заплатить сейчас",
+ "setup": "Настройка самостоятельного хранения"
},
"receive": {
"lessThan1BTCWarning": "Пожалуйста, введите сумму менее 1 биткойна.",
- "showQR": "Показать QR-код"
+ "showQR": "Показать QR-код",
+ "hideQR": "Скрыть QR"
},
"send": {
"makeQR": "QR-код",
@@ -277,7 +285,10 @@
"memoPromptPlaceholder": "например Пожалуйста, введите свое имя для заказа",
"rememberFor": "Помните о",
"import": "Импортировать ключ",
- "seconds": "секунды"
+ "seconds": "секунды",
+ "pushNotifications": "Push-уведомления",
+ "pushNotificationsDesc": "Получите платежные уведомления на вашем устройстве",
+ "pushNotificationsDisabled": "Вы отказали в разрешении на уведомление на этом устройстве. Проверьте настройки вашего браузера, если вы хотите отменить это."
},
"support": {
"header": "Поддерживать",
@@ -287,7 +298,11 @@
"send": "Отправлять"
},
"details": "Подробности",
- "noMessages": "Вы еще не отправляли и не получали сообщений"
+ "noMessages": "Вы еще не отправляли и не получали сообщений",
+ "install": "Установить приложение",
+ "moreDetails": "Ссылки и подробности",
+ "url": "Публичный URL-адрес",
+ "nwc": "Nostr кошелек подключить"
},
"payments": {
"networkFee": "Сетевая плата",
@@ -357,7 +372,36 @@
"tips": "Советы",
"options": "параметры",
"bump": "Дополнительный сбор",
- "for": "для"
+ "for": "для",
+ "legacyVersion": "Устаревшая версия",
+ "newVersion": "Новая версия",
+ "income": "Доход",
+ "subtotal": "Промежуточный итог",
+ "expenditure": "Расходы",
+ "spent": "Уже потрачено",
+ "mint": "Мята",
+ "ecash": "Электронные деньги",
+ "memo": "Примечания",
+ "voucherText": "Введите электронный или lnurlw-код",
+ "createEcash": "Создать электронные деньги",
+ "voucher": "Код платежа",
+ "copy": "Копировать",
+ "setAmount": "Установить сумму",
+ "redeemVoucher": "Электронные деньги или LNURLw",
+ "swap": "Менять",
+ "shareLink": "Поделиться ссылкой",
+ "showText": "Показать текст",
+ "showQr": "Показать QR-код",
+ "copyPr": "Копировать запрос на оплату",
+ "amountPrompt": "Всегда запрашивать сумму",
+ "enterWalletPass": "Пароль кошелька",
+ "failedToRoute": "Не удалось направить платеж, получатель может быть недоступен. Попробуйте отправить меньшую сумму или увеличить максимальный резерв комиссии.",
+ "ok": "Хорошо",
+ "cancel": "Отменить",
+ "message": "Послание",
+ "fundingAmount": "Сумма финансирования",
+ "ecashDesc": "Токены Ecash финансируются некоторым количеством биткойнов. Они могут быть выкуплены обратно в монеты или загружены в другие кошельки. Используйте их, чтобы дать биткойн кому-то, у кого еще нет кошелька, просто отправив им строку токена или поделившись URL. Узнать больше в",
+ "maxFeeDesc": "Устанавливает верхний предел платы за маршрутизацию сети. Если установить слишком низко, оплата может потерпеть неудачу. Вы можете установить его выше и попробовать снова. Мы списываем полную сумму при попытке оплаты, но возвращаем неиспользованную часть."
},
"items": {
"add": "Добавить элемент",
@@ -366,5 +410,31 @@
"price": "Цена",
"submit": "Представлять на рассмотрение",
"image": "Изображение"
+ },
+ "accounts": {
+ "back": "Назад",
+ "next": "Следующий",
+ "seedPhrase": "Исходная фраза",
+ "save": "Сохранять",
+ "copy": "Копировать",
+ "revealMnemonic": "Раскрыть начальную фразу",
+ "regenerate": "Регенерировать",
+ "deleteAccount": "Удалить аккаунт",
+ "addAccount": "Добавить аккаунт",
+ "create": "Создавать",
+ "import": "Импорт",
+ "accountSetup": "Настройка учетной записи",
+ "enterSeed": "Введите начальную фразу",
+ "passwordMismatch": "Пароли не совпадают",
+ "generateSeed": "Создайте новую исходную фразу в вашем браузере",
+ "accountPassword": "Пароль учетной записи",
+ "importSeed": "Введите существующую начальную фразу",
+ "passwordWarning": "Если вы потеряете этот пароль, вы не сможете вывести средства со счета или восстановить вашу seed-фразу. Мы не можем восстановить ее для вас.",
+ "savings": "Экономия",
+ "password": "Пароль",
+ "confirmPassword": "Подтвердите пароль",
+ "finish": "Заканчивать",
+ "showQR": "Показать QR-код",
+ "revealNwc": "Раскрыть NWC"
}
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 2a56c780..a8ec3732 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -10,17 +10,18 @@
"adam": {
"name": "亚当·索尔蒂斯",
"position": "创始人兼首席技术官",
- "bio": "Adam 是一名软件工程师,他相信采用稳健的货币将推动全球繁荣。他与妻子、女儿和儿子住在北温哥华。"
+ "bio": "亚当是一名软件工程师,他相信人们使用稳健的虚拟货币将推动全球繁荣。他与妻子、女儿和儿子住在北温哥华。"
},
"cole": {
- "name": "油菜",
- "position": "业务发展",
- "bio": "科尔是一个充满动力、热爱自由的人。他在2016年接触到了比特币并对其进行了深入研究。现在他想把闪电网络介绍给尽可能多的用户。"
+ "name": "科尔",
+ "position": "商务拓展",
+ "bio": "科尔是一个充满动力、热爱自由的人。他在2016年接触到了比特币并对其进行了深入研究,现在他想把比特币闪电网络介绍给尽可能多的用户。"
}
},
"locations": {
"header": "地点",
- "description": "以下是一些接受 Coinos 比特币的企业。我们希望下一个就是您的!"
+ "description": "以下是一些接受 Coinos 比特币支付平台的企业,希望您的公司可以加入我们!",
+ "viewMap": "查看地图"
}
},
"error": {
@@ -30,7 +31,7 @@
"unrecognizedInput": "无法识别的输入"
},
"faq": {
- "header": "常问问题",
+ "header": "常见问题",
"cost": {
"question": "费用是多少?",
"answer": "向您的帐户接收付款是免费的。提款到外部钱包会产生少量费用,具体费用根据网络状况而有所不同。"
@@ -41,7 +42,7 @@
},
"safety": {
"question": "我的资金什么时候结算?",
- "answer": "闪电支付立即结算。您可以在几秒钟内将余额提取到另一个钱包。链上存款平均需要 5-10 分钟才能确认。"
+ "answer": "比特币闪电支付立即结算,您可以在几秒钟内将余额提取到另一个钱包,链上存款平均需要 5-10 分钟才能确认。"
},
"pos": {
"question": "Coinos 可以与我现有的 PoS 集成吗?",
@@ -54,28 +55,29 @@
},
"footer": {
"company": "公司",
- "followUs": "跟着我们",
+ "followUs": "关注我们",
"github": "GitHub",
"linktree": "链接树",
"jobs": "工作",
"support": "支持",
"telegram": "电报",
"twitter": "推特",
- "documentation": "文档"
+ "documentation": "文档",
+ "nostr": "诺斯特"
},
"howItWorks": {
- "header": "怎么运行的",
+ "header": "如何操作",
"step1": {
"header": "1. 创建您的帐户",
"description": "您只需输入用户名和密码即可开始。"
},
"step2": {
"header": "2. 要求付款",
- "description": "和平常一样,但是使用比特币。"
+ "description": "和平时付款一样,但使用比特币支付。"
},
"step3": {
- "header": "3. 就这样!",
- "description": "立即花掉你的硬币或看着它升值。"
+ "header": "3. 就是这样!",
+ "description": "立刻花掉您的比特币,或看着它升值。"
}
},
"invoice": {
@@ -98,8 +100,8 @@
},
"landing": {
"header_before_icon": "这",
- "header_with_icon": "最简单的",
- "header_after_icon": "开始使用比特币的方式。",
+ "header_with_icon": "是开始使",
+ "header_after_icon": "用比特币最容易的方式。",
"subheader": "适合所有人的免费网络钱包和支付页面。",
"info1": {
"title": "通过闪电网络即时付款",
@@ -132,7 +134,9 @@
"noAccount": "没有帐户?",
"register": "登记",
"signIn": "登入",
- "failed": "登录失败"
+ "failed": "登录失败",
+ "createAccount": "创建账户",
+ "signUp": "报名"
},
"nav": {
"about": "关于",
@@ -188,11 +192,14 @@
"withdraw": "发送",
"deposit": "订金",
"voucher": "代金券",
- "checkout": "查看"
+ "checkout": "查看",
+ "payNow": "现在付款",
+ "setup": "设置自我监护"
},
"receive": {
"lessThan1BTCWarning": "请输入小于 1 比特币的金额。",
- "showQR": "显示二维码"
+ "showQR": "显示二维码",
+ "hideQR": "隐藏 QR"
},
"send": {
"makeQR": "二维码",
@@ -278,7 +285,10 @@
"memoPromptPlaceholder": "例如请输入您的订单姓名",
"rememberFor": "记住为",
"import": "导入密钥",
- "seconds": "秒"
+ "seconds": "秒",
+ "pushNotifications": "推动通知",
+ "pushNotificationsDesc": "在设备上获取付款通知",
+ "pushNotificationsDisabled": "你拒绝了这个设备的通知许可 如果您想要取消, 请检查您的浏览器设置 ."
},
"support": {
"header": "支持",
@@ -288,7 +298,11 @@
"send": "发送"
},
"details": "细节",
- "noMessages": "您尚未发送或接收任何消息"
+ "noMessages": "您尚未发送或接收任何消息",
+ "install": "安装应用程序",
+ "moreDetails": "链接和详细信息",
+ "url": "公共 URL",
+ "nwc": "Nostr 钱包连接"
},
"payments": {
"networkFee": "网络费",
@@ -358,7 +372,36 @@
"tips": "尖端",
"options": "选项",
"bump": "附加费",
- "for": "为了"
+ "for": "为了",
+ "legacyVersion": "旧版本",
+ "newVersion": "新版本",
+ "income": "收入",
+ "subtotal": "小计",
+ "expenditure": "支出",
+ "spent": "已花费",
+ "mint": "薄荷",
+ "ecash": "电子现金",
+ "memo": "笔记",
+ "voucherText": "输入 ecash 或 lnurlw 代码",
+ "createEcash": "创建电子现金",
+ "voucher": "付款代码",
+ "copy": "复制",
+ "setAmount": "设置金额",
+ "redeemVoucher": "Ecash 或 LNURLw",
+ "swap": "交换",
+ "shareLink": "分享链接",
+ "showText": "显示文本",
+ "showQr": "显示二维码",
+ "copyPr": "复制付款请求",
+ "amountPrompt": "始终提示金额",
+ "enterWalletPass": "钱包密码",
+ "failedToRoute": "付款路线失败,收款人可能无法联系到。请尝试发送较少的金额或增加最大费用储备。",
+ "ok": "还好",
+ "cancel": "取消",
+ "message": "消息",
+ "fundingAmount": "供资数额",
+ "ecashDesc": "Ecash代币得到一些比特币的资助. 它们可以被赎回为硬币或者装入其他钱包. 使用它们来给可能还没有钱包的人提供比特币,只要给他们发去信条字符串或者共享URL即可. 学习更多",
+ "maxFeeDesc": "设置网络路由费上限. 如果定得太低,付款可能失败。 你可以放高一点再试一次 在试图付款时,我们借记全额,但贷记任何未用部分."
},
"items": {
"add": "新增项目",
@@ -367,5 +410,31 @@
"price": "价格",
"submit": "提交",
"image": "图像"
+ },
+ "accounts": {
+ "back": "后退",
+ "next": "下一个",
+ "seedPhrase": "种子短语",
+ "save": "节省",
+ "copy": "复制",
+ "revealMnemonic": "显示种子短语",
+ "regenerate": "再生",
+ "deleteAccount": "删除帐户",
+ "addAccount": "添加帐户",
+ "create": "创造",
+ "import": "进口",
+ "accountSetup": "帐户设置",
+ "enterSeed": "输入种子短语",
+ "passwordMismatch": "密码不匹配",
+ "generateSeed": "在浏览器中生成新的种子短语",
+ "accountPassword": "账户密码",
+ "importSeed": "输入现有的种子短语",
+ "passwordWarning": "如果您丢失了此密码,您将无法从账户中提取资金或恢复您的种子短语。我们无法为您恢复它。",
+ "savings": "储蓄",
+ "password": "密码",
+ "confirmPassword": "确认密码",
+ "finish": "结束",
+ "showQR": "显示二维码",
+ "revealNwc": "揭示 NWC"
}
}
diff --git a/src/routes/(app)/+layout.server.js b/src/routes/(app)/+layout.server.js
deleted file mode 100644
index 50d51584..00000000
--- a/src/routes/(app)/+layout.server.js
+++ /dev/null
@@ -1,49 +0,0 @@
-import { error, redirect } from "@sveltejs/kit";
-import { get, post, auth, protectedRoutes } from "$lib/utils";
-import { PUBLIC_BTC as btc } from "$env/static/public";
-
-export async function load({ cookies, request, url, params }) {
- let { pathname } = url;
- let token = cookies.get("token");
- let rate,
- rates = { USD: 1 };
-
- let user;
- if (token) {
- try {
- user = await get("/me", auth(cookies));
- } catch (e) {}
- }
-
- if (user?.needsMigration) {
- redirect(307, `/migrate`);
- }
-
- if (
- user &&
- ["/login", "/register"].includes(pathname) &&
- request.method === "GET"
- ) {
- redirect(307, `/${user.username}`);
- }
-
- if (
- protectedRoutes.find((p) => pathname.match(p)) &&
- (!user || user.username !== params.username)
- ) {
- redirect(307, "/login");
- }
-
- if (user && !user.pubkey && !pathname.includes("generate")) {
- redirect(303, `/${user.username}/generate`);
- }
-
- try {
- rate = await get("/rate");
- rates = await get("/rates");
- } catch (e) {
- console.log(e);
- }
-
- return { user, token, rate, rates };
-}
diff --git a/src/routes/(app)/+layout.server.ts b/src/routes/(app)/+layout.server.ts
new file mode 100644
index 00000000..b5a279f2
--- /dev/null
+++ b/src/routes/(app)/+layout.server.ts
@@ -0,0 +1,59 @@
+import { auth, get, protectedRoutes, sleep } from "$lib/utils";
+import { error, redirect } from "@sveltejs/kit";
+
+export async function load({ cookies, request, url, params }) {
+ const { pathname } = url;
+ const { username } = params;
+ const token = cookies.get("token");
+ let rate;
+ let rates = { USD: 1 };
+
+ let user;
+ if (token) {
+ try {
+ user = await get("/me", auth(cookies));
+ } catch (e) {
+ if (e.message.startsWith("Rate")) await sleep(3000);
+ user = await get("/me", auth(cookies));
+ }
+ }
+
+ let subject;
+ if (username) {
+ try {
+ subject = await get(`/users/${username}`);
+ } catch (e) {
+ error(500, "Unable to retrieve user account data");
+ }
+ }
+
+ if (user?.needsMigration) {
+ redirect(307, "/migrate");
+ }
+
+ if (
+ user &&
+ ["/login", "/register"].includes(pathname) &&
+ request.method === "GET"
+ ) {
+ redirect(307, `/${user.username}`);
+ }
+
+ if (protectedRoutes.find((p) => pathname.match(p)) && !user) {
+ redirect(307, "/login");
+ }
+
+ if (user && !user.pubkey && !pathname.includes("generate")) {
+ console.log("user missing pubkey", user);
+ redirect(303, "/generate");
+ }
+
+ try {
+ rate = await get("/rate");
+ rates = await get("/rates");
+ } catch (e) {
+ console.log(e);
+ }
+
+ return { user, token, rate, rates, subject };
+}
diff --git a/src/routes/(app)/+layout.svelte b/src/routes/(app)/+layout.svelte
index 8d4e2940..ca0b5f90 100644
--- a/src/routes/(app)/+layout.svelte
+++ b/src/routes/(app)/+layout.svelte
@@ -14,26 +14,15 @@
import { page } from "$app/stores";
import { browser } from "$app/environment";
import LoadingSplash from "$comp/LoadingSplash.svelte";
+ import AppHeader from "$comp/AppHeader.svelte";
import Invoice from "$comp/Invoice.svelte";
import Password from "$comp/Password.svelte";
- import Request from "$comp/Request.svelte";
import { getCookie, warning, protectedRoutes } from "$lib/utils";
import { t, locale, loading } from "$lib/translations";
- import { goto, onNavigate } from "$app/navigation";
+ import { goto, afterNavigate, preloadData } from "$app/navigation";
export let data;
- onNavigate((navigation) => {
- if (!document.startViewTransition) return;
-
- return new Promise((resolve) => {
- document.startViewTransition(async () => {
- resolve();
- await navigation.complete;
- });
- });
- });
-
let { generate, rate, user, subject, token, rates } = data;
$: update(data);
@@ -41,6 +30,15 @@
({ rate, user, subject, token, rates } = data);
};
+ afterNavigate(() => {
+ if (user) {
+ preloadData(`/${user.username}`);
+ preloadData(`/${user.username}/receive`);
+ preloadData("/payments");
+ preloadData("/send");
+ }
+ });
+
onMount(async () => {
if (browser) {
checkSocket();
@@ -115,6 +113,7 @@
<SvelteToast options={{ reversed: true, intro: { y: 192 } }} />
<main class="pb-20">
+ <AppHeader {user} {subject} />
{#if !$loading}
<slot />
{/if}
@@ -123,43 +122,3 @@
{#if $invoice}
<Invoice {user} />
{/if}
-
-{#if $request}
- <Request {user} />
-{/if}
-
-<style>
- @keyframes fade-in {
- from {
- opacity: 0;
- }
- }
-
- @keyframes fade-out {
- to {
- opacity: 0;
- }
- }
-
- @keyframes slide-from-right {
- from {
- transform: translateX(60px);
- }
- }
-
- @keyframes slide-to-left {
- to {
- transform: translateX(-60px);
- }
- }
-
- :root::view-transition-old(root) {
- animation: 280ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
- 180ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
- }
-
- :root::view-transition-new(root) {
- animation: 280ms cubic-bezier(0, 0, 0.2, 1) 80ms both fade-in,
- 180ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
- }
-</style>
diff --git a/src/routes/(app)/[username]/(profile)/+layout.server.js b/src/routes/(app)/[username]/(profile)/+layout.server.js
deleted file mode 100644
index a508de92..00000000
--- a/src/routes/(app)/[username]/(profile)/+layout.server.js
+++ /dev/null
@@ -1,26 +0,0 @@
-import { get } from "$lib/utils";
-
-export async function load({ parent }) {
- let { subject, user } = await parent();
-
- subject.follows = [];
- subject.followers = [];
-
- try {
- subject.follows = await get(`/${subject.pubkey}/follows`);
- } catch (e) {
- console.log("problem fetching follows", e);
- }
-
- try {
- subject.followers = await get(`/${subject.pubkey}/followers`);
- } catch (e) {
- console.log("problem fetching followers", e);
- }
-
- if (user) {
- user.follows = await get(`/${user.pubkey}/follows?tagsonly=true`);
- }
-
- return { subject, user };
-}
diff --git a/src/routes/(app)/[username]/(profile)/+layout.server.ts b/src/routes/(app)/[username]/(profile)/+layout.server.ts
new file mode 100644
index 00000000..0ed3edb8
--- /dev/null
+++ b/src/routes/(app)/[username]/(profile)/+layout.server.ts
@@ -0,0 +1,16 @@
+import { get } from "$lib/utils";
+
+export async function load({ depends, parent }) {
+ depends("app:user");
+
+ const { subject, user } = await parent();
+
+ const { follows, followers } = await get(`/${subject.pubkey}/count`);
+ let followList = new Promise((r) => r([]));
+ if (user)
+ followList = get(`/${user.pubkey}/follows?pubkeysOnly=true`).catch(
+ () => [],
+ );
+
+ return { follows, followers, followList };
+}
diff --git a/src/routes/(app)/[username]/(profile)/+layout.svelte b/src/routes/(app)/[username]/(profile)/+layout.svelte
index d750e86c..5ad30f46 100644
--- a/src/routes/(app)/[username]/(profile)/+layout.svelte
+++ b/src/routes/(app)/[username]/(profile)/+layout.svelte
@@ -1,6 +1,8 @@
<script>
+ import { invalidate } from "$app/navigation";
+ import { browser } from "$app/environment";
import { hexToUint8Array } from "uint8array-extras";
- import { copy, f, post, s, sats, success, fail } from "$lib/utils";
+ import { copy, f, get, post, s, sats, success, fail, si } from "$lib/utils";
import Icon from "$comp/Icon.svelte";
import { t } from "$lib/translations";
import { sign, send } from "$lib/nostr";
@@ -10,52 +12,91 @@
export let data;
let { encode, toWords } = bech32m;
- let events, user, subject, src, text;
- $: ({ events, user, subject, src, rates, text } = data);
- $: ({ currency, username: n, display } = subject);
+ let {
+ events,
+ user,
+ subject,
+ src,
+ rates,
+ text,
+ follows,
+ followers,
+ followList,
+ } = data;
+ let { currency, npub, username: n, display } = subject;
- $: username = n.length > 60 ? n.substr(0, 6) : display || n;
- $: npub =
- subject.pubkey &&
- bech32m.encode("npub", toWords(hexToUint8Array(subject.pubkey)), 180);
- $: lnaddr = `${n}@${$page.url.host}`;
- $: profile = `${$page.url.host}/${n}`;
+ $: refresh(data);
+ let refresh = (data) => {
+ ({
+ events,
+ user,
+ subject,
+ src,
+ rates,
+ text,
+ follows,
+ followers,
+ followList,
+ } = data);
+ ({ currency, npub, username: n, display } = subject);
+ };
+
+ $: stripped = n.replace(/\s/g, "");
+ $: username = n.length > 60 ? n.substr(0, 6) : display || stripped;
+ $: lnaddr = subject?.anon
+ ? subject.lud16 || undefined
+ : `${stripped}@${$page.url.host}`;
+ $: profile = `${$page.url.host}/${subject.anon ? npub : stripped}`;
+ let list = [];
+ $: followList.then((l) => (list = l));
let follow = async () => {
- user.follows.push([
- "p",
- subject.pubkey,
- "wss://nostr.coinos.io",
- subject.username,
- ]);
- update();
+ list = [...list, subject.pubkey];
+ let tags = await get(
+ `/api/${user.pubkey}/follows?pubkeysOnly=true&nocache=true`,
+ );
+ tags.push(["p", subject.pubkey]);
+ await update(tags);
+ invalidate("app:user");
};
let unfollow = async () => {
- user.follows.splice(
- user.follows.findIndex((t) => t[1] === subject.pubkey),
- 1
+ list.splice(
+ list.findIndex((t) => t[1] === subject.pubkey),
+ 1,
+ );
+ list = list;
+ let tags = await get(
+ `/api/${user.pubkey}/follows?pubkeysOnly=true&nocache=true`,
);
- update();
+ tags.splice(
+ tags.findIndex((t) => t[1] === subject.pubkey),
+ 1,
+ );
+ await update(tags);
};
- let update = async () => {
+ let update = async (tags) => {
+ if (!browser) return;
+
let event = {
pubkey: user.pubkey,
created_at: Math.floor(Date.now() / 1000),
kind: 3,
content: "",
- tags: user.follows,
+ tags,
};
- await sign({ event, user });
- await send(event);
-
- user.follows = user.follows;
+ try {
+ await sign({ event, user });
+ await send(event);
+ } catch (e) {
+ console.log(e);
+ }
};
- $: following = !!user?.follows.find((t) => t.includes(subject.pubkey));
+ $: following = list.some((t) => t.includes(subject.pubkey));
let showBio;
let toggleBio = () => (showBio = !showBio);
@@ -67,7 +108,7 @@
let reset = async () => {
try {
- await post(`/${subject.username}/reset`, { password });
+ await post(`/reset`, { username: n, password });
success("Password reset");
} catch (e) {
fail(e.message);
@@ -78,51 +119,133 @@
<div class="container mx-auto w-full px-4 flex flex-wrap lg:flex-nowrap">
<div class="hidden lg:block lg:w-[280px] xl:w-[360px]" />
<div
- class="w-full lg:w-[280px] xl:w-[360px] lg:absolute space-y-5 left-20 mx-auto mb-5"
+ class="w-full lg:w-[280px] xl:w-[360px] lg:absolute space-y-2 left-20 mx-auto"
>
- <div
+ <button
+ type="button"
+ on:click={toggleDetails}
class="flex text-3xl font-bold text-center mx-auto justify-center gap-2"
>
- <div class="my-auto break-words w-full">{display || username}</div>
- </div>
+ <div class="my-auto break-words">{display || username}</div>
+ <Icon icon="qr" style="w-8 invert my-auto" />
+ </button>
- {#if subject.address}
+ {#if subject.address || subject.about}
<div
- class="text-secondary mx-auto text-center lg:mx-0"
+ class="text-secondary mx-auto text-center lg:mx-0 break-words space-y-1"
class:line-clamp-2={!showBio}
on:click={toggleBio}
on:keydown={toggleBio}
>
- {subject.address}
+ <div>
+ {subject.address || subject.about}
+ </div>
+
+ {#if subject.website}
+ <div>
+ <a href={subject.website} class="underline">{subject.website}</a>
+ </div>
+ {/if}
</div>
{/if}
- <div class="flex justify-center gap-2">
- <a href={`/${subject.pubkey}/follows`}
- ><b>{subject.follows.length}</b>
- <span class="text-secondary">{$t("user.following")}</span></a
- >
- <a href={`/${subject.pubkey}/followers`}
- ><b>{subject.followers.length}</b>
- <span class="text-secondary">{$t("user.followers")}</span></a
- >
+ <div>
+ <div class="flex justify-center gap-2">
+ <a
+ href={`/${subject.pubkey}/follows`}
+ data-sveltekit-preload-data="tap"
+ rel="nofollow"
+ ><b>{si(follows)}</b>
+ <span class="text-secondary">{$t("user.following")}</span></a
+ >
+ <a
+ href={`/${subject.pubkey}/followers`}
+ data-sveltekit-preload-data="tap"
+ rel="nofollow"
+ ><b>{si(followers)}</b>
+ <span class="text-secondary">{$t("user.followers")}</span></a
+ >
+ </div>
</div>
- <div class="flex flex-wrap gap-2 w-full text-xl">
+ {#if showDetails}
+ <div class="space-y-5 pb-20">
+ {#if lnaddr}
+ <div>
+ <div class="text-secondary">{$t("user.lightningAddress")}</div>
+ <div class="flex gap-4">
+ <div class="break-all grow text-xl">
+ {lnaddr}
+ </div>
+ <div class="flex mb-auto gap-1">
+ <button class="my-auto" on:click={() => copy(lnaddr)}
+ ><Icon
+ icon="copy"
+ style="max-w-max w-8 min-w-[32px]"
+ /></button
+ >
+ <a href={`/qr/${encodeURIComponent(lnaddr)}`} class="my-auto">
+ <Icon icon="qr" style="invert max-w-max min-w-[32px]" />
+ </a>
+ </div>
+ </div>
+ </div>
+ {/if}
+ <div>
+ <div class="text-secondary">{$t("user.url")}</div>
+ <div class="flex gap-4">
+ <div class="break-all grow text-xl">
+ {profile}
+ </div>
+ <div class="flex mb-auto gap-1">
+ <button class="my-auto" on:click={() => copy(profile)}
+ ><Icon icon="copy" style="max-w-max w-8 min-w-[32px]" /></button
+ >
+ <a
+ href={`/qr/${encodeURIComponent(
+ `${$page.url.protocol}//${profile}`,
+ )}`}
+ class="my-auto"
+ >
+ <Icon icon="qr" style="invert max-w-max min-w-[32px]" />
+ </a>
+ </div>
+ </div>
+ </div>
+ <div>
+ <div class="text-secondary">{$t("user.nostrPubkey")}</div>
+ <div class="flex gap-4">
+ <div class="break-all grow text-xl">
+ {npub}
+ </div>
+ <div class="flex my-auto gap-1">
+ <button class="my-auto" on:click={() => copy(npub)}
+ ><Icon icon="copy" style="max-w-max w-8 min-w-[32px]" /></button
+ >
+ <a href={`/qr/${encodeURIComponent(npub)}`} class="my-auto">
+ <Icon icon="qr" style="invert max-w-max min-w-[32px]" />
+ </a>
+ </div>
+ </div>
+ </div>
+ </div>
+ {/if}
+
+ <div class="flex flex-wrap gap-2 w-full text-lg">
{#if user && user.username !== subject.username && subject.pubkey}
{#if following}
<button
- class="mx-auto rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex bg-black text-white grow"
+ class="mx-auto rounded-2xl border py-2 px-3 font-bold hover:opacity-80 flex bg-black text-white grow"
on:click={unfollow}
>
<div class="mx-auto flex">
<Icon icon={"profile"} style="my-auto w-8 mr-2 invert" />
- <div class="my-auto">{$t("user.following")}</div>
+ <div class="my-auto">{$t("user.unfollow")}</div>
</div>
</button>
{:else}
<button
- class="mx-auto rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex grow"
+ class="mx-auto rounded-2xl border py-2 px-3 font-bold hover:opacity-80 flex grow"
on:click={follow}
>
<div class="mx-auto flex">
@@ -133,49 +256,18 @@
{/if}
{/if}
- {#if user && user.username !== subject.username && subject.pubkey}
- <a
- href={`/${user.username}/messages/${subject.username}`}
- class="contents"
- >
- <button
- class="rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex w-60 grow"
- >
- <div class="mx-auto flex">
- <Icon icon="message" style="w-8 mr-2 my-auto" />
- <div class="mt-1 my-auto">{$t("user.message")}</div>
- </div>
- </button>
- </a>
- {/if}
-
- {#if !subject.anon && subject.username !== user?.username && !subject.hidepay}
- <a
- href={user
- ? `/send/${subject.username}`
- : `/${subject.username}/receive`}
- class="contents"
- id="payButton"
- >
- <button
- class="rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex w-60 grow"
- >
- <div class="mx-auto flex">
- <Icon icon="send" style="w-8 mr-2" />
- <div class="mt-1">{$t("user.pay")}</div>
- </div>
- </button>
- </a>
- {/if}
-
- <button
- type="button"
- on:click={toggleDetails}
- class="rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex justify-center w-full"
- >
- <Icon icon="edit" style="w-8 mr-2" />
- <div class="mt-1">{$t("user.details")}</div>
- </button>
+ <!-- {#if user &#38;&#38; user.username !== subject.username &#38;&#38; subject.pubkey} -->
+ <!-- <a href={`/messages/${subject.username}`} class="contents"> -->
+ <!-- <button -->
+ <!-- class="rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex w-60 grow" -->
+ <!-- > -->
+ <!-- <div class="mx-auto flex"> -->
+ <!-- <Icon icon="message" style="w-8 mr-2 my-auto" /> -->
+ <!-- <div class="mt-1 my-auto">{$t("user.message")}</div> -->
+ <!-- </div> -->
+ <!-- </button> -->
+ <!-- </a> -->
+ <!-- {/if} -->
{#if user?.admin && user.username !== subject.username}
<form class="w-full flex" on:submit|preventDefault={reset}>
@@ -186,68 +278,17 @@
>
<div class="mx-auto flex">
<Icon icon="clock" style="mr-2 my-auto w-8" />
- <div class="mt-1 my-auto">Reset</div>
</div>
</button>
</form>
{/if}
</div>
- {#if showDetails}
- <div class="text-xl space-y-5">
- <div>
- <div class="font-bold">{$t("user.profilePage")}</div>
- <div class="flex gap-4">
- <div class="break-all grow text-secondary">
- {profile}
- </div>
- <div class="flex mb-auto gap-1">
- <button class="my-auto" on:click={() => copy(profile)}
- ><Icon icon="copy" style="max-w-max w-8 min-w-[32px]" /></button
- >
- <a href={`/qr/${encodeURIComponent(profile)}`} class="my-auto">
- <Icon icon="qr" style="invert max-w-max min-w-[32px]" />
- </a>
- </div>
- </div>
- </div>
- <div>
- <div class="font-bold">{$t("user.lightningAddress")}</div>
- <div class="flex gap-4">
- <div class="break-all grow text-secondary">
- {lnaddr}
- </div>
- <div class="flex mb-auto gap-1">
- <button class="my-auto" on:click={() => copy(lnaddr)}
- ><Icon icon="copy" style="max-w-max w-8 min-w-[32px]" /></button
- >
- <a href={`/qr/${encodeURIComponent(lnaddr)}`} class="my-auto">
- <Icon icon="qr" style="invert max-w-max min-w-[32px]" />
- </a>
- </div>
- </div>
- </div>
- <div>
- <div class="font-bold">{$t("user.nostrPubkey")}</div>
- <div class="flex gap-4">
- <div class="break-all grow text-secondary">
- {npub}
- </div>
- <div class="flex my-auto gap-1">
- <button class="my-auto" on:click={() => copy(npub)}
- ><Icon icon="copy" style="max-w-max w-8 min-w-[32px]" /></button
- >
- <a href={`/qr/${encodeURIComponent(npub)}`} class="my-auto">
- <Icon icon="qr" style="invert max-w-max min-w-[32px]" />
- </a>
- </div>
- </div>
- </div>
- </div>
- {/if}
</div>
<div class="w-full">
- <div class="mx-auto space-y-5 lg:max-w-xl lg:pl-10 xl:max-w-2xl lg:pl-10">
+ <div
+ class="mx-auto space-y-5 lg:max-w-xl xl:max-w-2xl lg:pl-10 mt-5 lg:mt-0"
+ >
<slot />
</div>
</div>
diff --git a/src/routes/(app)/[username]/(profile)/+page.server.js b/src/routes/(app)/[username]/(profile)/+page.server.js
deleted file mode 100644
index 59eb44d5..00000000
--- a/src/routes/(app)/[username]/(profile)/+page.server.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import { auth, get } from "$lib/utils";
-
-export async function load({ cookies, depends, parent }) {
- depends("app:items");
-
- let { subject } = await parent();
- let items = await get(`/${subject.id}/items`, auth(cookies));
- items.map((i) => (i.quantity = 0));
-
- return { items };
-}
diff --git a/src/routes/(app)/[username]/(profile)/+page.server.ts b/src/routes/(app)/[username]/(profile)/+page.server.ts
new file mode 100644
index 00000000..7d54592b
--- /dev/null
+++ b/src/routes/(app)/[username]/(profile)/+page.server.ts
@@ -0,0 +1,16 @@
+import { auth, get } from "$lib/utils";
+
+export async function load({ cookies, depends, parent }) {
+ depends("app:payments");
+ depends("app:items");
+
+ const { subject } = await parent();
+
+ let accounts = [];
+ if (cookies.get("token")) accounts = await get("/accounts", auth(cookies));
+
+ const items = await get(`/${subject.id}/items`, auth(cookies));
+ items.map((i) => (i.quantity = 0));
+
+ return { accounts, items };
+}
diff --git a/src/routes/(app)/[username]/(profile)/+page.svelte b/src/routes/(app)/[username]/(profile)/+page.svelte
index 99029d09..7de6ec37 100644
--- a/src/routes/(app)/[username]/(profile)/+page.svelte
+++ b/src/routes/(app)/[username]/(profile)/+page.svelte
@@ -1,289 +1,115 @@
<script>
- import { browser } from "$app/environment";
- import { goto, invalidate } from "$app/navigation";
- import { btc, f, sat, post } from "$lib/utils";
- import { onMount } from "svelte";
+ import { btc, f, sat } from "$lib/utils";
import Icon from "$comp/Icon.svelte";
+ import Account from "$comp/Account.svelte";
import Balance from "$comp/Balance.svelte";
- import DeleteItem from "$comp/DeleteItem.svelte";
+ import Items from "$comp/Items.svelte";
import { t } from "$lib/translations";
- import { fade } from "svelte/transition";
- import { cubicIn } from "svelte/easing";
- import { flip } from "svelte/animate";
-
- import {
- dndzone,
- SHADOW_ITEM_MARKER_PROPERTY_NAME,
- SOURCES,
- TRIGGERS,
- } from "svelte-dnd-action";
+ import { installPrompt } from "$lib/store";
+ import { afterNavigate, preloadData } from "$app/navigation";
export let data;
- let flipDurationMs = 200;
- let dropTargetStyle = {};
+ afterNavigate(() => {
+ preloadData(`/${user.username}/receive`);
+ preloadData("/send");
+ });
- let { subject, user, items, rates } = data;
+ let { accounts, subject, user, items, rates } = data;
$: ({ currency } = subject);
$: rate = rates[currency];
- $: refresh(data);
- let refresh = (d) => ({ items, subject, user, rates } = d);
- let dragDisabled =
- subject?.id !== user?.id || (browser && window.innerWidth < 768);
-
- let deleting;
$: total = items.reduce((a, b) => a + b.price * b.quantity, 0);
- let del = (item) => {
- deleting = item;
- };
-
- function handleConsider(e) {
- const {
- items: newItems,
- info: { source, trigger },
- } = e.detail;
- items = newItems;
- if (source === SOURCES.KEYBOARD && trigger === TRIGGERS.DRAG_STOPPED)
- reset();
- }
-
- async function handleFinalize(e) {
- const {
- items: newItems,
- info: { source },
- } = e.detail;
- items = newItems;
- if (source === SOURCES.POINTER) reset();
-
- if (subject?.id === user?.id) {
- await post("/api/items/sort", { items });
- invalidate("app:items");
- }
- }
-
- function startDrag(e) {
- e.preventDefault();
- dragDisabled = false;
- }
-
- function handleKeyDown(e) {
- if ((e.key === "Enter" || e.key === " ") && dragDisabled)
- dragDisabled = false;
- }
-
- $: if (total > 0 && browser) {
- let payButton = document.querySelector("#payButton");
- if (payButton) payButton.addEventListener("click", checkout);
- }
-
- let checkout = async () => {
- let invoice = {
- type: "lightning",
- amount: btc(total, rate),
- currency,
- items: items.filter((i) => i.quantity > 0),
- prompt: subject.prompt,
- memoPrompt: subject.memoPrompt,
- rate,
- };
- let { id } = await post(`/${subject.username}/invoice`, {
- invoice,
- user: { username: subject.username },
- });
+ let refresh = (d) => ({ accounts, items, subject, user, rates } = d);
+ $: refresh(data);
- goto(`/send/invoice/${id}`, { invalidateAll: true });
+ let install = async () => {
+ if (!$installPrompt) return;
+ await $installPrompt.prompt();
+ $installPrompt = null;
};
- let reset = () =>
- (dragDisabled =
- user?.username !== subject?.username || window.innerWidth < 768);
+ if (user) user.savings = 0;
</script>
-<svelte:window on:resize={reset} />
-
-{#if deleting}
- <DeleteItem bind:item={deleting} />
-{/if}
-
-<div class="space-y-5">
+<div class="space-y-2">
{#if user?.id === subject.id}
- <div class="flex justify-center lg:justify-start">
- <Balance {user} {rate} />
+ <div class="space-y-5" data-sveltekit-preload-data="false">
+ {#each accounts as account, i}
+ <Account {user} {rate} {account} last={i === accounts.length - 1} />
+ {/each}
</div>
- {#if !user.balance}
- <div class="mb-8">
- <p class="text-secondary text-lg">
- {$t("user.welcome")}
- </p>
- </div>
- {/if}
-
- <div class="flex flex-wrap gap-3 justify-center w-full text-xl">
- <a href={`/send`} class="contents grow">
- <button
- type="button"
- class="rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex bg-primary grow"
- >
- <div class="mx-auto flex gap-2">
- <Icon icon="send" style="w-8" />
- <div class="my-auto">{$t("user.dashboard.send")}</div>
+ <a href={`/account/savings`} class="contents">
+ <button
+ class="rounded-2xl py-5 px-6 hover:opacity-80 flex w-full justify-center bg-primary"
+ >
+ <div class="mx-auto flex gap-2">
+ <Icon icon="plus" style="w-8 mx-auto" />
+ <div class="my-auto text-xl whitespace-nowrap">
+ {$t("accounts.addAccount")}
</div>
- </button>
- </a>
+ </div>
+ </button>
+ </a>
- <a href={`/${user.username}/receive`} class="contents">
- <button
- class="rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex bg-primary grow"
- >
- <div class="mx-auto flex gap-2">
- <Icon icon="numpad" style="w-8" />
- <div class="my-auto">{$t("user.dashboard.receive")}</div>
+ {#if $installPrompt}
+ <button
+ class="rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex bg-black text-white xl:hidden w-full justify-center"
+ on:click={install}
+ >
+ <div class="mx-auto flex gap-2">
+ <Icon icon="save" style="w-8 mx-auto invert" />
+ <div class="my-auto text-xl whitespace-nowrap">
+ {$t("user.install")}
</div>
- </button>
- </a>
-
- {#if user?.username === subject.username}
- <a href={`/${user.username}/items/create`} class="contents">
- <button
- class="rounded-2xl border py-5 px-6 font-bold hover:opacity-80 flex bg-primary grow basis-full"
- >
- <div class="mx-auto flex gap-2">
- <Icon icon="plus" style="w-8 mx-auto" />
- <div class="my-auto text-xl whitespace-nowrap">
- {$t("items.add")}
- </div>
- </div>
- </button>
- </a>
- {/if}
- </div>
+ </div>
+ </button>
+ {/if}
{/if}
+ <Items {items} {subject} {user} {total} {currency} {rate} />
+
<div
- class="grid sm:grid-cols-2 gap-4"
- class:pb-20={total > 0}
- use:dndzone={{ items, flipDurationMs, dropTargetStyle, dragDisabled }}
- on:consider={handleConsider}
- on:finalize={handleFinalize}
+ class="fixed inset-x-0 mx-auto flex bottom-16"
+ class:static={!items.length}
>
- {#each items as i (i.id)}
+ {#if total > 0}
<button
- type="button"
- class="w-full text-center cursor-pointer hover:opacity-80 mb-auto"
- on:click={() => i.quantity++}
+ class="rounded-2xl py-5 px-6 font-bold hover:bg-neutral-700 flex bg-black text-white mx-auto"
+ on:click={checkout}
>
- <div class="relative w-full h-64 overflow-hidden rounded-xl">
- {#if i[SHADOW_ITEM_MARKER_PROPERTY_NAME]}
- <div
- in:fade={{ duration: 200, easing: cubicIn }}
- class="custom-shadow-item"
- />
- {:else if i.image}
- <img
- src={`/api/public/${i.image}.webp`}
- alt={i.name}
- class="mx-auto object-cover h-full w-full"
- />
- {:else}
- <div
- class="bg-gradient-to-r from-primary to-gradient mb-4 cursor-pointer hover:opacity-80 w-full h-full"
- alt="Banner"
- />
- {/if}
- {#if user?.username === subject.username}
- <div class="flex gap-2 justify-center absolute top-2 right-2">
- <button type="button" on:click|stopPropagation={() => {}}>
- <a href={`/${user.username}/items/${i.id}`}>
- <button
- class="bg-black rounded-full w-12 h-12 bg-opacity-40 hover:bg-opacity-100"
- >
- <Icon icon="edit" style="w-8 mx-auto invert" />
- </button>
- </a>
- </button>
- <button
- class="bg-black rounded-full w-12 h-12 bg-opacity-40 hover:bg-opacity-100"
- on:click|stopPropagation={() => del(i)}
- >
- <Icon icon="trash" style="w-8 mx-auto invert" />
- </button>
- <button
- type="button"
- on:click|stopPropagation={() => {}}
- class="sm:hidden"
- on:mousedown={startDrag}
- on:touchstart={startDrag}
- on:keydown={handleKeyDown}
- >
- <a href={`/${user.username}/items/${i.id}`}>
- <button
- class="bg-black rounded-full w-12 h-12 bg-opacity-40 hover:bg-opacity-100"
- >
- <Icon icon="move" style="w-8 mx-auto invert" />
- </button>
- </a>
- </button>
- </div>
- {/if}
- </div>
- <div class="bg-white rounded-xl py-2">
- <div class="flex text-left gap-2">
- <div class="overflow-hidden space-y-1">
- <div class="text-2xl break-words">{i.name}</div>
- <div class="flex gap-2">
- <div class="font-semibold text-lg">
- {f(i.price, currency)}
- </div>
- <div class="text-secondary my-auto">
- {sat(btc(i.price, rate))}
- </div>
- </div>
- </div>
- <div class="flex gap-1 ml-auto mb-auto justify-around tabular-nums">
- {#if i.quantity}
- <button
- type="button"
- on:click|stopPropagation={() =>
- i.quantity > 0 && i.quantity--}
- >
- <Icon icon="minus" style="w-10 min-w-10" />
- </button>
- {/if}
- <div class="text-2xl my-auto text-center">
- {#if i.quantity}{i.quantity}{:else}&mdash;{/if}
- </div>
- {#if i.quantity}
- <button
- type="button"
- on:click|stopPropagation={() => i.quantity++}
- >
- <Icon icon="plus" style="w-10 min-w-10" />
- </button>
- {/if}
- </div>
+ <div class="mx-auto flex">
+ <div class="my-auto text-2xl">
+ {$t("user.dashboard.checkout")}
+ {f(total, currency)}
+ <span class="text-base">
+ {sat(btc(total, rate), currency)}
+ </span>
</div>
</div>
</button>
- {/each}
+ {:else if user?.username !== subject.username && (!subject.anon || subject.lud16)}
+ <a
+ href={subject.anon
+ ? `/send/${encodeURIComponent(subject.lud16)}`
+ : `/pay/${subject.username}`}
+ class="contents"
+ >
+ <button
+ class="rounded-2xl py-5 px-6 min-w-[200px] font-bold hover:bg-neutral-700 flex bg-black text-white mx-auto"
+ >
+ <div class="mx-auto flex gap-2">
+ <div class="text-4xl my-auto">⚡️</div>
+ <div class="my-auto text-2xl">
+ {$t("user.pay")}
+ {subject.username}
+ </div>
+ </div>
+ </button>
+ </a>
+ {/if}
</div>
- {#if total > 0}
- <button
- class="rounded-2xl py-5 px-6 font-bold hover:opacity-80 flex bg-black text-white fixed bottom-16 right-4"
- on:click={checkout}
- >
- <div class="mx-auto flex">
- <div class="my-auto text-2xl">
- {$t("user.dashboard.checkout")}
- {f(total, currency)}
- <span class="text-base">
- {sat(btc(total, rate), currency)}
- </span>
- </div>
- </div>
- </button>
- {/if}
</div>
<style>
@@ -298,4 +124,8 @@
opacity: 0.5;
margin: 0;
}
+
+ .bottom-half {
+ @apply bottom-1/2;
+ }
</style>
diff --git a/src/routes/(app)/[username]/(profile)/event/[id]/+page.server.js b/src/routes/(app)/[username]/(profile)/event/[id]/+page.server.js
deleted file mode 100644
index 24f2b611..00000000
--- a/src/routes/(app)/[username]/(profile)/event/[id]/+page.server.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import { get } from "$lib/utils";
-import { error } from "@sveltejs/kit";
-
-export async function load({ params: { id } }) {
- try {
- let event = await get(`/event/${id}`);
- if (!event) error(500, "Event not found");
- return { event };
- } catch (e) {
- error(500, e.message);
- }
-}
diff --git a/src/routes/(app)/[username]/(profile)/event/[id]/+page.server.ts b/src/routes/(app)/[username]/(profile)/event/[id]/+page.server.ts
new file mode 100644
index 00000000..2c0050cf
--- /dev/null
+++ b/src/routes/(app)/[username]/(profile)/event/[id]/+page.server.ts
@@ -0,0 +1,12 @@
+import { get } from "$lib/utils";
+import { error } from "@sveltejs/kit";
+
+export async function load({ params: { id } }) {
+ try {
+ const event = await get(`/event/${id}`);
+ if (!event) error(500, "Event not found");
+ return { event };
+ } catch (e: any) {
+ error(500, e.message);
+ }
+}
diff --git a/src/routes/(app)/[username]/(profile)/followers/+page.server.js b/src/routes/(app)/[username]/(profile)/followers/+page.server.js
new file mode 100644
index 00000000..c7d9d67b
--- /dev/null
+++ b/src/routes/(app)/[username]/(profile)/followers/+page.server.js
@@ -0,0 +1,8 @@
+import { get } from "$lib/utils";
+
+export async function load({ depends, parent }) {
+ depends("app:user");
+ let { subject } = await parent();
+ let followers = get(`/${subject.pubkey}/followers`).catch(() => []);
+ return { followers };
+}
diff --git a/src/routes/(app)/[username]/(profile)/followers/+page.svelte b/src/routes/(app)/[username]/(profile)/followers/+page.svelte
index e087ad42..c0080990 100644
--- a/src/routes/(app)/[username]/(profile)/followers/+page.svelte
+++ b/src/routes/(app)/[username]/(profile)/followers/+page.svelte
@@ -5,26 +5,26 @@
import VirtualScroll from "svelte-virtual-scroll-list";
export let data;
- let {
- subject: { followers },
- } = data;
-
- let w;
+ let { followers } = data;
</script>
-<svelte:window bind:innerWidth={w} />
-
-<div class="px-3 md:px-0 w-full md:w-[400px] mx-auto space-y-8">
+<div class="px-3 md:px-0 w-full md:w-[400px] mx-auto space-y-5">
<h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold">
{$t("user.followers")}
</h1>
- {#if browser}
+ {#await followers}
+ <div>Loading followers...</div>
+ {:then followers}
{#if followers.length}
<VirtualScroll data={followers} key="pubkey" let:data pageMode={true}>
- <a href={`/${data.pubkey}`}>
+ <a
+ href={`/${data.pubkey}`}
+ data-sveltekit-preload-data="tap"
+ rel="nofollow"
+ >
<div
- class="flex border-b last:border-b-0 py-4 text-sm lg:text-lg text-secondary"
+ class="flex border-b last:border-b-0 py-4 text-2xl text-secondary"
:key={data.pubkey}
>
<div class="mb-auto mr-2">
@@ -38,8 +38,8 @@
<div class="w-full flex pb-1 text-black my-auto">
<div>
- {data.display_name || ""}
- <span class="text-secondary">@{data.username}</span>
+ <div>{data.display_name || ""}</div>
+ <div class="text-secondary text-lg">@{data.name}</div>
</div>
</div>
</div>
@@ -48,5 +48,5 @@
{:else}
<div>No followers</div>
{/if}
- {/if}
+ {/await}
</div>
diff --git a/src/routes/(app)/[username]/(profile)/follows/+page.server.js b/src/routes/(app)/[username]/(profile)/follows/+page.server.js
new file mode 100644
index 00000000..2a98b316
--- /dev/null
+++ b/src/routes/(app)/[username]/(profile)/follows/+page.server.js
@@ -0,0 +1,8 @@
+import { get } from "$lib/utils";
+
+export async function load({ depends, parent }) {
+ depends("app:user");
+ let { subject } = await parent();
+ let follows = get(`/${subject.pubkey}/follows`).catch(() => []);
+ return { follows };
+}
diff --git a/src/routes/(app)/[username]/(profile)/follows/+page.svelte b/src/routes/(app)/[username]/(profile)/follows/+page.svelte
index e4363796..9b2f70d1 100644
--- a/src/routes/(app)/[username]/(profile)/follows/+page.svelte
+++ b/src/routes/(app)/[username]/(profile)/follows/+page.svelte
@@ -1,51 +1,55 @@
<script>
+ import { onMount } from "svelte";
import { t } from "$lib/translations";
import Avatar from "$comp/Avatar.svelte";
import { browser } from "$app/environment";
import VirtualScroll from "svelte-virtual-scroll-list";
+ import { invalidate } from "$app/navigation";
export let data;
- let {
- subject: { follows },
- } = data;
- let w;
+ let { follows } = data;
+ $: refresh(data);
+ let refresh = (data) => ({ follows } = data);
</script>
-<svelte:window bind:innerWidth={w} />
-
-<div class="px-3 md:px-0 w-full md:w-[400px] mx-auto space-y-8">
+<div class="px-3 md:px-0 w-full md:w-[400px] mx-auto">
<h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold">
{$t("user.following")}
</h1>
- {#if browser}
+ {#await follows}
+ <div>Loading</div>
+ {:then follows}
{#if follows.length}
- <VirtualScroll data={follows} key="pubkey" let:data pageMode={true}>
- <a href={`/${data.pubkey}`}>
- <div
- class="flex py-4 text-sm lg:text-lg text-secondary"
- :key={data.pubkey}
+ {#if browser}
+ <VirtualScroll data={follows} key="pubkey" let:data pageMode={true}>
+ <a
+ href={`/${data.pubkey}`}
+ data-sveltekit-preload-data="tap"
+ rel="nofollow"
>
- <div class="mb-auto mr-2">
- <div class="md:hidden">
- <Avatar size={12} user={data} disabled={true} />
- </div>
- <div class="hidden md:block">
- <Avatar size={20} user={data} disabled={true} />
+ <div class="flex py-4 text-lg text-secondary" :key={data.pubkey}>
+ <div class="mb-auto mr-2">
+ <div class="md:hidden">
+ <Avatar size={12} user={data} disabled={true} />
+ </div>
+ <div class="hidden md:block">
+ <Avatar size={20} user={data} disabled={true} />
+ </div>
</div>
- </div>
- <div class="w-full flex pb-1 text-black my-auto">
- <div>
- {data.display_name || ""}
- <span class="text-secondary">@{data.username}</span>
+ <div class="w-full flex pb-1 text-black my-auto">
+ <div>
+ <div>{data.display_name || ""}</div>
+ <div class="text-secondary text-base">@{data.name}</div>
+ </div>
</div>
</div>
- </div>
- </a>
- </VirtualScroll>
+ </a>
+ </VirtualScroll>
+ {/if}
{:else}
<div>No follows</div>
{/if}
- {/if}
+ {/await}
</div>
diff --git a/src/routes/(app)/[username]/+layout.server.js b/src/routes/(app)/[username]/+layout.server.js
deleted file mode 100644
index 11e6d45c..00000000
--- a/src/routes/(app)/[username]/+layout.server.js
+++ /dev/null
@@ -1,18 +0,0 @@
-import { get } from "$lib/utils";
-import { error } from "@sveltejs/kit";
-
-export let load = async ({ cookies, depends, params: { username } }) => {
- depends("app:user");
-
- try {
- let subject = await get(`/users/${username}`);
-
- let expires = new Date();
- expires.setSeconds(expires.getSeconds() + 380 * 24 * 60 * 60);
- cookies.set("username", username, { path: "/", expires });
-
- return { subject };
- } catch (e) {
- error(500, "Unable to retrieve user account data");
- }
-};
diff --git a/src/routes/(app)/[username]/+layout.server.ts b/src/routes/(app)/[username]/+layout.server.ts
new file mode 100644
index 00000000..1dd163e9
--- /dev/null
+++ b/src/routes/(app)/[username]/+layout.server.ts
@@ -0,0 +1,24 @@
+import { get } from "$lib/utils";
+import { error } from "@sveltejs/kit";
+
+export const load = async ({
+ cookies,
+ depends,
+ params: { username },
+ parent,
+}) => {
+ depends("app:user");
+
+ try {
+ const subject = await get(`/users/${username}`);
+ const { user } = await parent();
+
+ const expires = new Date();
+ expires.setSeconds(expires.getSeconds() + 380 * 24 * 60 * 60);
+ cookies.set("username", username, { path: "/", expires });
+
+ return { subject, user };
+ } catch (e) {
+ error(500, "Unable to retrieve user account data");
+ }
+};
diff --git a/src/routes/(app)/[username]/+layout.svelte b/src/routes/(app)/[username]/+layout.svelte
index dd29e3aa..ce152831 100644
--- a/src/routes/(app)/[username]/+layout.svelte
+++ b/src/routes/(app)/[username]/+layout.svelte
@@ -1,57 +1,9 @@
<script>
- import AppHeader from "$comp/AppHeader.svelte";
- import { onNavigate } from "$app/navigation";
export let data;
-
- onNavigate((navigation) => {
- if (!document.startViewTransition) return;
-
- return new Promise((resolve) => {
- document.startViewTransition(async () => {
- resolve();
- await navigation.complete;
- });
- });
- });
</script>
-<AppHeader {data} />
<div class="content">
<slot />
</div>
-<style>
- @keyframes fade-in {
- from {
- opacity: 0;
- }
- }
-
- @keyframes fade-out {
- to {
- opacity: 0;
- }
- }
-
- @keyframes slide-from-right {
- from {
- transform: translateX(60px);
- }
- }
-
- @keyframes slide-to-left {
- to {
- transform: translateX(-60px);
- }
- }
-
- :root::view-transition-old(root) {
- animation: 280ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
- 180ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
- }
-
- :root::view-transition-new(root) {
- animation: 280ms cubic-bezier(0, 0, 0.2, 1) 80ms both fade-in,
- 180ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
- }
-</style>
+<slot name="fixed" />
diff --git a/src/routes/(app)/[username]/address/+page.server.js b/src/routes/(app)/[username]/address/+page.server.js
deleted file mode 100644
index f8e271f9..00000000
--- a/src/routes/(app)/[username]/address/+page.server.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import { auth, get, post } from "$lib/utils";
-import { redirect } from "@sveltejs/kit";
-
-export async function load({ cookies, params, parent }) {
- let user = (await parent()).subject;
- let rates = await get("/rates");
- let invoice = { type: "bitcoin" };
- let { hash } = await post(`/invoice`, { invoice, user }, auth(cookies));
- redirect(307, `/${user.username}/invoice/${hash}`);
-}
diff --git a/src/routes/(app)/[username]/card/[serial]/+page.server.js b/src/routes/(app)/[username]/card/[serial]/+page.server.js
deleted file mode 100644
index 945eee30..00000000
--- a/src/routes/(app)/[username]/card/[serial]/+page.server.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import { auth, get } from "$lib/utils";
-import { redirect } from "@sveltejs/kit";
-
-export let load = async ({ cookies, params }) => {
- let { serial } = params;
- let fund;
- try {
- fund = await get(`/fund/${serial}`, auth(cookies));
- } catch (e) {
- console.log(e);
- }
-
- if (fund) redirect(307, `/fund/${serial}`);
-
- return params;
-};
diff --git a/src/routes/(app)/[username]/card/[serial]/+page.svelte b/src/routes/(app)/[username]/card/[serial]/+page.svelte
deleted file mode 100644
index 1d11ebee..00000000
--- a/src/routes/(app)/[username]/card/[serial]/+page.svelte
+++ /dev/null
@@ -1,36 +0,0 @@
-<script>
- import Card from "$comp/Card.svelte";
- import Icon from "$comp/Icon.svelte";
- export let data;
- let { serial } = data;
- let balance = 0;
-</script>
-
-<div class="space-y-5">
- <div class="relative flex justify-center gap-2">
- <h1 class="text-2xl md:text-3xl font-semibold my-auto">Card {serial}</h1>
- </div>
- <div class="flex justify-center">
- <a href={`/send/pot/${serial}`}>
- <button
- class="rounded-full border py-3 px-6 font-bold hover:opacity-80 flex w-60 bg-black text-white justify-center gap-2"
- >
- <svg
- xmlns="http://www.w3.org/2000/svg"
- class="invert text-black peer-placeholder-shown:text-gray-300 h-6 w-6 my-auto"
- fill="none"
- viewBox="0 0 24 24"
- stroke="currentColor"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
- />
- </svg>
- <div class="my-auto">Add Funds</div>
- </button>
- </a>
- </div>
-</div>
diff --git a/src/routes/(app)/[username]/customers/+page.svelte b/src/routes/(app)/[username]/customers/+page.svelte
deleted file mode 100644
index e69de29b..00000000
--- a/src/routes/(app)/[username]/customers/+page.svelte
+++ /dev/null
diff --git a/src/routes/(app)/[username]/funds/+page.server.js b/src/routes/(app)/[username]/funds/+page.server.js
deleted file mode 100644
index e69de29b..00000000
--- a/src/routes/(app)/[username]/funds/+page.server.js
+++ /dev/null
diff --git a/src/routes/(app)/[username]/funds/+page.svelte b/src/routes/(app)/[username]/funds/+page.svelte
deleted file mode 100644
index 25686e86..00000000
--- a/src/routes/(app)/[username]/funds/+page.svelte
+++ /dev/null
@@ -1,52 +0,0 @@
-<script>
- import Avatar from "$comp/Avatar.svelte";
- import Icon from "$comp/Icon.svelte";
- import { t } from "$lib/translations";
-
- export let data;
-
- let { funds } = data;
-</script>
-
-<div class="mt-24 mb-20">
- <h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold mb-10">
- Funds
- </h1>
-
- <div class="container w-full mx-auto text-lg px-4 max-w-xl space-y-5">
- <div class="text-base">
- <div class="grid grid-cols-3 border-b h-24 hover:bg-gray-100 px-4">
- <div class="whitespace-nowrap my-auto">
- <div class="text-secondary" />
- </div>
-
- <div class="flex my-auto">
- <div class="text-secondary flex">
- <div class="my-auto mr-1">
- <img src="/images/moneypot.png" class="w-12" alt="Pot" />
- </div>
-
- <div class="my-auto">Pot</div>
- </div>
- </div>
-
- <div class="text-secondary text-right text-sm my-auto">
- <div />
- </div>
- </div>
- </div>
-
- <button
- class="ml-auto rounded-full border py-2 px-4 w-36 hover:opacity-80 flex mx-auto"
- >
- <Icon icon="plus" style="opacity-50 mr-2 my-auto" />
- <div class="my-auto">{$t("payments.create")}</div>
- </button>
- </div>
-</div>
-
-<style>
- .active * {
- @apply bg-black text-white border-black;
- }
-</style>
diff --git a/src/routes/(app)/[username]/generate/+server.js b/src/routes/(app)/[username]/generate/+server.js
deleted file mode 100644
index 3e3a9358..00000000
--- a/src/routes/(app)/[username]/generate/+server.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import { auth, post } from "$lib/utils";
-import { error, json } from "@sveltejs/kit";
-
-export async function POST({ cookies, request }) {
- try {
- let body = await request.json();
- return json(await post(`/user`, body, auth(cookies)));
- } catch (e) {
- error(500, e.message);
- }
-}
diff --git a/src/routes/(app)/[username]/invoice/+server.js b/src/routes/(app)/[username]/invoice/+server.js
deleted file mode 100644
index 5e3d0300..00000000
--- a/src/routes/(app)/[username]/invoice/+server.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import { auth, post } from "$lib/utils";
-import { json } from "@sveltejs/kit";
-
-export let POST = async ({ cookies: c, request: r }) => {
- let j = await r.json();
- return json(await post("/invoice", j, auth(c)));
-};
diff --git a/src/routes/(app)/[username]/invoice/[id]/+layout.server.js b/src/routes/(app)/[username]/invoice/[id]/+layout.server.js
deleted file mode 100644
index 0df10cca..00000000
--- a/src/routes/(app)/[username]/invoice/[id]/+layout.server.js
+++ /dev/null
@@ -1,38 +0,0 @@
-import Qr from "qrcode-base64";
-import { get } from "$lib/utils";
-import { redirect } from "@sveltejs/kit";
-
-export async function load({ depends, params, url, parent }) {
- depends("app:invoice");
-
- let { user } = await parent();
- let { id } = params;
- let invoice = await get(`/invoice/${id}`);
- let options = !!url.searchParams.get("options");
-
- if (
- user &&
- invoice.uid !== user.id &&
- !(url.pathname.includes("tip") || url.pathname.includes("memo")) &&
- !options
- ) {
- redirect(307, `/send/invoice/${id}`);
- }
-
- let { amount, pending, received } = invoice;
- amount = parseInt(amount);
-
- let paid =
- (!amount && (pending || received)) ||
- (amount > 0 && (pending >= amount || received >= amount));
- if (paid && !url.pathname.endsWith("paid")) {
- redirect(
- 307,
- `/${params.username}/invoice/${id}/paid` +
- (options ? "?options=true" : "")
- );
- }
-
- let src = Qr.drawImg(invoice.text || "", { size: 340 });
- return { id, invoice, src };
-}
diff --git a/src/routes/(app)/[username]/invoice/[id]/+layout.svelte b/src/routes/(app)/[username]/invoice/[id]/+layout.svelte
deleted file mode 100644
index 4fa864ce..00000000
--- a/src/routes/(app)/[username]/invoice/[id]/+layout.svelte
+++ /dev/null
@@ -1 +0,0 @@
-<slot />
diff --git a/src/routes/(app)/[username]/invoice/[id]/+page.svelte b/src/routes/(app)/[username]/invoice/[id]/+page.svelte
deleted file mode 100644
index a7ffbff3..00000000
--- a/src/routes/(app)/[username]/invoice/[id]/+page.svelte
+++ /dev/null
@@ -1,298 +0,0 @@
-<script>
- import { enhance } from "$app/forms";
- import { send } from "$lib/socket";
- import {
- btc,
- post,
- back,
- copy,
- f,
- get,
- types,
- sat,
- reverseFormat,
- s,
- sats,
- } from "$lib/utils";
- import { tick, onMount, onDestroy } from "svelte";
- import { browser } from "$app/environment";
- import { last, showQr } from "$lib/store";
- import Avatar from "$comp/Avatar.svelte";
- import Icon from "$comp/Icon.svelte";
- import Heart from "$comp/Heart.svelte";
- import Image from "$comp/Image.svelte";
- import { t } from "$lib/translations";
- import { goto, invalidate } from "$app/navigation";
-
- export let data;
-
- let ndef;
- let showOptions;
-
- let reading = async ({ message, serialNumber }) => {
- let name = serialNumber.replace(/:/g, "-");
- let result = await post(`/fund/${name}/withdraw`, { amount, hash, name });
- };
-
- let readingerror = (e) => console.log("nfc error", e);
-
- $: refresh(data);
- let { invoice, id, user, src } = data;
- let {
- amount,
- hash,
- type,
- memoPrompt,
- rate,
- received,
- prompt,
- text,
- tip,
- user: { username, currency },
- } = invoice;
-
- let qr;
- let tipPercent = 0;
-
- let refresh = async (data) => {
- ({ invoice, id, user, src } = data);
- ({
- amount,
- hash,
- type,
- rate,
- received,
- prompt,
- text,
- tip,
- user: { username, currency },
- } = invoice);
-
- tipPercent = (tip / amount) * 100;
-
- // if (browser && window.NDEFReader) {
- // try {
- // ndef = new NDEFReader();
- // await ndef.scan();
- //
- // ndef.removeEventListener('readingerror', readingerror);
- // ndef.removeEventListener('reading', reading);
- //
- // ndef.addEventListener('readingerror', readingerror);
- // ndef.addEventListener('reading', reading);
- // } catch (e) {
- // console.log(e);
- // }
- // }
- };
-
- $: amountFiat = parseFloat(((amount * rate) / sats).toFixed(2));
- $: tipAmount = ((tip * rate) / sats).toFixed(2);
-
- let subbed;
-
- onMount(async () => {
- $showQr = $showQr && 1;
- if (browser) {
- last.subscribe((v) => {
- if (!v || subbed) return;
- subbed = true;
- send("subscribe", invoice);
- });
- }
- });
-
- onDestroy(() => {
- if (ndef) {
- ndef.removeEventListener("readingerror", readingerror);
- ndef.removeEventListener("reading", reading);
- }
- });
-
- $: link = [types.bitcoin, types.liquid].includes(type)
- ? text
- : `lightning:${text}`;
- $: txt = [types.bitcoin, types.liquid].includes(type) ? hash : text;
-
- let setType = async (type) => {
- invoice.type = type;
- ({ id } = await post(`/${username}/invoice`, {
- invoice,
- user: { username, currency },
- }));
-
- goto(`./${id}?options=true`, { invalidateAll: true, noScroll: true });
- };
-</script>
-
-<div class="invoice container mx-auto max-w-xl px-4 space-y-2">
- {#if $showQr === 1}
- <div>
- <a
- href={[types.bitcoin, types.liquid].includes(invoice.type)
- ? invoice.text
- : "lightning:" + invoice.text}
- >
- <img
- {src}
- class="mx-auto z-10 shadow-inner rounded-2xl"
- bind:this={qr}
- alt={txt}
- />
- </a>
- </div>
- {/if}
-
- {#each invoice.items as i}
- <div class="grid grid-cols-12 text-xl">
- <div class="col-span-1 my-auto">{i.quantity}</div>
- <div class="mr-auto grow col-span-7 my-auto">
- {i.name}
- </div>
- <div class="col-span-2 font-semibold text-right my-auto">
- {f(i.price * i.quantity, currency)}
- </div>
- <div class="col-span-2 text-secondary text-right text-lg my-auto">
- {sat(btc(i.price * i.quantity, rate))}
- </div>
- </div>
- {/each}
-
- {#if amount > 0}
- <div class="text-center font-bold text-2xl">
- <div>
- {f(amountFiat, currency)}
-
- {#if tip}
- <span class="text-sm">
- +{f(tip * (rate / sats), currency)}
- </span>
- {/if}
- </div>
- <div>
- <span class="text-secondary font-normal text-xl"
- >⚡️{`${s(amount)}`}</span
- >
-
- {#if tip}
- <span class="text-sm text-secondary font-normal">
- +⚡️{s(tip)}
- </span>
- {/if}
- </div>
- </div>
- {/if}
-
- <button
- type="button"
- class="flex gap-2 text-center break-all rounded-2xl hover:opacity-80 py-5 px-6 w-full mx-auto justify-center border bg-black text-white text-xl whitespace-nowrap"
- on:click={() => copy(txt)}
- >
- <Icon icon="copy" style="w-8 my-auto invert" />
- <div class="my-auto font-bold">
- {txt.substr(0, 11)}..{txt.substr(-10)}
- </div>
- </button>
-
- <div
- class="w-full flex justify-center gap-2 flex-wrap text-secondary text-xl"
- >
- <a href={link} class="w-full">
- <button
- class="w-full flex justify-center rounded-2xl border py-5 px-6 hover:opacity-80"
- >
- <Icon icon="mobile" style="mr-1 w-8" />
- <div class="my-auto">{$t("payments.openLink")}</div>
- </button>
- </a>
-
- <button
- class="w-full flex justify-center rounded-2xl border py-5 px-6 hover:opacity-80"
- on:click={() => ($showQr = $showQr ? false : 2)}
- >
- <Icon icon="qr" style="w-8 mr-1 invert my-auto" />
- <div class="my-auto">
- {$showQr ? $t("payments.hide") : $t("payments.show")}
- {$t("payments.qr")}
- </div></button
- >
-
- <!-- <button -->
- <!-- class="w-full flex justify-center rounded-2xl border py-3 px-5 hover:opacity-80 text-lg" -->
- <!-- on:click={() => (showOptions = !showOptions)} -->
- <!-- > -->
- <!-- <Icon icon="settings" style="w-8 mr-1 my-auto" /> -->
- <!-- <div class="my-auto"> -->
- <!-- {showOptions ? $t("payments.hide") : $t("payments.show")} -->
- <!-- {$t("payments.options")} -->
- <!-- </div></button -->
- <!-- > -->
- </div>
-
- <div class="flex justify-around text-secondary">
- <button
- class="hover:bg-primary my-auto flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 w-full justify-center"
- class:bg-primary={type === types.bitcoin}
- class:text-black={type === types.bitcoin}
- on:click={() => setType(types.bitcoin)}
- >
- <img src="/images/bitcoin.svg" class="w-8" alt="Bitcoin" />
- <div class="my-auto text-lg">Bitcoin</div>
- </button>
-
- <button
- class="hover:bg-primary my-auto flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 w-full justify-center"
- class:bg-primary={type === types.liquid}
- class:text-black={type === types.liquid}
- on:click={() => setType(types.liquid)}
- >
- <img src="/images/liquid.svg" class="w-8" alt="Liquid" />
- <div class="my-auto text-lg">Liquid</div>
- </button>
-
- <button
- class="hover:bg-primary flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 w-full justify-center"
- class:bg-primary={type === types.lightning}
- class:text-black={type === types.lightning}
- on:click={() => setType(types.lightning)}
- >
- <div class="bg-white rounded-full w-8 h-8 text-center flex">
- <div class="m-auto">⚡️</div>
- </div>
- <div class="my-auto text-lg">Lightning</div>
- </button>
- </div>
-
- {#if type === types.liquid}
- <div class="flex justify-center">
- <div class="my-auto text-xl text-center text-secondary">
- {$t("payments.onlyLbtc")}
- <span class="text-teal-500 font-bold">L-BTC</span>,
- {$t("payments.dontDeposit")}
- </div>
- </div>
- {/if}
-
- {#if $showQr === 2}
- <div>
- <a
- href={[types.bitcoin, types.liquid].includes(invoice.type)
- ? invoice.text
- : "lightning:" + invoice.text}
- >
- <img
- {src}
- class="mx-auto z-10 shadow-inner rounded-2xl"
- bind:this={qr}
- alt={txt}
- />
- </a>
- </div>
- {/if}
-</div>
-
-<style>
- .invoice {
- view-transition-name: invoice;
- }
-</style>
diff --git a/src/routes/(app)/[username]/invoice/[id]/tip/+page.server.js b/src/routes/(app)/[username]/invoice/[id]/tip/+page.server.js
deleted file mode 100644
index b81e2364..00000000
--- a/src/routes/(app)/[username]/invoice/[id]/tip/+page.server.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import invoice from "$lib/invoice";
-import { redirect } from "@sveltejs/kit";
-
-export async function load({ parent, params }) {
- let { invoice } = await parent();
- if (!invoice.amount)
- redirect(307, `/${params.username}/invoice/${invoice.id}`);
-}
-
-export const actions = {
- default: invoice,
-};
diff --git a/src/routes/(app)/[username]/items/[id]/+page.server.js b/src/routes/(app)/[username]/items/[id]/+page.server.js
deleted file mode 100644
index 4cfc952c..00000000
--- a/src/routes/(app)/[username]/items/[id]/+page.server.js
+++ /dev/null
@@ -1,21 +0,0 @@
-import { fd, auth, get, post } from "$lib/utils";
-import { fail, redirect } from "@sveltejs/kit";
-
-export let load = async ({ cookies, params: { id } }) => {
- let item = await get(`/items/${id}`);
- return { item };
-};
-
-export const actions = {
- default: async ({ cookies, request, url }) => {
- let form = await fd(request);
- try {
- await post(`/items`, form, auth(cookies));
- } catch (e) {
- return fail(400, { message: e.message });
- }
-
- let success = `/${url.pathname.split("/")[1]}`;
- redirect(307, success);
- },
-};
diff --git a/src/routes/(app)/[username]/items/create/+page.server.js b/src/routes/(app)/[username]/items/create/+page.server.js
deleted file mode 100644
index 8cb48399..00000000
--- a/src/routes/(app)/[username]/items/create/+page.server.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import { fail, redirect } from "@sveltejs/kit";
-import { fd, auth, get, post } from "$lib/utils";
-
-export const actions = {
- default: async ({ cookies, request, url }) => {
- let form = await fd(request);
- try {
- await post("/items", form, auth(cookies));
- } catch (e) {
- return fail(400, { message: e.message });
- }
-
- let success = `/${url.pathname.split("/")[1]}`;
- redirect(307, success);
- },
-};
diff --git a/src/routes/(app)/[username]/map/+page.server.js b/src/routes/(app)/[username]/map/+page.server.js
deleted file mode 100644
index 616d28f6..00000000
--- a/src/routes/(app)/[username]/map/+page.server.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import { get } from "$lib/utils";
-
-// export const prerender = true;
-export let load = async () => {
- let data = { locations: [] };
-
- try {
- data = await get("/locations");
- } catch (e) {}
-
- return data;
-};
diff --git a/src/routes/(app)/[username]/map/+page.svelte b/src/routes/(app)/[username]/map/+page.svelte
deleted file mode 100644
index bfa115e4..00000000
--- a/src/routes/(app)/[username]/map/+page.svelte
+++ /dev/null
@@ -1,8 +0,0 @@
-<script>
- import LocationsMap from "$comp/LocationsMap.svelte";
- export let data;
-
- let { locations } = data;
-</script>
-
-<LocationsMap {locations} />
diff --git a/src/routes/(app)/[username]/messages/+page.server.js b/src/routes/(app)/[username]/messages/+page.server.js
deleted file mode 100644
index 33d9ccaa..00000000
--- a/src/routes/(app)/[username]/messages/+page.server.js
+++ /dev/null
@@ -1,33 +0,0 @@
-import { auth, get } from "$lib/utils";
-import { redirect } from "@sveltejs/kit";
-
-export async function load({ cookies, params, parent, url }) {
- let { user } = await parent();
- if (user.username !== params.username) redirect(307, `/${params.username}`);
- let { since = 0 } = params;
-
- let messages = [],
- notes = [];
-
- if (user?.pubkey) {
- let { pubkey } = user;
- try {
- messages = await get(`/${pubkey}/${since}/messages`);
- messages = messages.sort((a, b) => b.created_at - a.created_at);
- } catch (e) {
- console.log(`failed to fetch nostr messages`, e);
- }
-
- try {
- notes = await get(`/${pubkey}/notes`);
- } catch (e) {
- console.log(`failed to fetch nostr notes for ${pubkey}`, e);
- }
-
- notes.map((e) => {
- e.seen = e.created_at;
- });
- }
-
- return { messages, notes };
-}
diff --git a/src/routes/(app)/[username]/messages/[recipient]/+page.server.js b/src/routes/(app)/[username]/messages/[recipient]/+page.server.js
deleted file mode 100644
index 6936a06b..00000000
--- a/src/routes/(app)/[username]/messages/[recipient]/+page.server.js
+++ /dev/null
@@ -1,23 +0,0 @@
-import { get } from "$lib/utils";
-
-export async function load({ params, parent, url }) {
- let { user } = await parent();
- let { since = 0 } = params;
-
- let messages = [];
- let recipient = await get(`/users/${params.recipient}`);
-
- try {
- messages = await get(`/${user.pubkey}/${since}/messages`);
-
- messages = messages
- .filter(
- (m) => m.recipient?.id === recipient.id || m.author?.id === recipient.id
- )
- .sort((a, b) => a.created_at - b.created_at);
- } catch (e) {
- console.log(`failed to fetch nostr messages`, e);
- }
-
- return { messages, recipient, user };
-}
diff --git a/src/routes/(app)/[username]/payments/[...page]/+page.server.js b/src/routes/(app)/[username]/payments/[...page]/+page.server.js
deleted file mode 100644
index 7a3bc179..00000000
--- a/src/routes/(app)/[username]/payments/[...page]/+page.server.js
+++ /dev/null
@@ -1,26 +0,0 @@
-import { get, auth } from "$lib/utils";
-
-let limit = 25;
-
-export async function load({ cookies, depends, params, request }) {
- depends("app:payments");
-
- let parts = params.page.split("/");
-
- let start, end, page;
- if (parts.length === 1) [page] = parts;
- if (parts.length === 2) [start, page] = parts;
- if (parts.length === 3) [start, end, page] = parts;
- if (!parseInt(page)) page = 1;
-
- let offset = (page - 1) * limit;
- if (!start) start = Date.now() / 1000 - 24 * 60 * 60;
-
- let url = `/payments?start=${start * 1000}&limit=${limit}&offset=${offset}`;
- if (end) url += `&end=${end * 1000}`;
-
- let { count, payments, totals } = await get(url, auth(cookies));
- let pages = new Array(Math.ceil(count / limit));
-
- return { payments, page, pages, start, end, totals };
-}
diff --git a/src/routes/(app)/[username]/payments/[...page]/+server.js b/src/routes/(app)/[username]/payments/[...page]/+server.js
deleted file mode 100644
index a81faaf3..00000000
--- a/src/routes/(app)/[username]/payments/[...page]/+server.js
+++ /dev/null
@@ -1,18 +0,0 @@
-import { get, auth } from "$lib/utils";
-import { json } from "@sveltejs/kit";
-
-export async function GET({ cookies, params }) {
- let parts = params.page.split("/");
-
- let start, end;
- if (parts.length === 1) [start] = parts;
- if (parts.length === 2) [start, end] = parts;
-
- if (!start) start = Date.now() / 1000 - 24 * 60 * 60;
-
- let url = `/payments?start=${start * 1000}`;
- if (end) url += `&end=${end * 1000}`;
-
- let { payments } = await get(url, auth(cookies));
- return json({ payments });
-}
diff --git a/src/routes/(app)/[username]/receive/+page.server.js b/src/routes/(app)/[username]/receive/+page.server.js
new file mode 100644
index 00000000..8a4d754c
--- /dev/null
+++ b/src/routes/(app)/[username]/receive/+page.server.js
@@ -0,0 +1,8 @@
+import * as Qr from "qrcode-base64";
+export let load = async ({ cookies, url }) => {
+ let username = cookies.get("username");
+ let text = `${username}@${url.host}`;
+ let src = Qr.drawImg(text, { size: 500 });
+
+ return { src, text };
+};
diff --git a/src/routes/(app)/[username]/receive/+page.svelte b/src/routes/(app)/[username]/receive/+page.svelte
new file mode 100644
index 00000000..2a0cb6b3
--- /dev/null
+++ b/src/routes/(app)/[username]/receive/+page.svelte
@@ -0,0 +1,272 @@
+<script>
+ import { send } from "$lib/socket";
+ import { btc, post, copy, f, get, types, sat, s, sats } from "$lib/utils";
+ import { tick, onMount, onDestroy } from "svelte";
+ import { browser } from "$app/environment";
+ import { last, showQr, amountPrompt } from "$lib/store";
+ import Avatar from "$comp/Avatar.svelte";
+ import Icon from "$comp/Icon.svelte";
+ import Numpad from "$comp/Numpad.svelte";
+ import { t } from "$lib/translations";
+ import { goto, invalidate } from "$app/navigation";
+ import Toggle from "$comp/Toggle.svelte";
+
+ export let data;
+
+ let showOptions;
+
+ let { id, rates, subject, user, src, text } = data;
+ $: refresh(data);
+ let refresh = (data) => {
+ ({ id, rates, subject, user, src, text } = data);
+ };
+
+ let { currency, username } = subject;
+ let rate = rates[currency];
+ let type = types.lightning;
+ let hash = "";
+
+ let qr;
+
+ $: link = [types.bitcoin, types.liquid].includes(type)
+ ? text
+ : `lightning:${text}`;
+ $: txt = [types.bitcoin, types.liquid].includes(type) ? hash : text;
+
+ let aid = subject.id;
+ let invoice = {
+ aid,
+ type: types.lightning,
+ items: [],
+ user: subject,
+ };
+ let amount, amountFiat, tip;
+
+ let setType = async (type) => {
+ invoice.type = type;
+ ({ id } = await post(`/invoice`, {
+ invoice,
+ user: { username, currency },
+ }));
+
+ goto(`/invoice/${id}?options=true`, {
+ invalidateAll: true,
+ noScroll: true,
+ });
+ };
+
+ let setAmount = async () => {
+ if (typeof $amountPrompt === "undefined") $amountPrompt = true;
+ settingAmount = false;
+ amount = newAmount;
+ invoice.amount = newAmount;
+ invoice.tip = 0;
+ ({ id } = await post(`/invoice`, {
+ invoice,
+ user: { username, currency },
+ }));
+
+ let url = `/invoice/${id}`;
+ if (subject?.prompt) url += "/tip";
+ else url += "?options=true";
+
+ goto(url, { invalidateAll: true, noScroll: true });
+ };
+
+ let newAmount;
+ let settingAmount;
+ let toggleAmount = () => (settingAmount = !settingAmount);
+ let fiat;
+ let submit;
+</script>
+
+<div class="invoice container mx-auto max-w-xl px-4 space-y-2">
+ {#if $showQr}
+ <div>
+ <a href={link}>
+ <img
+ {src}
+ class="mx-auto z-10 max-w-[360px]"
+ bind:this={qr}
+ alt={txt}
+ />
+ </a>
+ </div>
+ {/if}
+
+ <div class="break-all text-center text-secondary text-xl">
+ {txt}
+ </div>
+
+ {#each invoice.items as i}
+ <div class="grid grid-cols-12 text-xl">
+ <div class="col-span-1 my-auto">{i.quantity}</div>
+ <div class="mr-auto grow col-span-7 my-auto">
+ {i.name}
+ </div>
+ <div class="col-span-2 font-semibold text-right my-auto">
+ {f(i.price * i.quantity, currency)}
+ </div>
+ <div class="col-span-2 text-secondary text-right text-lg my-auto">
+ {sat(btc(i.price * i.quantity, rate))}
+ </div>
+ </div>
+ {/each}
+
+ {#if amount > 0}
+ <div class="text-center font-bold text-2xl">
+ <div>
+ {f(amountFiat, currency)}
+
+ {#if tip}
+ <span class="text-sm">
+ +{f(tip * (rate / sats), currency)}
+ </span>
+ {/if}
+ </div>
+ <div>
+ <span class="text-secondary font-normal text-xl"
+ >⚡️{`${s(amount)}`}</span
+ >
+
+ {#if tip}
+ <span class="text-sm text-secondary font-normal">
+ +⚡️{s(tip)}
+ </span>
+ {/if}
+ </div>
+ </div>
+ {/if}
+
+ <div class="text-secondary space-y-2 text-xl pt-2">
+ <button
+ type="button"
+ class="flex gap-2 text-center break-all rounded-2xl hover:opacity-80 py-5 px-6 w-full mx-auto justify-center border whitespace-nowrap mb-2"
+ on:click={() => copy(txt)}
+ >
+ <Icon icon="copy" style="w-8 my-auto" />
+ <div class="my-auto">
+ {$t("payments.copy")}
+ </div>
+ </button>
+
+ {#if user?.id === invoice?.user?.id}
+ <button
+ class="w-full flex justify-center rounded-2xl border py-5 px-6 hover:opacity-80"
+ on:click={toggleAmount}
+ >
+ <Icon icon="edit" style="mr-1 w-8" />
+ <div class="my-auto">{$t("payments.setAmount")}</div>
+ </button>
+ {:else}
+ <a href={link} class="w-full">
+ <button
+ class="w-full flex justify-center rounded-2xl border py-5 px-6 hover:opacity-80"
+ >
+ <Icon icon="mobile" style="mr-1 w-8" />
+ <div class="my-auto">{$t("payments.openLink")}</div>
+ </button>
+ </a>
+ {/if}
+ </div>
+
+ {#if aid === user.id}
+ <div class="grid grid-cols-2 justify-around text-secondary">
+ <button
+ class="hover:bg-primary my-auto flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 justify-center"
+ class:bg-primary={type === types.bitcoin}
+ class:text-black={type === types.bitcoin}
+ on:click={() => setType(types.bitcoin)}
+ >
+ <img src="/images/bitcoin.svg" class="w-8" alt="Bitcoin" />
+ <div class="my-auto text-lg">Bitcoin</div>
+ </button>
+
+ <button
+ class="hover:bg-primary my-auto flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 justify-center"
+ class:bg-primary={type === types.liquid}
+ class:text-black={type === types.liquid}
+ on:click={() => setType(types.liquid)}
+ >
+ <img src="/images/liquid.svg" class="w-8" alt="Liquid" />
+ <div class="my-auto text-lg">Liquid</div>
+ </button>
+
+ <button
+ class="hover:bg-primary flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 justify-center"
+ class:bg-primary={type === types.lightning}
+ class:text-black={type === types.lightning}
+ on:click={() => setType(types.lightning)}
+ >
+ <div class="bg-white rounded-full w-8 h-8 text-center flex">
+ <div class="m-auto">⚡️</div>
+ </div>
+ <div class="my-auto text-lg">Lightning</div>
+ </button>
+
+ {#if user?.id === invoice?.user?.id}
+ <a href={`/receive`} class="block contents">
+ <button
+ class="hover:bg-primary flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 justify-center"
+ >
+ <img src="/images/cash.png" class="w-8 my-auto" />
+ <div class="my-auto text-lg">Ecash</div>
+ </button>
+ </a>
+ {/if}
+ </div>
+
+ {#if type === types.liquid}
+ <div class="flex justify-center">
+ <div class="my-auto text-xl text-center text-secondary">
+ {$t("payments.onlyLbtc")}
+ <span class="text-teal-500 font-bold">L-BTC</span>,
+ {$t("payments.dontDeposit")}
+ </div>
+ </div>
+ {/if}
+ {/if}
+</div>
+
+{#if settingAmount}
+ <div
+ class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50"
+ >
+ <div
+ class="relative mx-auto p-12 border max-w-xl shadow-lg rounded-md bg-white space-y-5 top-5"
+ >
+ <form on:submit|preventDefault={setAmount} class="space-y-5">
+ <Numpad
+ bind:amount={newAmount}
+ bind:currency
+ bind:rate
+ bind:fiat
+ bind:submit
+ />
+ <div class="w-full flex flex-wrap gap-2">
+ <button
+ bind:this={submit}
+ type="submit"
+ on:click={setAmount}
+ class="border-2 border-black rounded-xl font-semibold mx-auto py-3 w-40 hover:opacity-80 mx-auto bg-black text-white w-full"
+ >
+ <div class="my-auto">{$t("payments.ok")}</div>
+ </button>
+ <button
+ type="button"
+ class="border-2 border-black rounded-xl font-semibold mx-auto py-3 w-40 hover:opacity-80 mx-auto w-full"
+ on:click={toggleAmount}
+ on:keydown={toggleAmount}
+ >
+ <div class="my-auto">{$t("payments.cancel")}</div>
+ </button>
+ </div>
+ </form>
+
+ <div class="flex justify-center gap-3">
+ <div class="text-secondary">{$t("payments.amountPrompt")}</div>
+ <Toggle id="notify" bind:value={$amountPrompt} />
+ </div>
+ </div>
+ </div>
+{/if}
diff --git a/src/routes/(app)/[username]/receive/[...param]/+page.server.js b/src/routes/(app)/[username]/receive/[...param]/+page.server.js
deleted file mode 100644
index a6e59175..00000000
--- a/src/routes/(app)/[username]/receive/[...param]/+page.server.js
+++ /dev/null
@@ -1,15 +0,0 @@
-import { auth, get } from "$lib/utils";
-import invoice from "$lib/invoice";
-
-export let load = async ({ cookies, params }) => {
- let id = params.param;
-
- let request;
- if (id) ({ request } = await get(`/request/${id}`, auth(cookies)));
-
- return { ...params, request };
-};
-
-export const actions = {
- default: invoice,
-};
diff --git a/src/routes/(app)/[username]/receive/[...param]/+page.svelte b/src/routes/(app)/[username]/receive/[...param]/+page.svelte
deleted file mode 100644
index d643d181..00000000
--- a/src/routes/(app)/[username]/receive/[...param]/+page.svelte
+++ /dev/null
@@ -1,52 +0,0 @@
-<script>
- import Icon from "$comp/Icon.svelte";
- import Numpad from "$comp/Numpad.svelte";
- import Toggle from "$comp/Toggle.svelte";
- import { t } from "$lib/translations";
- import { enhance } from "$app/forms";
- import { page } from "$app/stores";
- import { requestRedirect } from "$lib/store";
- import { browser } from "$app/environment";
-
- export let data;
- let type = "lightning";
-
- if ($page.params.param === "bitcoin") type = "bitcoin";
-
- let { request } = data;
-
- let amount;
-
- let lightning = true;
- let { currency, username, prompt } = data.subject;
- let { rates, user } = data;
- let submit;
-
- $: rate = rates[currency];
- $: type = lightning ? "lightning" : "bitcoin";
-</script>
-
-<form
- method="POST"
- class="flex justify-center items-center mb-3 px-3"
- use:enhance
->
- <input type="hidden" name="amount" value={amount} />
- <input type="hidden" name="currency" value={currency} />
- <input type="hidden" name="username" value={username} />
- <input type="hidden" name="type" value={type} />
- <input type="hidden" name="rate" value={rate} />
- <input type="hidden" name="prompt" value={prompt} />
-
- <div class="space-y-3 w-[300px] mx-auto">
- <Numpad bind:amount bind:currency bind:rate {submit} />
- <button
- bind:this={submit}
- type="submit"
- class="bg-black text-white rounded-xl w-full h-[48px] flex justify-center items-center font-semibold
- opacity-100 hover:opacity-80"
- >
- {$t("payments.next")}
- </button>
- </div>
-</form>
diff --git a/src/routes/(app)/[username]/reset/+server.js b/src/routes/(app)/[username]/reset/+server.js
deleted file mode 100644
index f7dba02c..00000000
--- a/src/routes/(app)/[username]/reset/+server.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import { json } from "@sveltejs/kit";
-import { auth, post } from "$lib/utils";
-
-export async function POST({ cookies, request, params }) {
- let { username } = params;
- let r = await request.json();
- let { password } = r;
- let result = await post("/reset", { password, username }, auth(cookies));
- return json(result);
-}
diff --git a/src/routes/(app)/[username]/settings/[...tab]/+page.server.js b/src/routes/(app)/[username]/settings/[...tab]/+page.server.js
deleted file mode 100644
index 5ff691f0..00000000
--- a/src/routes/(app)/[username]/settings/[...tab]/+page.server.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import { fail, redirect } from "@sveltejs/kit";
-import { fd, auth, get, post } from "$lib/utils";
-
-export function load({ cookies, params, url }) {
- if (url.pathname.endsWith("settings"))
- redirect(307, url.pathname + "/account");
- params.cookies = cookies.getAll();
- return { cookies: cookies.getAll(), tab: params.tab };
-}
-
-export const actions = {
- default: async ({ cookies, request }) => {
- let form = await fd(request);
-
- if (form.tab === "pos") {
- form.notify = form.notify === "on";
- form.nip5 = form.nip5 === "on";
- form.prompt = form.prompt === "on";
- form.autowithdraw = form.autowithdraw === "on";
- }
-
- let user = { ...(await get("/me", auth(cookies))), ...form };
-
- try {
- ({ user } = await post(`/user`, user, auth(cookies)));
- } catch (e) {
- return fail(400, { message: e.message });
- }
-
- if (user.language) cookies.set("lang", user.language, { path: "/" });
-
- return { user, success: true };
- },
-};
diff --git a/src/routes/(app)/[username]/shopify.js/+server.js b/src/routes/(app)/[username]/shopify.js/+server.ts
index c93ac729..f76d6998 100644
--- a/src/routes/(app)/[username]/shopify.js/+server.js
+++ b/src/routes/(app)/[username]/shopify.js/+server.ts
@@ -1,7 +1,7 @@
-export async function GET({ cookies, params, url }) {
- let { username } = params;
+export async function GET({ params, url }) {
+ const { username } = params;
- let js = `
+ const js = `
var qrcode=function(r,_){var t=r,e=QRErrorCorrectLevel[_],n=null,$=0,o=null,a=[],f={},i=function(r,_){n=function(r){for(var _=Array(r),t=0;t<r;t+=1){_[t]=Array(r);for(var e=0;e<r;e+=1)_[t][e]=null}return _}($=4*t+17),u(0,0),u($-7,0),u(0,$-7),l(),g(),v(r,_),t>=7&&h(r),null==o&&(o=x(t,e,a)),s(o,_)},u=function(r,_){for(var t=-1;t<=7;t+=1)if(!(r+t<=-1)&&!($<=r+t))for(var e=-1;e<=7;e+=1)_+e<=-1||$<=_+e||(0<=t&&t<=6&&(0==e||6==e)||0<=e&&e<=6&&(0==t||6==t)||2<=t&&t<=4&&2<=e&&e<=4?n[r+t][_+e]=!0:n[r+t][_+e]=!1)},c=function(){for(var r=0,_=0,t=0;t<8;t+=1){i(!0,t);var e=QRUtil.getLostPoint(f);(0==t||r>e)&&(r=e,_=t)}return _},g=function(){for(var r=8;r<$-8;r+=1)null==n[r][6]&&(n[r][6]=r%2==0);for(var _=8;_<$-8;_+=1)null==n[6][_]&&(n[6][_]=_%2==0)},l=function(){for(var r=QRUtil.getPatternPosition(t),_=0;_<r.length;_+=1)for(var e=0;e<r.length;e+=1){var $=r[_],o=r[e];if(null==n[$][o])for(var a=-2;a<=2;a+=1)for(var f=-2;f<=2;f+=1)-2==a||2==a||-2==f||2==f||0==a&&0==f?n[$+a][o+f]=!0:n[$+a][o+f]=!1}},h=function(r){for(var _=QRUtil.getBCHTypeNumber(t),e=0;e<18;e+=1){var o=!r&&(_>>e&1)==1;n[Math.floor(e/3)][e%3+$-8-3]=o}for(var e=0;e<18;e+=1){var o=!r&&(_>>e&1)==1;n[e%3+$-8-3][Math.floor(e/3)]=o}},v=function(r,_){for(var t=QRUtil.getBCHTypeInfo(e<<3|_),o=0;o<15;o+=1){var a=!r&&(t>>o&1)==1;o<6?n[o][8]=a:o<8?n[o+1][8]=a:n[$-15+o][8]=a}for(var o=0;o<15;o+=1){var a=!r&&(t>>o&1)==1;o<8?n[8][$-o-1]=a:o<9?n[8][15-o-1+1]=a:n[8][15-o-1]=a}n[$-8][8]=!r},s=function(r,_){for(var t=-1,e=$-1,o=7,a=0,f=QRUtil.getMaskFunction(_),i=$-1;i>0;i-=2)for(6==i&&(i-=1);;){for(var u=0;u<2;u+=1)if(null==n[e][i-u]){var c=!1;a<r.length&&(c=(r[a]>>>o&1)==1),f(e,i-u)&&(c=!c),n[e][i-u]=c,-1==(o-=1)&&(a+=1,o=7)}if((e+=t)<0||$<=e){e-=t,t=-t;break}}},d=function(r,_){for(var t=0,e=0,n=0,$=Array(_.length),o=Array(_.length),a=0;a<_.length;a+=1){var f=_[a].dataCount,i=_[a].totalCount-f;e=Math.max(e,f),n=Math.max(n,i),$[a]=Array(f);for(var u=0;u<$[a].length;u+=1)$[a][u]=255&r.getBuffer()[u+t];t+=f;var c=QRUtil.getErrorCorrectPolynomial(i),g=qrPolynomial($[a],c.getLength()-1).mod(c);o[a]=Array(c.getLength()-1);for(var u=0;u<o[a].length;u+=1){var l=u+g.getLength()-o[a].length;o[a][u]=l>=0?g.getAt(l):0}}for(var h=0,u=0;u<_.length;u+=1)h+=_[u].totalCount;for(var v=Array(h),s=0,u=0;u<e;u+=1)for(var a=0;a<_.length;a+=1)u<$[a].length&&(v[s]=$[a][u],s+=1);for(var u=0;u<n;u+=1)for(var a=0;a<_.length;a+=1)u<o[a].length&&(v[s]=o[a][u],s+=1);return v},x=function(r,_,t){for(var e=QRRSBlock.getRSBlocks(r,_),n=qrBitBuffer(),$=0;$<t.length;$+=1){var o=t[$];n.put(o.getMode(),4),n.put(o.getLength(),QRUtil.getLengthInBits(o.getMode(),r)),o.write(n)}for(var a=0,$=0;$<e.length;$+=1)a+=e[$].dataCount;if(n.getLengthInBits()>8*a)throw Error("code length overflow. ("+n.getLengthInBits()+">"+8*a+")");for(n.getLengthInBits()+4<=8*a&&n.put(0,4);n.getLengthInBits()%8!=0;)n.putBit(!1);for(;!(n.getLengthInBits()>=8*a)&&(n.put(236,8),!(n.getLengthInBits()>=8*a));){;n.put(17,8)}return d(n,e)};return f.addData=function(r){var _=qr8BitByte(r);a.push(_),o=null},f.isDark=function(r,_){if(r<0||$<=r||_<0||$<=_)throw Error(r+","+_);return n[r][_]},f.getModuleCount=function(){return $},f.make=function(){i(!1,c())},f.createTableTag=function(r,_){r=r||2;var t="";t+='<table style="',t+=" border-width: 0px; border-style: none;",t+=" border-collapse: collapse;",t+=" padding: 0px; margin: "+(_=void 0===_?4*r:_)+"px;",t+='">',t+="<tbody>";for(var e=0;e<f.getModuleCount();e+=1){t+="<tr>";for(var n=0;n<f.getModuleCount();n+=1)t+='<td style="',t+=" border-width: 0px; border-style: none;",t+=" border-collapse: collapse;",t+=" padding: 0px; margin: 0px;",t+=" width: "+r+"px;",t+=" height: "+r+"px;",t+=" background-color: ",t+=f.isDark(e,n)?"#000000":"#ffffff",t+=";",t+='"/>';t+="</tr>"}return t+="</tbody>",t+="</table>"},f.createImgTag=function(r,_,t){r=r||2;var e=_=void 0===_?4*r:_,n=f.getModuleCount()*r+_;return createImgTag(t,t,function(_,t){if(!(e<=_)||!(_<n)||!(e<=t)||!(t<n))return 1;var $=Math.floor((_-e)/r),o=Math.floor((t-e)/r);return f.isDark(o,$)?0:1})},f};qrcode.stringToBytes=function(r){for(var _=[],t=0;t<r.length;t+=1){var e=r.charCodeAt(t);_.push(255&e)}return _},qrcode.createStringToBytes=function(r,_){var t=function(){for(var t=base64DecodeInputStream(r),e=function(){var r=t.read();if(-1==r)throw Error();return r},n=0,$={};;){var o=t.read();if(-1==o)break;var a=e(),f=e(),i=e(),u=String.fromCharCode(o<<8|a),c=f<<8|i;$[u]=c,n+=1}if(n!=_)throw Error(n+" != "+_);return $}();return function(r){for(var _=[],e=0;e<r.length;e+=1){var n=r.charCodeAt(e);if(n<128)_.push(n);else{var $=t[r.charAt(e)];"number"==typeof $?(255&$)==$?_.push($):(_.push($>>>8),_.push(255&$)):_.push(63)}}return _}};var QRMode={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},QRErrorCorrectLevel={L:1,M:0,Q:3,H:2},QRMaskPattern={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},QRUtil=function(){var r=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],_={},t=function(r){for(var _=0;0!=r;)_+=1,r>>>=1;return _};return _.getBCHTypeInfo=function(r){for(var _=r<<10;t(_)-t(1335)>=0;)_^=1335<<t(_)-t(1335);return(r<<10|_)^21522},_.getBCHTypeNumber=function(r){for(var _=r<<12;t(_)-t(7973)>=0;)_^=7973<<t(_)-t(7973);return r<<12|_},_.getPatternPosition=function(_){return r[_-1]},_.getMaskFunction=function(r){switch(r){case QRMaskPattern.PATTERN000:return function(r,_){return(r+_)%2==0};case QRMaskPattern.PATTERN001:return function(r,_){return r%2==0};case QRMaskPattern.PATTERN010:return function(r,_){return _%3==0};case QRMaskPattern.PATTERN011:return function(r,_){return(r+_)%3==0};case QRMaskPattern.PATTERN100:return function(r,_){return(Math.floor(r/2)+Math.floor(_/3))%2==0};case QRMaskPattern.PATTERN101:return function(r,_){return r*_%2+r*_%3==0};case QRMaskPattern.PATTERN110:return function(r,_){return(r*_%2+r*_%3)%2==0};case QRMaskPattern.PATTERN111:return function(r,_){return(r*_%3+(r+_)%2)%2==0};default:throw Error("bad maskPattern:"+r)}},_.getErrorCorrectPolynomial=function(r){for(var _=qrPolynomial([1],0),t=0;t<r;t+=1)_=_.multiply(qrPolynomial([1,QRMath.gexp(t)],0));return _},_.getLengthInBits=function(r,_){if(1<=_&&_<10)switch(r){case QRMode.MODE_NUMBER:return 10;case QRMode.MODE_ALPHA_NUM:return 9;case QRMode.MODE_8BIT_BYTE:case QRMode.MODE_KANJI:return 8;default:throw Error("mode:"+r)}else if(_<27)switch(r){case QRMode.MODE_NUMBER:return 12;case QRMode.MODE_ALPHA_NUM:return 11;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 10;default:throw Error("mode:"+r)}else if(_<41)switch(r){case QRMode.MODE_NUMBER:return 14;case QRMode.MODE_ALPHA_NUM:return 13;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 12;default:throw Error("mode:"+r)}else throw Error("type:"+_)},_.getLostPoint=function(r){for(var _=r.getModuleCount(),t=0,e=0;e<_;e+=1)for(var n=0;n<_;n+=1){for(var $=0,o=r.isDark(e,n),a=-1;a<=1;a+=1)if(!(e+a<0)&&!(_<=e+a))for(var f=-1;f<=1;f+=1)!(n+f<0)&&!(_<=n+f)&&(0!=a||0!=f)&&o==r.isDark(e+a,n+f)&&($+=1);$>5&&(t+=3+$-5)}for(var e=0;e<_-1;e+=1)for(var n=0;n<_-1;n+=1){var i=0;r.isDark(e,n)&&(i+=1),r.isDark(e+1,n)&&(i+=1),r.isDark(e,n+1)&&(i+=1),r.isDark(e+1,n+1)&&(i+=1),(0==i||4==i)&&(t+=3)}for(var e=0;e<_;e+=1)for(var n=0;n<_-6;n+=1)r.isDark(e,n)&&!r.isDark(e,n+1)&&r.isDark(e,n+2)&&r.isDark(e,n+3)&&r.isDark(e,n+4)&&!r.isDark(e,n+5)&&r.isDark(e,n+6)&&(t+=40);for(var n=0;n<_;n+=1)for(var e=0;e<_-6;e+=1)r.isDark(e,n)&&!r.isDark(e+1,n)&&r.isDark(e+2,n)&&r.isDark(e+3,n)&&r.isDark(e+4,n)&&!r.isDark(e+5,n)&&r.isDark(e+6,n)&&(t+=40);for(var u=0,n=0;n<_;n+=1)for(var e=0;e<_;e+=1)r.isDark(e,n)&&(u+=1);return t+10*(Math.abs(100*u/_/_-50)/5)},_}(),QRMath=function(){for(var r=Array(256),_=Array(256),t=0;t<8;t+=1)r[t]=1<<t;for(var t=8;t<256;t+=1)r[t]=r[t-4]^r[t-5]^r[t-6]^r[t-8];for(var t=0;t<255;t+=1)_[r[t]]=t;var e={};return e.glog=function(r){if(r<1)throw Error("glog("+r+")");return _[r]},e.gexp=function(_){for(;_<0;)_+=255;for(;_>=256;)_-=255;return r[_]},e}();function qrPolynomial(r,_){if(void 0===r.length)throw Error(r.length+"/"+_);var t=function(){for(var t=0;t<r.length&&0==r[t];)t+=1;for(var e=Array(r.length-t+_),n=0;n<r.length-t;n+=1)e[n]=r[n+t];return e}(),e={};return e.getAt=function(r){return t[r]},e.getLength=function(){return t.length},e.multiply=function(r){for(var _=Array(e.getLength()+r.getLength()-1),t=0;t<e.getLength();t+=1)for(var n=0;n<r.getLength();n+=1)_[t+n]^=QRMath.gexp(QRMath.glog(e.getAt(t))+QRMath.glog(r.getAt(n)));return qrPolynomial(_,0)},e.mod=function(r){if(e.getLength()-r.getLength()<0)return e;for(var _=QRMath.glog(e.getAt(0))-QRMath.glog(r.getAt(0)),t=Array(e.getLength()),n=0;n<e.getLength();n+=1)t[n]=e.getAt(n);for(var n=0;n<r.getLength();n+=1)t[n]^=QRMath.gexp(QRMath.glog(r.getAt(n))+_);return qrPolynomial(t,0).mod(r)},e}var QRRSBlock=function(){var r=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],_=function(r,_){var t={};return t.totalCount=r,t.dataCount=_,t},t={},e=function(_,t){switch(t){case QRErrorCorrectLevel.L:return r[(_-1)*4+0];case QRErrorCorrectLevel.M:return r[(_-1)*4+1];case QRErrorCorrectLevel.Q:return r[(_-1)*4+2];case QRErrorCorrectLevel.H:return r[(_-1)*4+3];default:return}};return t.getRSBlocks=function(r,t){var n=e(r,t);if(void 0===n)throw Error("bad rs block @ typeNumber:"+r+"/errorCorrectLevel:"+t);for(var $=n.length/3,o=[],a=0;a<$;a+=1)for(var f=n[3*a+0],i=n[3*a+1],u=n[3*a+2],c=0;c<f;c+=1)o.push(_(i,u));return o},t}(),qrBitBuffer=function(){var r=[],_=0,t={};return t.getBuffer=function(){return r},t.getAt=function(_){return(r[Math.floor(_/8)]>>>7-_%8&1)==1},t.put=function(r,_){for(var e=0;e<_;e+=1)t.putBit((r>>>_-e-1&1)==1)},t.getLengthInBits=function(){return _},t.putBit=function(t){var e=Math.floor(_/8);r.length<=e&&r.push(0),t&&(r[e]|=128>>>_%8),_+=1},t},qr8BitByte=function(r){for(var _=QRMode.MODE_8BIT_BYTE,t=r,e=[],n={},$=0,o=t.length;$<o;$++){var a=[],f=t.charCodeAt($);f>65536?(a[0]=240|(1835008&f)>>>18,a[1]=128|(258048&f)>>>12,a[2]=128|(4032&f)>>>6,a[3]=128|63&f):f>2048?(a[0]=224|(61440&f)>>>12,a[1]=128|(4032&f)>>>6,a[2]=128|63&f):f>128?(a[0]=192|(1984&f)>>>6,a[1]=128|63&f):a[0]=f,e.push(a)}(e=Array.prototype.concat.apply([],e)).length!=t.length&&(e.unshift(191),e.unshift(187),e.unshift(239));var i=e;return n.getMode=function(){return _},n.getLength=function(r){return i.length},n.write=function(r){for(var _=0;_<i.length;_+=1)r.put(i[_],8)},n},byteArrayOutputStream=function(){var r=[],_={};return _.writeByte=function(_){r.push(255&_)},_.writeShort=function(r){_.writeByte(r),_.writeByte(r>>>8)},_.writeBytes=function(r,t,e){t=t||0,e=e||r.length;for(var n=0;n<e;n+=1)_.writeByte(r[n+t])},_.writeString=function(r){for(var t=0;t<r.length;t+=1)_.writeByte(r.charCodeAt(t))},_.toByteArray=function(){return r},_.toString=function(){var _="";_+="[";for(var t=0;t<r.length;t+=1)t>0&&(_+=","),_+=r[t];return _+"]"},_},base64EncodeOutputStream=function(){var r=0,_=0,t=0,e="",n={},$=function(r){e+=String.fromCharCode(o(63&r))},o=function(r){if(r<0);else if(r<26)return 65+r;else if(r<52)return 97+(r-26);else if(r<62)return 48+(r-52);else if(62==r)return 43;else if(63==r)return 47;throw Error("n:"+r)};return n.writeByte=function(e){for(r=r<<8|255&e,_+=8,t+=1;_>=6;)$(r>>>_-6),_-=6},n.flush=function(){if(_>0&&($(r<<6-_),r=0,_=0),t%3!=0)for(var n=3-t%3,o=0;o<n;o+=1)e+="="},n.toString=function(){return e},n},base64DecodeInputStream=function(r){var _=r,t=0,e=0,n=0,$={};$.read=function(){for(;n<8;){if(t>=_.length){if(0==n)return -1;throw Error("unexpected end of file./"+n)}var r=_.charAt(t);if(t+=1,"="==r)return n=0,-1;!r.match(/^\s$/)&&(e=e<<6|o(r.charCodeAt(0)),n+=6)}var $=e>>>n-8&255;return n-=8,$};var o=function(r){if(65<=r&&r<=90)return r-65;if(97<=r&&r<=122)return r-97+26;if(48<=r&&r<=57)return r-48+52;if(43==r)return 62;if(47==r)return 63;else throw Error("c:"+r)};return $},gifImage=function(r,_){var t=r,e=_,n=Array(r*_),$={};$.setPixel=function(r,_,e){n[_*t+r]=e},$.write=function(r){r.writeString("GIF87a"),r.writeShort(t),r.writeShort(e),r.writeByte(128),r.writeByte(0),r.writeByte(0),r.writeByte(0),r.writeByte(0),r.writeByte(0),r.writeByte(255),r.writeByte(255),r.writeByte(255),r.writeString(","),r.writeShort(0),r.writeShort(0),r.writeShort(t),r.writeShort(e),r.writeByte(0);var _=a(2);r.writeByte(2);for(var n=0;_.length-n>255;)r.writeByte(255),r.writeBytes(_,n,255),n+=255;r.writeByte(_.length-n),r.writeBytes(_,n,_.length-n),r.writeByte(0),r.writeString(";")};var o=function(r){var _=r,t=0,e=0,n={};return n.write=function(r,n){if(r>>>n!=0)throw Error("length over");for(;t+n>=8;)_.writeByte(255&(r<<t|e)),n-=8-t,r>>>=8-t,e=0,t=0;e=r<<t|e,t+=n},n.flush=function(){t>0&&_.writeByte(e)},n},a=function(r){for(var _=1<<r,t=(1<<r)+1,e=r+1,$=f(),a=0;a<_;a+=1)$.add(String.fromCharCode(a));$.add(String.fromCharCode(_)),$.add(String.fromCharCode(t));var i=byteArrayOutputStream(),u=o(i);u.write(_,e);var c=0,g=String.fromCharCode(n[c]);for(c+=1;c<n.length;){var l=String.fromCharCode(n[c]);c+=1,$.contains(g+l)?g+=l:(u.write($.indexOf(g),e),4095>$.size()&&($.size()==1<<e&&(e+=1),$.add(g+l)),g=l)}return u.write($.indexOf(g),e),u.write(t,e),u.flush(),i.toByteArray()},f=function(){var r={},_=0,t={};return t.add=function(e){if(t.contains(e))throw Error("dup key:"+e);r[e]=_,_+=1},t.size=function(){return _},t.indexOf=function(_){return r[_]},t.contains=function(_){return void 0!==r[_]},t};return $},createImgTag=function(r,_,t,e){for(var n=gifImage(r,_),$=0;$<_;$+=1)for(var o=0;o<r;o+=1)n.setPixel(o,$,t(o,$));var a=byteArrayOutputStream();n.write(a);for(var f=base64EncodeOutputStream(),i=a.toByteArray(),u=0;u<i.length;u+=1)f.writeByte(i[u]);f.flush();var c="";return c+="data:image/gif;base64,",c+=f},drawImg=function(r,_){var t,e=(_=_||{}).typeNumber||4,n=_.errorCorrectLevel||"M",$=_.size||500;try{(t=qrcode(e,n||"M")).addData(r),t.make()}catch(o){if(!(e>=40))return drawImg(r,{size:$,errorCorrectLevel:n,typeNumber:e+1});throw Error("Text too long to encode")}var a=parseInt($/t.getModuleCount()),f=parseInt(($-t.getModuleCount()*a)/2);return t.createImgTag(a,f,$)};
@@ -183,9 +183,9 @@ window.addEventListener('load', async () => {
});
`;
- return new Response(js, {
- headers: {
- "Content-Type": "application/javascript",
- },
- });
+ return new Response(js, {
+ headers: {
+ "Content-Type": "application/javascript",
+ },
+ });
}
diff --git a/src/routes/(app)/[username]/verify/[code]/+page.server.js b/src/routes/(app)/[username]/verify/[code]/+page.server.js
deleted file mode 100644
index 19453d9d..00000000
--- a/src/routes/(app)/[username]/verify/[code]/+page.server.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import { get } from "$lib/utils";
-import { error, redirect } from "@sveltejs/kit";
-
-export let load = async ({ params: { code } }) => {
- let user;
- try {
- user = await get(`/verify/${code}`);
- } catch (e) {
- console.log(e);
- return { error: "Verification failed" };
- }
-
- redirect(307, `/${user.username}/settings/account?verified=true`);
-};
diff --git a/src/routes/(app)/account/+server.ts b/src/routes/(app)/account/+server.ts
new file mode 100644
index 00000000..e6dc7e0c
--- /dev/null
+++ b/src/routes/(app)/account/+server.ts
@@ -0,0 +1,12 @@
+import { auth, post } from "$lib/utils";
+import { error, json } from "@sveltejs/kit";
+
+export async function POST({ cookies, request }) {
+ try {
+ const body = await request.json();
+ return json(await post("/accounts", body, auth(cookies)));
+ } catch (e: any) {
+ console.log(e);
+ error(500, e.message);
+ }
+}
diff --git a/src/routes/(app)/account/[id]/+page.server.ts b/src/routes/(app)/account/[id]/+page.server.ts
new file mode 100644
index 00000000..b91a0788
--- /dev/null
+++ b/src/routes/(app)/account/[id]/+page.server.ts
@@ -0,0 +1,24 @@
+import { error, redirect } from "@sveltejs/kit";
+import { auth, get, post, fd } from "$lib/utils";
+
+export const load = async ({ cookies, params }) => {
+ const account = await get(`/account/${params.id}`, auth(cookies));
+ return { account };
+};
+
+export const actions = {
+ default: async ({ cookies, params, request }) => {
+ const { id } = params;
+ const body = await fd(request);
+ const username = cookies.get("username");
+
+ try {
+ await post(`/account/${id}`, body, auth(cookies));
+ } catch (e: any) {
+ console.log(e);
+ error(400, { message: e.message });
+ }
+
+ redirect(303, `/${username}`);
+ },
+};
diff --git a/src/routes/(app)/account/[id]/+page.svelte b/src/routes/(app)/account/[id]/+page.svelte
new file mode 100644
index 00000000..63fd7a42
--- /dev/null
+++ b/src/routes/(app)/account/[id]/+page.svelte
@@ -0,0 +1,125 @@
+<script>
+ import Mnemonic from "$comp/Mnemonic.svelte";
+ import WalletPass from "$comp/WalletPass.svelte";
+ import { goto } from "$app/navigation";
+ import { copy, fail, focus, post } from "$lib/utils";
+ import { enhance } from "$app/forms";
+ import { t } from "$lib/translations";
+ import Icon from "$comp/Icon.svelte";
+ import { decrypt } from "nostr-tools/nip49";
+ import { entropyToMnemonic, mnemonicToSeed } from "@scure/bip39";
+ import { wordlist } from "@scure/bip39/wordlists/english";
+ import {
+ PUBLIC_COINOS_PUBKEY as pk,
+ PUBLIC_COINOS_RELAY as relay,
+ } from "$env/static/public";
+
+ export let data;
+ let { account, user } = data;
+ let { id, name, seed } = account;
+ let mnemonic, password;
+ let passwordPrompt;
+ let cancel = () => (passwordPrompt = false);
+ let toggle = () => (passwordPrompt = !passwordPrompt);
+
+ let submit = async () => {
+ toggle();
+ let entropy = await decrypt(seed, password);
+ mnemonic = entropyToMnemonic(entropy, wordlist);
+ };
+
+ let del = async () => {
+ try {
+ await post("/api/account/delete", { id });
+ goto(`/${user.username}`);
+ } catch (e) {
+ fail(e.message);
+ }
+ };
+
+ let nwc;
+ let revealNwc = () =>
+ (nwc = `nostr+walletconnect://${pk}?relay=${encodeURIComponent(
+ relay,
+ )}&secret=${user.nwc}`);
+</script>
+
+<div class="space-y-5">
+ <h1 class="text-center text-3xl font-semibold">Account settings</h1>
+
+ <div class="container w-full mx-auto text-lg px-4 max-w-xl space-y-2">
+ <form class="space-y-5" method="POST">
+ <div class="space-y-2">
+ {#if mnemonic}
+ <Mnemonic {mnemonic} />
+
+ <button
+ on:click={() => copy(mnemonic)}
+ type="button"
+ class="flex gap-2 rounded-2xl border py-5 mx-auto px-6 w-full justify-center"
+ >
+ <Icon icon="copy" style="w-8 my-auto" />
+ <div class="my-auto">{$t("accounts.copy")}</div></button
+ >
+ {:else if seed}
+ <button
+ on:click={toggle}
+ type="button"
+ class="flex gap-2 rounded-2xl border py-5 mx-auto px-6 w-full justify-center"
+ >
+ <Icon icon="eye" style="w-8 my-auto" />
+ <div class="my-auto">{$t("accounts.revealMnemonic")}</div></button
+ >
+ {:else if nwc}
+ <div class="break-all grow text-xl">
+ {nwc}
+ </div>
+ <button
+ on:click={() => copy(nwc)}
+ type="button"
+ class="flex gap-2 rounded-2xl border py-5 mx-auto px-6 w-full justify-center"
+ >
+ <Icon icon="copy" style="w-8 my-auto" />
+ <div class="my-auto">{$t("accounts.copy")}</div></button
+ >
+ <a href={`/qr/${encodeURIComponent(nwc)}`} class="my-auto block">
+ <button
+ on:click={() => copy(nwc)}
+ type="button"
+ class="flex gap-2 rounded-2xl border py-5 mx-auto px-6 w-full justify-center"
+ >
+ <Icon icon="qr" style="w-8 my-auto invert" />
+ <div class="my-auto">{$t("user.receive.showQR")}</div></button
+ >
+ </a>
+ {:else}
+ <button
+ on:click={revealNwc}
+ type="button"
+ class="flex gap-2 rounded-2xl border py-5 mx-auto px-6 w-full justify-center"
+ >
+ <Icon icon="eye" style="w-8 my-auto" />
+ <div class="my-auto">{$t("accounts.revealNwc")}</div></button
+ >
+ {/if}
+
+ {#if seed}
+ <button
+ on:click={del}
+ type="button"
+ class="flex gap-2 rounded-2xl border py-5 mx-auto px-6 w-full justify-center"
+ >
+ <Icon icon="trash" style="w-8 my-auto" />
+ <div class="my-auto">{$t("accounts.deleteAccount")}</div></button
+ >
+ {/if}
+ </div>
+
+ <div />
+ </form>
+ </div>
+</div>
+
+{#if passwordPrompt}
+ <WalletPass bind:password bind:cancel bind:submit />
+{/if}
diff --git a/src/routes/(app)/account/cash/+page.svelte b/src/routes/(app)/account/cash/+page.svelte
new file mode 100644
index 00000000..b0e2e757
--- /dev/null
+++ b/src/routes/(app)/account/cash/+page.svelte
@@ -0,0 +1,37 @@
+<script>
+ import { t } from "$lib/translations";
+ import Icon from "$comp/Icon.svelte";
+</script>
+
+<div class="space-y-5">
+ <h1 class="text-center text-3xl font-semibold">Choose your custodian</h1>
+
+ <div class="container w-full mx-auto text-lg px-4 max-w-xl space-y-2">
+ <div class="space-y-5">
+ <a href="/account/cash" class="block">
+ <div class="shadow p-8 rounded-xl flex gap-4 hover:bg-primary">
+ <img src="/icons/logo-symbol.svg" class="w-20" />
+ <div>
+ <div class="text-xl">Coinos</div>
+ <div class="text-secondary">https://mint.coinos.io</div>
+ </div>
+ </div>
+ </a>
+ <a href="/account/cash" class="block">
+ <div class="shadow p-8 rounded-xl flex gap-4 hover:bg-primary">
+ <img src="/images/minibits.png" class="w-20" />
+ <div>
+ <div class="text-xl">Minibits</div>
+ <div class="text-secondary">https://mint.minibits.cash/bitcoin</div>
+ </div>
+ </div>
+ </a>
+ </div>
+ <!-- <a href="/account/mints" class="block"> -->
+ <!-- <div class="p-4 border rounded-xl flex justify-center gap-2"> -->
+ <!-- <Icon icon="plus" style="w-8 my-auto" /> -->
+ <!-- <div class="text-xl my-auto">More</div> -->
+ <!-- </div> -->
+ <!-- </a> -->
+ </div>
+</div>
diff --git a/src/routes/(app)/account/import/+page.svelte b/src/routes/(app)/account/import/+page.svelte
new file mode 100644
index 00000000..a1d6549b
--- /dev/null
+++ b/src/routes/(app)/account/import/+page.svelte
@@ -0,0 +1,55 @@
+<script>
+ import { goto } from "$app/navigation";
+ import { mnemonic } from "$lib/store";
+ import { fail, focus, versions } from "$lib/utils";
+ import { t } from "$lib/translations";
+ import { browser } from "$app/environment";
+ import Icon from "$comp/Icon.svelte";
+ import { validateMnemonic } from "@scure/bip39";
+ import { wordlist } from "@scure/bip39/wordlists/english";
+
+ let el, pasted, text;
+
+ let paste = async () => {
+ text = await navigator.clipboard.readText();
+ pasted = true;
+ };
+
+ let submit = () => {
+ text = text.replace(/,/g, " ").trim();
+ let valid = validateMnemonic(text, wordlist);
+ if (valid) {
+ $mnemonic = text;
+ goto("/account/pass");
+ } else {
+ fail("Failed to validate seed phrase");
+ }
+ };
+
+ $: if (browser && pasted && text) form.submit() && (pasted = false);
+</script>
+
+<div class="space-y-5">
+ <h1 class="text-center text-3xl font-semibold">{$t("accounts.import")}</h1>
+
+ <div class="container w-full mx-auto text-lg px-4 max-w-xl space-y-2">
+ <form on:submit|preventDefault={submit} class="space-y-2">
+ <textarea
+ use:focus
+ name="text"
+ placeholder={$t("accounts.enterSeed")}
+ class="w-full p-4 border rounded-xl h-48 text-xl"
+ bind:value={text}
+ autocapitalize="none"
+ />
+ <button
+ bind:this={el}
+ type="submit"
+ class="flex bg-black text-white border rounded-2xl px-6 py-5 w-full font-bold gap-2 justify-center"
+ >
+ <Icon icon="send" style="w-8 my-auto invert" />
+ <div class="my-auto">{$t("user.send.next")}</div>
+ </button>
+ </form>
+ </div>
+</div>
diff --git a/src/routes/(app)/account/mints/+page.svelte b/src/routes/(app)/account/mints/+page.svelte
new file mode 100644
index 00000000..1080269e
--- /dev/null
+++ b/src/routes/(app)/account/mints/+page.svelte
@@ -0,0 +1 @@
+mints
diff --git a/src/routes/(app)/account/pass/+page.svelte b/src/routes/(app)/account/pass/+page.svelte
new file mode 100644
index 00000000..5becf337
--- /dev/null
+++ b/src/routes/(app)/account/pass/+page.svelte
@@ -0,0 +1,158 @@
+<script lang="ts">
+ import { tick, onMount } from "svelte";
+ import { t } from "$lib/translations";
+ import { mnemonic } from "$lib/store";
+ import Icon from "$comp/Icon.svelte";
+ import Spinner from "$comp/Spinner.svelte";
+ import { encrypt } from "nostr-tools/nip49";
+ import {
+ mnemonicToSeed,
+ mnemonicToEntropy,
+ entropyToMnemonic,
+ } from "@scure/bip39";
+ import { wordlist } from "@scure/bip39/wordlists/english";
+ import { focus, versions, fail, post } from "$lib/utils";
+ import { goto } from "$app/navigation";
+ import { HDKey } from "@scure/bip32";
+
+ export let data;
+
+ let { user } = data;
+ let submitting;
+
+ let confirm, password, revealPassword, revealConfirm;
+ let type = "bitcoin";
+ let name = $t("accounts.savings");
+
+ onMount(() => {
+ if (!$mnemonic) goto("/account/savings");
+ });
+
+ let submit = async () => {
+ submitting = true;
+ await tick();
+ if (!password || password !== confirm) {
+ fail($t("accounts.passwordMismatch"));
+ return;
+ }
+
+ try {
+ let seed = await encrypt(
+ mnemonicToEntropy($mnemonic, wordlist),
+ password,
+ );
+
+ let master = HDKey.fromMasterSeed(
+ await mnemonicToSeed($mnemonic, password),
+ versions,
+ );
+
+ let child = master.derive("m/84'/0'/0'");
+ let pubkey = child.publicExtendedKey;
+ let fingerprint = child.fingerprint.toString(16).padStart(8, "0");
+ await post("/account", { fingerprint, pubkey, name, seed, type });
+ $mnemonic = "";
+ goto(`/${user.username}`);
+ } catch (e) {
+ console.log(e);
+ fail(e.message);
+ }
+
+ submitting = false;
+ };
+</script>
+
+<div class="space-y-5">
+ <div>
+ <h1 class="text-center text-3xl font-semibold">
+ {$t("accounts.accountPassword")}
+ </h1>
+ </div>
+
+ <form
+ on:submit|preventDefault={submit}
+ class="container w-full mx-auto text-lg px-4 max-w-xl space-y-5"
+ >
+ <p class="text-secondary mb-1">
+ {$t("accounts.passwordWarning")}
+ </p>
+
+ <div class="relative">
+ {#if revealPassword}
+ <input
+ name="password"
+ type="text"
+ required
+ bind:value={password}
+ autocapitalize="none"
+ />
+ {:else}
+ <input
+ use:focus
+ name="password"
+ type="password"
+ placeholder={$t("accounts.password")}
+ required
+ bind:value={password}
+ autocapitalize="none"
+ />
+ {/if}
+ <button
+ tabindex="-1"
+ type="button"
+ on:click={() => (revealPassword = !revealPassword)}
+ class="absolute right-5 -translate-y-1/2 top-1/2"
+ >
+ <Icon icon={revealPassword ? "eye" : "eye-off"} />
+ </button>
+ </div>
+
+ <div class="relative">
+ {#if revealConfirm}
+ <input
+ name="password"
+ type="text"
+ placeholder="Confirm password"
+ required
+ bind:value={confirm}
+ autocapitalize="none"
+ />
+ {:else}
+ <input
+ type="password"
+ placeholder={$t("accounts.confirmPassword")}
+ required
+ bind:value={confirm}
+ autocapitalize="none"
+ />
+ {/if}
+ <button
+ type="button"
+ tabindex="-1"
+ on:click={() => (revealConfirm = !revealConfirm)}
+ class="absolute right-5 -translate-y-1/2 top-1/2"
+ >
+ <Icon icon={revealConfirm ? "eye" : "eye-off"} />
+ </button>
+ </div>
+
+ <div class="flex gap-2">
+ <a href={`/account/seed`} class="contents">
+ <button type="button" class="border grow px-5 py-6 text-xl rounded-2xl">
+ {$t("accounts.back")}
+ </button>
+ </a>
+ <button
+ disabled={submitting}
+ type="submit"
+ class="border grow px-5 py-6 text-xl rounded-2xl bg-black text-white"
+ >
+ {#if submitting}
+ <Spinner />
+ {:else}
+ {$t("accounts.finish")}
+ {/if}
+ </button>
+ </div>
+ </form>
+</div>
diff --git a/src/routes/(app)/account/savings/+page.svelte b/src/routes/(app)/account/savings/+page.svelte
new file mode 100644
index 00000000..8cc24aa2
--- /dev/null
+++ b/src/routes/(app)/account/savings/+page.svelte
@@ -0,0 +1,33 @@
+<script>
+ import { t } from "$lib/translations";
+ import Icon from "$comp/Icon.svelte";
+</script>
+
+<div class="space-y-5">
+ <h1 class="text-center text-3xl font-semibold">
+ {$t("accounts.accountSetup")}
+ </h1>
+
+ <div class="container w-full mx-auto text-lg px-4 max-w-xl space-y-2">
+ <div class="space-y-5">
+ <a href="/account/seed" class="block">
+ <div class="shadow p-8 rounded-xl flex gap-4 hover:bg-primary">
+ <img src="/icons/random.svg" class="w-20" />
+ <div>
+ <div class="text-xl">{$t("accounts.create")}</div>
+ <div class="text-secondary">{$t("accounts.generateSeed")}</div>
+ </div>
+ </div>
+ </a>
+ <a href="/account/import" class="block">
+ <div class="shadow p-8 rounded-xl flex gap-4 hover:bg-primary">
+ <img src="/images/keys.png" class="w-20" />
+ <div>
+ <div class="text-xl">{$t("accounts.import")}</div>
+ <div class="text-secondary">{$t("accounts.importSeed")}</div>
+ </div>
+ </div>
+ </a>
+ </div>
+ </div>
+</div>
diff --git a/src/routes/(app)/account/seed/+page.svelte b/src/routes/(app)/account/seed/+page.svelte
new file mode 100644
index 00000000..5d828369
--- /dev/null
+++ b/src/routes/(app)/account/seed/+page.svelte
@@ -0,0 +1,76 @@
+<script>
+ import Mnemonic from "$comp/Mnemonic.svelte";
+ import { browser } from "$app/environment";
+ import { tick, onMount } from "svelte";
+ import { copy } from "$lib/utils";
+ import { t } from "$lib/translations";
+ import Icon from "$comp/Icon.svelte";
+ import { mnemonic } from "$lib/store";
+ import { generateMnemonic } from "@scure/bip39";
+ import { wordlist } from "@scure/bip39/wordlists/english";
+
+ export let data;
+ let { user } = data;
+
+ onMount(async () => {
+ if (!browser) return;
+ if (!$mnemonic) await generate();
+ });
+
+ let generate = async () => {
+ $mnemonic = await generateMnemonic(wordlist);
+ };
+</script>
+
+<div class="space-y-5">
+ <h1 class="text-center text-3xl font-semibold">
+ {$t("accounts.seedPhrase")}
+ </h1>
+
+ <div class="container w-full mx-auto text-lg px-4 max-w-xl space-y-5">
+ {#if $mnemonic}
+ <Mnemonic mnemonic={$mnemonic} />
+ {/if}
+
+ <div>
+ <button
+ type="button"
+ class="flex gap-2 text-center break-all rounded-2xl hover:opacity-80 py-3 px-4 w-full mx-auto justify-center border whitespace-nowrap mb-2"
+ on:click={generate}
+ >
+ <Icon icon="random" style="w-8 my-auto" />
+ <div class="my-auto">{$t("accounts.regenerate")}</div>
+ </button>
+
+ <button
+ type="button"
+ class="flex gap-2 text-center break-all rounded-2xl hover:opacity-80 py-3 px-4 w-full mx-auto justify-center border whitespace-nowrap mb-2"
+ on:click={() => copy($mnemonic)}
+ >
+ <Icon icon="copy" style="w-8 my-auto" />
+ <div class="my-auto">
+ {$t("payments.copy")}
+ </div>
+ </button>
+ </div>
+
+ <div class="flex gap-2">
+ <a href={`/account/savings`} class="contents">
+ <button
+ type="button"
+ class="border w-full py-5 px-6 text-xl rounded-2xl"
+ >
+ {$t("accounts.back")}
+ </button>
+ </a>
+ <a href={`/account/pass`} class="contents">
+ <button
+ type="button"
+ class="border w-full py-5 px-6 text-xl rounded-2xl"
+ >
+ {$t("accounts.next")}
+ </button>
+ </a>
+ </div>
+ </div>
+</div>
diff --git a/src/routes/(app)/account/setup/+page.svelte b/src/routes/(app)/account/setup/+page.svelte
new file mode 100644
index 00000000..24b6e248
--- /dev/null
+++ b/src/routes/(app)/account/setup/+page.svelte
@@ -0,0 +1,33 @@
+<script>
+ import { t } from "$lib/translations";
+</script>
+
+<div class="space-y-5">
+ <h1 class="text-center text-3xl font-semibold">Choose account type</h1>
+
+ <div class="container w-full mx-auto text-lg px-4 max-w-xl space-y-5">
+ <a href="/account/cash" class="block">
+ <div class="shadow p-8 rounded-xl flex gap-4 hover:bg-primary">
+ <img src="/images/cash.png" class="w-20 my-auto" />
+ <div>
+ <div class="text-xl">Cash</div>
+ <div class="text-secondary">
+ Your balance is held with a custodian. Payments are fast and free.
+ </div>
+ </div>
+ </div>
+ </a>
+ <a href="/account/savings" class="block">
+ <div class="shadow p-8 rounded-xl flex gap-4 hover:bg-primary">
+ <img src="/images/keys.png" class="w-20 my-auto" />
+ <div>
+ <div class="text-xl">Savings</div>
+ <div class="text-secondary">
+ You hold the keys to the account and are responsible for
+ safeguarding them.
+ </div>
+ </div>
+ </div>
+ </a>
+ </div>
+</div>
diff --git a/src/routes/(app)/admin/+layout.server.js b/src/routes/(app)/admin/+layout.server.js
deleted file mode 100644
index 9250a7d4..00000000
--- a/src/routes/(app)/admin/+layout.server.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import { auth, get } from "$lib/utils";
-import { redirect } from "@sveltejs/kit";
-
-export async function load({ cookies, parent }) {
- let token = cookies.get("token");
- if (!token) redirect(307, "/login");
- let user = await get("/me", auth(cookies));
- if (!user) redirect(307, "/login");
-
- return { user };
-}
diff --git a/src/routes/(app)/admin/+layout.server.ts b/src/routes/(app)/admin/+layout.server.ts
new file mode 100644
index 00000000..d4aa181d
--- /dev/null
+++ b/src/routes/(app)/admin/+layout.server.ts
@@ -0,0 +1,11 @@
+import { auth, get } from "$lib/utils";
+import { redirect } from "@sveltejs/kit";
+
+export async function load({ cookies }) {
+ const token = cookies.get("token");
+ if (!token) redirect(307, "/login");
+ const user = await get("/me", auth(cookies));
+ if (!user) redirect(307, "/login");
+
+ return { user };
+}
diff --git a/src/routes/(app)/admin/+page.server.js b/src/routes/(app)/admin/+page.server.js
deleted file mode 100644
index 96a1cd78..00000000
--- a/src/routes/(app)/admin/+page.server.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import { auth, get } from "$lib/utils";
-import { redirect } from "@sveltejs/kit";
-
-export async function load({ cookies, parent }) {
- let { user } = await parent();
- if (!user) redirect(307, "/login");
-
- let users = (await get("/users", auth(cookies))).sort(
- (a, b) => b.balance - a.balance
- );
- return { users };
-}
diff --git a/src/routes/(app)/admin/+page.server.ts b/src/routes/(app)/admin/+page.server.ts
new file mode 100644
index 00000000..8c250026
--- /dev/null
+++ b/src/routes/(app)/admin/+page.server.ts
@@ -0,0 +1,12 @@
+import { auth, get } from "$lib/utils";
+import { redirect } from "@sveltejs/kit";
+
+export async function load({ cookies, parent }) {
+ const { user } = await parent();
+ if (!user) redirect(307, "/login");
+
+ const users = (await get("/users", auth(cookies))).sort(
+ (a, b) => b.balance - a.balance,
+ );
+ return { users };
+}
diff --git a/src/routes/(app)/admin/+page.svelte b/src/routes/(app)/admin/+page.svelte
index c61a2e45..214bf5b3 100644
--- a/src/routes/(app)/admin/+page.svelte
+++ b/src/routes/(app)/admin/+page.svelte
@@ -1,7 +1,7 @@
<script>
import { post } from "$lib/utils";
export let data;
- let reset = (username) => post(`/${username}/reset`, { password });
+ let reset = (username) => post(`/reset`, { password });
let { users } = data;
let password;
</script>
diff --git a/src/routes/(app)/buy/+page.server.js b/src/routes/(app)/buy/+page.server.js
deleted file mode 100644
index b8897741..00000000
--- a/src/routes/(app)/buy/+page.server.js
+++ /dev/null
@@ -1,28 +0,0 @@
-import { env } from "$env/dynamic/private";
-import { error, fail, redirect } from "@sveltejs/kit";
-import { post, auth } from "$lib/utils";
-import { createTicket } from "$lib/ticket";
-
-export const actions = {
- default: async ({ cookies, request }) => {
- let form = await request.formData();
-
- let amount = parseFloat(form.get("amount"));
- if (!amount || amount < 0 || amount > 500)
- return fail(400, { message: "Invalid amount" });
-
- await post(
- "/buy",
- {
- amount: form.get("amount"),
- number: form.get("number").replace(/\s+/g, ""),
- month: form.get("expiry").slice(0, 2),
- year: form.get("expiry").slice(-2),
- cvc: form.get("cvc"),
- },
- auth(cookies)
- );
-
- redirect(307, `/${form.get("username")}/payments`);
- },
-};
diff --git a/src/routes/(app)/buy/+page.svelte b/src/routes/(app)/buy/+page.svelte
deleted file mode 100644
index 2b81b7a8..00000000
--- a/src/routes/(app)/buy/+page.svelte
+++ /dev/null
@@ -1,138 +0,0 @@
-<script>
- import { enhance } from "$app/forms";
- import Icon from "$comp/Icon.svelte";
- import Lock from "$comp/Lock.svelte";
- import Card from "$comp/Card.svelte";
- import Calendar from "$comp/Calendar.svelte";
- import Spinner from "$comp/Spinner.svelte";
- import { f } from "$lib/utils";
-
- export let data, form;
-
- let { username, currency } = data.user;
- let loading;
-
- let amount, n, d, cvc;
-</script>
-
-<div class="container px-4 max-w-xl mx-auto mt-10 space-y-5">
- <div class="w-full flex">
- <a href="/" class="mx-auto">
- <Icon icon="logo" />
- </a>
- </div>
-
- <div class="flex justify-center items-center">
- <div class="shadow-xl rounded-3xl px-10 pt-5 pb-10 space-y-5 w-full mx-5">
- <div class="relative">
- <h1 class="text-2xl md:text-3xl font-semibold text-center">
- Buy Bitcoin
- </h1>
- </div>
- <p class="text-secondary text-center">
- Purchase up to $500 worth of Bitcoin
- </p>
-
- {#if form?.message}
- <div class="text-red-600 text-center">
- {form.message}
- </div>
- {/if}
-
- <form
- method="POST"
- class="flex flex-wrap gap-5 w-full p-5 mt-20"
- use:enhance={() => {
- loading = true;
- return ({ update }) => update() && (loading = false);
- }}
- >
- <input type="hidden" name="username" value={username} />
-
- <label class="relative w-full flex flex-col">
- <span class="font-bold mb-3">Amount</span>
- <input
- class="rounded-md peer pl-12 pr-2 py-2 border-2 border-gray-200 placeholder-gray-300"
- type="text"
- name="amount"
- placeholder="&bull;&bull;&bull;"
- bind:value={amount}
- />
- <span
- class="absolute bottom-[9px] left-0 translate-x-1/2 w-6 text-black peer-placeholder-shown:text-gray-300
- ">$</span
- >
- </label>
-
- <label class="relative w-full flex flex-col">
- <span class="font-bold mb-3">Card number</span>
- <input
- class="rounded-md peer pl-12 pr-2 py-2 border-2 border-gray-200 placeholder-gray-300"
- type="text"
- name="number"
- placeholder="0000 0000 0000 0000"
- bind:value={n}
- />
- <Card />
- </label>
-
- <label class="relative flex-1 flex flex-col">
- <span class="font-bold mb-3">Expire date</span>
- <input
- class="rounded-md peer pl-12 pr-2 py-2 border-2 border-gray-200 placeholder-gray-300"
- type="text"
- name="expiry"
- placeholder="MM/YY"
- bind:value={d}
- />
- <Calendar />
- </label>
-
- <label class="relative flex-1 flex flex-col">
- <span class="font-bold flex items-center gap-3 mb-3">
- CVC/CVV
- <span class="relative group">
- <span
- class="hidden group-hover:flex justify-center items-center px-2 py-1 text-xs absolute -right-2 transform translate-x-full -translate-y-1/2 w-max top-1/2 bg-black text-white"
- >
- 3-digit number on the back of your card</span
- >
- </span>
- </span>
- <input
- class="rounded-md peer pl-12 pr-2 py-2 border-2 border-gray-200 placeholder-gray-300"
- type="text"
- name="cvc"
- placeholder="&bull;&bull;&bull;"
- bind:value={cvc}
- />
- <Lock />
- </label>
-
- <div class="w-full flex mt-8">
- <button
- class="bg-black text-white border rounded-full px-8 py-4 font-bold hover:opacity-80 mx-auto text-xl"
- type="submit"
- disabled={loading}
- >
- {#if loading}
- <Spinner />
- {:else}
- Submit
- {/if}
- </button>
- </div>
- </form>
-
- <div class="flex">
- <div class="text-secondary flex mr-auto">
- <div class="flex mr-1">
- <div class="my-auto mr-1">1</div>
- <img src="/images/bitcoin.svg" class="w-5 my-auto" alt="Bitcoin" />
- </div>
- </div>
- <p class="text-secondary">3% credit card fee applies</p>
- </div>
- </div>
- </div>
-</div>
diff --git a/src/routes/(app)/disable2fa/+server.js b/src/routes/(app)/disable2fa/+server.js
deleted file mode 100644
index 0afda3b9..00000000
--- a/src/routes/(app)/disable2fa/+server.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import { error, json } from "@sveltejs/kit";
-import { auth, post } from "$lib/utils";
-
-export async function POST({ cookies, request }) {
- try {
- let body = await request.json();
- let res = await post("/disable2fa", body, auth(cookies));
-
- return json(res);
- } catch (e) {
- error(500, "Problem disabling 2fa");
- }
-}
diff --git a/src/routes/(app)/disable2fa/+server.ts b/src/routes/(app)/disable2fa/+server.ts
new file mode 100644
index 00000000..81ee2ff2
--- /dev/null
+++ b/src/routes/(app)/disable2fa/+server.ts
@@ -0,0 +1,13 @@
+import { error, json } from "@sveltejs/kit";
+import { auth, post } from "$lib/utils";
+
+export async function POST({ cookies, request }) {
+ try {
+ const body = await request.json();
+ const res = await post("/disable2fa", body, auth(cookies));
+
+ return json(res);
+ } catch (e) {
+ error(500, "Problem disabling 2fa");
+ }
+}
diff --git a/src/routes/(app)/ecash/[id]/[...version]/+layout.server.ts b/src/routes/(app)/ecash/[id]/[...version]/+layout.server.ts
new file mode 100644
index 00000000..e7ac3787
--- /dev/null
+++ b/src/routes/(app)/ecash/[id]/[...version]/+layout.server.ts
@@ -0,0 +1,11 @@
+import { get } from "$lib/utils";
+
+export async function load({ params }) {
+ let { id, version } = params;
+ version ||= 4;
+ version = parseInt(version);
+
+ const { token, status } = await get(`/cash/${id}/${version}`);
+ const { spent, total, mint, external } = status;
+ return { id, token, spent, total, mint, external, version };
+}
diff --git a/src/routes/(app)/ecash/[id]/[...version]/+layout.svelte b/src/routes/(app)/ecash/[id]/[...version]/+layout.svelte
new file mode 100644
index 00000000..f9c80329
--- /dev/null
+++ b/src/routes/(app)/ecash/[id]/[...version]/+layout.svelte
@@ -0,0 +1,56 @@
+<script>
+ import { copy, sats, f, s } from "$lib/utils";
+ import { t } from "$lib/translations";
+ import Icon from "$comp/Icon.svelte";
+
+ export let data;
+
+ let { id, rates, user, token, total, spent, external, mint } = data;
+ let currency = user?.currency || "USD";
+ let rate = rates[currency];
+
+ let amount = total - spent;
+
+ $: amountFiat = parseFloat(((amount * rate) / sats).toFixed(2));
+ $: spentFiat = parseFloat(((spent * rate) / sats).toFixed(2));
+</script>
+
+<div class="container px-4 max-w-lg mx-auto space-y-5 mt-20">
+ <h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold">
+ {$t("payments.ecash")}
+ </h1>
+
+ {#if amount > 0}
+ <div class="text-center font-bold text-2xl">
+ <div>
+ {f(amountFiat, currency)}
+ </div>
+ <div>
+ <span class="text-secondary font-normal text-xl"
+ >⚡️{`${s(amount)}`}</span
+ >
+ </div>
+ </div>
+ {/if}
+
+ <div class="text-center text-xl">
+ <span class="capitalize">{$t("payments.from")}</span>
+ <span class="text-secondary">{mint}</span>
+ </div>
+
+ {#if spent > 0}
+ <div class="text-center font-bold text-2xl">
+ <div>
+ {f(spentFiat, currency)}
+ <span class=" text-red-600">{$t("payments.spent")}</span>
+ </div>
+ <div>
+ <span class="text-secondary font-normal text-xl"
+ >⚡️{`${s(spent)}`}</span
+ >
+ </div>
+ </div>
+ {/if}
+
+ <slot />
+</div>
diff --git a/src/routes/(app)/ecash/[id]/[...version]/+page.server.ts b/src/routes/(app)/ecash/[id]/[...version]/+page.server.ts
new file mode 100644
index 00000000..68ccfda6
--- /dev/null
+++ b/src/routes/(app)/ecash/[id]/[...version]/+page.server.ts
@@ -0,0 +1,21 @@
+import { fail, redirect } from "@sveltejs/kit";
+import { auth, fd, post } from "$lib/utils";
+
+export const actions = {
+ default: async ({ cookies, request, url }) => {
+ if (!cookies.get("username"))
+ redirect(307, `/register?redirect=${url.pathname}`);
+
+ const { token } = await fd(request);
+ let claimed;
+ try {
+ claimed = await post("/claim", { token }, auth(cookies));
+ claimed = { ok: true };
+ } catch (e: any) {
+ return fail(400, { error: e.message });
+ }
+ if (claimed?.ok) {
+ redirect(307, "/payments");
+ }
+ },
+};
diff --git a/src/routes/(app)/ecash/[id]/[...version]/+page.svelte b/src/routes/(app)/ecash/[id]/[...version]/+page.svelte
new file mode 100644
index 00000000..d9829c12
--- /dev/null
+++ b/src/routes/(app)/ecash/[id]/[...version]/+page.svelte
@@ -0,0 +1,86 @@
+<script>
+ import { enhance } from "$app/forms";
+ import { copy, sats, f, s } from "$lib/utils";
+ import { t } from "$lib/translations";
+ import Icon from "$comp/Icon.svelte";
+ import { page } from "$app/stores";
+
+ export let data;
+ export let form;
+
+ let link = $page.url.href;
+ let { id, total, version, token, external, spent } = data;
+</script>
+
+{#if form?.error}
+ <div class="mb-5">
+ <div class="text-red-600">
+ {form.error === "default" ? $t("error.unrecognizedInput") : form.error}
+ </div>
+ </div>
+{/if}
+
+<div class="flex flex-wrap gap-2 text-xl">
+ <button
+ type="button"
+ class="flex border rounded-2xl px-6 py-5 font-bold hover:opacity-80 w-full justify-center gap-2"
+ on:click={() => copy(link)}
+ >
+ <Icon icon="link" style="w-8 my-auto" />
+ <div class="my-auto">{$t("payments.shareLink")}</div>
+ </button>
+
+ {#if spent < total}
+ {#if external}
+ <a href={`/ecash/${id}/swap`} class="contents">
+ <button
+ type="submit"
+ class="flex border rounded-2xl px-6 py-5 font-bold hover:opacity-80 w-full justify-center gap-2"
+ >
+ <Icon icon="receive" style="w-8 my-auto" />
+ <div class="my-auto">{$t("payments.swap")}</div>
+ </button>
+ </a>
+ {:else}
+ <form method="POST" use:enhance class="w-full">
+ <input type="hidden" name="token" bind:value={token} />
+ <button
+ type="submit"
+ class="flex border rounded-2xl px-6 py-5 font-bold hover:opacity-80 w-full justify-center gap-2"
+ >
+ <Icon icon="receive" style="w-8 my-auto" />
+ <div class="my-auto">{$t("payments.redeem")}</div>
+ </button>
+ </form>
+ {/if}
+ {/if}
+
+ <button
+ class="border rounded-2xl px-6 py-5 w-full break-all text-xl hover:bg-slate-100"
+ on:click={() => copy(token)}
+ >
+ {token}
+ </button>
+
+ {#if version === 4}
+ <a data-sveltekit-reload href={`/ecash/${id}/3`} class="contents">
+ <button
+ type="button"
+ class="flex border rounded-2xl px-6 py-5 font-bold hover:opacity-80 w-full justify-center gap-2"
+ >
+ <Icon icon="settings" style="w-8 my-auto" />
+ <div class="my-auto">{$t("payments.legacyVersion")}</div>
+ </button>
+ </a>
+ {:else}
+ <a data-sveltekit-reload href={`/ecash/${id}`} class="contents">
+ <button
+ type="button"
+ class="flex border rounded-2xl px-6 py-5 font-bold hover:opacity-80 w-full justify-center gap-2"
+ >
+ <Icon icon="settings" style="w-8 my-auto" />
+ <div class="my-auto">{$t("payments.newVersion")}</div>
+ </button>
+ </a>
+ {/if}
+</div>
diff --git a/src/routes/(app)/ecash/[id]/[...version]/swap/+page.server.ts b/src/routes/(app)/ecash/[id]/[...version]/swap/+page.server.ts
new file mode 100644
index 00000000..f82bdbb1
--- /dev/null
+++ b/src/routes/(app)/ecash/[id]/[...version]/swap/+page.server.ts
@@ -0,0 +1,3 @@
+export async function load() {
+ return { test: 123 };
+}
diff --git a/src/routes/(app)/ecash/[id]/[...version]/swap/+page.svelte b/src/routes/(app)/ecash/[id]/[...version]/swap/+page.svelte
new file mode 100644
index 00000000..ee22cea2
--- /dev/null
+++ b/src/routes/(app)/ecash/[id]/[...version]/swap/+page.svelte
@@ -0,0 +1,7 @@
+<script>
+ export let data;
+</script>
+
+<div class="text-center">
+ Support for swapping in cash from other mints is coming soon
+</div>
diff --git a/src/routes/(app)/enable2fa/+server.js b/src/routes/(app)/enable2fa/+server.js
deleted file mode 100644
index 6917ae21..00000000
--- a/src/routes/(app)/enable2fa/+server.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import { auth, post } from "$lib/utils";
-
-export async function POST({ cookies, request }) {
- let body = await request.json();
- let res = await post("/2fa", body, auth(cookies));
-
- return new Response(JSON.stringify(res));
-}
diff --git a/src/routes/(app)/enable2fa/+server.ts b/src/routes/(app)/enable2fa/+server.ts
new file mode 100644
index 00000000..988dd0ed
--- /dev/null
+++ b/src/routes/(app)/enable2fa/+server.ts
@@ -0,0 +1,8 @@
+import { auth, post } from "$lib/utils";
+
+export async function POST({ cookies, request }) {
+ const body = await request.json();
+ const res = await post("/2fa", body, auth(cookies));
+
+ return new Response(JSON.stringify(res));
+}
diff --git a/src/routes/(app)/events/+server.ts b/src/routes/(app)/events/+server.ts
new file mode 100644
index 00000000..42b9f3dd
--- /dev/null
+++ b/src/routes/(app)/events/+server.ts
@@ -0,0 +1,12 @@
+import { auth, post } from "$lib/utils";
+import { json, error } from "@sveltejs/kit";
+
+export async function POST({ cookies, request }) {
+ const body = await request.json();
+ try {
+ const result = await post("/event", body, auth(cookies));
+ return json(result);
+ } catch (e: any) {
+ error(500, e.message);
+ }
+}
diff --git a/src/routes/(app)/forgot/+page.server.js b/src/routes/(app)/forgot/+page.server.js
deleted file mode 100644
index 48411539..00000000
--- a/src/routes/(app)/forgot/+page.server.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import { fail, redirect } from "@sveltejs/kit";
-import { fd, post, login } from "$lib/utils";
-
-export const actions = {
- default: async ({ request }) => {
- try {
- let { email } = await fd(request);
- await post("/forgot", { email });
- return { success: true };
- } catch (e) {
- return fail(400, { error: e.message });
- }
- },
-};
diff --git a/src/routes/(app)/forgot/+page.server.ts b/src/routes/(app)/forgot/+page.server.ts
new file mode 100644
index 00000000..55169a5e
--- /dev/null
+++ b/src/routes/(app)/forgot/+page.server.ts
@@ -0,0 +1,14 @@
+import { fail } from "@sveltejs/kit";
+import { fd, post } from "$lib/utils";
+
+export const actions = {
+ default: async ({ request }) => {
+ try {
+ const { email } = await fd(request);
+ await post("/forgot", { email });
+ return { success: true };
+ } catch (e: any) {
+ return fail(400, { error: e.message });
+ }
+ },
+};
diff --git a/src/routes/(app)/fund/[id]/+page.server.js b/src/routes/(app)/fund/[id]/+page.server.js
deleted file mode 100644
index c5c8db2f..00000000
--- a/src/routes/(app)/fund/[id]/+page.server.js
+++ /dev/null
@@ -1,23 +0,0 @@
-import { error, redirect } from "@sveltejs/kit";
-import { auth, get, post } from "$lib/utils";
-import Qr from "qrcode-base64";
-
-export let load = async ({ params: { id }, url }) => {
- let { amount, payments } = await get(`/fund/${id}`);
-
- let src = Qr.drawImg(url.href, { size: 300 });
- return { amount, payments, src };
-};
-
-export const actions = {
- default: async ({ cookies, locals, params, request }) => {
- let { user } = locals;
-
- if (user) {
- await post("/redeem", params, auth(cookies));
- redirect(307, `/${user.username}/payments`);
- }
-
- redirect(307, "/register");
- },
-};
diff --git a/src/routes/(app)/fund/[id]/+page.server.ts b/src/routes/(app)/fund/[id]/+page.server.ts
new file mode 100644
index 00000000..4f189133
--- /dev/null
+++ b/src/routes/(app)/fund/[id]/+page.server.ts
@@ -0,0 +1,23 @@
+import { redirect } from "@sveltejs/kit";
+import { auth, get, post } from "$lib/utils";
+import Qr from "qrcode-base64";
+
+export const load = async ({ params: { id }, url }) => {
+ const { amount, payments } = await get(`/fund/${id}`);
+
+ const src = Qr.drawImg(url.href, { size: 300 });
+ return { amount, payments, src };
+};
+
+export const actions = {
+ default: async ({ cookies, locals, params }) => {
+ const { user } = locals;
+
+ if (user) {
+ await post("/redeem", params, auth(cookies));
+ redirect(307, "/payments");
+ }
+
+ redirect(307, "/register");
+ },
+};
diff --git a/src/routes/(app)/fund/[id]/sweep/+page.server.js b/src/routes/(app)/fund/[id]/sweep/+page.server.js
deleted file mode 100644
index 613cf8e2..00000000
--- a/src/routes/(app)/fund/[id]/sweep/+page.server.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import { get, auth, post } from "$lib/utils";
-import { redirect } from "@sveltejs/kit";
-
-export async function load({ cookies, params, parent }) {
- let { user } = await parent();
- let { id } = params;
- let { amount } = await get(`/fund/${id}`);
-
- if (!amount) redirect(307, `/fund/${id}`);
- if (!user) redirect(307, `/register?redirect=/fund/${id}/sweep`);
- await post("/take", { amount, id }, auth(cookies));
- return { amount, id };
-}
diff --git a/src/routes/(app)/fund/[id]/sweep/+page.server.ts b/src/routes/(app)/fund/[id]/sweep/+page.server.ts
new file mode 100644
index 00000000..5bb42fa4
--- /dev/null
+++ b/src/routes/(app)/fund/[id]/sweep/+page.server.ts
@@ -0,0 +1,13 @@
+import { get, auth, post } from "$lib/utils";
+import { redirect } from "@sveltejs/kit";
+
+export async function load({ cookies, params, parent }) {
+ const { user } = await parent();
+ const { id } = params;
+ const { amount } = await get(`/fund/${id}`);
+
+ if (!amount) redirect(307, `/fund/${id}`);
+ if (!user) redirect(307, `/register?redirect=/fund/${id}/sweep`);
+ await post("/take", { amount, id }, auth(cookies));
+ return { amount, id };
+}
diff --git a/src/routes/(app)/fund/[id]/sweep/+page.svelte b/src/routes/(app)/fund/[id]/sweep/+page.svelte
index 4a48edf8..e142f00d 100644
--- a/src/routes/(app)/fund/[id]/sweep/+page.svelte
+++ b/src/routes/(app)/fund/[id]/sweep/+page.svelte
@@ -32,7 +32,7 @@
</h3>
</div>
-<a href={`/${user.username}/payments`}>
+<a href={`/payments`}>
<div class="opacity-0 w-screen h-screen fixed top-0 left-0 z-50" />
</a>
diff --git a/src/routes/(app)/fund/[id]/withdraw/+page.server.js b/src/routes/(app)/fund/[id]/withdraw/+page.server.js
deleted file mode 100644
index 1da349f8..00000000
--- a/src/routes/(app)/fund/[id]/withdraw/+page.server.js
+++ /dev/null
@@ -1,20 +0,0 @@
-import { fail, json, redirect } from "@sveltejs/kit";
-import { fd, auth, post } from "$lib/utils";
-
-export async function load({ parent }) {
- let { user } = await parent();
- if (!user) redirect(307, "/register");
-}
-
-export const actions = {
- default: async ({ cookies, request }) => {
- let body = await fd(request);
- try {
- await post("/take", body, auth(cookies));
- } catch (e) {
- return fail(400, { message: e.message });
- }
-
- redirect(307, `/fund/${body.id}`);
- },
-};
diff --git a/src/routes/(app)/fund/[id]/withdraw/+page.server.ts b/src/routes/(app)/fund/[id]/withdraw/+page.server.ts
new file mode 100644
index 00000000..1e477918
--- /dev/null
+++ b/src/routes/(app)/fund/[id]/withdraw/+page.server.ts
@@ -0,0 +1,20 @@
+import { fail, redirect } from "@sveltejs/kit";
+import { fd, auth, post } from "$lib/utils";
+
+export async function load({ parent }) {
+ const { user } = await parent();
+ if (!user) redirect(307, "/register");
+}
+
+export const actions = {
+ default: async ({ cookies, request }) => {
+ const body = await fd(request);
+ try {
+ await post("/take", body, auth(cookies));
+ } catch (e: any) {
+ return fail(400, { message: e.message });
+ }
+
+ redirect(307, `/fund/${body.id}`);
+ },
+};
diff --git a/src/routes/(app)/fund/[id]/withdraw/+page.svelte b/src/routes/(app)/fund/[id]/withdraw/+page.svelte
index 7af07e38..0ad3c2cf 100644
--- a/src/routes/(app)/fund/[id]/withdraw/+page.svelte
+++ b/src/routes/(app)/fund/[id]/withdraw/+page.svelte
@@ -37,7 +37,7 @@
{/if}
<div class="container px-4 mt-20 max-w-xl mx-auto">
- <Numpad bind:amount bind:currency bind:rate {submit} />
+ <Numpad bind:amount bind:currency bind:rate />
<form method="POST" use:enhance on:submit={submit}>
<input name="id" value={id} type="hidden" />
diff --git a/src/routes/(app)/events/+server.js b/src/routes/(app)/fund/[id]/withdraw/+server.ts
index 95df0bc5..dabef6f8 100644
--- a/src/routes/(app)/events/+server.js
+++ b/src/routes/(app)/fund/[id]/withdraw/+server.ts
@@ -1,6 +1,6 @@
-import { auth, post } from "$lib/utils";
import { json } from "@sveltejs/kit";
+import { auth, post } from "$lib/utils";
export async function POST({ cookies, request }) {
- return json(post("/event", await request.json(), auth(cookies)));
+ return json(await post("/take", await request.json(), auth(cookies)));
}
diff --git a/src/routes/(app)/[username]/generate/+page.svelte b/src/routes/(app)/generate/+page.svelte
index 767b7545..49d75dc6 100644
--- a/src/routes/(app)/[username]/generate/+page.svelte
+++ b/src/routes/(app)/generate/+page.svelte
@@ -28,7 +28,7 @@
try {
user.pin = $pin;
- await post(`/${user.username}/generate`, user);
+ await post(`/generate`, user);
goto($loginRedirect || `/${user.username}`, { invalidateAll: true });
} catch (e) {
$pin = "";
diff --git a/src/routes/(app)/generate/+server.ts b/src/routes/(app)/generate/+server.ts
new file mode 100644
index 00000000..b16d0b37
--- /dev/null
+++ b/src/routes/(app)/generate/+server.ts
@@ -0,0 +1,12 @@
+import { auth, post } from "$lib/utils";
+import { error, json } from "@sveltejs/kit";
+
+export async function POST({ cookies, request }) {
+ try {
+ const body = await request.json();
+ return json(await post("/user", body, auth(cookies)));
+ } catch (e: any) {
+ console.log(e);
+ error(500, e.message);
+ }
+}
diff --git a/src/routes/(app)/invoice/+page.server.ts b/src/routes/(app)/invoice/+page.server.ts
new file mode 100644
index 00000000..8d2f3b7f
--- /dev/null
+++ b/src/routes/(app)/invoice/+page.server.ts
@@ -0,0 +1,29 @@
+import type { Invoice } from "$lib/types";
+import { auth, post } from "$lib/utils";
+import { error, redirect } from "@sveltejs/kit";
+
+export const load = async ({ cookies, parent }) => {
+ const aid = cookies.get("aid");
+ let { subject, user, rates } = await parent();
+ if (aid === user.id) redirect(307, `/${user.username}/receive`);
+
+ let invoice: Invoice = {
+ aid,
+ rate: rates[user?.currency || subject?.currency],
+ };
+
+ if (!user) user = subject;
+
+ try {
+ invoice = await post("/invoice", { invoice, aid, user }, auth(cookies));
+ } catch (e) {
+ console.log(e);
+ error(500, "Failed to generate invoice");
+ }
+
+ const { id } = invoice;
+
+ if (invoice.memoPrompt && !invoice.memo) {
+ redirect(307, `/invoice/${id}/memo`);
+ } else redirect(307, `/invoice/${id}`);
+};
diff --git a/src/routes/(app)/[username]/address/+page.svelte b/src/routes/(app)/invoice/+page.svelte
index e69de29b..e69de29b 100644
--- a/src/routes/(app)/[username]/address/+page.svelte
+++ b/src/routes/(app)/invoice/+page.svelte
diff --git a/src/routes/(app)/invoice/+server.ts b/src/routes/(app)/invoice/+server.ts
new file mode 100644
index 00000000..f20d70f3
--- /dev/null
+++ b/src/routes/(app)/invoice/+server.ts
@@ -0,0 +1,7 @@
+import { auth, post } from "$lib/utils";
+import { json } from "@sveltejs/kit";
+
+export const POST = async ({ cookies, request }) => {
+ const body = await request.json();
+ return json(await post("/invoice", body, auth(cookies)));
+};
diff --git a/src/routes/(app)/invoice/[id]/+layout.server.ts b/src/routes/(app)/invoice/[id]/+layout.server.ts
new file mode 100644
index 00000000..a844b928
--- /dev/null
+++ b/src/routes/(app)/invoice/[id]/+layout.server.ts
@@ -0,0 +1,40 @@
+import * as Qr from "qrcode-base64";
+import { get } from "$lib/utils";
+import { redirect } from "@sveltejs/kit";
+
+export async function load({ cookies, depends, params, url, parent }) {
+ depends("app:invoice");
+
+ const token = cookies.get("token");
+ let { subject, user } = await parent();
+ const { id } = params;
+ let invoice;
+
+ if (id) {
+ invoice = await get(`/invoice/${id}`);
+ const options = !!url.searchParams.get("options");
+
+ if (
+ user &&
+ invoice.uid !== user.id &&
+ !(url.pathname.includes("tip") || url.pathname.includes("memo")) &&
+ !options
+ ) {
+ redirect(307, `/send/invoice/${id}`);
+ }
+
+ let { amount, pending, received } = invoice;
+ amount = parseInt(amount);
+ subject = user || invoice.user;
+
+ const paid =
+ (!amount && (pending || received)) ||
+ (amount > 0 && (pending >= amount || received >= amount));
+ if (paid && !url.pathname.endsWith("paid")) {
+ redirect(307, `/invoice/${id}/paid` + (options ? "?options=true" : ""));
+ }
+ }
+
+ const src = Qr.drawImg(invoice?.text || "", { size: 500 });
+ return { id, invoice, subject, src, user, token };
+}
diff --git a/src/routes/(app)/invoice/[id]/[email protected] b/src/routes/(app)/invoice/[id]/[email protected]
new file mode 100644
index 00000000..db14b046
--- /dev/null
+++ b/src/routes/(app)/invoice/[id]/[email protected]
@@ -0,0 +1,115 @@
+<script>
+ import { SvelteToast } from "@zerodevx/svelte-toast";
+ import { onDestroy, onMount } from "svelte";
+ import { close, connect, send } from "$lib/socket";
+ import {
+ last,
+ invoice,
+ request,
+ ndef,
+ passwordPrompt,
+ password,
+ pin,
+ } 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 Invoice from "$comp/Invoice.svelte";
+ import Password from "$comp/Password.svelte";
+ import { getCookie, warning, protectedRoutes } from "$lib/utils";
+ import { t, locale, loading } from "$lib/translations";
+ import { goto, onNavigate } from "$app/navigation";
+
+ export let data;
+
+ let { generate, rate, user, subject, token, rates } = data;
+
+ $: update(data);
+ let update = (data) => {
+ ({ rate, user, subject, token, rates } = data);
+ };
+
+ onMount(async () => {
+ if (browser) {
+ checkSocket();
+ $pin = getCookie("pin");
+
+ if (window.NDEFReader && user.nfc) {
+ try {
+ $ndef = new NDEFReader();
+ await $ndef.scan();
+
+ $ndef.addEventListener("readingerror", (e) => {
+ console.log("nfc error", e);
+ });
+
+ $ndef.addEventListener("reading", ({ message, serialNumber }) => {
+ goto(`/send/${message}`);
+ });
+ } catch (error) {
+ console.log("Argh! " + error);
+ }
+ }
+ }
+ });
+
+ $: browser && connect(token);
+
+ let lost,
+ checkTimer,
+ expireTimer,
+ counter = 0;
+
+ let checkSocket = () => {
+ counter++;
+ lost = Date.now() - $last > 30000;
+ if (lost) connect(token);
+ if (counter > 5) {
+ send("heartbeat", token);
+ counter = 0;
+ }
+
+ checkTimer = setTimeout(checkSocket, 1000);
+ };
+
+ onDestroy(() => {
+ if (browser) {
+ close();
+ clearTimeout(checkTimer);
+ clearTimeout(expireTimer);
+ }
+ });
+</script>
+
+{#if browser && user && $passwordPrompt}
+ <Password {user} />
+{/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-20">
+ <AppHeader {user} {subject} />
+ {#if !$loading}
+ <slot />
+ {/if}
+</main>
+
+{#if $invoice}
+ <Invoice {user} />
+{/if}
diff --git a/src/routes/(app)/[username]/invoice/[id]/+page.server.js b/src/routes/(app)/invoice/[id]/+page.server.ts
index a57efa64..d54ff30d 100644
--- a/src/routes/(app)/[username]/invoice/[id]/+page.server.js
+++ b/src/routes/(app)/invoice/[id]/+page.server.ts
@@ -1,5 +1,5 @@
import invoice from "$lib/invoice";
export const actions = {
- default: invoice,
+ default: invoice,
};
diff --git a/src/routes/(app)/invoice/[id]/+page.svelte b/src/routes/(app)/invoice/[id]/+page.svelte
new file mode 100644
index 00000000..1a32b5b4
--- /dev/null
+++ b/src/routes/(app)/invoice/[id]/+page.svelte
@@ -0,0 +1,334 @@
+<script>
+ import { enhance } from "$app/forms";
+ import { send } from "$lib/socket";
+ import { btc, post, copy, f, get, types, sat, s, sats } from "$lib/utils";
+ import { tick, onMount, onDestroy } from "svelte";
+ import { browser } from "$app/environment";
+ import { last, showQr, amountPrompt } from "$lib/store";
+ import Avatar from "$comp/Avatar.svelte";
+ import Icon from "$comp/Icon.svelte";
+ import Numpad from "$comp/Numpad.svelte";
+ import { t } from "$lib/translations";
+ import { goto, invalidate } from "$app/navigation";
+ import Toggle from "$comp/Toggle.svelte";
+
+ export let data;
+
+ let showOptions;
+
+ let reading = async ({ message, serialNumber }) => {
+ let name = serialNumber.replace(/:/g, "-");
+ let result = await post(`/fund/${name}/withdraw`, { amount, hash, name });
+ };
+
+ let readingerror = (e) => console.log("nfc error", e);
+
+ $: refresh(data);
+ let { invoice, id, subject, user, src } = data;
+ let {
+ aid,
+ amount,
+ hash,
+ type,
+ rate,
+ text,
+ tip,
+ user: { username, currency },
+ } = invoice;
+
+ let qr;
+ let tipPercent = 0;
+
+ let refresh = async (data) => {
+ ({ invoice, id, user, src } = data);
+ ({
+ aid,
+ amount,
+ hash,
+ type,
+ rate,
+ text,
+ tip,
+ user: { username, currency },
+ } = invoice);
+
+ if (browser && !subbed[id])
+ send("subscribe", invoice)
+ .then(() => (subbed[id] = true))
+ .catch((e) => {
+ console.log("failed to subscribe to invoice notifications", invoice);
+ console.log(e);
+ });
+
+ tipPercent = (tip / amount) * 100;
+ };
+
+ $: amountFiat = parseFloat(((amount * rate) / sats).toFixed(2));
+ $: tipAmount = ((tip * rate) / sats).toFixed(2);
+
+ let subbed = {};
+
+ onMount(async () => {
+ if (browser) {
+ last.subscribe((v) => {
+ if (!v || subbed) return;
+ subbed = true;
+ send("subscribe", invoice);
+ });
+
+ if ($amountPrompt && !amount) toggleAmount();
+ }
+ });
+
+ $: link = [types.bitcoin, types.liquid].includes(type)
+ ? text
+ : `lightning:${text}`;
+ $: txt = [types.bitcoin, types.liquid].includes(type) ? hash : text;
+
+ let setType = async (type) => {
+ invoice.type = type;
+ ({ id } = await post(`/invoice`, {
+ invoice,
+ user: { username, currency },
+ }));
+
+ goto(`./${id}?options=true`, { invalidateAll: true, noScroll: true });
+ };
+
+ let setAmount = async () => {
+ if (typeof $amountPrompt === "undefined") $amountPrompt = true;
+ settingAmount = false;
+ amount = newAmount;
+ invoice.amount = newAmount;
+ invoice.tip = 0;
+ ({ id } = await post(`/invoice`, {
+ invoice,
+ user: { username, currency },
+ }));
+
+ let url = `./${id}`;
+ if (subject?.prompt) url += "/tip";
+ else url += "?options=true";
+
+ goto(url, { invalidateAll: true, noScroll: true });
+ };
+
+ let newAmount;
+ let settingAmount;
+ let toggleAmount = () => (settingAmount = !settingAmount);
+ let fiat;
+ let submit;
+</script>
+
+<div class="invoice container mx-auto max-w-xl px-4 space-y-2">
+ {#if $showQr}
+ <div>
+ <a
+ href={[types.bitcoin, types.liquid].includes(invoice.type)
+ ? invoice.text
+ : "lightning:" + invoice.text}
+ >
+ <img
+ {src}
+ class="mx-auto z-10 max-w-[360px]"
+ bind:this={qr}
+ alt={txt}
+ />
+ </a>
+ </div>
+ {/if}
+
+ {#if type !== types.lightning || !$showQr}
+ <div class="break-all text-center text-xl text-secondary flex">
+ <div class="m-auto">{txt}</div>
+ </div>
+ {/if}
+
+ {#each invoice.items as i}
+ <div class="grid grid-cols-12 text-xl">
+ <div class="col-span-1 my-auto">{i.quantity}</div>
+ <div class="mr-auto grow col-span-7 my-auto">
+ {i.name}
+ </div>
+ <div class="col-span-2 font-semibold text-right my-auto">
+ {f(i.price * i.quantity, currency)}
+ </div>
+ <div class="col-span-2 text-secondary text-right text-lg my-auto">
+ {sat(btc(i.price * i.quantity, rate))}
+ </div>
+ </div>
+ {/each}
+
+ {#if amount > 0}
+ <div class="text-center font-bold text-2xl">
+ <div>
+ {f(amountFiat, currency)}
+
+ {#if tip}
+ <span class="text-sm">
+ +{f(tip * (rate / sats), currency)}
+ </span>
+ {/if}
+ </div>
+ <div>
+ <span class="text-secondary font-normal text-xl"
+ >⚡️{`${s(amount)}`}</span
+ >
+
+ {#if tip}
+ <span class="text-sm text-secondary font-normal">
+ +⚡️{s(tip)}
+ </span>
+ {/if}
+ </div>
+ </div>
+ {/if}
+
+ <div class="text-secondary space-y-2 text-xl pt-2">
+ <button
+ type="button"
+ class="flex gap-2 text-center break-all rounded-2xl hover:opacity-80 py-5 px-6 w-full mx-auto justify-center border whitespace-nowrap mb-2"
+ on:click={() => copy(txt)}
+ >
+ <Icon icon="copy" style="w-8 my-auto" />
+ <div class="my-auto">
+ {$t("payments.copy")}
+ </div>
+ </button>
+
+ {#if user?.id === invoice?.user?.id}
+ <button
+ class="w-full flex justify-center rounded-2xl border py-5 px-6 hover:opacity-80"
+ on:click={toggleAmount}
+ >
+ <Icon icon="edit" style="mr-1 w-8" />
+ <div class="my-auto">{$t("payments.setAmount")}</div>
+ </button>
+ {:else}
+ <a href={link} class="w-full">
+ <button
+ class="w-full flex justify-center rounded-2xl border py-5 px-6 hover:opacity-80"
+ >
+ <Icon icon="mobile" style="mr-1 w-8" />
+ <div class="my-auto">{$t("payments.openLink")}</div>
+ </button>
+ </a>
+ {/if}
+
+ {#if type === types.lightning}
+ <div class="w-full flex justify-center gap-2 flex-wrap">
+ <button
+ class="w-full flex justify-center rounded-2xl border py-5 px-6 hover:opacity-80"
+ on:click={() => ($showQr = !$showQr)}
+ >
+ {#if $showQr}
+ <Icon icon="text" style="w-6 mr-2 my-auto" />
+ {:else}
+ <Icon icon="qr" style="w-8 mr-1 invert my-auto" />
+ {/if}
+ <div class="my-auto">
+ {$showQr ? $t("payments.showText") : $t("payments.showQr")}
+ </div></button
+ >
+ </div>
+ {/if}
+ </div>
+
+ {#if aid === user?.id}
+ <div class="grid grid-cols-2 justify-around text-secondary">
+ <button
+ class="hover:bg-primary my-auto flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 justify-center"
+ class:bg-primary={type === types.bitcoin}
+ class:text-black={type === types.bitcoin}
+ on:click={() => setType(types.bitcoin)}
+ >
+ <img src="/images/bitcoin.svg" class="w-8" alt="Bitcoin" />
+ <div class="my-auto text-lg">Bitcoin</div>
+ </button>
+
+ <button
+ class="hover:bg-primary my-auto flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 justify-center"
+ class:bg-primary={type === types.liquid}
+ class:text-black={type === types.liquid}
+ on:click={() => setType(types.liquid)}
+ >
+ <img src="/images/liquid.svg" class="w-8" alt="Liquid" />
+ <div class="my-auto text-lg">Liquid</div>
+ </button>
+
+ <button
+ class="hover:bg-primary flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 justify-center"
+ class:bg-primary={type === types.lightning}
+ class:text-black={type === types.lightning}
+ on:click={() => setType(types.lightning)}
+ >
+ <div class="bg-white rounded-full w-8 h-8 text-center flex">
+ <div class="m-auto">⚡️</div>
+ </div>
+ <div class="my-auto text-lg">Lightning</div>
+ </button>
+
+ <a href={`/receive`} class="block contents">
+ <button
+ class="hover:bg-primary flex gap-1 sm:gap-2 py-3 px-2 sm:px-5 justify-center"
+ >
+ <img src="/images/cash.png" class="w-8 my-auto" />
+ <div class="my-auto text-lg">Ecash</div>
+ </button>
+ </a>
+ </div>
+
+ {#if type === types.liquid}
+ <div class="flex justify-center">
+ <div class="my-auto text-xl text-center text-secondary">
+ {$t("payments.onlyLbtc")}
+ <span class="text-teal-500 font-bold">L-BTC</span>,
+ {$t("payments.dontDeposit")}
+ </div>
+ </div>
+ {/if}
+ {/if}
+</div>
+
+{#if settingAmount}
+ <div
+ class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50"
+ >
+ <div
+ class="relative mx-auto p-12 border max-w-xl shadow-lg rounded-md bg-white space-y-5 top-5"
+ >
+ <form on:submit|preventDefault={setAmount} class="space-y-5">
+ <Numpad
+ bind:amount={newAmount}
+ bind:currency
+ bind:rate
+ bind:fiat
+ bind:submit
+ />
+ <div class="w-full flex flex-wrap gap-2">
+ <button
+ bind:this={submit}
+ type="submit"
+ on:click={setAmount}
+ class="border-2 border-black rounded-xl font-semibold mx-auto py-3 w-40 hover:opacity-80 mx-auto bg-black text-white w-full"
+ >
+ <div class="my-auto">{$t("payments.ok")}</div>
+ </button>
+ <button
+ type="button"
+ class="border-2 border-black rounded-xl font-semibold mx-auto py-3 w-40 hover:opacity-80 mx-auto w-full"
+ on:click={toggleAmount}
+ on:keydown={toggleAmount}
+ >
+ <div class="my-auto">{$t("payments.cancel")}</div>
+ </button>
+ </div>
+ </form>
+
+ <div class="flex justify-center gap-3">
+ <div class="text-secondary">{$t("payments.amountPrompt")}</div>
+ <Toggle id="notify" bind:value={$amountPrompt} />
+ </div>
+ </div>
+ </div>
+{/if}
diff --git a/src/routes/(app)/[username]/invoice/[id]/memo/+page.server.js b/src/routes/(app)/invoice/[id]/memo/+page.server.ts
index b81e2364..a2609658 100644
--- a/src/routes/(app)/[username]/invoice/[id]/memo/+page.server.js
+++ b/src/routes/(app)/invoice/[id]/memo/+page.server.ts
@@ -2,11 +2,12 @@ import invoice from "$lib/invoice";
import { redirect } from "@sveltejs/kit";
export async function load({ parent, params }) {
- let { invoice } = await parent();
- if (!invoice.amount)
- redirect(307, `/${params.username}/invoice/${invoice.id}`);
+ const { invoice } = await parent();
+ if (!invoice.amount) {
+ redirect(307, `/invoice/${invoice.id}`);
+ }
}
export const actions = {
- default: invoice,
+ default: invoice,
};
diff --git a/src/routes/(app)/[username]/invoice/[id]/memo/+page.svelte b/src/routes/(app)/invoice/[id]/memo/+page.svelte
index ddc60d1e..4d23ff19 100644
--- a/src/routes/(app)/[username]/invoice/[id]/memo/+page.svelte
+++ b/src/routes/(app)/invoice/[id]/memo/+page.svelte
@@ -13,10 +13,8 @@
sats,
} from "$lib/utils";
import Icon from "$comp/Icon.svelte";
- import { goto } from "$app/navigation";
import { t } from "$lib/translations";
import { enhance } from "$app/forms";
- import { tick } from "svelte";
let submitting;
let submit;
diff --git a/src/routes/(app)/[username]/invoice/[id]/paid/+page.svelte b/src/routes/(app)/invoice/[id]/paid/+page.svelte
index 700ac972..e4279e48 100644
--- a/src/routes/(app)/[username]/invoice/[id]/paid/+page.svelte
+++ b/src/routes/(app)/invoice/[id]/paid/+page.svelte
@@ -76,7 +76,7 @@
{/if}
</div>
-<a href={`/${user.username}/receive`}>
+<a href={`/${user.username}`}>
<div class="opacity-0 w-screen h-screen fixed top-0 left-0 z-50" />
</a>
diff --git a/src/routes/(app)/invoice/[id]/tip/+page.server.ts b/src/routes/(app)/invoice/[id]/tip/+page.server.ts
new file mode 100644
index 00000000..a1ba8924
--- /dev/null
+++ b/src/routes/(app)/invoice/[id]/tip/+page.server.ts
@@ -0,0 +1,15 @@
+import { get } from "$lib/utils";
+import invoice from "$lib/invoice";
+import { redirect } from "@sveltejs/kit";
+
+export async function load({ parent }) {
+ const rates = await get("/rates");
+ const { invoice } = await parent();
+ if (!invoice.amount) redirect(307, `/invoice/${invoice.id}`);
+
+ return { rates };
+}
+
+export const actions = {
+ default: invoice,
+};
diff --git a/src/routes/(app)/[username]/invoice/[id]/tip/+page.svelte b/src/routes/(app)/invoice/[id]/tip/+page.svelte
index 35b24bf1..217b8474 100644
--- a/src/routes/(app)/[username]/invoice/[id]/tip/+page.svelte
+++ b/src/routes/(app)/invoice/[id]/tip/+page.svelte
@@ -59,6 +59,7 @@
$: refresh(data);
let { invoice, id, user, rates } = data;
let {
+ aid,
amount,
hash,
items,
@@ -81,6 +82,7 @@
({ invoice, id } = data);
({
+ aid,
amount,
hash,
items,
@@ -111,6 +113,7 @@
<div class="container px-4 max-w-lg text-center mx-auto">
<form method="POST" use:enhance class:invisible={submitting}>
+ <input type="hidden" name="aid" value={aid} />
<input type="hidden" name="amount" value={amount} />
<input type="hidden" name="tip" value={tip} />
<input type="hidden" name="username" value={username} />
@@ -150,12 +153,21 @@
<button type="button" on:click={() => (tipPercent = 0)}>Reset</button>
</div>
{:else}
- {#each tipAmounts as amount}
- <button
- type="button"
- class:active={active(amount, tipPercent)}
- on:click={() => handleTipButtonClick(amount)}>{amount}</button
- >
+ {#each tipAmounts as amount, i}
+ {#if i === 0}
+ <button
+ use:focus
+ type="button"
+ class:active={active(amount, tipPercent)}
+ on:click={() => handleTipButtonClick(amount)}>{amount}</button
+ >
+ {:else}
+ <button
+ type="button"
+ class:active={active(amount, tipPercent)}
+ on:click={() => handleTipButtonClick(amount)}>{amount}</button
+ >
+ {/if}
{/each}
{/if}
diff --git a/src/routes/(app)/[username]/invoice/sent/+page.svelte b/src/routes/(app)/invoice/sent/+page.svelte
index b95bc85e..b95bc85e 100644
--- a/src/routes/(app)/[username]/invoice/sent/+page.svelte
+++ b/src/routes/(app)/invoice/sent/+page.svelte
diff --git a/src/routes/(app)/items/[id]/+page.server.ts b/src/routes/(app)/items/[id]/+page.server.ts
new file mode 100644
index 00000000..32924d03
--- /dev/null
+++ b/src/routes/(app)/items/[id]/+page.server.ts
@@ -0,0 +1,21 @@
+import { fd, auth, get, post } from "$lib/utils";
+import { fail, redirect } from "@sveltejs/kit";
+
+export const load = async ({ params: { id } }) => {
+ const item = await get(`/items/${id}`);
+ return { item };
+};
+
+export const actions = {
+ default: async ({ cookies, request, url }) => {
+ const form = await fd(request);
+ try {
+ await post("/items", form, auth(cookies));
+ } catch (e: any) {
+ return fail(400, { message: e.message });
+ }
+
+ const success = `/${url.pathname.split("/")[1]}`;
+ redirect(307, success);
+ },
+};
diff --git a/src/routes/(app)/[username]/items/[id]/+page.svelte b/src/routes/(app)/items/[id]/+page.svelte
index 65720350..65720350 100644
--- a/src/routes/(app)/[username]/items/[id]/+page.svelte
+++ b/src/routes/(app)/items/[id]/+page.svelte
diff --git a/src/routes/(app)/items/create/+page.server.ts b/src/routes/(app)/items/create/+page.server.ts
new file mode 100644
index 00000000..e125e047
--- /dev/null
+++ b/src/routes/(app)/items/create/+page.server.ts
@@ -0,0 +1,16 @@
+import { fail, redirect } from "@sveltejs/kit";
+import { fd, auth, post } from "$lib/utils";
+
+export const actions = {
+ default: async ({ cookies, request, url }) => {
+ const form = await fd(request);
+ try {
+ await post("/items", form, auth(cookies));
+ } catch (e: any) {
+ return fail(400, { message: e.message });
+ }
+
+ const success = `/${url.pathname.split("/")[1]}`;
+ redirect(307, success);
+ },
+};
diff --git a/src/routes/(app)/[username]/items/create/+page.svelte b/src/routes/(app)/items/create/+page.svelte
index b82889c9..b82889c9 100644
--- a/src/routes/(app)/[username]/items/create/+page.svelte
+++ b/src/routes/(app)/items/create/+page.svelte
diff --git a/src/routes/(app)/ln/[lnurl]/+page.server.js b/src/routes/(app)/ln/[lnurl]/+page.server.js
deleted file mode 100644
index 910ce5a5..00000000
--- a/src/routes/(app)/ln/[lnurl]/+page.server.js
+++ /dev/null
@@ -1,75 +0,0 @@
-import { fd, auth, get, post } from "$lib/utils";
-import { error, fail, redirect } from "@sveltejs/kit";
-
-export async function load({ params, parent }) {
- let { user } = await parent();
- if (!user) redirect(307, "/register");
-
- let data;
-
- try {
- let { lnurl } = params;
- data = await get(`/decode?text=${lnurl}`);
- } catch (e) {
- error(500, e.message);
- }
-
- if (!["payRequest", "withdrawRequest"].includes(data.tag))
- error(500, "We only support LNURLp and LNURLw at this time");
-
- return data;
-}
-
-export const actions = {
- pay: async ({ cookies, fetch, request }) => {
- let error;
-
- let { callback, amount, minSendable, maxSendable } = await fd(request);
- minSendable = Math.round(minSendable / 1000);
- maxSendable = Math.round(maxSendable / 1000);
-
- if (amount < minSendable)
- error = `Amount must be at least ${minSendable} sats`;
- if (amount > maxSendable)
- error = `Amount must be at most ${maxSendable} sats`;
- if (error) return fail(400, { error });
-
- let { pr } = await fetch(`${callback}?amount=${amount * 1000}`).then((r) =>
- r.json()
- );
- redirect(307, `/send/lightning/${pr}`);
- },
-
- withdraw: async ({ cookies, fetch, request }) => {
- let error;
-
- let {
- callback,
- amount,
- username,
- currency,
- minWithdrawable,
- maxWithdrawable,
- k1,
- } = await fd(request);
-
- minWithdrawable = Math.round(minWithdrawable / 1000);
- maxWithdrawable = Math.round(maxWithdrawable / 1000);
-
- if (amount < minWithdrawable)
- error = `Amount must be at least ${minWithdrawable} sats`;
- if (amount > maxWithdrawable)
- error = `Amount must be at most ${maxWithdrawable} sats`;
- if (error) return fail(400, { error });
-
- let invoice = { amount, type: "lightning" };
- let user = { username, currency };
-
- let { text: pr } = await post("/invoice", { invoice, user }, auth(cookies));
-
- let c = callback.includes("?") ? "&" : "?";
- await fetch(`${callback}${c}k1=${k1}&pr=${pr}`).then((r) => r.json());
-
- redirect(307, `/ln/withdrawal/sent`);
- },
-};
diff --git a/src/routes/(app)/ln/[lnurl]/+page.server.ts b/src/routes/(app)/ln/[lnurl]/+page.server.ts
new file mode 100644
index 00000000..b405f427
--- /dev/null
+++ b/src/routes/(app)/ln/[lnurl]/+page.server.ts
@@ -0,0 +1,81 @@
+import { fd, auth, get, post } from "$lib/utils";
+import { error, fail, redirect } from "@sveltejs/kit";
+
+export async function load({ params, parent }) {
+ const { user } = await parent();
+ if (!user) redirect(307, "/register");
+
+ let data;
+
+ try {
+ const { lnurl } = params;
+ data = await get(`/decode?text=${lnurl}`);
+ } catch (e: any) {
+ error(500, e.message);
+ }
+
+ if (!["payRequest", "withdrawRequest"].includes(data.tag))
+ error(500, "We only support LNURLp and LNURLw at this time");
+
+ return data;
+}
+
+export const actions = {
+ pay: async ({ fetch, request }) => {
+ let error;
+
+ let { callback, amount, minSendable, maxSendable, comment } =
+ await fd(request);
+ minSendable = Math.round(minSendable / 1000);
+ maxSendable = Math.round(maxSendable / 1000);
+
+ if (amount < minSendable)
+ error = `Amount must be at least ${minSendable} sats`;
+ if (amount > maxSendable)
+ error = `Amount must be at most ${maxSendable} sats`;
+ if (error) return fail(400, { error });
+
+ let url = `${callback}?amount=${amount * 1000}`;
+ if (comment) url += `&comment=${comment}`;
+
+ const { pr } = await fetch(url).then((r) => r.json());
+ redirect(307, `/send/lightning/${pr}`);
+ },
+
+ withdraw: async ({ cookies, fetch, request }) => {
+ let error;
+
+ let {
+ callback,
+ amount,
+ username,
+ currency,
+ minWithdrawable,
+ maxWithdrawable,
+ k1,
+ } = await fd(request);
+
+ minWithdrawable = Math.round(minWithdrawable / 1000);
+ maxWithdrawable = Math.round(maxWithdrawable / 1000);
+
+ if (amount < minWithdrawable)
+ error = `Amount must be at least ${minWithdrawable} sats`;
+ if (amount > maxWithdrawable)
+ error = `Amount must be at most ${maxWithdrawable} sats`;
+ if (error) return fail(400, { error });
+
+ const invoice = { amount, type: "lightning" };
+ const user = { username, currency };
+
+ const { text: pr } = await post(
+ "/invoice",
+ { invoice, user },
+ auth(cookies),
+ );
+
+ const c = callback.includes("?") ? "&" : "?";
+ await fetch(`${callback}${c}k1=${k1}&pr=${pr}`).then((r) => r.json());
+
+ redirect(307, "/payments");
+ },
+};
diff --git a/src/routes/(app)/ln/withdrawal/sent/+page.svelte b/src/routes/(app)/ln/withdrawal/sent/+page.svelte
index c1a2bdb2..90814960 100644
--- a/src/routes/(app)/ln/withdrawal/sent/+page.svelte
+++ b/src/routes/(app)/ln/withdrawal/sent/+page.svelte
@@ -19,7 +19,7 @@
<h1 class="text-3xl md:text-4xl font-bold mb-6">Request Sent!</h1>
</div>
-<a href={`/${user.username}/payments`}>
+<a href={`/payments`}>
<div class="opacity-0 w-screen h-screen fixed top-0 left-0 z-50" />
</a>
diff --git a/src/routes/(app)/locations/+server.js b/src/routes/(app)/locations/+server.js
deleted file mode 100644
index 8a046475..00000000
--- a/src/routes/(app)/locations/+server.js
+++ /dev/null
@@ -1,15 +0,0 @@
-import { get } from "$lib/utils";
-import { json } from "@sveltejs/kit";
-
-export async function GET({ fetch, setHeaders }) {
- let locations = [];
-
- try {
- ({ locations } = await get("/locations"));
- setHeaders({ "cache-control": "public, max-age=600" });
- } catch (e) {
- console.log("failed to fetch locations");
- }
-
- return json({ locations });
-}
diff --git a/src/routes/(app)/locations/+server.ts b/src/routes/(app)/locations/+server.ts
new file mode 100644
index 00000000..3184ebdf
--- /dev/null
+++ b/src/routes/(app)/locations/+server.ts
@@ -0,0 +1,15 @@
+import { get } from "$lib/utils";
+import { json } from "@sveltejs/kit";
+
+export async function GET({ setHeaders }) {
+ let locations = [];
+
+ try {
+ ({ locations } = await get("/locations"));
+ setHeaders({ "cache-control": "public, max-age=600" });
+ } catch (e) {
+ console.log("failed to fetch locations");
+ }
+
+ return json({ locations });
+}
diff --git a/src/routes/(app)/login/+page.server.js b/src/routes/(app)/login/+page.server.js
deleted file mode 100644
index 7fb1a6b3..00000000
--- a/src/routes/(app)/login/+page.server.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import { fail, redirect } from "@sveltejs/kit";
-import { login, fd } from "$lib/utils";
-
-export const load = async ({ parent, url }) => {
- let { user } = await parent();
- if (user?.pubkey) redirect(307, `/${user.username}`);
-};
-
-export const actions = {
- default: async ({ cookies, request }) => {
- let form = await fd(request);
- let { username, password, token, loginRedirect } = form;
- let user = { username, password, token };
-
- if (loginRedirect === "undefined") loginRedirect = undefined;
-
- try {
- let r = await login(
- user,
- cookies,
- request.headers.get("cf-connecting-ip")
- );
- } catch (e) {
- return fail(400, { error: "Login failed", message: e.message, ...form });
- }
-
- redirect(307, loginRedirect || `/${user.username}`);
- },
-};
diff --git a/src/routes/(app)/login/+page.svelte b/src/routes/(app)/login/+page.svelte
deleted file mode 100644
index 61ea23b7..00000000
--- a/src/routes/(app)/login/+page.svelte
+++ /dev/null
@@ -1,188 +0,0 @@
-<script>
- import { onMount } from "svelte";
- import { applyAction, deserialize } from "$app/forms";
- import { tick } from "svelte";
- import { fly } from "svelte/transition";
- import { enhance } from "$app/forms";
- import Pin from "$comp/Pin.svelte";
- import Icon from "$comp/Icon.svelte";
- import Spinner from "$comp/Spinner.svelte";
- import { focus, fail } from "$lib/utils";
- import { password, pin, loginRedirect } from "$lib/store";
- import { t } from "$lib/translations";
- import { page } from "$app/stores";
- import { generate } from "$lib/nostr";
- import { invalidateAll } from "$app/navigation";
-
- onMount(() => {
- $pin = undefined;
- localStorage.clear();
- sessionStorage.clear();
-
- let lang = $page.url.searchParams.get("lang");
- if (lang) document.cookie = `lang=${lang} ;`;
- });
-
- export let form;
-
- let token, formElement;
- let code = [];
- let redirect;
-
- $password = undefined;
-
- $: need2fa = form?.message === "2fa";
- let cancel = () => (need2fa = false);
- $: if (form?.message === "2fa" && form.token === token) token = "";
-
- let username, email, btn;
-
- $: update(form);
- let update = (form) => form && ({ username, password: $password } = form);
-
- $: token && token?.length === 6 && tick().then(() => btn.click());
-
- let revealPassword = false;
-
- let loading;
- async function handleSubmit(e) {
- loading = true;
-
- let data = new FormData(this);
- let user = Object.fromEntries(data);
- await generate(user);
-
- for (let k in user) {
- data.set(k, user[k]);
- }
-
- const response = await fetch("/login", {
- method: "POST",
- body: data,
- });
-
- const result = deserialize(await response.text());
-
- if (result.type === "success") {
- await invalidateAll();
- }
-
- applyAction(result);
- loading = false;
- }
-</script>
-
-{#if need2fa}
- <Pin bind:value={token} title="Enter 2FA Code" {cancel} notify={false} />
-{/if}
-
-<div class="pt-10">
- <div class="w-[243px] mx-auto mb-10">
- <a href="/">
- <Icon icon="logo" />
- </a>
- </div>
-
- <div class="flex justify-center items-center">
- <div
- class="shadow-xl rounded-3xl p-10 pb-12 space-y-5 w-full mx-5 md:mx-0 md:w-[400px]"
- >
- <h1 class="text-2xl font-bold text-center">{$t("login.signIn")}</h1>
-
- {#if form?.error}
- <div class="text-red-600 text-center" in:fly>
- {form.error}
- </div>
- {/if}
-
- <form
- class="space-y-5"
- on:submit|preventDefault={handleSubmit}
- method="POST"
- >
- <input
- type="hidden"
- name="loginRedirect"
- value={$loginRedirect || $page.url.searchParams.get("redirect")}
- />
- <input type="hidden" name="token" value={token} />
-
- <div>
- <label for="username" class="font-semibold"
- >{$t("login.username")}</label
- >
- <input
- name="username"
- type="text"
- required
- class="bg-primary"
- bind:value={username}
- use:focus
- autocapitalize="none"
- />
- </div>
-
- <div class="relative">
- <label for="password" class="block font-semibold"
- >{$t("login.password")}</label
- >
- {#if revealPassword}
- <input
- name="password"
- type="text"
- required
- class="bg-primary"
- bind:value={$password}
- autocapitalize="none"
- />
- {:else}
- <input
- name="password"
- type="password"
- required
- class="bg-primary"
- bind:value={$password}
- autocapitalize="none"
- />
- {/if}
- <button
- type="button"
- on:click={() => (revealPassword = !revealPassword)}
- class="absolute right-5 top-10"
- >
- <Icon icon={revealPassword ? "eye" : "eye-off"} />
- </button>
- </div>
-
- <div class="flex justify-end items-center">
- <a href="/forgot" class="underline underline-offset-4 text-black"
- >{$t("login.forgotUserOrPassword")}</a
- >
- </div>
-
- <button
- type="submit"
- class="bg-black text-white w-full rounded-2xl p-4 font-semibold hover:opacity-80"
- disabled={loading}
- bind:this={btn}
- >
- {#if loading}
- <Spinner />
- {:else}
- {$t("login.signIn")}
- {/if}
- </button>
- </form>
-
- <p class="text-secondary text-center font-medium">
- {$t("login.noAccount")}
- <a
- href={"/register"}
- class="block md:inline text-black underline underline-offset-4 hover:opacity-80"
- >
- {$t("login.register")}
- </a>
- </p>
- </div>
- </div>
-</div>
diff --git a/src/routes/(app)/logout/+page.server.js b/src/routes/(app)/logout/+page.server.js
deleted file mode 100644
index ab5df7b9..00000000
--- a/src/routes/(app)/logout/+page.server.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import { redirect } from "@sveltejs/kit";
-
-const opts = {
- expires: new Date(0),
- path: "/",
-};
-
-export async function load({ cookies }) {
- let lang = cookies.get("lang");
- cookies.set("lang", "", opts);
- cookies.set("username", "", opts);
- cookies.set("token", "", opts);
- redirect(307, `/login?lang=${lang}`);
-}
diff --git a/src/routes/(app)/logout/+page.server.ts b/src/routes/(app)/logout/+page.server.ts
new file mode 100644
index 00000000..2a6fc71f
--- /dev/null
+++ b/src/routes/(app)/logout/+page.server.ts
@@ -0,0 +1,15 @@
+import { redirect } from "@sveltejs/kit";
+
+const opts = {
+ expires: new Date(0),
+ path: "/",
+};
+
+export async function load({ cookies }) {
+ const lang = cookies.get("lang");
+ cookies.set("aid", "", opts);
+ cookies.set("lang", "", opts);
+ cookies.set("username", "", opts);
+ cookies.set("token", "", opts);
+ redirect(307, `/login?lang=${lang}`);
+}
diff --git a/src/routes/(app)/messages/+page.server.ts b/src/routes/(app)/messages/+page.server.ts
new file mode 100644
index 00000000..b64dfb42
--- /dev/null
+++ b/src/routes/(app)/messages/+page.server.ts
@@ -0,0 +1,44 @@
+import { get } from "$lib/utils";
+import { redirect } from "@sveltejs/kit";
+
+interface Message {
+ created_at: number;
+}
+
+interface Note {
+ created_at: number;
+ seen: number;
+}
+
+export async function load({ params, parent }) {
+ const { user } = await parent();
+ if (user.username !== params.username) redirect(307, `/${params.username}`);
+ const { since = 0 } = params;
+
+ let messages = [];
+ let notes = [];
+
+ if (user?.pubkey) {
+ const { pubkey } = user;
+ try {
+ messages = await get(`/${pubkey}/${since}/messages`);
+ messages = messages.sort(
+ (a: Message, b: Message) => b.created_at - a.created_at,
+ );
+ } catch (e) {
+ console.log("failed to fetch nostr messages", e);
+ }
+
+ try {
+ notes = await get(`/${pubkey}/notes`);
+ } catch (e) {
+ console.log(`failed to fetch nostr notes for ${pubkey}`, e);
+ }
+
+ notes.map((e: Note) => {
+ e.seen = e.created_at;
+ });
+ }
+
+ return { messages, notes };
+}
diff --git a/src/routes/(app)/[username]/messages/+page.svelte b/src/routes/(app)/messages/+page.svelte
index 4738ea2c..547a1f21 100644
--- a/src/routes/(app)/[username]/messages/+page.svelte
+++ b/src/routes/(app)/messages/+page.svelte
@@ -71,7 +71,7 @@
<div class="relative">
{#each latest as { content, pubkey, author, recipient }}
{@const user = author.id === user.id ? recipient : author}
- <a href={`/${subject.username}/messages/${user.username}`}>
+ <a href={`/messages/${user.username}`}>
<div class="flex hover:bg-gray-100 p-4 rounded-2xl">
<div class="my-auto">
<Avatar {user} size={"20"} disabled={true} />
diff --git a/src/routes/(app)/messages/[recipient]/+page.server.ts b/src/routes/(app)/messages/[recipient]/+page.server.ts
new file mode 100644
index 00000000..6e61e1b4
--- /dev/null
+++ b/src/routes/(app)/messages/[recipient]/+page.server.ts
@@ -0,0 +1,25 @@
+import { get } from "$lib/utils";
+import type { Message } from "$lib/types";
+
+export async function load({ params, parent }) {
+ const { user } = await parent();
+ const { since = 0 } = params;
+
+ let messages: Message[] = [];
+ const recipient = await get(`/users/${params.recipient}`);
+
+ try {
+ messages = await get(`/${user.pubkey}/${since}/messages`);
+
+ messages = messages
+ .filter(
+ (m: Message) =>
+ m.recipient?.id === recipient.id || m.author?.id === recipient.id,
+ )
+ .sort((a, b) => a.created_at - b.created_at);
+ } catch (e) {
+ console.log("failed to fetch nostr messages", e);
+ }
+
+ return { messages, recipient, user };
+}
diff --git a/src/routes/(app)/[username]/messages/[recipient]/+page.svelte b/src/routes/(app)/messages/[recipient]/+page.svelte
index 98638389..9b9f6f47 100644
--- a/src/routes/(app)/[username]/messages/[recipient]/+page.svelte
+++ b/src/routes/(app)/messages/[recipient]/+page.svelte
@@ -17,7 +17,7 @@
function fadeScale(
node,
- { delay = 0, duration = 200, easing = (x) => x, baseScale = 0 }
+ { delay = 0, duration = 200, easing = (x) => x, baseScale = 0 },
) {
const o = +getComputedStyle(node).opacity;
const m = getComputedStyle(node).transform.match(/scale\(([0-9.]+)\)/);
@@ -43,8 +43,8 @@
let initialize = async (p) => {
await Promise.all(
messages.map(
- async (event) => (event.message = await decrypt({ event, user }))
- )
+ async (event) => (event.message = await decrypt({ event, user })),
+ ),
);
messages = messages;
diff --git a/src/routes/(app)/otpsecret/+server.js b/src/routes/(app)/otpsecret/+server.js
deleted file mode 100644
index 63d06849..00000000
--- a/src/routes/(app)/otpsecret/+server.js
+++ /dev/null
@@ -1,17 +0,0 @@
-import { auth, post } from "$lib/utils";
-import Qr from "qrcode-base64";
-import { error } from "@sveltejs/kit";
-
-export async function POST({ cookies, request }) {
- try {
- let body = await request.json();
- let { username, secret } = await post("/otpsecret", body, auth(cookies));
- let uri = `otpauth://totp/coinos:${username}?secret=${secret}&period=30&digits=6&algorithm=SHA1&issuer=coinos`;
- return new Response(
- JSON.stringify({ secret, uri, qr: Qr.drawImg(uri, { size: 600 }) })
- );
- } catch (e) {
- if (e.message.includes("pin")) throw e;
- throw new error(500, "Problem saving secret");
- }
-}
diff --git a/src/routes/(app)/otpsecret/+server.ts b/src/routes/(app)/otpsecret/+server.ts
new file mode 100644
index 00000000..7226a7c9
--- /dev/null
+++ b/src/routes/(app)/otpsecret/+server.ts
@@ -0,0 +1,17 @@
+import { auth, post } from "$lib/utils";
+import Qr from "qrcode-base64";
+import { error } from "@sveltejs/kit";
+
+export async function POST({ cookies, request }) {
+ try {
+ const body = await request.json();
+ const { username, secret } = await post("/otpsecret", body, auth(cookies));
+ const uri = `otpauth://totp/coinos:${username}?secret=${secret}&period=30&digits=6&algorithm=SHA1&issuer=coinos`;
+ return new Response(
+ JSON.stringify({ secret, uri, qr: Qr.drawImg(uri, { size: 600 }) }),
+ );
+ } catch (e: any) {
+ if (e.message.includes("pin")) throw e;
+ error(500, "Problem saving secret");
+ }
+}
diff --git a/src/routes/(app)/password/+server.js b/src/routes/(app)/password/+server.ts
index 26ed3858..8e41b9c9 100644
--- a/src/routes/(app)/password/+server.js
+++ b/src/routes/(app)/password/+server.ts
@@ -2,6 +2,6 @@ import { json } from "@sveltejs/kit";
import { auth, post } from "$lib/utils";
export async function POST({ cookies, request }) {
- let result = await post("/password", await request.json(), auth(cookies));
- return json(result);
+ const result = await post("/password", await request.json(), auth(cookies));
+ return json(result);
}
diff --git a/src/routes/(app)/pay/[username]/[...amount]/+page.server.ts b/src/routes/(app)/pay/[username]/[...amount]/+page.server.ts
new file mode 100644
index 00000000..9c8a6927
--- /dev/null
+++ b/src/routes/(app)/pay/[username]/[...amount]/+page.server.ts
@@ -0,0 +1,54 @@
+import { auth, fd, get, post, sats, types } from "$lib/utils";
+import { error, fail, redirect } from "@sveltejs/kit";
+
+export async function load({ cookies, params, parent }) {
+ const { username } = params;
+ const { rates, user } = await parent();
+
+ if (user?.username === username) error(500, "Cannot send to self");
+ const subject = await get(`/users/${username}`);
+
+ let [amount, currency] = params.amount.split("/");
+
+ let rate;
+
+ if (amount) {
+ rate = rates[currency ? currency.toUpperCase() : subject.currency];
+ if (!rate) error(500, "Invalid currency symbol");
+ if (currency) amount = (amount * sats) / rate;
+
+ const { id } = await post(
+ "/invoice",
+ {
+ invoice: {
+ amount,
+ currency: currency === subject.currency ? currency : undefined,
+ prompt: false,
+ rate: currency === subject.currency ? rate : undefined,
+ type: types.lightning,
+ },
+ user: { username },
+ },
+ auth(cookies),
+ );
+
+ redirect(307, `/invoice/${id}`);
+ }
+
+ return { amount, rate, subject };
+}
+
+export const actions = {
+ default: async ({ cookies, request }) => {
+ let p;
+ try {
+ const body = await fd(request);
+ p = await post("/payments", body, auth(cookies));
+ } catch (e: any) {
+ console.log(e);
+ return fail(400, { message: e.message });
+ }
+
+ redirect(307, `/sent/${p.id}`);
+ },
+};
diff --git a/src/routes/(app)/send/user/[username]/[...amount]/+page.svelte b/src/routes/(app)/pay/[username]/[...amount]/+page.svelte
index e9273647..5089e78c 100644
--- a/src/routes/(app)/send/user/[username]/[...amount]/+page.svelte
+++ b/src/routes/(app)/pay/[username]/[...amount]/+page.svelte
@@ -3,19 +3,18 @@
import { goto } from "$app/navigation";
import { pin } from "$lib/store";
import { enhance } from "$app/forms";
- import AppHeader from "$comp/AppHeader.svelte";
import Avatar from "$comp/Avatar.svelte";
import Icon from "$comp/Icon.svelte";
import Numpad from "$comp/Numpad.svelte";
import Spinner from "$comp/Spinner.svelte";
import { page } from "$app/stores";
- import { f, post, s, sat, sats } from "$lib/utils";
+ import { f, fail, post, s, sat, sats } from "$lib/utils";
export let data;
export let form;
let { subject, rate, rates, user } = data;
- let currency = user.currency || subject.currency || "USD";
+ let currency = subject?.currency || "USD";
let next;
let amount = form?.amount || data.amount;
@@ -25,25 +24,29 @@
hash,
amountFiat = 0;
- $: r = rate || rates[user.currency || subject.currency];
+ $: r = rate || rates[subject?.currency];
let setAmount = async () => {
amount = a;
amountFiat = parseFloat(af).toFixed(2);
rate = fiat ? (sats * amountFiat) / amount : r;
- ({ hash } = await post(`/${subject.username}/invoice`, {
- invoice: {
- amount,
- hash: "internal",
- rate: rates[subject.currency],
- prompt: subject.prompt,
- type: "internal",
- },
- user: subject,
- }));
+ let id;
+ try {
+ ({ id, hash } = await post(`/invoice`, {
+ invoice: {
+ amount,
+ rate: rates[subject.currency],
+ prompt: subject.prompt,
+ type: "lightning",
+ },
+ user: subject,
+ }));
+ } catch (e) {
+ fail(e.message);
+ }
- goto(`/${subject.username}/invoice/${hash}`);
+ goto(`/send/invoice/${id}`);
};
let loading;
@@ -56,15 +59,13 @@
};
</script>
-<AppHeader {data} />
-
{#if form?.message}
<div class="text-red-600 text-center">
{form.message}
</div>
{/if}
-<div class="container px-4 mt-20 max-w-xl mx-auto space-y-8">
+<div class="container px-4 mt-20 max-w-xl mx-auto space-y-2">
<Numpad
bind:amount={a}
bind:amountFiat={af}
diff --git a/src/routes/(app)/payment/[id]/+page.server.js b/src/routes/(app)/payment/[id]/+page.server.js
deleted file mode 100644
index 1dfc0c09..00000000
--- a/src/routes/(app)/payment/[id]/+page.server.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import { auth, get } from "$lib/utils";
-
-export async function load({ cookies, depends, params }) {
- depends("app:payments");
- let payment = await get(`/payments/${params.id}`, auth(cookies));
- return { payment };
-}
diff --git a/src/routes/(app)/payment/[id]/+page.server.ts b/src/routes/(app)/payment/[id]/+page.server.ts
new file mode 100644
index 00000000..fffdb451
--- /dev/null
+++ b/src/routes/(app)/payment/[id]/+page.server.ts
@@ -0,0 +1,7 @@
+import { auth, get } from "$lib/utils";
+
+export async function load({ cookies, depends, params }) {
+ depends("app:payments");
+ const payment = await get(`/payments/${params.id}`, auth(cookies));
+ return { payment };
+}
diff --git a/src/routes/(app)/payment/[id]/+page.svelte b/src/routes/(app)/payment/[id]/+page.svelte
index 3e40d984..619c6d04 100644
--- a/src/routes/(app)/payment/[id]/+page.svelte
+++ b/src/routes/(app)/payment/[id]/+page.svelte
@@ -3,7 +3,6 @@
import { onMount, tick } from "svelte";
import { t, loading } from "$lib/translations";
import {
- back,
copy,
f,
s,
@@ -18,9 +17,12 @@
import Icon from "$comp/Icon.svelte";
import { format } from "date-fns";
import { PUBLIC_EXPLORER, PUBLIC_LIQUID_EXPLORER } from "$env/static/public";
+ import locales from "$lib/locales";
export let data;
let { user, payment: p } = data;
+ let locale = locales[user.language];
+
$: refresh(data);
let refresh = (d) => {
({ user, payment: p } = d);
@@ -30,9 +32,11 @@
amount,
created,
confirmed,
+ memo,
rate,
type,
ref,
+ path,
tip,
ourfee,
fee,
@@ -52,9 +56,11 @@
amount,
created,
confirmed,
+ memo,
rate,
type,
ref,
+ path,
tip,
ourfee,
fee,
@@ -94,12 +100,6 @@
});
</script>
-<a href={`/${username}/payments`}>
- <button class="ml-5 md:ml-20 mt-5 md:mt-10 hover:opacity-80">
- <Icon icon="arrow-left" style="w-10" />
- </button>
-</a>
-
<div class="container mx-auto max-w-lg px-4 space-y-8 break-all text-2xl">
<h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold mb-10">
{$t(amount < 0 ? "payments.sent" : "payments.received")}
@@ -154,7 +154,7 @@
</div>
<div>
- <span class="text-lg text-secondary">Total</span>
+ <span class="text-lg text-secondary">{$t("payments.total")}</span>
<div>
{f(fiat(a + (tip || 0), rate), currency)}
<span class="text-secondary text-lg">⚡️{`${s(a + (tip || 0))}`} </span>
@@ -163,7 +163,7 @@
{/if}
<div>
- <span class="text-lg text-secondary">Network fee</span>
+ <span class="text-lg text-secondary">{$t("payments.networkFee")}</span>
<div>
{f(fiat(fee, rate), currency)}
<span class="text-secondary text-lg">⚡️{`${s(fee)}`}</span>
@@ -172,7 +172,7 @@
{#if ourfee > 0}
<div>
- <span class="text-lg text-secondary">Platform fee</span>
+ <span class="text-lg text-secondary">{$t("payments.platformFee")}</span>
<div>
{f(fiat(ourfee, rate), currency)}
<span class="text-secondary">⚡️{`${s(ourfee)}`}</span>
@@ -181,13 +181,36 @@
{/if}
<div>
- <span class="text-lg text-secondary">Date</span>
+ <span class="text-lg text-secondary">{$t("payments.date")}</span>
<div>
- {format(new Date(created), "h:mmaaa")}
- {format(new Date(created), "MMM d, yyyy")}
+ {format(new Date(created), "h:mmaaa", { locale })}
+ {format(new Date(created), "MMM d, yyyy", { locale })}
</div>
</div>
+ {#if type === types.ecash && amount < 0}
+ <a href={`/ecash/${memo}`} class="block">
+ <button
+ class="rounded-2xl py-5 px-6 font-bold hover:bg-neutral-700 flex bg-black text-white gap-2 items-center"
+ >
+ <img src="/images/cash.png" class="w-8" />
+ <div>{$t("payments.ecashToken")}</div>
+ </button>
+ </a>
+ {:else if memo}
+ <div>
+ <span class="text-lg text-secondary">{$t("payments.memo")}</span>
+ <div>{memo}</div>
+ </div>
+ {/if}
+
+ {#if type === types.lightning}
+ <div>
+ <span class="text-lg text-secondary">{$t("payments.preimage")}</span>
+ <div>{ref}</div>
+ </div>
+ {/if}
+
{#if type === "bitcoin" || type === "liquid"}
<div>
<span class="text-lg text-secondary">Txid</span>
@@ -209,40 +232,18 @@
</div>
{/if}
- <div class="flex gap-2">
- {#if amount < 0 && !confirmed}
- <button
- class="rounded-full border py-3 px-6 hover:opacity-80 flex w-full md:w-60"
- on:click={bump}
- >
- <div class="mx-auto flex">
- <Icon icon="clock" style="my-auto h-6 mr-2" />
- <div class="my-auto mt-1 text-base">{$t("payments.bump")}</div>
- </div>
- </button>
- {/if}
-
- {#if user.hasprinter}
- <button
- class="rounded-full border py-3 px-6 hover:opacity-80 flex w-full md:w-60"
- on:click={print}
- >
- <div class="mx-auto flex">
- <Icon icon="printer" style="my-auto h-6 mr-2" />
- <div class="my-auto mt-1 text-base">{$t("payments.print")}</div>
- </div>
- </button>
- {:else}
- <a href={`/payment/${id}/plain`}>
+ {#if path}
+ <div>
+ <span class="text-lg text-secondary">Path</span>
+ <div class="flex">
+ <div>{path}</div>
<button
- class="rounded-full border py-3 px-6 hover:opacity-80 flex w-full md:w-60"
+ class="flex font-bold hover:opacity-80 mb-auto my-auto"
+ on:click={() => copy(path)}
>
- <div class="mx-auto flex">
- <Icon icon="printer" style="my-auto h-6 mr-2" />
- <div class="my-auto mt-1 text-base">{$t("payments.print")}</div>
- </div>
+ <Icon icon="copy" style="ml-2 w-12 my-auto" />
</button>
- </a>
- {/if}
- </div>
+ </div>
+ </div>
+ {/if}
</div>
diff --git a/src/routes/(app)/payment/[id]/bump/+server.js b/src/routes/(app)/payment/[id]/bump/+server.js
deleted file mode 100644
index 513198b0..00000000
--- a/src/routes/(app)/payment/[id]/bump/+server.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import { auth, post } from "$lib/utils";
-import { json, error } from "@sveltejs/kit";
-
-export async function POST({ cookies, request }) {
- let body = await request.json();
- try {
- let res = await post("/replace", body, auth(cookies));
- return json(res);
- } catch (e) {
- error(400, e.message);
- }
-}
diff --git a/src/routes/(app)/payment/[id]/bump/+server.ts b/src/routes/(app)/payment/[id]/bump/+server.ts
new file mode 100644
index 00000000..ae25999c
--- /dev/null
+++ b/src/routes/(app)/payment/[id]/bump/+server.ts
@@ -0,0 +1,12 @@
+import { auth, post } from "$lib/utils";
+import { json, error } from "@sveltejs/kit";
+
+export async function POST({ cookies, request }) {
+ const body = await request.json();
+ try {
+ const res = await post("/replace", body, auth(cookies));
+ return json(res);
+ } catch (e: any) {
+ error(400, e.message);
+ }
+}
diff --git a/src/routes/(app)/payment/[id]/plain/+page.server.js b/src/routes/(app)/payment/[id]/plain/+page.server.ts
index 5a364c65..49d9b98b 100644
--- a/src/routes/(app)/payment/[id]/plain/+page.server.js
+++ b/src/routes/(app)/payment/[id]/plain/+page.server.ts
@@ -1,6 +1,6 @@
import { auth, get } from "$lib/utils";
export async function load({ cookies, params }) {
- let payment = await get(`/payments/${params.id}`, auth(cookies));
- return { payment };
+ const payment = await get(`/payments/${params.id}`, auth(cookies));
+ return { payment };
}
diff --git a/src/routes/(app)/payment/[id]/print/+server.js b/src/routes/(app)/payment/[id]/print/+server.ts
index 2fdfc8c1..aab6d3f4 100644
--- a/src/routes/(app)/payment/[id]/print/+server.js
+++ b/src/routes/(app)/payment/[id]/print/+server.ts
@@ -2,6 +2,6 @@ import { auth, post } from "$lib/utils";
import { json } from "@sveltejs/kit";
export async function POST({ cookies, request }) {
- let body = await request.json();
- return json(post("/print", body, auth(cookies)));
+ const body = await request.json();
+ return json(post("/print", body, auth(cookies)));
}
diff --git a/src/routes/(app)/payments/[...page]/+page.server.ts b/src/routes/(app)/payments/[...page]/+page.server.ts
new file mode 100644
index 00000000..268fd32b
--- /dev/null
+++ b/src/routes/(app)/payments/[...page]/+page.server.ts
@@ -0,0 +1,31 @@
+import { get, auth } from "$lib/utils";
+
+const limit = 25;
+
+export async function load({ cookies, depends, params }) {
+ depends("app:payments");
+
+ const aid = cookies.get("aid");
+ const parts = params.page.split("/");
+
+ let start;
+ let end;
+ let page;
+ if (parts.length === 1) [page] = parts;
+ if (parts.length === 2) [start, page] = parts;
+ if (parts.length === 3) [start, end, page] = parts;
+ if (!parseInt(page)) page = 1;
+
+ const offset = (page - 1) * limit;
+ if (!start) start = Date.now() / 1000 - 24 * 60 * 60;
+
+ let url = `/payments?aid=${aid}&start=${
+ start * 1000
+ }&limit=${limit}&offset=${offset}`;
+ if (end) url += `&end=${end * 1000}`;
+
+ const { count, payments, incoming, outgoing } = await get(url, auth(cookies));
+ const pages = new Array(Math.ceil(count / limit));
+
+ return { payments, page, pages, start, end, incoming, outgoing };
+}
diff --git a/src/routes/(app)/[username]/payments/[...page]/+page.svelte b/src/routes/(app)/payments/[...page]/+page.svelte
index 90f2ddbc..f0ee1393 100644
--- a/src/routes/(app)/[username]/payments/[...page]/+page.svelte
+++ b/src/routes/(app)/payments/[...page]/+page.svelte
@@ -9,10 +9,11 @@
import { page } from "$app/stores";
import { differenceInDays, getUnixTime, sub } from "date-fns";
import { goto, invalidate } from "$app/navigation";
-
+ import locales from "$lib/locales";
export let data;
let { start, end, user, rates, payments } = data;
+ let locale = locales[user.language];
let change = ({ target: { value } }) => goto(value);
let link = (p) => {
@@ -46,14 +47,16 @@
$: selection = start
? presets.findIndex(
- (p) => Math.abs(differenceInDays(new Date(start * 1000), p.start)) < 1
+ (p) => Math.abs(differenceInDays(new Date(start * 1000), p.start)) < 1,
)
: 0;
let p,
- totals,
+ incoming,
+ outgoing,
pages = [];
- $: data && ({ page: p, pages, start, end, totals, payments } = data);
+ $: data &&
+ ({ page: p, pages, start, end, incoming, outgoing, payments } = data);
$: $page && ($newPayment = false);
$: $newPayment && invalidate(`/users/${user.username}`);
@@ -63,7 +66,7 @@
: $page.url.pathname;
let csv = async () => {
- let url = `/${user.username}/payments`;
+ let url = `/payments`;
if (start) url += `/${start}`;
if (end) url += `/${end}`;
@@ -73,8 +76,12 @@
...p,
created: new Date(p.created),
total: p.amount + (p.tip || 0),
+ platform_fee: p.ourfee,
amount_fiat: f((p.amount * p.rate) / sats, p.currency),
fee_fiat: p.fee ? f((p.fee * p.rate) / sats, p.currency) : null,
+ platform_fee_fiat: p.ourfee
+ ? f((p.ourfee * p.rate) / sats, p.currency)
+ : null,
tip_fiat: p.tip ? f((p.tip * p.rate) / sats, p.currency) : null,
total_fiat: f(((p.amount + (p.tip || 0)) * p.rate) / sats, p.currency),
}));
@@ -89,10 +96,12 @@
"tip",
"total",
"fee",
+ "platform_fee",
"amount_fiat",
"tip_fiat",
"total_fiat",
"fee_fiat",
+ "platform_fee_fiat",
];
let csv =
@@ -121,30 +130,28 @@
};
</script>
-<div class="mt-24 mb-20 payments">
- <h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold mb-10">
+<div class="space-y-5">
+ <h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold">
{$t("payments.header")}
</h1>
- <div class="container w-full mx-auto text-lg px-4 max-w-xl space-y-5">
- <div class="flex text-md text-secondary relative">
- <div class="mx-auto flex justify-center w-full gap-1">
- {#each presets as { start, end, title }, i}
- <a
- class:active={selection === i}
- href={`/${user.username}/payments/${getUnixTime(start) + "/"}1`}
+ <div class="container w-full mx-auto text-lg px-4 max-w-xl space-y-2">
+ <div class="mx-auto flex justify-center w-full gap-1">
+ {#each presets as { start, end, title }, i}
+ <a
+ class:active={selection === i}
+ href={`/payments/${getUnixTime(start) + "/"}1`}
+ >
+ <button
+ class="text-sm md:text-lg rounded-full border py-2 px-4 hover:opacity-80 min-w-[72px]"
>
- <button
- class="text-sm md:text-lg rounded-full border py-2 px-4 hover:opacity-80 min-w-[72px]"
- >
- <div class="my-auto">{title}</div>
- </button>
- </a>
- {/each}
- </div>
+ <div class="my-auto">{title}</div>
+ </button>
+ </a>
+ {/each}
</div>
- <div class="flex flex-wrap justify-center mb-8">
+ <div class="flex flex-wrap justify-center">
{#if pages.length > 1}
{#each pages as _, i}
<a
@@ -165,8 +172,8 @@
<div class="text-base">
{#each payments as p}
<a href={`/payment/${p.id}`}>
- <div class="grid grid-cols-3 border-b h-24 hover:bg-gray-100 px-4">
- <div class="whitespace-nowrap my-auto">
+ <div class="grid grid-cols-12 border-b h-24 hover:bg-gray-100 px-4">
+ <div class="whitespace-nowrap my-auto col-span-3">
<div class="font-bold" class:text-red-800={p.amount < 0}>
{f(Math.abs(p.amount) * (p.rate / sats), p.currency)}
{#if p.tip}
@@ -181,7 +188,9 @@
</div>
</div>
- <div class="flex my-auto">
+ <div
+ class="flex my-auto col-span-5 truncate text-ellipsis overflow-hidden mx-auto"
+ >
{#if p.type === types.pot}
<a href={`/pot/${p.memo}`}>
<div class="text-secondary flex">
@@ -195,18 +204,22 @@
{:else if p.with}
<div class="flex">
<div class="my-auto">
- <Avatar user={p.with} size={16} disabled={true} />
+ <Avatar user={p.with} size={12} disabled={true} />
</div>
<div class="my-auto ml-1 text-secondary">
{p.with.username}
</div>
</div>
{:else}
- <div class="text-secondary flex">
+ <div class="text-secondary flex gap-2">
{#if p.type === types.lightning}
<div class="text-3xl">⚡️</div>
+ {:else if p.type === types.ecash}
+ <img src="/images/cash.png" class="w-12" />
+ {:else if p.type === types.reconcile}
+ <Icon icon="balance" style="w-6" />
{:else if p.type === types.bitcoin}
- <div class="my-auto mr-1">
+ <div class="my-auto">
<img
src="/images/bitcoin.svg"
class="w-12 border-4 border-transparent"
@@ -214,7 +227,7 @@
/>
</div>
{:else if p.type === types.liquid}
- <div class="my-auto mr-1">
+ <div class="my-auto">
<img
src="/images/liquid.svg"
class="w-12 border-4 border-transparent"
@@ -234,12 +247,12 @@
{/if}
</div>
- <div class="text-secondary text-right text-sm my-auto">
+ <div class="text-secondary text-right text-sm my-auto col-span-3">
<div>
- {format(new Date(p.created), "h:mm aaa")}
+ {format(new Date(p.created), "h:mm aaa", { locale })}
</div>
<div>
- {format(new Date(p.created), "MMM d, yyyy")}
+ {format(new Date(p.created), "MMM d, yy", { locale })}
</div>
</div>
</div>
@@ -249,48 +262,52 @@
{/each}
</div>
- <div class="grid grid-cols-3 w-full text-center">
- <span class="text-lg text-secondary">{$t("payments.total")}</span>
- <span class="text-lg text-secondary">
- {#if payments.some((p) => p.tip > 0)}
- {$t("payments.tips")}
- {/if}
- </span>
- <span></span>
-
- {#each Object.keys(totals) as c}
- {@const total = totals[c]["fiat"]}
- {@const tips = totals[c]["fiatTips"]}
- {@const pv = (totals[c]["sats"] * rates[c]) / sats}
- {@const gain = (pv * 100) / total - 100}
- <span class="text-lg"><b>{f(total, c)}</b></span>
- <span class="text-lg">
-
- {#if payments.some((p) => p.tip > 0)}
- <b>{f(tips, c)}</b>
- {/if}
- <span></span>
-
+ <div class="grid grid-cols-3 w-full text-center text-lg">
+ {#each Object.keys(incoming) as c}
+ <span class="text-base text-secondary text-left" />
+ <!-- <span class="text-base text-secondary" -->
+ <!-- >{$t("payments.subtotal")}</span -->
+ <!-- > -->
+ <span class="text-base text-secondary">
+ {#if tipsIn || tipsOut}{$t("payments.tips")}{/if}
</span>
+ <span class="text-base text-secondary">{$t("payments.total")}</span>
+
+ {@const totalIn = incoming[c]?.fiat || 0}
+ {@const tipsIn = incoming[c]?.fiatTips || 0}
+ {@const subtotalIn = totalIn - tipsIn}
+
+ {@const totalOut = -outgoing[c]?.fiat || 0}
+ {@const tipsOut = outgoing[c]?.fiatTips || 0}
+ {@const subtotalOut = totalOut - tipsOut}
+
+ <span class="text-left text-base text-secondary"
+ >{$t("payments.income")}</span
+ >
+ <!-- <span><b>{subtotalIn ? f(subtotalIn, c) : "-"}</b></span> -->
+ <span><b>{tipsIn ? f(tipsIn, c) : "-"}</b></span>
+ <span><b>{totalIn ? f(totalIn, c) : "-"}</b></span>
+
+ <span class="text-left text-base text-secondary"
+ >{$t("payments.expenditure")}</span
+ >
+ <!-- <span><b>{subtotalOut ? f(subtotalOut, c) : "-"}</b></span> -->
+ <span><b>{tipsOut ? f(tipsOut, c) : "-"}</b></span>
+ <span><b>{totalOut ? f(totalOut, c) : "-"}</b></span>
{/each}
</div>
-
- <button
- class="ml-auto rounded-full border py-2 px-4 w-36 hover:opacity-80 flex mx-auto"
- on:click={csv}
- >
- <Icon icon="save" style="opacity-50 mr-2 my-auto" />
- <div class="my-auto">{$t("payments.export")}</div>
- </button>
</div>
+ <button
+ class="ml-auto rounded-2xl border py-5 px-6 hover:opacity-80 flex mx-auto text-xl gap-2"
+ on:click={csv}
+ >
+ <Icon icon="save" style="my-auto" />
+ <div class="my-auto">{$t("payments.export")}</div>
+ </button>
</div>
<style>
.active * {
@apply bg-black text-white border-black;
}
-
- .payments {
- view-transition-name: payments;
- }
</style>
diff --git a/src/routes/(app)/payments/[...page]/+server.ts b/src/routes/(app)/payments/[...page]/+server.ts
new file mode 100644
index 00000000..20315da4
--- /dev/null
+++ b/src/routes/(app)/payments/[...page]/+server.ts
@@ -0,0 +1,19 @@
+import { get, auth } from "$lib/utils";
+import { json } from "@sveltejs/kit";
+
+export async function GET({ cookies, params }) {
+ const parts = params.page.split("/");
+
+ let start;
+ let end;
+ if (parts.length === 1) [start] = parts;
+ if (parts.length === 2) [start, end] = parts;
+
+ if (!start) start = Date.now() / 1000 - 24 * 60 * 60;
+
+ let url = `/payments?start=${start * 1000}`;
+ if (end) url += `&end=${end * 1000}`;
+
+ const { payments } = await get(url, auth(cookies));
+ return json({ payments });
+}
diff --git a/src/routes/(app)/pin/+server.js b/src/routes/(app)/pin/+server.ts
index 76d407bf..d819ee5f 100644
--- a/src/routes/(app)/pin/+server.js
+++ b/src/routes/(app)/pin/+server.ts
@@ -2,6 +2,6 @@ import { json } from "@sveltejs/kit";
import { auth, post } from "$lib/utils";
export async function POST({ cookies, request }) {
- let result = await post("/pin", await request.json(), auth(cookies));
- return json(result);
+ const result = await post("/pin", await request.json(), auth(cookies));
+ return json(result);
}
diff --git a/src/routes/(app)/qr/[text]/+page.server.js b/src/routes/(app)/qr/[text]/+page.server.js
deleted file mode 100644
index 5eaafe57..00000000
--- a/src/routes/(app)/qr/[text]/+page.server.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import Qr from "qrcode-base64";
-
-export async function load({ params }) {
- let { text } = params;
- let src = Qr.drawImg(text, { size: 600 });
-
- return { src, text };
-}
diff --git a/src/routes/(app)/qr/[text]/+page.server.ts b/src/routes/(app)/qr/[text]/+page.server.ts
new file mode 100644
index 00000000..09e7593f
--- /dev/null
+++ b/src/routes/(app)/qr/[text]/+page.server.ts
@@ -0,0 +1,8 @@
+import Qr from "qrcode-base64";
+
+export async function load({ params }) {
+ const { text } = params;
+ const src = Qr.drawImg(text, { size: 600 });
+
+ return { src, text };
+}
diff --git a/src/routes/(app)/qr/[text]/+page.svelte b/src/routes/(app)/qr/[text]/+page.svelte
index da164b50..e073b66e 100644
--- a/src/routes/(app)/qr/[text]/+page.svelte
+++ b/src/routes/(app)/qr/[text]/+page.svelte
@@ -1,25 +1,22 @@
<script>
import Icon from "$comp/Icon.svelte";
import Qr from "$comp/Qr.svelte";
- import { back } from "$lib/utils";
+ import { back, copy } from "$lib/utils";
export let data;
let { src, text } = data;
</script>
-<button class="ml-5 md:ml-20 mt-5 md:mt-10 hover:opacity-80" on:click={back}>
- <Icon icon="arrow-left" style="w-10" />
-</button>
-
<div class="container px-4 max-w-4xl mx-auto space-y-5">
- <div class="flex justify-center items-center">
- <div
- class="md:shadow-xl rounded-3xl md:px-10 pt-5 pb-10 space-y-5 w-full md:mx-5"
- >
- <Qr {src} />
+ <Qr {src} />
- <div class="text-center w-full text-lg break-all">
- {text}
- </div>
+ <button
+ type="button"
+ class="flex gap-2 text-center break-all rounded-2xl hover:opacity-80 py-5 px-6 w-full mx-auto justify-center border text-xl hover:bg-slate-100"
+ on:click={() => copy(text)}
+ >
+ <Icon icon="copy" style="w-8" />
+ <div class="my-auto">
+ {text}
</div>
- </div>
+ </button>
</div>
diff --git a/src/routes/(app)/qr/create/+page.svelte b/src/routes/(app)/qr/create/+page.svelte
new file mode 100644
index 00000000..fd99a54b
--- /dev/null
+++ b/src/routes/(app)/qr/create/+page.svelte
@@ -0,0 +1,60 @@
+<script>
+ import { goto } from "$app/navigation";
+ import { browser } from "$app/environment";
+ import { t } from "$lib/translations";
+ import Icon from "$comp/Icon.svelte";
+ let el, text, pasted;
+
+ let keypress = (e) =>
+ e.key === "Enter" ? e.preventDefault() || el.click() : (pasted = false);
+
+ let paste = async () => {
+ text = await navigator.clipboard.readText();
+ pasted = true;
+ };
+
+ let submit = () => goto(`/qr/${encodeURIComponent(text)}`);
+
+ $: if (browser && pasted && text) el.click() && (pasted = false);
+</script>
+
+<div class="container px-4 max-w-lg mx-auto space-y-5 mt-20">
+ <h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold">
+ Create QR
+ </h1>
+
+ <form on:submit|preventDefault={submit} class="space-y-2 text-xl">
+ <div class="mb-2">
+ <textarea
+ use:focus
+ name="text"
+ placeholder="Enter some text or a URL to put in a QR"
+ on:keypress={keypress}
+ class="w-full p-4 border rounded-xl h-32 text-xl"
+ bind:value={text}
+ on:paste={() => (pasted = true)}
+ autocapitalize="none"
+ />
+ </div>
+
+ <div class="flex gap-2">
+ <button
+ type="button"
+ class="flex border rounded-2xl px-6 py-5 font-bold hover:opacity-80 w-full bg-primary justify-center gap-2"
+ on:click={paste}
+ >
+ <Icon icon="paste" style="w-8 my-auto" />
+ <div class="my-auto">{$t("user.send.paste")}</div>
+ </button>
+
+ <button
+ bind:this={el}
+ type="submit"
+ class="flex bg-black text-white border rounded-2xl px-6 py-5 w-full font-bold gap-2 justify-center"
+ >
+ <Icon icon="send" style="w-8 my-auto invert" />
+ <div class="my-auto">{$t("user.dashboard.go")}</div>
+ </button>
+ </div>
+ </form>
+</div>
diff --git a/src/routes/(app)/receive/[...token]/+page.server.ts b/src/routes/(app)/receive/[...token]/+page.server.ts
new file mode 100644
index 00000000..05b2dad8
--- /dev/null
+++ b/src/routes/(app)/receive/[...token]/+page.server.ts
@@ -0,0 +1,17 @@
+import { fd } from "$lib/utils";
+import { fail, redirect } from "@sveltejs/kit";
+import parse from "$lib/parse";
+
+export async function load({ params, parent, url }) {
+ const { user } = await parent();
+ if (!user) redirect(307, `/register?redirect=${url.pathname}`);
+ await parse(params.token, url.host);
+}
+
+export const actions = {
+ default: async ({ request, url }) => {
+ const { text } = await fd(request);
+ await parse(text, url.host);
+ return fail(400, { error: "default" });
+ },
+};
diff --git a/src/routes/(app)/receive/[...token]/+page.svelte b/src/routes/(app)/receive/[...token]/+page.svelte
new file mode 100644
index 00000000..988c1e6c
--- /dev/null
+++ b/src/routes/(app)/receive/[...token]/+page.svelte
@@ -0,0 +1,90 @@
+<script>
+ import { page } from "$app/stores";
+ import { fly } from "svelte/transition";
+ import { enhance } from "$app/forms";
+ import { tick } from "svelte";
+ import { browser } from "$app/environment";
+ import { t } from "$lib/translations";
+ import Avatar from "$comp/Avatar.svelte";
+ import Icon from "$comp/Icon.svelte";
+ import Spinner from "$comp/Spinner.svelte";
+ import { back, fail, focus } from "$lib/utils";
+
+ export let data;
+ export let form;
+
+ let { token } = data;
+ data.subject = data.user;
+
+ let el, text, pasted, w;
+
+ let keypress = (e) => e.key === "Enter" && (e.preventDefault() || el.click());
+
+ let paste = async () => {
+ text = await navigator.clipboard.readText();
+ };
+
+ $: if (browser && pasted && text) el.click() && (pasted = false);
+</script>
+
+<svelte:window bind:innerWidth={w} />
+
+<div class="container px-4 max-w-lg mx-auto space-y-5 mt-20">
+ <h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold">
+ {$t("user.dashboard.receive")}
+ </h1>
+
+ <form method="POST" use:enhance class="space-y-2 text-xl">
+ {#if form?.error}
+ <div class="mb-5">
+ <div class="text-red-600">
+ {form.error === "default"
+ ? $t("error.unrecognizedInput")
+ : form.error}
+ </div>
+ </div>
+ {/if}
+
+ <div class="mb-2">
+ <textarea
+ use:focus
+ name="text"
+ placeholder={$t("payments.voucherText")}
+ on:keypress={keypress}
+ class="w-full p-4 border rounded-xl h-32 text-xl"
+ bind:value={text}
+ on:paste={() => (pasted = true)}
+ autocapitalize="none"
+ />
+ </div>
+
+ <div class="flex gap-2">
+ <a href="/scan" class="w-full">
+ <button
+ type="button"
+ class="flex border rounded-2xl px-5 py-4 hover:opacity-80 w-full justify-center gap-1"
+ >
+ <Icon icon="camera" style="w-8 my-auto" />
+ <div class="my-auto">{$t("user.send.scan")}</div>
+ </button>
+ </a>
+
+ <button
+ type="button"
+ class="flex border rounded-2xl px-5 py-4 hover:opacity-80 w-full justify-center gap-1"
+ on:click={paste}
+ >
+ <Icon icon="paste" style="w-8 my-auto" />
+ <div class="my-auto">{$t("user.send.paste")}</div>
+ </button>
+ </div>
+
+ <button
+ bind:this={el}
+ type="submit"
+ class="bg-black text-white border rounded-2xl px-6 py-5 w-full font-bold"
+ >
+ {$t("user.send.next")}
+ </button>
+ </form>
+</div>
diff --git a/src/routes/(app)/redeem/[redeemcode]/+page.server.js b/src/routes/(app)/redeem/[redeemcode]/+page.server.js
deleted file mode 100644
index 25153533..00000000
--- a/src/routes/(app)/redeem/[redeemcode]/+page.server.js
+++ /dev/null
@@ -1,17 +0,0 @@
-import { error, redirect } from "@sveltejs/kit";
-import { auth, post } from "$lib/utils";
-
-export async function load({ cookies, locals, params }) {
- let { user } = locals;
-
- if (user) {
- try {
- await post("/redeem", params, auth(cookies));
- } catch (e) {
- redirect(307, "/");
- }
- redirect(307, `/${user.username}/payments`);
- }
-
- redirect(307, "/login");
-}
diff --git a/src/routes/(app)/redeem/[redeemcode]/+page.svelte b/src/routes/(app)/redeem/[redeemcode]/+page.svelte
deleted file mode 100644
index b2fcf2f4..00000000
--- a/src/routes/(app)/redeem/[redeemcode]/+page.svelte
+++ /dev/null
@@ -1,4 +0,0 @@
-<script>
- import { loginRedirect } from "$lib/store";
- $loginRedirect = undefined;
-</script>
diff --git a/src/routes/(app)/register/+page.server.js b/src/routes/(app)/register/+page.server.js
deleted file mode 100644
index 318f6b98..00000000
--- a/src/routes/(app)/register/+page.server.js
+++ /dev/null
@@ -1,41 +0,0 @@
-import { fail, redirect } from "@sveltejs/kit";
-import { fd, post, login } from "$lib/utils";
-
-export const load = async ({ parent }) => {
- let { user } = await parent();
- if (user) redirect(307, `/${user.username}`);
-
- let index = Math.floor(Math.random() * 64) + 1;
-
- return { index };
-};
-
-export const actions = {
- default: async ({ cookies, request }) => {
- let ip = request.headers.get("cf-connecting-ip");
-
- let form = await fd(request);
- let { profile, username, password, cipher, salt, pubkey, loginRedirect } =
- form;
- let user = { profile, username, password, cipher, salt, pubkey };
- let error;
-
- if (loginRedirect === "undefined") loginRedirect = undefined;
-
- try {
- await post("/register", { user }, { "cf-connecting-ip": ip });
- } catch (e) {
- if (e.message.includes("taken")) error = e.message;
- }
-
- try {
- await login(user, cookies, ip);
- error = null;
- } catch (e) {
- error ||= e.message;
- }
-
- if (error) return fail(400, { error });
- redirect(307, loginRedirect || `/${user.username}`);
- },
-};
diff --git a/src/routes/(app)/register/+page.svelte b/src/routes/(app)/register/+page.svelte
deleted file mode 100644
index 5783059a..00000000
--- a/src/routes/(app)/register/+page.svelte
+++ /dev/null
@@ -1,315 +0,0 @@
-<script>
- import punks from "$lib/punks";
- import { upload } from "$lib/upload";
- import { afterNavigate, invalidateAll } from "$app/navigation";
- import { applyAction, deserialize } from "$app/forms";
- import { tick } from "svelte";
- import { fly } from "svelte/transition";
- import { enhance } from "$app/forms";
-
- import Pin from "$comp/Pin.svelte";
- import Icon from "$comp/Icon.svelte";
- import Spinner from "$comp/Spinner.svelte";
-
- import { focus, fail } from "$lib/utils";
- import { avatar, password, loginRedirect } from "$lib/store";
- import { t } from "$lib/translations";
- import { page } from "$app/stores";
- import { generate } from "$lib/nostr";
- import {
- NumberDictionary,
- uniqueNamesGenerator,
- colors,
- adjectives,
- animals,
- } from "unique-names-generator";
-
- export let form;
- export let data;
-
- $: data && ($avatar = undefined);
- let username;
- let { index } = data;
-
- let cleared;
- let clear = () => {
- if (!cleared) {
- cleared = true;
- username = "";
- $password = "";
- revealPassword = false;
- }
- };
-
- let refresh = async () => {
- username = uniqueNamesGenerator({
- dictionaries: [animals, NumberDictionary.generate({ min: 10, max: 99 })],
- length: 2,
- separator: "",
- });
-
- $password = uniqueNamesGenerator({
- dictionaries: [colors, NumberDictionary.generate({ min: 100, max: 999 })],
- length: 2,
- separator: "",
- });
-
- revealPassword = true;
- };
-
- afterNavigate(async () => {
- try {
- await invalidateAll();
- } catch (e) {
- console.log(e);
- }
- });
-
- let token, formElement;
- let code = [];
- let redirect;
-
- $: need2fa = form?.message === "2fa";
- let cancel = () => (need2fa = false);
- $: if (form?.message === "2fa" && form.token === token) token = "";
-
- let email, btn;
-
- $: update(form);
- let update = (form) => form && ({ username, password: $password } = form);
-
- $: token && token?.length === 6 && tick().then(() => btn.click());
-
- let revealPassword;
-
- let loading;
- async function handleSubmit(e) {
- loading = true;
-
- let data = new FormData(this);
- let user = Object.fromEntries(data);
- await generate(user);
-
- for (let k in user) {
- data.set(k, user[k]);
- }
-
- data.set("profile", punks[index]);
- if ($avatar) {
- try {
- let { hash } = JSON.parse(
- await upload($avatar.file, $avatar.type, $avatar.progress, token)
- );
-
- data.set("profile", hash);
- await fetch(`/api/public/${hash}.webp`, {
- cache: "reload",
- mode: "no-cors",
- });
- } catch (e) {
- console.log("problem uploading avatar", e);
- }
- }
-
- const response = await fetch("/register", {
- method: "POST",
- body: data,
- });
-
- const result = deserialize(await response.text());
-
- if (result.type === "success") {
- await invalidateAll();
- }
-
- applyAction(result);
- loading = false;
- }
-
- let avatarInput;
- $: src = `/api/public/${punks[index]}.webp`;
- let decr = () => (index = index <= 0 ? 63 : index - 1);
- let incr = () => (index = index >= 63 ? 0 : index + 1);
- let selectAvatar = () => avatarInput.click();
-
- let progress;
- let handleFile = async ({ target }) => {
- let type = "profile";
- let file = target.files[0];
- if (!file) return;
-
- if (file.size > 10000000) form.error = "File too large";
- $avatar = { file, type, progress };
-
- var reader = new FileReader();
- reader.onload = async (e) => {
- src = e.target.result;
- };
-
- reader.readAsDataURL(file);
- };
-</script>
-
-{#if need2fa}
- <Pin bind:value={token} title="Enter 2FA Code" {cancel} notify={false} />
-{/if}
-
-<div class="pt-4">
- <div class="w-[243px] mx-auto">
- <a href="/">
- <Icon icon="logo" />
- </a>
- </div>
-
- <div class="flex justify-center items-center">
- <div
- class="shadow-xl rounded-3xl p-4 pt-0 space-y-5 w-full mx-5 md:mx-0 md:w-[400px]"
- >
- <input
- type="file"
- class="hidden"
- bind:this={avatarInput}
- on:change={(e) => handleFile(e, "profile")}
- />
-
- <div class="relative">
- <button
- class="absolute w-8 h-12 left-12 bg-white rounded top-12"
- on:click={decr}
- >
- <Icon icon="chevron-left" style="w-8 " />
- </button>
- <div class="relative w-32 mx-auto" on:click={selectAvatar}>
- <button
- class="w-32 h-32 rounded-full border-4 border-white overflow-hidden flex mx-auto relative"
- >
- <img
- {src}
- class="w-full h-full object-cover object-center overflow-hidden"
- alt={username}
- />
- </button>
- <button
- class="absolute bg-white rounded-full p-2 mx-auto right-0 bottom-0 z-10 bg-opacity-80"
- >
- <Icon icon="upload" style="w-8" />
- </button>
- </div>
- <button
- class="absolute w-8 h-12 right-12 bg-white rounded top-12"
- on:click={incr}
- >
- <Icon icon="chevron-left" style="w-8 rotate-180" />
- </button>
- </div>
-
- {#if form?.error}
- <div class="text-red-600 text-center" in:fly>
- {form.error}
- </div>
- {/if}
-
- <form
- class="space-y-5"
- on:submit|preventDefault={handleSubmit}
- method="POST"
- >
- <input
- type="hidden"
- name="loginRedirect"
- value={$loginRedirect || $page.url.searchParams.get("redirect")}
- />
- <input type="hidden" name="token" value={token} />
-
- <div class="relative">
- <label for="username" class="font-semibold"
- >{$t("login.username")}</label
- >
- <input
- use:focus
- tabindex="1"
- name="username"
- type="text"
- required
- class="bg-primary"
- bind:value={username}
- on:focus={clear}
- autocapitalize="none"
- />
- <button
- type="button"
- on:click={refresh}
- class="absolute right-0 top-4"
- tabindex="5"
- >
- <Icon icon="random" style="w-10 m-4" />
- </button>
- </div>
-
- <div class="relative">
- <label for="password" class="block font-semibold"
- >{$t("login.password")}</label
- >
- {#if revealPassword}
- <input
- tabindex="2"
- name="password"
- type="text"
- required
- class="bg-primary"
- bind:value={$password}
- autocapitalize="none"
- />
- {:else}
- <input
- tabindex="2"
- name="password"
- type="password"
- required
- class="bg-primary"
- bind:value={$password}
- autocapitalize="none"
- on:focus={clear}
- />
- {/if}
- <button
- type="button"
- tabindex="4"
- on:click={() => (revealPassword = !revealPassword)}
- class="absolute right-0 top-4"
- >
- <Icon icon={revealPassword ? "eye" : "eye-off"} style="m-6" />
- </button>
- </div>
-
- <p class="text-secondary text-sm">
- {$t("login.passwordRecommendation")}
- </p>
-
- <button
- tabindex="3"
- type="submit"
- class="bg-black text-white w-full rounded-2xl p-4 font-semibold hover:opacity-80"
- disabled={loading}
- bind:this={btn}
- >
- {#if loading}
- <Spinner />
- {:else}
- {$t("login.register")}
- {/if}
- </button>
- </form>
-
- <p class="text-secondary text-center font-medium">
- {$t("login.haveAccount")}
- <a
- href={"/login"}
- class="block md:inline text-black underline underline-offset-4 hover:opacity-80"
- >
- {$t("login.signIn")}
- </a>
- </p>
- </div>
- </div>
-</div>
diff --git a/src/routes/(app)/fund/[id]/withdraw/+server.js b/src/routes/(app)/reset/+server.ts
index 96d66413..4e8deeaa 100644
--- a/src/routes/(app)/fund/[id]/withdraw/+server.js
+++ b/src/routes/(app)/reset/+server.ts
@@ -2,5 +2,6 @@ import { json } from "@sveltejs/kit";
import { auth, post } from "$lib/utils";
export async function POST({ cookies, request }) {
- return json(await post("/take", await request.json(), auth(cookies)));
+ const result = await post("/reset", await request.json(), auth(cookies));
+ return json(result);
}
diff --git a/src/routes/(app)/reset/[code]/+page.server.js b/src/routes/(app)/reset/[code]/+page.server.js
deleted file mode 100644
index 67f2d919..00000000
--- a/src/routes/(app)/reset/[code]/+page.server.js
+++ /dev/null
@@ -1,30 +0,0 @@
-import { fail, redirect } from "@sveltejs/kit";
-import { fd, post, login } from "$lib/utils";
-
-export const actions = {
- default: async ({ cookies, params, request }) => {
- let ip = request.headers.get("cf-connecting-ip");
- let error;
-
- let { code } = params;
- let { password } = await fd(request);
-
- try {
- let user = await post("/reset", { code, password });
- user.password = password;
-
- try {
- await login(user, cookies, ip);
- error = null;
- } catch (e) {
- error ||= e.message;
- }
-
- if (error) return fail(400, { error });
- redirect(307, `/${user.username}`);
- } catch (e) {
- console.log(e.message);
- return fail(400, { error: e.message });
- }
- },
-};
diff --git a/src/routes/(app)/reset/[code]/+page.server.ts b/src/routes/(app)/reset/[code]/+page.server.ts
new file mode 100644
index 00000000..533e21f5
--- /dev/null
+++ b/src/routes/(app)/reset/[code]/+page.server.ts
@@ -0,0 +1,30 @@
+import { fail, redirect } from "@sveltejs/kit";
+import { fd, post, login } from "$lib/utils";
+
+export const actions = {
+ default: async ({ cookies, params, request }) => {
+ const ip = request.headers.get("cf-connecting-ip");
+ let error;
+
+ const { code } = params;
+ const { password } = await fd(request);
+
+ try {
+ const user = await post("/reset", { code, password });
+ user.password = password;
+
+ try {
+ await login(user, cookies, ip);
+ error = null;
+ } catch (e: any) {
+ error ||= e.message;
+ }
+
+ if (error) return fail(400, { error });
+ redirect(307, `/${user.username}`);
+ } catch (e: any) {
+ console.log(e.message);
+ return fail(400, { error: e.message });
+ }
+ },
+};
diff --git a/src/routes/(app)/scan/[email protected] b/src/routes/(app)/scan/[email protected]
new file mode 100644
index 00000000..16ba5888
--- /dev/null
+++ b/src/routes/(app)/scan/[email protected]
@@ -0,0 +1,3 @@
+<div class="container mt-4">
+ <slot />
+</div>
diff --git a/src/routes/(app)/scan/+page.svelte b/src/routes/(app)/scan/+page.svelte
index e23b9bb8..e9bf4fd6 100644
--- a/src/routes/(app)/scan/+page.svelte
+++ b/src/routes/(app)/scan/+page.svelte
@@ -1,35 +1,42 @@
<script>
+ import { tick } from "svelte";
import Icon from "$comp/Icon.svelte";
import QrScanner from "qr-scanner";
import { onMount, onDestroy } from "svelte";
import { back } from "$lib/utils";
import { goto } from "$app/navigation";
- let scanner, vid;
- onMount(() => {
- scanner = new QrScanner(
- vid,
- ({ data }) => scanner.stop() || goto(`/send/${encodeURI(data)}`),
- {
- highlightScanRegion: true,
- highlightCodeOutline: true,
- }
- );
+ let scanner, vid, resizing;
+
+ let resize = () => {
+ if (resizing) clearTimeout(resizing);
+ resizing = setTimeout(initialize, 1000);
+ };
+
+ let initialize = async () => {
+ if (scanner) {
+ scanner.stop();
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+
+ let options = { highlightScanRegion: true, highlightCodeOutline: true };
+ let cb = ({ data }) => scanner.stop() || goto(`/send/${encodeURI(data)}`);
+ scanner = new QrScanner(vid, cb, options);
+ await tick();
scanner.start();
- });
+ };
+ onMount(initialize);
onDestroy(() => scanner?.stop());
</script>
-<button class="ml-5 md:ml-20 mt-5 md:mt-10 hover:opacity-80" on:click={back}>
- <Icon icon="arrow-left" style="w-10" />
-</button>
+<svelte:window on:resize={resize} />
<div class="flex w-full mb-4 px-4">
<div class="bg-black mx-auto rounded-3xl">
<video
bind:this={vid}
- class="border-4 rounded-3xl border-black md:max-w-[600px] !max-h-[80vh] !min-w-[300px]"
+ class="border-4 rounded-3xl border-black max-h-[calc(100vh*0.7)]"
/>
</div>
</div>
diff --git a/src/routes/(app)/send/+layout.svelte b/src/routes/(app)/send/+layout.svelte
index 5e379c32..9e14fa39 100644
--- a/src/routes/(app)/send/+layout.svelte
+++ b/src/routes/(app)/send/+layout.svelte
@@ -9,7 +9,7 @@
let cancel = () => goto(`/${user.username}`);
</script>
-{#if user.haspin && (!$pin || $pin?.length !== 6)}
+{#if user?.haspin && (!$pin || $pin?.length !== 6)}
<Pin bind:value={$pin} {cancel} />
{/if}
diff --git a/src/routes/(app)/send/[...text]/+page.server.js b/src/routes/(app)/send/[...text]/+page.server.js
deleted file mode 100644
index 061eb35f..00000000
--- a/src/routes/(app)/send/[...text]/+page.server.js
+++ /dev/null
@@ -1,98 +0,0 @@
-import { validate } from "bitcoin-address-validation";
-import bip21 from "bip21";
-import { auth, get, isLiquid, post } from "$lib/utils";
-import { fail, redirect } from "@sveltejs/kit";
-import { PUBLIC_DOMAIN } from "$env/static/public";
-
-let parse = async (t, host) => {
- if (!t) return;
-
- if (t.startsWith("http")) redirect(307, t);
- if (t.startsWith(host)) redirect(307, `http://${t}`);
-
- let amount, user, id;
-
- t = t.trim();
- t.toLowerCase().startsWith("bitcoin:") &&
- ({
- address: t,
- options: { amount },
- } = bip21.decode(t));
-
- if (t.startsWith("lightning:")) t = t.replace("lightning:", "");
- if (t.endsWith(`@${PUBLIC_DOMAIN}`)) t = t.split("@")[0];
- if (t.includes("@") && t.includes(".")) {
- try {
- t = await get(`/encode?address=${t}`);
- } catch (e) {}
- }
-
- if (t.includes("/fund")) redirect(307, t.substring(t.indexOf("/fund")));
-
- // lightning
- if (t.toLowerCase().startsWith("lightning:"))
- t = t.toLowerCase().replace("lightning:", "");
- if (t.toLowerCase().startsWith("lnurl")) redirect(307, `/ln/${t}`);
- if (t.includes(":")) t = t.split(":")[1];
-
- if (t.toLowerCase().startsWith("ln")) {
- try {
- ({ id } = await get(`/invoice/${t}`));
- } catch (e) {
- redirect(307, `/send/lightning/${t}`);
- }
- }
-
- // bitcoin
- if (validate(t) || isLiquid(t)) {
- try {
- ({ id, user } = await get(`/invoice/${t}`));
- } catch (e) {
- let r = `/send/bitcoin/${t}`;
- if (amount) r += "/" + amount;
- redirect(307, r);
- }
-
- if (user) redirect(307, `/send/${user.username}`);
- else if (id) redirect(307, `/send/${id}`);
- }
-
- // user
- try {
- user = await get(`/users/${t.split("/")[0]}`);
- if (user.anon) user = null;
- } catch (e) {}
-
- if (user) redirect(307, `/send/user/${t}`);
-
- let fund;
- try {
- fund = await get(`/fund/${t}`);
- } catch (e) {}
-
- if (fund) redirect(307, `/send/fund/${t}`);
-
- // invoice
- let invoice;
- try {
- invoice = await get(`/invoice/${t}`);
- } catch (e) {}
-
- if (invoice) redirect(307, `/send/invoice/${invoice.hash}`);
-};
-
-export async function load({ cookies, params, request, url }) {
- let { text } = params;
- await parse(text, url.host);
- let contacts = await get("/contacts", auth(cookies));
- return { contacts };
-}
-
-export const actions = {
- default: async ({ request, url }) => {
- const form = await request.formData();
- let t = form.get("text");
- await parse(t, url.host);
- return fail(400, { error: true });
- },
-};
diff --git a/src/routes/(app)/send/[...text]/+page.server.ts b/src/routes/(app)/send/[...text]/+page.server.ts
new file mode 100644
index 00000000..b0baa2d5
--- /dev/null
+++ b/src/routes/(app)/send/[...text]/+page.server.ts
@@ -0,0 +1,19 @@
+import { auth, fd, get } from "$lib/utils";
+import { fail } from "@sveltejs/kit";
+import parse from "$lib/parse";
+
+export async function load({ cookies, params, url }) {
+ const { text } = params;
+
+ await parse(text, url.host);
+ const contacts = await get("/contacts", auth(cookies));
+ return { contacts };
+}
+
+export const actions = {
+ default: async ({ request, url }) => {
+ const { text } = await fd(request);
+ await parse(text, url.host);
+ return fail(400, { error: "default" });
+ },
+};
diff --git a/src/routes/(app)/send/[...text]/+page.svelte b/src/routes/(app)/send/[...text]/+page.svelte
index 71db4e55..d27df639 100644
--- a/src/routes/(app)/send/[...text]/+page.svelte
+++ b/src/routes/(app)/send/[...text]/+page.svelte
@@ -5,7 +5,6 @@
import { tick } from "svelte";
import { browser } from "$app/environment";
import { t } from "$lib/translations";
- import AppHeader from "$comp/AppHeader.svelte";
import Avatar from "$comp/Avatar.svelte";
import Icon from "$comp/Icon.svelte";
import Spinner from "$comp/Spinner.svelte";
@@ -16,20 +15,23 @@
data.subject = data.user;
let { contacts } = data;
- let w;
- let el, text;
+ let el, text, pasted, w;
- let keypress = (e) => e.key === "Enter" && (e.preventDefault() || el.click());
+ let keypress = (e) =>
+ e.key === "Enter" ? e.preventDefault() || el.click() : (pasted = false);
let paste = async () => {
text = await navigator.clipboard.readText();
+ await tick();
+ pasted = true;
};
+
+ $: if (browser && pasted && text) el.click() && (pasted = false);
</script>
<svelte:window bind:innerWidth={w} />
-<AppHeader {data} />
<div class="container px-4 max-w-lg mx-auto space-y-5 mt-20">
<h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold">
{$t("payments.send")}
@@ -39,7 +41,9 @@
{#if form?.error}
<div class="mb-5">
<div class="text-red-600">
- {$t("error.unrecognizedInput")}
+ {form.error === "default"
+ ? $t("error.unrecognizedInput")
+ : form.error}
</div>
</div>
{/if}
@@ -50,8 +54,9 @@
name="text"
placeholder={$t("user.send.placeholder")}
on:keypress={keypress}
- class="w-full p-4 border rounded-xl h-48 text-xl"
+ class="w-full p-4 border rounded-xl h-32 text-xl"
bind:value={text}
+ on:paste={() => (pasted = true)}
autocapitalize="none"
/>
</div>
@@ -60,30 +65,43 @@
<a href="/scan" class="w-full">
<button
type="button"
- class="flex border rounded-2xl px-6 py-5 font-bold hover:opacity-80 w-full bg-primary justify-center"
+ class="flex border rounded-2xl px-5 py-4 hover:opacity-80 w-full justify-center gap-2"
>
- <Icon icon="camera" style="mr-2 w-6 my-auto" />
+ <Icon icon="camera" style="w-8 my-auto" />
<div class="my-auto">{$t("user.send.scan")}</div>
</button>
</a>
<button
type="button"
- class="flex border rounded-2xl px-6 py-5 font-bold hover:opacity-80 w-full bg-primary justify-center"
+ class="flex border rounded-2xl px-5 py-4 hover:opacity-80 w-full justify-center gap-2"
on:click={paste}
>
- <Icon icon="paste" style="mr-2 w-6 my-auto" />
+ <Icon icon="paste" style="w-8 my-auto" />
<div class="my-auto">{$t("user.send.paste")}</div>
</button>
</div>
- <button
- bind:this={el}
- type="submit"
- class="bg-black text-white border rounded-2xl px-6 py-5 w-full font-bold"
- >
- {$t("user.send.next")}
- </button>
+ <div class="flex gap-2 flex-wrap">
+ <button
+ bind:this={el}
+ type="submit"
+ class="flex bg-black text-white border rounded-2xl px-6 py-5 w-full font-bold gap-2 justify-center"
+ >
+ <Icon icon="send" style="w-8 my-auto invert" />
+ <div class="my-auto">{$t("user.send.next")}</div>
+ </button>
+
+ <a href="/send/ecash" class="contents">
+ <button
+ type="button"
+ class="flex border rounded-2xl px-6 py-5 w-full font-bold gap-2 justify-center text-xl bg-primary"
+ >
+ <img src="/images/cash.png" class="w-8" />
+ <div class="my-auto">{$t("payments.createEcash")}</div>
+ </button>
+ </a>
+ </div>
</form>
{#if contacts.length}
@@ -93,7 +111,7 @@
</h1>
<div>
{#each contacts as c}
- <a href={`/send/${c.username}`}>
+ <a href={`/pay/${c.username}`}>
<div
class="border-b p-2 last:border-b-0 hover:bg-gray-100 rounded-2xl"
>
diff --git a/src/routes/(app)/send/bitcoin/[address]/+layout.server.ts b/src/routes/(app)/send/bitcoin/[address]/+layout.server.ts
new file mode 100644
index 00000000..68191311
--- /dev/null
+++ b/src/routes/(app)/send/bitcoin/[address]/+layout.server.ts
@@ -0,0 +1,23 @@
+import { auth, get } from "$lib/utils";
+import { redirect } from "@sveltejs/kit";
+
+export async function load({ cookies, params, parent }) {
+ const { user } = await parent();
+ const aid = cookies.get("aid");
+ const { address } = params;
+ const { balance } = await get(`/account/${aid}`, auth(cookies));
+
+ try {
+ const invoice = await get(`/invoice/${address}`);
+
+ if (invoice) {
+ const recipient = await get(`/users/${invoice.uid}`);
+ if (recipient?.id !== user.id)
+ redirect(307, `/pay/${recipient.username}`);
+ }
+ } catch (e) {
+ // invoice not found
+ }
+
+ return { balance };
+}
diff --git a/src/routes/(app)/send/bitcoin/[address]/+page.server.ts b/src/routes/(app)/send/bitcoin/[address]/+page.server.ts
new file mode 100644
index 00000000..f27d3fab
--- /dev/null
+++ b/src/routes/(app)/send/bitcoin/[address]/+page.server.ts
@@ -0,0 +1,7 @@
+import { auth, get } from "$lib/utils";
+
+export async function load({ cookies }) {
+ const aid = cookies.get("aid");
+ const { balance } = await get(`/account/${aid}`, auth(cookies));
+ return { balance };
+}
diff --git a/src/routes/(app)/send/bitcoin/[address]/+page.svelte b/src/routes/(app)/send/bitcoin/[address]/+page.svelte
index 838c5c04..6b938c38 100644
--- a/src/routes/(app)/send/bitcoin/[address]/+page.svelte
+++ b/src/routes/(app)/send/bitcoin/[address]/+page.svelte
@@ -8,9 +8,9 @@
export let data;
- let { rates, user } = data;
+ let { balance, rates, user } = data;
let { address } = $page.params;
- let { balance, currency, username } = user;
+ let { currency, username } = user;
let amount = 0;
let submit, fiat;
@@ -24,12 +24,6 @@
};
</script>
-<a href="/send">
- <button type="button" class="ml-5 md:ml-20 mt-5 md:mt-10 hover:opacity-80">
- <Icon icon="arrow-left" style="w-10" />
- </button>
-</a>
-
<div class="container px-4 max-w-xl mx-auto space-y-5 text-center">
<h1 class="text-3xl md:text-4xl font-semibold mb-2">{$t("payments.send")}</h1>
diff --git a/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.server.js b/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.server.js
deleted file mode 100644
index d4498b39..00000000
--- a/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.server.js
+++ /dev/null
@@ -1,35 +0,0 @@
-import { fail, redirect } from "@sveltejs/kit";
-import { auth, post, fd } from "$lib/utils";
-
-let seen = {};
-
-export async function load({ params: { address, amount, feeRate }, cookies }) {
- try {
- let { fee, fees, ourfee, hex } = await post(
- "/bitcoin/fee",
- { address, amount, feeRate },
- auth(cookies)
- );
-
- return { amount, address, fee, fees, feeRate, ourfee, hex };
- } catch (e) {
- return { amount, address, feeRate, message: e.message };
- }
-}
-
-export const actions = {
- default: async ({
- cookies,
- params: { address, amount, feeRate },
- request,
- }) => {
- try {
- let r = await post("/bitcoin/send", await fd(request), auth(cookies));
- } catch (e) {
- console.log("problem sending bitcoin", e);
- return fail(400, { address, amount, feeRate, message: e.message });
- }
-
- redirect(307, "/sent");
- },
-};
diff --git a/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.server.ts b/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.server.ts
new file mode 100644
index 00000000..1122e689
--- /dev/null
+++ b/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.server.ts
@@ -0,0 +1,49 @@
+import { auth, fd, get, post } from "$lib/utils";
+import { fail, redirect } from "@sveltejs/kit";
+
+export async function load({ params: { address, amount, feeRate }, cookies }) {
+ const aid = cookies.get("aid");
+
+ try {
+ const { fee, fees, inputs, ourfee, hex } = await post(
+ "/bitcoin/fee",
+ { address, amount, feeRate, aid },
+ auth(cookies),
+ );
+
+ const account = await get(`/account/${aid}`, auth(cookies));
+
+ return {
+ account,
+ amount,
+ address,
+ fee,
+ fees,
+ feeRate,
+ ourfee,
+ hex,
+ inputs,
+ };
+ } catch (e: any) {
+ return { amount, address, feeRate, message: e.message };
+ }
+}
+
+export const actions = {
+ default: async ({
+ cookies,
+ params: { address, amount, feeRate },
+ request,
+ }) => {
+ let p;
+ try {
+ const body = await fd(request);
+ p = await post("/bitcoin/send", body, auth(cookies));
+ } catch (e: any) {
+ console.log("problem sending bitcoin", e);
+ return fail(400, { address, amount, feeRate, message: e.message });
+ }
+
+ redirect(307, `/sent/${p.id}`);
+ },
+};
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 84506e6b..903bd372 100644
--- a/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.svelte
+++ b/src/routes/(app)/send/bitcoin/[address]/[amount]/[...feeRate]/+page.svelte
@@ -1,20 +1,96 @@
<script>
+ import { tick } from "svelte";
import { t } from "$lib/translations";
import { enhance } from "$app/forms";
import Toggle from "$comp/Toggle.svelte";
import Icon from "$comp/Icon.svelte";
import Spinner from "$comp/Spinner.svelte";
+ import WalletPass from "$comp/WalletPass.svelte";
import { page } from "$app/stores";
- import { fiat as toFiat, f, focus, s, sat, closest } from "$lib/utils";
+ import {
+ fiat as toFiat,
+ f,
+ focus,
+ s,
+ sat,
+ closest,
+ network,
+ } 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 { hex as hexUtil } from "@scure/base";
+ import * as btc from "@scure/btc-signer";
+ import { hash160 } from "@scure/btc-signer/utils";
+ import { decrypt } from "nostr-tools/nip49";
+ import { HDKey } from "@scure/bip32";
+ import { entropyToMnemonic, mnemonicToSeed } from "@scure/bip39";
+ import { wordlist } from "@scure/bip39/wordlists/english";
export let data;
export let form;
- let { amount, address, message, fee, fees, feeRate, ourfee, rates, hex } =
- data;
+ let { encode, decode } = hexUtil;
+ let passwordPrompt;
+ let password;
+ let cancel = () => (passwordPrompt = false);
+ let signed;
+
+ let togglePassword = () => (passwordPrompt = !passwordPrompt);
+ let handler = ({ cancel }) => {
+ if (account.seed && !signed) cancel(), togglePassword();
+ return async ({ result }) => {
+ if (result.type === "redirect") {
+ goto(result.location);
+ } else {
+ await applyAction(result);
+ invalidate("app:payments");
+ }
+ };
+ };
+
+ let signTx = async () => {
+ let entropy = await decrypt(account.seed, password);
+ let mnemonic = entropyToMnemonic(entropy, wordlist);
+ let seed = await mnemonicToSeed(mnemonic, password);
+ let master = HDKey.fromMasterSeed(seed, network);
+ let child = master.derive("m/84'/0'/0'");
+
+ let tx = btc.Transaction.fromRaw(decode(hex));
+
+ for (let [i, input] of tx.inputs.entries()) {
+ let { witnessUtxo, path } = inputs[i];
+ witnessUtxo.amount = BigInt(witnessUtxo.amount);
+ witnessUtxo.script = decode(witnessUtxo.script);
+ let key = child.derive(path);
+ tx.updateInput(i, { witnessUtxo });
+ tx.signIdx(key.privateKey, i);
+ }
+
+ tx.finalize();
+ hex = tx.hex;
+ console.log("HEX", hex);
+ signed = true;
+ await tick();
+ submit.click();
+ };
+
+ let toggle = () => (submitting = !submitting);
+
+ let {
+ account,
+ amount,
+ address,
+ message,
+ fee,
+ fees,
+ feeRate,
+ ourfee,
+ rates,
+ hex,
+ inputs,
+ } = data;
$: reload(data);
let reload = () => {
@@ -22,7 +98,7 @@
data);
if (!fees) return;
delete fees.minimumFee;
- feeRate = closest(Object.values(fees), feeRate);
+ feeRate = feeRate ? closest(Object.values(fees), feeRate) : fees.halfHourFee;
if (!$rate) $rate = rates[currency];
};
@@ -30,10 +106,9 @@
let submitting, submit, showSettings;
let feeNames = {
- fastestFee: "Fastest",
- halfHourFee: "Fast",
- hourFee: "Medium",
- economyFee: "Slow",
+ fastestFee: $t("payments.fastest"),
+ halfHourFee: $t("payments.fast"),
+ hourFee: $t("payments.medium"),
};
let toggleSettings = () => (showSettings = !showSettings);
@@ -48,15 +123,6 @@
let goBack = () => goto(`/send/bitcoin/${address}`);
</script>
-<button
- type="button"
- class="ml-5 md:ml-20 mt-5 md:mt-10 hover:opacity-80"
- data-sveltekit-preload-data="false"
- on:click={goBack}
->
- <Icon icon="arrow-left" style="w-10" />
-</button>
-
<div
class="container px-4 max-w-xl mx-auto space-y-5 text-center no-transition"
>
@@ -85,7 +151,7 @@
on:change={setFee}
class="border text-lg bg-white p-4 rounded-2xl text-center my-auto"
>
- {#each Object.keys(fees) as feeName}
+ {#each Object.keys(feeNames) as feeName}
<option value={fees[feeName]}
>{feeNames[feeName]} &mdash; ⚡️{fees[feeName]}/vb</option
>
@@ -115,10 +181,12 @@
</div>
{/if}
- <form method="POST" use:enhance on:submit={() => (submitting = true)}>
+ <form method="POST" use:enhance={handler}>
<input name="pin" value={$pin} type="hidden" />
<input name="hex" value={hex} type="hidden" />
<input name="rate" value={$rate} type="hidden" />
+ <input name="aid" value={account.id} type="hidden" />
+ <input name="signed" value={signed} type="hidden" />
<div class="flex justify-center gap-2">
<button
@@ -139,6 +207,10 @@
{/if}
</div>
+{#if passwordPrompt}
+ <WalletPass bind:password bind:cancel submit={signTx} />
+{/if}
+
<style>
.no-transition {
view-transition-name: fee;
diff --git a/src/routes/(app)/send/ecash/+page.server.ts b/src/routes/(app)/send/ecash/+page.server.ts
new file mode 100644
index 00000000..6a535524
--- /dev/null
+++ b/src/routes/(app)/send/ecash/+page.server.ts
@@ -0,0 +1,18 @@
+import { error, redirect } from "@sveltejs/kit";
+import { auth, post, fd } from "$lib/utils";
+
+export const actions = {
+ default: async ({ cookies, request }) => {
+ let id;
+ const body = await fd(request);
+
+ try {
+ ({ id } = await post("/mint", body, auth(cookies)));
+ } catch (e: any) {
+ console.log("problem creating ecash", e);
+ error(400, { message: e.message });
+ }
+
+ redirect(307, `/ecash/${id}`);
+ },
+};
diff --git a/src/routes/(app)/send/ecash/+page.svelte b/src/routes/(app)/send/ecash/+page.svelte
new file mode 100644
index 00000000..f4978869
--- /dev/null
+++ b/src/routes/(app)/send/ecash/+page.svelte
@@ -0,0 +1,73 @@
+<script>
+ import { enhance, applyAction } from "$app/forms";
+ import { t } from "$lib/translations";
+ import Icon from "$comp/Icon.svelte";
+ import Numpad from "$comp/Numpad.svelte";
+ import Spinner from "$comp/Spinner.svelte";
+ import { page } from "$app/stores";
+ import { rate } from "$lib/store";
+ import { fail, s } from "$lib/utils";
+ import handler from "$lib/handler";
+
+ export let data;
+
+ let { rates, user } = data;
+ let { balance, currency, username } = user;
+
+ let amount = 0;
+ let submit, fiat;
+
+ $: update(data);
+ let update = () => ($rate = data.rates[currency]);
+
+ let setMax = () => {
+ fiat = false;
+ amount = balance;
+ };
+
+ let submitting;
+ let toggle = () => (submitting = !submitting);
+</script>
+
+<div class="container px-4 max-w-xl mx-auto space-y-5 text-center">
+ <div
+ class="p-4 border rounded-2xl space-y-2 text-lg text-left flex gap-2"
+ >
+ <div class="space-y-5">
+ <div>
+ {$t("payments.ecashDesc")}
+ <a href="https://cashu.space/" class="font-bold">cashu.space</a>.
+ </div>
+ </div>
+ </div>
+ <form use:enhance={handler(toggle)} method="POST" class="space-y-5">
+ <h1 class="px-3 md:px-0 text-center text-3xl md:text-4xl font-semibold">
+ {$t("payments.fundingAmount")}
+ </h1>
+ <Numpad bind:amount bind:fiat {currency} {submit} bind:rate={$rate} />
+ <input type="hidden" name="amount" bind:value={amount} />
+
+ <div>
+ <button
+ type="button"
+ class="hover:opacity-80 rounded-2xl py-5 px-6 mt-2 font-bold w-full mx-auto bg-primary"
+ on:click|preventDefault={setMax}
+ disabled={submitting}
+ on:keydown={setMax}>Max ⚡️{s(balance)}</button
+ >
+
+ <button
+ use:focus
+ bind:this={submit}
+ type="submit"
+ class="opacity-100 hover:opacity-80 rounded-2xl border py-5 font-bold mt-2 bg-black text-white px-6 w-full flex justify-center gap-2 mx-auto"
+ >
+ {#if submitting}
+ <Spinner />
+ {:else}
+ <div class="my-auto">{$t("payments.mint")}</div>
+ {/if}
+ </button>
+ </div>
+ </form>
+</div>
diff --git a/src/routes/(app)/send/fund/[name]/[...amount]/+page.server.js b/src/routes/(app)/send/fund/[name]/[...amount]/+page.server.js
deleted file mode 100644
index 51277e5d..00000000
--- a/src/routes/(app)/send/fund/[name]/[...amount]/+page.server.js
+++ /dev/null
@@ -1,17 +0,0 @@
-import { fail, redirect } from "@sveltejs/kit";
-import { auth, fd, post } from "$lib/utils";
-
-export const actions = {
- default: async ({ cookies, request }) => {
- let body = await fd(request);
- let p;
-
- try {
- p = await post("/payments", body, auth(cookies));
- } catch (e) {
- return fail(400, { message: e.message });
- }
-
- if (p) redirect(307, `/fund/${body.name}`);
- },
-};
diff --git a/src/routes/(app)/send/fund/[name]/[...amount]/+page.server.ts b/src/routes/(app)/send/fund/[name]/[...amount]/+page.server.ts
new file mode 100644
index 00000000..ed39f96b
--- /dev/null
+++ b/src/routes/(app)/send/fund/[name]/[...amount]/+page.server.ts
@@ -0,0 +1,17 @@
+import { fail, redirect } from "@sveltejs/kit";
+import { auth, fd, post } from "$lib/utils";
+
+export const actions = {
+ default: async ({ cookies, request }) => {
+ const body = await fd(request);
+ let p;
+
+ try {
+ p = await post("/payments", body, auth(cookies));
+ } catch (e: any) {
+ return fail(400, { message: e.message });
+ }
+
+ if (p) redirect(307, `/fund/${body.name}`);
+ },
+};
diff --git a/src/routes/(app)/send/invoice/[id]/+page.server.js b/src/routes/(app)/send/invoice/[id]/+page.server.js
deleted file mode 100644
index 2cb19b80..00000000
--- a/src/routes/(app)/send/invoice/[id]/+page.server.js
+++ /dev/null
@@ -1,35 +0,0 @@
-import { error, fail, redirect } from "@sveltejs/kit";
-import { fd, auth, get, post } from "$lib/utils";
-
-export async function load({ params: { id }, parent, url }) {
- let { rates, user } = await parent();
-
- let invoice = await get(`/invoice/${id}`);
-
- if (invoice.prompt && invoice.tip === null)
- redirect(307, `/${invoice.user.username}/invoice/${id}/tip`);
-
- if (invoice.memoPrompt && invoice.memo === null)
- redirect(307, `/${invoice.user.username}/invoice/${id}/memo`);
-
- if (invoice.user.username === user.username)
- error(500, { message: "Cannot send to self" });
-
- return { invoice, rates, user };
-}
-
-export const actions = {
- default: async ({ cookies, params: { id }, request }) => {
- try {
- let body = await fd(request);
- body.hash = id;
-
- await post("/payments", body, auth(cookies));
- } catch (e) {
- console.log("payment failed", id, e);
- return fail(400, { message: e.message });
- }
-
- redirect(307, "/sent");
- },
-};
diff --git a/src/routes/(app)/send/invoice/[id]/+page.server.ts b/src/routes/(app)/send/invoice/[id]/+page.server.ts
new file mode 100644
index 00000000..55228025
--- /dev/null
+++ b/src/routes/(app)/send/invoice/[id]/+page.server.ts
@@ -0,0 +1,39 @@
+import { auth, fd, get, post, types } from "$lib/utils";
+import { error, redirect } from "@sveltejs/kit";
+
+export async function load({ cookies, params: { id }, parent }) {
+ const aid = cookies.get("aid");
+ const { rates, user } = await parent();
+
+ const invoice = await get(`/invoice/${id}`);
+
+ if (invoice.prompt && invoice.tip === null)
+ redirect(307, `/invoice/${id}/tip`);
+
+ if (invoice.memoPrompt && invoice.memo === null)
+ redirect(307, `/invoice/${id}/memo`);
+
+ if (invoice.aid === aid) error(500, { message: "Cannot send to self" });
+ else if (user && invoice.type !== types.lightning) redirect(307, `/send/${invoice.type}/${invoice.hash}`);
+
+ if (!user) redirect(307, `/invoice/${id}`);
+
+ return { invoice, rates, user };
+}
+
+export const actions = {
+ default: async ({ cookies, params: { id }, request }) => {
+ let p;
+ try {
+ const body = await fd(request);
+ body.hash = id;
+
+ p = await post("/payments", body, auth(cookies));
+ } catch (e: any) {
+ console.log("payment failed", id, e);
+ error(500, e.message);
+ }
+
+ redirect(307, `/sent/${p.id}`);
+ },
+};
diff --git a/src/routes/(app)/send/invoice/[id]/+page.svelte b/src/routes/(app)/send/invoice/[id]/+page.svelte
index e3ee9297..fe60c9a6 100644
--- a/src/routes/(app)/send/invoice/[id]/+page.svelte
+++ b/src/routes/(app)/send/invoice/[id]/+page.svelte
@@ -1,4 +1,5 @@
<script>
+ import handler from "$lib/handler";
import { onDestroy, onMount } from "svelte";
import { t } from "$lib/translations";
import { goto, invalidateAll } from "$app/navigation";
@@ -47,17 +48,21 @@
amountFiat = af;
};
- let submitting;
- let submit = () => (submitting = true);
+ let submit, submitting;
+ let toggle = () => (submitting = !submitting);
let external = async () => {
- let invoice = { type: "lightning", amount, currency };
- let { id } = await post(`/${recipient.username}/invoice`, {
- invoice,
+ let { id } = await post(`/invoice`, {
+ invoice: {
+ ...invoice,
+ type: "lightning",
+ amount,
+ currency,
+ },
user: { username: recipient.username },
});
- goto(`/${recipient.username}/invoice/${id}?options=true`, {
+ goto(`/invoice/${id}?options=true`, {
invalidateAll: true,
});
};
@@ -88,10 +93,6 @@
// });
</script>
-<button class="ml-5 md:ml-20 mt-5 md:mt-10 hover:opacity-80" on:click={back}>
- <Icon icon="arrow-left" style="w-10" />
-</button>
-
{#if form?.message}
<div class="text-red-600 text-center">
{form.message}
@@ -161,10 +162,11 @@
{currency}
bind:fiat
bind:rate
+ {submit}
/>
{/if}
- <form method="POST" use:enhance on:submit={submit}>
+ <form method="POST" use:enhance={handler(toggle)}>
<input name="address" value={address} type="hidden" />
<input name="amount" value={amount} type="hidden" />
<input name="payreq" value={payreq} type="hidden" />
@@ -187,6 +189,7 @@
</button>
{:else}
<button
+ bind:this={submit}
type="button"
class="opacity-100 hover:opacity-80'} rounded-2xl border py-5 font-bold mx-auto mt-2 bg-black text-white px-6 w-40"
on:click={setAmount}
diff --git a/src/routes/(app)/send/lightning/[payreq]/+page.server.js b/src/routes/(app)/send/lightning/[payreq]/+page.server.js
deleted file mode 100644
index 89bcc3c3..00000000
--- a/src/routes/(app)/send/lightning/[payreq]/+page.server.js
+++ /dev/null
@@ -1,24 +0,0 @@
-import { fail, redirect } from "@sveltejs/kit";
-import { fd, auth, post } from "$lib/utils";
-
-export async function load({ cookies, params }) {
- return post("/parse", params, auth(cookies));
-}
-
-export const actions = {
- setAmount: async ({ cookies, request }) => fd(request),
-
- send: async ({ cookies, request }) => {
- try {
- let body = await fd(request);
-
- await post("/payments", body, auth(cookies));
- } catch (e) {
- if (e.message.includes("unusable"))
- e.message = "Failed to route payment, try sending a lower amount";
- return fail(400, { message: e.message });
- }
-
- redirect(307, "/sent");
- },
-};
diff --git a/src/routes/(app)/send/lightning/[payreq]/+page.server.ts b/src/routes/(app)/send/lightning/[payreq]/+page.server.ts
new file mode 100644
index 00000000..a101b803
--- /dev/null
+++ b/src/routes/(app)/send/lightning/[payreq]/+page.server.ts
@@ -0,0 +1,29 @@
+import { auth, fd, post } from "$lib/utils";
+import { fail, redirect } from "@sveltejs/kit";
+
+export async function load({ cookies, params }) {
+ return post("/parse", params, auth(cookies));
+}
+
+export const actions = {
+ setAmount: async ({ request }) => fd(request),
+
+ send: async ({ cookies, request }) => {
+ let p;
+ try {
+ const body = await fd(request);
+
+ p = await post("/payments", body, auth(cookies));
+ } catch (e: any) {
+ if (
+ e.message.includes("unusable") ||
+ e.message.includes("routes") ||
+ e.message.includes("minflow")
+ )
+ e.message = "payments.failedToRoute";
+ return fail(400, { message: e.message });
+ }
+
+ redirect(307, `/sent/${p.id}`);
+ },
+};
diff --git a/src/routes/(app)/send/lightning/[payreq]/+page.svelte b/src/routes/(app)/send/lightning/[payreq]/+page.svelte
index 57a17e01..7324c4f1 100644
--- a/src/routes/(app)/send/lightning/[payreq]/+page.svelte
+++ b/src/routes/(app)/send/lightning/[payreq]/+page.svelte
@@ -32,19 +32,8 @@
};
$: amount = form?.amount || data.amount;
- $: maxfee = Math.round(
- amount < 100
- ? amount * 5
- : amount < 1000
- ? amount
- : amount < 10000
- ? amount * 0.5
- : amount < 100000
- ? amount * 0.1
- : amount < 1000000
- ? amount * 0.05
- : amount * 0.01
- );
+ $: maxfee = Math.round(amount * 0.01) || 1;
+ let showMax;
let loading;
let submit = () => (loading = true);
@@ -58,15 +47,11 @@
let toggle = () => (show = !show);
</script>
-<button class="ml-5 md:ml-20 mt-5 md:mt-10 hover:opacity-80" on:click={back}>
- <Icon icon="arrow-left" style="w-10" />
-</button>
-
-<div class="container px-4 max-w-xl mx-auto text-center space-y-5">
+<div class="container px-4 max-w-xl mx-auto text-center space-y-2">
{#if amount}
{#if form?.message}
<div class="text-red-600 text-center">
- {form.message}
+ {$t(form.message)}
</div>
{/if}
@@ -81,12 +66,9 @@
<h3 class="text-secondary text-xl">⚡️{s(amount)}</h3>
</div>
- <div>
- <div class="text-lg text-secondary">
- {$t("payments.to")}
- </div>
-
- <p class="text-2xl break-words font-semibold mb-8">{alias}</p>
+ <div class="text-xl">
+ <span class="text-secondary">{$t("payments.to")}</span>
+ <span class="break-words font-semibold">{alias}</span>
</div>
{#if ourfee}
@@ -109,31 +91,40 @@
use:enhance
on:submit={submit}
action="?/send"
- class="space-y-5"
+ class="space-y-2"
>
<input name="payreq" value={payreq} type="hidden" />
<input name="amount" value={amount} type="hidden" />
<input name="pin" value={$pin} type="hidden" />
- <div class="w-40 mx-auto">
- <label for="maxfee" class="text-lg text-secondary"
- >{$t("payments.maxfee")}</label
- >
-
- <div class="flex">
- <input
- id="maxfee"
- name="maxfee"
- bind:value={maxfee}
- class="border-r-0 rounded-r-none py-2"
- />
- <div
- class="text-gray-600 rounded-r-2xl p-4 my-auto rounded-l-none rounded border bg-gray-100"
+ {#if form?.message || showMax}
+ <div class="mx-auto space-y-2">
+ <label for="maxfee" class="text-lg text-secondary"
+ >{$t("payments.maxfee")}</label
>
- ⚡️
+
+ <div class="text-secondary">
+ {$t("payments.maxFeeDesc")}
+ </div>
+
+ <div class="flex">
+ <input
+ id="maxfee"
+ name="maxfee"
+ bind:value={maxfee}
+ class="border-r-0 rounded-r-none py-2"
+ />
+ <div
+ class="text-gray-600 rounded-r-2xl p-4 my-auto rounded-l-none rounded border bg-gray-100"
+ >
+ ⚡️
+ </div>
</div>
</div>
- </div>
+ {:else}
+ <button on:click={() => (showMax = !showMax)}>Advanced settings</button>
+ <input name="maxfee" type="hidden" bind:value={maxfee} />
+ {/if}
<div class="flex w-full">
<button
diff --git a/src/routes/(app)/send/user/[username]/[...amount]/+page.server.js b/src/routes/(app)/send/user/[username]/[...amount]/+page.server.js
deleted file mode 100644
index 884e3eee..00000000
--- a/src/routes/(app)/send/user/[username]/[...amount]/+page.server.js
+++ /dev/null
@@ -1,50 +0,0 @@
-import { error, fail, redirect } from "@sveltejs/kit";
-import { types, sats, fd, auth, get, post } from "$lib/utils";
-
-export async function load({ cookies, params, parent }) {
- let subject = await get(`/users/${params.username}`);
-
- let { rates, user } = await parent();
- let { username } = params;
- let [amount, currency] = params.amount.split("/");
-
- let rate;
- if (amount) {
- rate = rates[currency ? currency.toUpperCase() : subject.currency];
- if (!rate) error(500, "Invalid currency symbol");
- if (currency) amount = (amount * sats) / rate;
-
- let { id } = await post(
- "/invoice",
- {
- invoice: {
- amount,
- currency: currency === subject.currency ? currency : undefined,
- prompt: false,
- rate: currency === subject.currency ? rate : undefined,
- type: types.lightning,
- },
- user: { username },
- },
- auth(cookies)
- );
-
- redirect(307, `/${username}/invoice/${id}`);
- }
-
- return { amount, rate, subject };
-}
-
-export const actions = {
- default: async ({ cookies, request }) => {
- try {
- let body = await fd(request);
- await post("/payments", body, auth(cookies));
- } catch (e) {
- console.log(e);
- return fail(400, { message: e.message });
- }
-
- redirect(307, "/sent");
- },
-};
diff --git a/src/routes/(app)/sent/+page.server.js b/src/routes/(app)/sent/+page.server.js
deleted file mode 100644
index 62a4d9b4..00000000
--- a/src/routes/(app)/sent/+page.server.js
+++ /dev/null
@@ -1,6 +0,0 @@
-import { get, auth } from "$lib/utils";
-
-export let load = async ({ cookies }) => {
- let { payments } = await get("/payments", auth(cookies));
- return { payments };
-};
diff --git a/src/routes/(app)/sent/[id]/+page.server.ts b/src/routes/(app)/sent/[id]/+page.server.ts
new file mode 100644
index 00000000..d3d98ea5
--- /dev/null
+++ b/src/routes/(app)/sent/[id]/+page.server.ts
@@ -0,0 +1,7 @@
+import { get, auth } from "$lib/utils";
+
+export const load = async ({ cookies, params }) => {
+ const { id } = params;
+ const p = await get(`/payments/${id}`, auth(cookies));
+ return p;
+};
diff --git a/src/routes/(app)/sent/+page.svelte b/src/routes/(app)/sent/[id]/+page.svelte
index 136bd395..a71a5360 100644
--- a/src/routes/(app)/sent/+page.svelte
+++ b/src/routes/(app)/sent/[id]/+page.svelte
@@ -6,21 +6,15 @@
import { t } from "$lib/translations";
export let data;
- let { payments, user } = data;
+ let { amount, rate, tip, user } = data;
let { currency, username } = user;
-
- let payment = payments[0];
- let { amount, rate, tip } = payment;
amount = Math.abs(amount);
toast.pop(0);
</script>
<div class="text-center mt-20 md:mt-0">
- <div
- class="flex w-full max-w-[200px] mx-auto py-20"
- in:scale={{ start: 0.5 }}
- >
+ <div class="flex w-full max-w-[200px] mx-auto py-4" in:scale={{ start: 0.5 }}>
<Icon icon="check" style="mx-auto" />
</div>
<h1 class="text-3xl md:text-4xl font-bold mb-6">{$t("payments.sent")}!</h1>
@@ -43,7 +37,7 @@
</h3>
</div>
-<a href={`/${username}/payments`} use:focus>
+<a href={`/${username}`} use:focus>
<div class="opacity-0 w-screen h-screen fixed top-0 left-0 z-50" />
</a>
diff --git a/src/routes/(app)/settings/[...tab]/+page.server.ts b/src/routes/(app)/settings/[...tab]/+page.server.ts
new file mode 100644
index 00000000..39533426
--- /dev/null
+++ b/src/routes/(app)/settings/[...tab]/+page.server.ts
@@ -0,0 +1,36 @@
+import { auth, fd, get, post } from "$lib/utils";
+import { fail, redirect } from "@sveltejs/kit";
+
+export async function load({ cookies, params, url }) {
+ if (url.pathname.endsWith("settings"))
+ redirect(307, `${url.pathname}/account`);
+ params.cookies = cookies.getAll();
+ const subscriptions = await get("/subscriptions", auth(cookies));
+ return { cookies: cookies.getAll(), subscriptions, tab: params.tab };
+}
+
+export const actions = {
+ default: async ({ cookies, request }) => {
+ const form = await fd(request);
+
+ if (form.tab === "pos") {
+ form.notify = form.notify === "on";
+ form.push = form.push === "on";
+ form.nip5 = form.nip5 === "on";
+ form.prompt = form.prompt === "on";
+ form.autowithdraw = form.autowithdraw === "on";
+ }
+
+ let user = { ...(await get("/me", auth(cookies))), ...form };
+
+ try {
+ ({ user } = await post("/user", user, auth(cookies)));
+ } catch (e: any) {
+ return fail(400, { message: e.message });
+ }
+
+ if (user.language) cookies.set("lang", user.language, { path: "/" });
+
+ return { user, success: true };
+ },
+};
diff --git a/src/routes/(app)/[username]/settings/[...tab]/+page.svelte b/src/routes/(app)/settings/[...tab]/+page.svelte
index cdbe0623..0a3a6ddf 100644
--- a/src/routes/(app)/[username]/settings/[...tab]/+page.svelte
+++ b/src/routes/(app)/settings/[...tab]/+page.svelte
@@ -28,12 +28,12 @@
let submit;
let formElement;
- let { user, token, rates, tab, cookies } = data;
+ let { user, token, rates, tab, cookies, subscriptions } = data;
let prev;
$: update(data);
let update = () => {
- ({ user, token, rates, tab } = data);
+ ({ user, token, rates, tab, subscriptions } = data);
prev = { ...user };
};
@@ -87,7 +87,7 @@
try {
data.set(
"cipher",
- await reEncryptEntropy(user, data.get("password"))
+ await reEncryptEntropy(user, data.get("password")),
);
} catch (e) {
console.log("Failed to encrypt keys with new password");
@@ -98,7 +98,7 @@
if ($avatar) {
try {
let { hash } = JSON.parse(
- await upload($avatar.file, $avatar.type, $avatar.progress, token)
+ await upload($avatar.file, $avatar.type, $avatar.progress, token),
);
data.set("profile", hash);
@@ -115,7 +115,7 @@
if ($banner) {
try {
let { hash } = JSON.parse(
- await upload($banner.file, $banner.type, $banner.progress, token)
+ await upload($banner.file, $banner.type, $banner.progress, token),
);
data.set("banner", hash);
@@ -137,7 +137,7 @@
content: JSON.stringify({
name: user.username,
about: user.address,
- picture: `${PUBLIC_COINOS_URL}/public/${user.profile}.webp`,
+ picture: `${$page.url.origin}/public/${user.profile}.webp`,
}),
tags: [],
};
@@ -161,11 +161,12 @@
await post(
"/api/request",
{ id: user.id, email: user.email },
- auth(cookies)
+ auth(cookies),
);
warning($t("user.settings.verifying"), false);
} catch (e) {
+ fail(e.message);
console.log(e);
}
}
@@ -205,7 +206,7 @@
<input type="hidden" name="pin" value={$pin} />
<input type="hidden" name="tab" value={tab} />
- <div class="mt-24 mb-20 px-3 md:px-0 w-full md:w-[400px] mx-auto space-y-8">
+ <div class="mt-24 mb-20 px-3 md:px-0 w-full md:max-w-lg mx-auto space-y-8">
<div class="header">
<h1 class="text-center text-3xl md:text-4xl font-semibold mb-10">
{$t("user.settings.header")}
@@ -215,7 +216,7 @@
class="font-bold flex justify-around items-center border-b pb-3 text-secondary"
>
{#each tabs.filter((t) => t.name !== "shopify") as { name, key }}
- <a href={`/${user.username}/settings/${name}`}>
+ <a href={`/settings/${name}`}>
<button
type="button"
class="hover:opacity-80"
@@ -228,7 +229,7 @@
</div>
</div>
- <svelte:component this={comp} {user} {rates} {submit} />
+ <svelte:component this={comp} {user} {rates} {submit} {subscriptions} />
</div>
<div
@@ -248,9 +249,3 @@
</button>
</div>
</form>
-
-<style>
- .settings {
- view-transition-name: settings;
- }
-</style>
diff --git a/src/routes/(app)/[username]/settings/[...tab]/_account.svelte b/src/routes/(app)/settings/[...tab]/_account.svelte
index 8e3323c7..8e3323c7 100644
--- a/src/routes/(app)/[username]/settings/[...tab]/_account.svelte
+++ b/src/routes/(app)/settings/[...tab]/_account.svelte
diff --git a/src/routes/(app)/[username]/settings/[...tab]/_pos.svelte b/src/routes/(app)/settings/[...tab]/_pos.svelte
index e9dd0e39..8cff4b1f 100644
--- a/src/routes/(app)/[username]/settings/[...tab]/_pos.svelte
+++ b/src/routes/(app)/settings/[...tab]/_pos.svelte
@@ -1,19 +1,21 @@
<script>
- import { tick } from "svelte";
+ import { onMount, tick } from "svelte";
+ import { browser } from "$app/environment";
import Icon from "$comp/Icon.svelte";
import Numpad from "$comp/Numpad.svelte";
import LocaleSelector from "$comp/LocaleSelector.svelte";
import Toggle from "$comp/Toggle.svelte";
import { locale, t } from "$lib/translations";
- import { success, fail } from "$lib/utils";
+ import { post, success, fail } from "$lib/utils";
import { page } from "$app/stores";
+ import { PUBLIC_VAPID_PUBKEY } from "$env/static/public";
- export let user, rates, submit;
+ export let user, rates, submit, subscriptions;
let { currency } = user;
let rate = rates[currency];
- let fiats = Object.keys(rates);
+ let fiats = Object.keys(rates).sort((a, b) => a.localeCompare(b));
$: user.language = $locale;
let keypress = (e) => e.key === "Enter" && (e.preventDefault() || el.click());
@@ -38,6 +40,47 @@
if (!user.threshold) user.threshold = 1000000;
if (!user.reserve) user.reserve = 100000;
let reserveEl, thresholdEl;
+
+ let push, pm, subscription;
+
+ onMount(async () => {
+ if (!browser) return;
+
+ pm =
+ navigator?.serviceWorker &&
+ (await navigator.serviceWorker.getRegistration()).pushManager;
+
+ permission = await pm.permissionState({
+ userVisibleOnly: true,
+ applicationServerKey: PUBLIC_VAPID_PUBKEY,
+ });
+
+ if (permission === "granted") {
+ subscription = await pm.getSubscription();
+ if (subscriptions.includes(JSON.stringify(subscription))) push = true;
+ }
+ });
+
+ let permission;
+ $: updateNotifications(push);
+ let updateNotifications = async (push) => {
+ if (!browser || !pm) return (push = false);
+
+ if (subscription && !push) {
+ return post("/subscription/delete", { subscription });
+ }
+
+ if (push && permission !== "denied") {
+ subscription = await pm.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: PUBLIC_VAPID_PUBKEY,
+ });
+ }
+
+ if (subscription) {
+ await post("/subscription", { subscription });
+ }
+ };
</script>
<div>
@@ -63,17 +106,6 @@
</div>
<div>
- <label for="memoPrompt" class="font-bold mb-1 block"
- >{$t("user.settings.memoPrompt")}</label
- >
- <textarea
- name="memoPrompt"
- placeholder={$t("user.settings.memoPromptPlaceholder")}
- bind:value={user.memoPrompt}
- />
-</div>
-
-<div>
<div class="flex justify-between items-center">
<span class="font-bold">{$t("user.settings.notifications")}</span>
<Toggle id="notify" bind:value={user.notify} />
@@ -85,23 +117,27 @@
<div>
<div class="flex justify-between items-center">
- <span class="font-bold">{$t("user.settings.tipPrompt")}</span>
- <Toggle id="prompt" bind:value={user.prompt} />
+ <span class="font-bold">{$t("user.settings.pushNotifications")}</span>
+ {#if permission !== "denied"}
+ <Toggle id="push" bind:value={push} />
+ {/if}
</div>
<p class="text-secondary mt-1 w-9/12">
- {$t("user.settings.tipPromptDescription")}
+ {#if permission === "denied"}
+ {$t("user.settings.pushNotificationsDisabled")}
+ {:else}
+ {$t("user.settings.pushNotificationsDesc")}
+ {/if}
</p>
</div>
<div>
<div class="flex justify-between items-center">
- <span class="font-bold">{$t("user.settings.publishNip5")}</span>
- <Toggle id="nip5" bind:value={user.nip5} />
+ <span class="font-bold">{$t("user.settings.tipPrompt")}</span>
+ <Toggle id="prompt" bind:value={user.prompt} />
</div>
<p class="text-secondary mt-1 w-9/12">
- {$t("user.settings.nip5a")}
- <span class="font-bold">{user.username}@{$page.url.host}</span>
- {$t("user.settings.nip5b")}
+ {$t("user.settings.tipPromptDescription")}
</p>
</div>
diff --git a/src/routes/(app)/[username]/settings/[...tab]/_security.svelte b/src/routes/(app)/settings/[...tab]/_security.svelte
index 6b44f830..6b44f830 100644
--- a/src/routes/(app)/[username]/settings/[...tab]/_security.svelte
+++ b/src/routes/(app)/settings/[...tab]/_security.svelte
diff --git a/src/routes/(app)/[username]/settings/[...tab]/_shopify.svelte b/src/routes/(app)/settings/[...tab]/_shopify.svelte
index 0266fa9c..0266fa9c 100644
--- a/src/routes/(app)/[username]/settings/[...tab]/_shopify.svelte
+++ b/src/routes/(app)/settings/[...tab]/_shopify.svelte
diff --git a/src/routes/(app)/subscription/+server.ts b/src/routes/(app)/subscription/+server.ts
new file mode 100644
index 00000000..47dfc770
--- /dev/null
+++ b/src/routes/(app)/subscription/+server.ts
@@ -0,0 +1,8 @@
+import { auth, post } from "$lib/utils";
+import { json } from "@sveltejs/kit";
+
+export async function POST({ cookies, request }) {
+ const body = await request.json();
+ const result = await post("/subscription", body, auth(cookies));
+ return json(result);
+}
diff --git a/src/routes/(app)/subscription/delete/+server.ts b/src/routes/(app)/subscription/delete/+server.ts
new file mode 100644
index 00000000..f4c8357c
--- /dev/null
+++ b/src/routes/(app)/subscription/delete/+server.ts
@@ -0,0 +1,8 @@
+import { auth, post } from "$lib/utils";
+import { json } from "@sveltejs/kit";
+
+export async function POST({ cookies, request }) {
+ const body = await request.json();
+ const result = await post("/subscription/delete", body, auth(cookies));
+ return json(result);
+}
diff --git a/src/routes/(app)/verify/[code]/+page.server.ts b/src/routes/(app)/verify/[code]/+page.server.ts
new file mode 100644
index 00000000..a7edede6
--- /dev/null
+++ b/src/routes/(app)/verify/[code]/+page.server.ts
@@ -0,0 +1,14 @@
+import { get } from "$lib/utils";
+import { redirect } from "@sveltejs/kit";
+
+export const load = async ({ params: { code } }) => {
+ let user;
+ try {
+ user = await get(`/verify/${code}`);
+ } catch (e) {
+ console.log(e);
+ return { error: "Verification failed" };
+ }
+
+ redirect(307, "/settings/account?verified=true");
+};
diff --git a/src/routes/(app)/[username]/verify/[code]/+page.svelte b/src/routes/(app)/verify/[code]/+page.svelte
index 1e099dae..1e099dae 100644
--- a/src/routes/(app)/[username]/verify/[code]/+page.svelte
+++ b/src/routes/(app)/verify/[code]/+page.svelte
diff --git a/src/routes/(app)/withdraw/+server.js b/src/routes/(app)/withdraw/+server.js
deleted file mode 100644
index a75a72f8..00000000
--- a/src/routes/(app)/withdraw/+server.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import { auth, post } from "$lib/utils";
-
-export async function POST({ cookies, request }) {
- let body = await request.json();
- await post("/payments", body, auth(cookies));
-
- return new Response(JSON.stringify("ok"), {
- headers: { "content-type": "application/json" },
- });
-}
diff --git a/src/routes/(app)/withdraw/+server.ts b/src/routes/(app)/withdraw/+server.ts
new file mode 100644
index 00000000..51f6e3d0
--- /dev/null
+++ b/src/routes/(app)/withdraw/+server.ts
@@ -0,0 +1,10 @@
+import { auth, post } from "$lib/utils";
+
+export async function POST({ cookies, request }) {
+ const body = await request.json();
+ await post("/payments", body, auth(cookies));
+
+ return new Response(JSON.stringify("ok"), {
+ headers: { "content-type": "application/json" },
+ });
+}
diff --git a/src/routes/(static)/+layout.server.js b/src/routes/(static)/+layout.server.js
deleted file mode 100644
index 81d1d3dc..00000000
--- a/src/routes/(static)/+layout.server.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import { get, post, auth, protectedRoutes } from "$lib/utils";
-
-export async function load({ cookies, request, url, params }) {
- let token = cookies.get("token");
- let rate,
- rates = { USD: 1 };
-
- let user;
- if (token) {
- try {
- user = await get("/me", auth(cookies));
- } catch (e) {}
- }
-
- return { user };
-}
diff --git a/src/routes/(static)/+layout.server.ts b/src/routes/(static)/+layout.server.ts
new file mode 100644
index 00000000..c780b5e0
--- /dev/null
+++ b/src/routes/(static)/+layout.server.ts
@@ -0,0 +1,14 @@
+import { get, auth } from "$lib/utils";
+
+export async function load({ cookies }) {
+ const token = cookies.get("token");
+
+ let user;
+ if (token) {
+ try {
+ user = await get("/me", auth(cookies));
+ } catch (e) {}
+ }
+
+ return { user };
+}
diff --git a/src/routes/(static)/+layout.svelte b/src/routes/(static)/+layout.svelte
index 13073d5a..8b14fd38 100644
--- a/src/routes/(static)/+layout.svelte
+++ b/src/routes/(static)/+layout.svelte
@@ -9,7 +9,7 @@
<SvelteToast options={{ reversed: true, intro: { y: 192 } }} />
<LandingHeader {user} />
-<main class="container flex px-10 md:px-40 mx-auto min-h-[600px] pb-20">
+<main class="container flex px-4 md:px-40 mx-auto min-h-[600px]">
<slot />
</main>
<Footer />
diff --git a/src/routes/(static)/docs/+page.server.js b/src/routes/(static)/docs/+page.server.js
deleted file mode 100644
index 41176b14..00000000
--- a/src/routes/(static)/docs/+page.server.js
+++ /dev/null
@@ -1,4 +0,0 @@
-export let load = async ({ cookies }) => {
- let token = cookies.get("token");
- return { token };
-};
diff --git a/src/routes/(static)/docs/+page.server.ts b/src/routes/(static)/docs/+page.server.ts
new file mode 100644
index 00000000..86f95824
--- /dev/null
+++ b/src/routes/(static)/docs/+page.server.ts
@@ -0,0 +1,4 @@
+export const load = async ({ cookies }) => {
+ const token = cookies.get("token");
+ return { token };
+};
diff --git a/src/routes/(static)/login/+page.server.ts b/src/routes/(static)/login/+page.server.ts
new file mode 100644
index 00000000..268f95b7
--- /dev/null
+++ b/src/routes/(static)/login/+page.server.ts
@@ -0,0 +1,25 @@
+import { fail, redirect } from "@sveltejs/kit";
+import { login, fd } from "$lib/utils";
+
+export const load = async ({ parent }) => {
+ const { user } = await parent();
+ if (user?.pubkey) redirect(307, `/${user.username}`);
+};
+
+export const actions = {
+ default: async ({ cookies, request }) => {
+ const form = await fd(request);
+ let { username, password, token, loginRedirect } = form;
+ const user = { username, password, token };
+
+ if (loginRedirect === "undefined") loginRedirect = undefined;
+
+ try {
+ await login(user, cookies, request.headers.get("cf-connecting-ip"));
+ } catch (e: any) {
+ return fail(400, { error: "Login failed", message: e.message, ...form });
+ }
+
+ redirect(307, loginRedirect || `/${user.username}`);
+ },
+};
diff --git a/src/routes/(static)/login/+page.svelte b/src/routes/(static)/login/+page.svelte
new file mode 100644
index 00000000..efaa84b8
--- /dev/null
+++ b/src/routes/(static)/login/+page.svelte
@@ -0,0 +1,172 @@
+<script>
+ import { onMount } from "svelte";
+ import { applyAction, deserialize } from "$app/forms";
+ import { tick } from "svelte";
+ import { fly } from "svelte/transition";
+ import { enhance } from "$app/forms";
+ import Pin from "$comp/Pin.svelte";
+ import Icon from "$comp/Icon.svelte";
+ import Spinner from "$comp/Spinner.svelte";
+ import { focus, fail } from "$lib/utils";
+ import { password, pin, loginRedirect } from "$lib/store";
+ import { t } from "$lib/translations";
+ import { page } from "$app/stores";
+ import { generate } from "$lib/nostr";
+ import { invalidateAll } from "$app/navigation";
+
+ onMount(() => {
+ $pin = undefined;
+ localStorage.clear();
+ sessionStorage.clear();
+
+ let lang = $page.url.searchParams.get("lang");
+ if (lang) document.cookie = `lang=${lang} ;`;
+ });
+
+ export let form;
+
+ let token, formElement;
+ let code = [];
+ let redirect;
+
+ $password = undefined;
+
+ $: need2fa = form?.message === "2fa";
+ let cancel = () => (need2fa = false);
+ $: if (form?.message === "2fa" && form.token === token) token = "";
+
+ let username, email, btn;
+
+ $: update(form);
+ let update = (form) => form && ({ username, password: $password } = form);
+
+ $: token && token?.length === 6 && tick().then(() => btn.click());
+
+ let revealPassword = false;
+
+ let loading;
+ async function handleSubmit(e) {
+ loading = true;
+
+ let data = new FormData(this);
+ let user = Object.fromEntries(data);
+ await generate(user);
+
+ for (let k in user) {
+ data.set(k, user[k]);
+ }
+
+ const response = await fetch("/login", {
+ method: "POST",
+ body: data,
+ });
+
+ const result = deserialize(await response.text());
+
+ if (result.type === "success") {
+ await invalidateAll();
+ }
+
+ applyAction(result);
+ loading = false;
+ }
+</script>
+
+{#if need2fa}
+ <Pin bind:value={token} title="Enter 2FA Code" {cancel} notify={false} />
+{/if}
+
+<div
+ class="mx-auto md:shadow-xl rounded-3xl max-w-xl w-full md:w-[480px] md:p-8 mb-20"
+>
+ <h1 class="text-2xl font-bold text-center">{$t("login.signIn")}</h1>
+
+ {#if form?.error}
+ <div class="text-red-600 text-center" in:fly>
+ {form.error}
+ </div>
+ {/if}
+
+ <form class="space-y-5" on:submit|preventDefault={handleSubmit} method="POST">
+ <input
+ type="hidden"
+ name="loginRedirect"
+ value={$loginRedirect || $page.url.searchParams.get("redirect")}
+ />
+ <input type="hidden" name="token" value={token} />
+
+ <div>
+ <label for="username" class="font-semibold">{$t("login.username")}</label>
+ <input
+ name="username"
+ type="text"
+ required
+ class="bg-primary"
+ bind:value={username}
+ use:focus
+ autocapitalize="none"
+ />
+ </div>
+
+ <div class="relative">
+ <label for="password" class="block font-semibold"
+ >{$t("login.password")}</label
+ >
+ {#if revealPassword}
+ <input
+ name="password"
+ type="text"
+ required
+ class="bg-primary"
+ bind:value={$password}
+ autocapitalize="none"
+ />
+ {:else}
+ <input
+ name="password"
+ type="password"
+ required
+ class="bg-primary"
+ bind:value={$password}
+ autocapitalize="none"
+ />
+ {/if}
+ <button
+ type="button"
+ on:click={() => (revealPassword = !revealPassword)}
+ class="absolute right-5 top-10"
+ >
+ <Icon icon={revealPassword ? "eye" : "eye-off"} />
+ </button>
+ </div>
+
+ <div class="flex justify-end items-center">
+ <a href="/forgot" class="underline underline-offset-4 text-black"
+ >{$t("login.forgotUserOrPassword")}</a
+ >
+ </div>
+
+ <button
+ type="submit"
+ class="bg-black text-white w-full rounded-2xl p-4 font-semibold hover:opacity-80"
+ disabled={loading}
+ bind:this={btn}
+ >
+ {#if loading}
+ <Spinner />
+ {:else}
+ {$t("login.signIn")}
+ {/if}
+ </button>
+
+ <p class="text-secondary text-center font-medium">
+ {$t("login.noAccount")}
+ <a
+ href={"/register"}
+ class="block md:inline text-black underline underline-offset-4 hover:opacity-80"
+ >
+ {$t("login.register")}
+ </a>
+ </p>
+ </form>
+</div>
diff --git a/src/routes/(static)/privacy/+page.svelte b/src/routes/(static)/privacy/+page.svelte
new file mode 100644
index 00000000..7b21a5be
--- /dev/null
+++ b/src/routes/(static)/privacy/+page.svelte
@@ -0,0 +1,16 @@
+<div class="space-y-5">
+ <div class="text-2xl font-bold">Privacy Policy</div>
+
+ <div>
+ The only personal information we require to create an account is a username
+ and password. Some users may provide an email address for notification or
+ password reset purposes. We will not share your email with anyone or use it
+ for anything other than the purposes stated.
+ </div>
+
+ <div>
+ We keep records of payment history associated to accounts and may be
+ obligated to share our records with financial authorities. You may request
+ that your account be deleted by visiting https://coinos.io/removal
+ </div>
+</div>
diff --git a/src/routes/(static)/register/+page.server.ts b/src/routes/(static)/register/+page.server.ts
new file mode 100644
index 00000000..2dffef01
--- /dev/null
+++ b/src/routes/(static)/register/+page.server.ts
@@ -0,0 +1,41 @@
+import { fail, redirect } from "@sveltejs/kit";
+import { fd, post, login } from "$lib/utils";
+
+export const load = async ({ parent }) => {
+ const { user } = await parent();
+ if (user) redirect(307, `/${user.username}`);
+
+ const index = Math.floor(Math.random() * 64) + 1;
+
+ return { index };
+};
+
+export const actions = {
+ default: async ({ cookies, request }) => {
+ const ip = request.headers.get("cf-connecting-ip");
+
+ const form = await fd(request);
+ let { profile, username, password, cipher, salt, pubkey, loginRedirect } =
+ form;
+ const user = { profile, username, password, cipher, salt, pubkey };
+ let error;
+
+ if (loginRedirect === "undefined") loginRedirect = undefined;
+
+ try {
+ await post("/register", { user }, { "cf-connecting-ip": ip });
+ } catch (e: any) {
+ error = e.message;
+ }
+
+ try {
+ await login(user, cookies, ip);
+ error = null;
+ } catch (e: any) {
+ error ||= e.message;
+ }
+
+ if (error) return fail(400, { error });
+ redirect(307, loginRedirect || `/${user.username}`);
+ },
+};
diff --git a/src/routes/(static)/register/+page.svelte b/src/routes/(static)/register/+page.svelte
new file mode 100644
index 00000000..1749bd16
--- /dev/null
+++ b/src/routes/(static)/register/+page.svelte
@@ -0,0 +1,292 @@
+<script>
+ import punks from "$lib/punks";
+ import { upload } from "$lib/upload";
+ import { afterNavigate, invalidateAll } from "$app/navigation";
+ import { applyAction, deserialize } from "$app/forms";
+ import { tick } from "svelte";
+ import { fly } from "svelte/transition";
+ import { enhance } from "$app/forms";
+
+ import Pin from "$comp/Pin.svelte";
+ import Icon from "$comp/Icon.svelte";
+ import Spinner from "$comp/Spinner.svelte";
+
+ import { focus, fail } from "$lib/utils";
+ import { avatar, password, loginRedirect } from "$lib/store";
+ import { t } from "$lib/translations";
+ import { page } from "$app/stores";
+ import { generate } from "$lib/nostr";
+ import {
+ NumberDictionary,
+ uniqueNamesGenerator,
+ colors,
+ adjectives,
+ animals,
+ } from "unique-names-generator";
+
+ export let form;
+ export let data;
+
+ $: data && ($avatar = undefined);
+ let username;
+ let { index } = data;
+
+ let cleared;
+ let clear = () => {
+ if (!cleared) {
+ cleared = true;
+ username = "";
+ $password = "";
+ revealPassword = false;
+ }
+ };
+
+ let refresh = async () => {
+ username = uniqueNamesGenerator({
+ dictionaries: [animals, NumberDictionary.generate({ min: 10, max: 99 })],
+ length: 2,
+ separator: "",
+ });
+
+ $password = uniqueNamesGenerator({
+ dictionaries: [colors, NumberDictionary.generate({ min: 100, max: 999 })],
+ length: 2,
+ separator: "",
+ });
+
+ revealPassword = true;
+ };
+
+ afterNavigate(async () => {
+ try {
+ await invalidateAll();
+ } catch (e) {
+ console.log(e);
+ }
+ });
+
+ let token, formElement;
+ let code = [];
+ let redirect;
+
+ $: need2fa = form?.message === "2fa";
+ let cancel = () => (need2fa = false);
+ $: if (form?.message === "2fa" && form.token === token) token = "";
+
+ let email, btn;
+
+ $: update(form);
+ let update = (form) => form && ({ username, password: $password } = form);
+
+ $: token && token?.length === 6 && tick().then(() => btn.click());
+
+ let revealPassword;
+
+ let loading;
+ async function handleSubmit(e) {
+ loading = true;
+
+ let data = new FormData(this);
+ let user = Object.fromEntries(data);
+ await generate(user);
+
+ for (let k in user) {
+ data.set(k, user[k]);
+ }
+
+ data.set("profile", punks[index]);
+ if ($avatar) {
+ try {
+ let { hash } = JSON.parse(
+ await upload($avatar.file, $avatar.type, $avatar.progress, token),
+ );
+
+ data.set("profile", hash);
+ await fetch(`/api/public/${hash}.webp`, {
+ cache: "reload",
+ mode: "no-cors",
+ });
+ } catch (e) {
+ console.log("problem uploading avatar", e);
+ }
+ }
+
+ const response = await fetch("/register", {
+ method: "POST",
+ body: data,
+ });
+
+ const result = deserialize(await response.text());
+
+ if (result.type === "success") {
+ await invalidateAll();
+ }
+
+ applyAction(result);
+ loading = false;
+ }
+
+ let avatarInput;
+ $: src = `/api/public/${punks[index]}.webp`;
+ let decr = () => (index = index <= 0 ? 63 : index - 1);
+ let incr = () => (index = index >= 63 ? 0 : index + 1);
+ let selectAvatar = () => avatarInput.click();
+
+ let progress;
+ let handleFile = async ({ target }) => {
+ let type = "profile";
+ let file = target.files[0];
+ if (!file) return;
+
+ if (file.size > 10000000) form.error = "File too large";
+ $avatar = { file, type, progress };
+
+ var reader = new FileReader();
+ reader.onload = async (e) => {
+ src = e.target.result;
+ };
+
+ reader.readAsDataURL(file);
+ };
+</script>
+
+{#if need2fa}
+ <Pin bind:value={token} title="Enter 2FA Code" {cancel} notify={false} />
+{/if}
+
+<div
+ class="mx-auto md:shadow-xl rounded-3xl max-w-xl w-full md:w-[480px] md:p-8 space-y-5 mb-20"
+>
+ <h1 class="text-2xl font-bold text-center">{$t("login.createAccount")}</h1>
+ <input
+ type="file"
+ class="hidden"
+ bind:this={avatarInput}
+ on:change={(e) => handleFile(e, "profile")}
+ />
+
+ <div class="relative">
+ <button
+ class="absolute w-8 h-12 left-12 bg-white rounded top-12"
+ on:click={decr}
+ >
+ <Icon icon="chevron-left" style="w-8 " />
+ </button>
+ <button class="block relative w-32 mx-auto" on:click={selectAvatar}>
+ <button
+ class="w-32 h-32 rounded-full border-4 border-white overflow-hidden flex mx-auto relative"
+ >
+ <img
+ {src}
+ class="w-full h-full object-cover object-center overflow-hidden"
+ alt={username}
+ />
+ </button>
+ <button
+ class="absolute bg-white rounded-full p-2 mx-auto right-0 bottom-0 z-10 bg-opacity-80"
+ >
+ <Icon icon="upload" style="w-8" />
+ </button>
+ </button>
+ <button
+ class="absolute w-8 h-12 right-12 bg-white rounded top-12"
+ on:click={incr}
+ >
+ <Icon icon="chevron-left" style="w-8 rotate-180" />
+ </button>
+ </div>
+
+ {#if form?.error}
+ <div class="text-red-600 text-center" in:fly>
+ {form.error}
+ </div>
+ {/if}
+
+ <form class="space-y-5" on:submit|preventDefault={handleSubmit} method="POST">
+ <input
+ type="hidden"
+ name="loginRedirect"
+ value={$loginRedirect || $page.url.searchParams.get("redirect")}
+ />
+ <input type="hidden" name="token" value={token} />
+
+ <div class="relative">
+ <label for="username" class="font-semibold">{$t("login.username")}</label>
+ <input
+ use:focus
+ name="username"
+ type="text"
+ required
+ class="bg-primary"
+ bind:value={username}
+ on:focus={clear}
+ autocapitalize="none"
+ />
+ <button
+ tabindex="-1"
+ type="button"
+ on:click={refresh}
+ class="absolute right-0 top-4"
+ >
+ <Icon icon="random" style="w-10 m-4" />
+ </button>
+ </div>
+
+ <div class="relative">
+ <label for="password" class="block font-semibold"
+ >{$t("login.password")}</label
+ >
+ {#if revealPassword}
+ <input
+ name="password"
+ type="text"
+ required
+ class="bg-primary"
+ bind:value={$password}
+ autocapitalize="none"
+ />
+ {:else}
+ <input
+ name="password"
+ type="password"
+ required
+ class="bg-primary"
+ bind:value={$password}
+ autocapitalize="none"
+ on:focus={clear}
+ />
+ {/if}
+ <button
+ type="button"
+ tabindex="-1"
+ on:click={() => (revealPassword = !revealPassword)}
+ class="absolute right-0 top-4"
+ >
+ <Icon icon={revealPassword ? "eye" : "eye-off"} style="m-6" />
+ </button>
+ </div>
+
+ <button
+ type="submit"
+ class="bg-black text-white w-full rounded-2xl p-4 font-semibold hover:opacity-80"
+ disabled={loading}
+ bind:this={btn}
+ >
+ {#if loading}
+ <Spinner />
+ {:else}
+ {$t("login.register")}
+ {/if}
+ </button>
+
+ <p class="text-secondary text-center font-medium">
+ {$t("login.haveAccount")}
+ <a
+ href={"/login"}
+ class="block md:inline text-black underline underline-offset-4 hover:opacity-80"
+ >
+ {$t("login.signIn")}
+ </a>
+ </p>
+ </form>
+</div>
diff --git a/src/routes/(static)/removal/+page.svelte b/src/routes/(static)/removal/+page.svelte
new file mode 100644
index 00000000..9ce4eab1
--- /dev/null
+++ b/src/routes/(static)/removal/+page.svelte
@@ -0,0 +1,9 @@
+<div class="space-y-5">
+ <div class="text-2xl font-bold">Data Removal</div>
+
+ <div>
+ If you wish to delete your account and have your data removed, please add a
+ verified email address to your account and send an email from it to
+ <b>[email protected]</b> requesting that we delete your account data.
+ </div>
+</div>
diff --git a/src/routes/(app)/support/+page.svelte b/src/routes/(static)/support/+page.svelte
index ad31ad1a..062f552b 100644
--- a/src/routes/(app)/support/+page.svelte
+++ b/src/routes/(static)/support/+page.svelte
@@ -1,8 +1,8 @@
<script>
+ import { browser } from "$app/environment";
import { onDestroy } from "svelte";
import { fail, success, post } from "$lib/utils";
import { scale } from "svelte/transition";
- import AppHeader from "$comp/AppHeader.svelte";
import Icon from "$comp/Icon.svelte";
import { t } from "$lib/translations";
@@ -24,12 +24,13 @@
grecaptcha.execute(recaptchaSiteKey, { action: "submit" }).then((token) =>
post("/support", { username: user?.username, email, message, token })
.then(() => (sent = true))
- .catch(() => fail("problem submitting"))
+ .catch(() => fail("problem submitting")),
);
});
};
onDestroy(() => {
+ if (!browser) return;
const nodeBadge = document.querySelector(".grecaptcha-badge");
if (nodeBadge) {
document.body.removeChild(nodeBadge.parentNode);
@@ -52,13 +53,9 @@
></script></svelte:head
>
-{#if user}
- <AppHeader {data} />
-{/if}
-
-<div class="container px-4 max-w-lg mx-auto mt-20 space-y-8">
+<div class="container max-w-lg mx-auto space-y-8 p-4 pb-20">
{#if sent}
- <h1 class="text-center text-3xl md:text-4xl font-semibold">Thank you!</h1>
+ <h1 class="text-center text-3xl lg:text-4xl font-semibold">Thank you!</h1>
<div class="text-center text-lg text-secondary">
Someone will be in touch shortly.
</div>
@@ -89,7 +86,6 @@
>{$t("user.support.accountName")}</label
>
<input
- class="bg-primary"
type="text"
name="account"
required
@@ -101,13 +97,7 @@
<label for="email" class="font-semibold"
>{$t("user.support.email")}</label
>
- <input
- class="bg-primary"
- type="email"
- name="email"
- bind:value={email}
- required
- />
+ <input type="email" name="email" bind:value={email} required />
</div>
<div class="mb-4">
@@ -116,7 +106,6 @@
>
<textarea
rows={5}
- class="bg-primary"
type="text"
name="message"
bind:value={message}
@@ -127,12 +116,8 @@
<button
type="submit"
disabled={!email || !message}
- class="g-recaptcha {!email || !message
- ? 'opacity-50'
- : 'opacity-100'} bg-black text-white font-bold rounded-xl py-3 w-full mx-auto {email &&
- message
- ? 'hover:opacity-80'
- : ''}">{$t("user.support.send")}</button
+ class="g-recaptcha bg-black text-white font-bold rounded-xl py-3 w-full mx-auto hover:opacity-80"
+ >{$t("user.support.send")}</button
>
</form>
{/if}
diff --git a/src/routes/(app)/support/+server.js b/src/routes/(static)/support/+server.ts
index e9a16cfc..4b179fe2 100644
--- a/src/routes/(app)/support/+server.js
+++ b/src/routes/(static)/support/+server.ts
@@ -4,6 +4,6 @@ import { auth, post } from "$lib/utils";
export const prerender = false;
export async function POST({ cookies, request }) {
- let result = await post("/email", await request.json(), auth(cookies));
- return json(result);
+ const result = await post("/email", await request.json(), auth(cookies));
+ return json(result);
}
diff --git a/src/routes/+error.svelte b/src/routes/+error.svelte
new file mode 100644
index 00000000..faa7d738
--- /dev/null
+++ b/src/routes/+error.svelte
@@ -0,0 +1,37 @@
+<script>
+ import Icon from "$comp/Icon.svelte";
+ import { page } from "$app/stores";
+
+ export let data;
+ let { user } = data;
+
+ let link = user ? `/${user.username}` : "/";
+</script>
+
+<div class="container px-4 max-w-xl mx-auto mt-10 space-y-5">
+ <div class="w-full flex">
+ <a href="/" class="mx-auto">
+ <Icon icon="logo" />
+ </a>
+ </div>
+
+ <div class="flex justify-center items-center">
+ <div class="shadow-xl rounded-3xl px-10 pt-5 pb-10 space-y-5 w-full mx-5">
+ <div class="relative">
+ <h1 class="text-2xl md:text-3xl font-semibold text-center">Error</h1>
+ </div>
+ <p class="text-secondary text-center">Something went wrong</p>
+ <p class="text-secondary text-center">{$page.error.message}</p>
+
+ <div class="flex justify-center py-24">
+ <a href={link}>
+ <button
+ class="bg-black text-white border rounded-full px-8 py-4 font-bold hover:opacity-80 text-xl"
+ >
+ Back
+ </button>
+ </a>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/src/routes/+layout.js b/src/routes/+layout.js
deleted file mode 100644
index 7b5d4f44..00000000
--- a/src/routes/+layout.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import { addTranslations, setLocale, setRoute } from "$lib/translations";
-
-/** @type {import('@sveltejs/kit').Load} */
-export const load = async ({ data }) => {
- const { i18n, translations } = data;
- const { locale, route } = i18n;
-
- addTranslations(translations);
-
- await setRoute(route);
- await setLocale(locale);
-
- return i18n;
-};
diff --git a/src/routes/+layout.server.js b/src/routes/+layout.server.js
deleted file mode 100644
index 5d1688fc..00000000
--- a/src/routes/+layout.server.js
+++ /dev/null
@@ -1,45 +0,0 @@
-import { auth, get } from "$lib/utils";
-import {
- locales,
- loadTranslations,
- translations,
- defaultLocale,
-} from "$lib/translations";
-
-export let load = async ({ cookies, request, url }) => {
- let { host, pathname } = url;
- let user;
- let token = cookies.get("token");
- if (token) {
- try {
- user = await get("/me", auth(cookies));
- } catch (e) {}
- }
-
- // Try to get the locale from cookie
- let locale = user?.language || (cookies.get("lang") || "").toLowerCase();
-
- // Get user preferred locale
- if (!locale) {
- locale = `${`${request.headers.get("accept-language")}`.match(
- /[a-zA-Z]+?(?=-|_|,|;)/
- )}`.toLowerCase();
- }
-
- // Get defined locales
- let supportedLocales = locales.get().map((l) => l.toLowerCase());
-
- // Use default locale if current locale is not supported
- if (!supportedLocales.includes(locale)) {
- locale = defaultLocale;
- }
-
- await loadTranslations(locale, pathname); // keep this just before the `return`
-
- return {
- host,
- pathname,
- i18n: { locale, route: pathname },
- translations: translations.get(),
- };
-};
diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts
new file mode 100644
index 00000000..b4022e69
--- /dev/null
+++ b/src/routes/+layout.server.ts
@@ -0,0 +1,47 @@
+import {
+ defaultLocale,
+ loadTranslations,
+ locales,
+} from "$lib/translations/index";
+import { auth, get, sleep } from "$lib/utils";
+
+export const load = async ({ cookies, request, url }) => {
+ const { host, pathname } = url;
+ let user;
+ const token = cookies.get("token");
+ if (token) {
+ try {
+ user = await get("/me", auth(cookies));
+ } catch (e) {
+ if (e.message.startsWith("Rate")) await sleep(3000);
+ user = await get("/me", auth(cookies));
+ }
+ }
+
+ // Try to get the locale from cookie
+ let locale = user?.language || (cookies.get("lang") || "").toLowerCase();
+
+ // Get user preferred locale
+ if (!locale) {
+ locale = `${`${request.headers.get("accept-language")}`.match(
+ /[a-zA-Z]+?(?=-|_|,|;)/,
+ )}`.toLowerCase();
+ }
+
+ // Get defined locales
+ const supportedLocales = locales.get().map((l) => l.toLowerCase());
+
+ // Use default locale if current locale is not supported
+ if (!supportedLocales.includes(locale)) {
+ locale = defaultLocale;
+ }
+
+ await loadTranslations(locale, pathname); // keep this just before the `return`
+
+ return {
+ host,
+ pathname,
+ i18n: { locale, route: pathname },
+ user,
+ };
+};
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 545018ed..a07c42cb 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -1,7 +1,10 @@
<script>
+ import { browser } from "$app/environment";
import { PUBLIC_DOMAIN } from "$env/static/public";
import "../app.css";
import { loading, t } from "$lib/translations";
+ import { onMount } from "svelte";
+ import { installPrompt } from "$lib/store";
export let data;
let { pathname } = data;
@@ -9,6 +12,14 @@
let host = PUBLIC_DOMAIN.includes("localhost")
? `http://${PUBLIC_DOMAIN}`
: `https://${PUBLIC_DOMAIN}`;
+
+ onMount(() => {
+ if (!browser) return;
+ window.addEventListener("beforeinstallprompt", (event) => {
+ event.preventDefault();
+ $installPrompt = event;
+ });
+ });
</script>
<svelte:head>
diff --git a/src/routes/+layout.ts b/src/routes/+layout.ts
new file mode 100644
index 00000000..20892e44
--- /dev/null
+++ b/src/routes/+layout.ts
@@ -0,0 +1,14 @@
+import { addTranslations, setLocale, setRoute } from "$lib/translations/index";
+
+/** @type {import('@sveltejs/kit').Load} */
+export const load = async ({ data }) => {
+ const { i18n, translations } = data;
+ const { locale, route } = i18n;
+
+ addTranslations(translations);
+
+ await setRoute(route);
+ await setLocale(locale);
+
+ return i18n;
+};
diff --git a/src/routes/+page.server.js b/src/routes/+page.server.js
deleted file mode 100644
index 904e543d..00000000
--- a/src/routes/+page.server.js
+++ /dev/null
@@ -1,4 +0,0 @@
-// export const prerender = true;
-export let load = async () => {
- return { faqs: ["cost", "compatibility", "safety", "pos", "bitcoin"] };
-};
diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts
new file mode 100644
index 00000000..5679ea61
--- /dev/null
+++ b/src/routes/+page.server.ts
@@ -0,0 +1,3 @@
+export const load = async () => {
+ return { faqs: ["cost", "compatibility", "safety", "pos", "bitcoin"] };
+};
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index f1158391..150d29b1 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -6,6 +6,7 @@
import FaqCard from "$comp/FaqCard.svelte";
import Image from "$comp/Image.svelte";
import Footer from "$comp/Footer.svelte";
+ import About from "$comp/About.svelte";
import { locale, t } from "$lib/translations";
import { onDestroy, onMount, tick } from "svelte";
@@ -28,19 +29,9 @@
let loaded;
let observer;
- let isIntersecting = false;
- let About;
onMount(async () => {
- observer = new IntersectionObserver(async (entries) => {
- About = (await import("$comp/About.svelte")).default;
- isIntersecting = isIntersecting || entries[0].isIntersecting;
- });
-
loaded = true;
-
- await tick();
- observer.observe(document.getElementById("faq"));
});
onDestroy(() => (loaded = false));
@@ -103,9 +94,7 @@
<div bind:this={about} />
</div>
- {#if isIntersecting}
- <About />
- {/if}
+ <About />
</main>
<Footer />
diff --git a/src/routes/about/+server.js b/src/routes/about/+server.ts
index b6912cb4..7cc1b7e8 100644
--- a/src/routes/about/+server.js
+++ b/src/routes/about/+server.ts
@@ -1,5 +1,5 @@
import { redirect } from "@sveltejs/kit";
export async function GET() {
- throw new redirect(307, "/#about");
+ redirect(307, "/#about");
}
diff --git a/src/routes/map/+page.server.js b/src/routes/map/+page.server.js
deleted file mode 100644
index 5012e7e3..00000000
--- a/src/routes/map/+page.server.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import { get } from "$lib/utils";
-
-export let load = async () => {
- let data = { locations: [] };
-
- try {
- data = await get("/locations");
- } catch (e) {}
-
- return data;
-};
diff --git a/src/routes/map/+page.server.ts b/src/routes/map/+page.server.ts
new file mode 100644
index 00000000..b921cc22
--- /dev/null
+++ b/src/routes/map/+page.server.ts
@@ -0,0 +1,11 @@
+import { get } from "$lib/utils";
+
+export const load = async () => {
+ let data = { locations: [] };
+
+ try {
+ data = await get("/locations");
+ } catch (e) {}
+
+ return data;
+};
diff --git a/src/routes/map/+page.svelte b/src/routes/map/+page.svelte
index 53cd8bdc..2addca54 100644
--- a/src/routes/map/+page.svelte
+++ b/src/routes/map/+page.svelte
@@ -6,14 +6,6 @@
let { locations } = data;
</script>
-<div class="pt-4">
- <div class="w-[243px] mx-auto mb-4">
- <a href="/">
- <Icon icon="logo" />
- </a>
- </div>
-
- <div class="flex justify-center items-center">
- <LocationsMap {locations} />
- </div>
+<div class="h-screen w-screen">
+ <LocationsMap {locations} />
</div>
diff --git a/src/routes/start/+server.js b/src/routes/start/+server.js
deleted file mode 100644
index babe7db6..00000000
--- a/src/routes/start/+server.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import { auth, get } from "$lib/utils";
-import { redirect } from "@sveltejs/kit";
-
-export async function GET({ cookies }) {
- let username = cookies.get("username");
- if (username) {
- redirect(307, `/${username}/receive`);
- }
-
- redirect(307, "/");
-}
diff --git a/src/routes/start/+server.ts b/src/routes/start/+server.ts
new file mode 100644
index 00000000..58bca85f
--- /dev/null
+++ b/src/routes/start/+server.ts
@@ -0,0 +1,10 @@
+import { redirect } from "@sveltejs/kit";
+
+export async function GET({ cookies }) {
+ const username = cookies.get("username");
+ if (username) {
+ redirect(307, `/${username}/receive`);
+ }
+
+ redirect(307, "/");
+}
diff --git a/src/service-worker.js b/src/service-worker.js
new file mode 100644
index 00000000..fa934333
--- /dev/null
+++ b/src/service-worker.js
@@ -0,0 +1,37 @@
+import { build, files, version } from "$service-worker";
+
+self.addEventListener("install", (event) => {});
+self.addEventListener("activate", (event) => {});
+self.addEventListener("fetch", (event) => {});
+self.addEventListener("push", (event) => {
+ const { title, body, url } = event.data.json();
+ const icon = "/images/icon.png";
+ const badge = "/images/badge.png";
+ self.registration.showNotification(title, {
+ body,
+ icon,
+ badge,
+ data: { url },
+ });
+});
+
+self.addEventListener("notificationclick", (event) => {
+ event.notification.close();
+
+ const url = event.notification.data.url || "/";
+
+ event.waitUntil(
+ clients
+ .matchAll({ type: "window", includeUncontrolled: true })
+ .then((clientList) => {
+ for (const client of clientList) {
+ if (client.url === url && "focus" in client) {
+ return client.focus();
+ }
+ }
+ if (clients.openWindow) {
+ return clients.openWindow(url);
+ }
+ }),
+ );
+});