ekzyis 371e7417ce
Wallet definitions with uniform interface (#1243)
* wip: Use uniform interface for wallets

* Fix import error

* Update wallet logging + other stuff

* add canPay and canSend to wallet definition
* rename 'default payment method' to 'enabled' and add enable + disable method

* Set canPay, canReceive in useWallet

* Enable wallet if just configured

* Don't pass logger to sendPayment

* Add logging to attach & detach

* Add schema to wallet def

* Add NWC wallet

* Fix unused isDefault saved in config

* Fix enableWallet

* wrong storage key was used
* broke if wallets with no configs existed

* Run validation during save

* Use INFO level for 'wallet disabled' message

* Pass config with spread operator

* Support help, optional, hint in wallet fields

* wip: Add LNC

* Fix 20s page load for /settings/wallets.json?nodata=true

For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load.

* Fix extremely slow page load for LNC import

I noticed that the combination of

```
import { Form, PasswordInput, SubmitButton } from '@/components/form'
```

in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads.

* Use normal imports

* Revert "Fix 20s page load for /settings/wallets.json?nodata=true"

This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2.

Not using the dynamic import for LNC fixed the slow page load with ?nodata=true.

* Remove follow and show recent logs first

* Fix position of log start marker

* Add FIXMEs for LNC

I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs.

* Remove logger.error since already handled in useWallet

* Don't require destructuring to pass props to input

* wip: Add LND autowithdrawals

* receiving wallets need to export 'server' object field
* don't print macaroon error stack
* fix missing wallet logs order update
* mark autowithdrawl settings as required
* fix server wallet logs deletion
* remove canPay and canReceive since it was confusing where it is available

TODO

* also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined
* define createInvoice function in wallet definition
* consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated'
* see FIXMEs

* Fix TypeError

* Fix sendPayment called with empty config

* removed useEffect such that config is available on first render
* fix hydration error using dynamic import without SSR

* Fix confusing UX around enabled

* Remove FIXMEs

Rebase on master seemed to have fixed these, weird

* Use same error format in toast and wallet log

* Fix usage of conditional hooks in useConfig

* Fix isConfigured

* Fix delete wallet logs on server

* Fix wallet logs refetch

onError does not exist on client.mutate

* Fix TypeError in isConfigured if no enabled wallet found

* Only include local/server config if required

* Fix another hydration error

* Fix server config not updated after save or detach

* Also use 'enabled' for server wallets

* Fix wallet logs not updated after server delete

* Consistent logs between local and server wallets

* 'wallet attached' on create
* 'wallet updated' on config updates
* 'wallet enabled' and 'wallet disabled' if checkbox changed
* 'wallet detached' on delete

* Also enable server wallets on create

* Disable checkbox if not configured yet

* Move all validation schema into lib/validate

* Implement drag & drop w/o persistence

* Use dynamic import for WalletCard

This fixes a lot of issues with hydration

* Save order as priority

* Fix autowithdrawSettings not applied

Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field.

I have decided that config will be in flat form format. It will be transformed into mutation format during save.

* Save dedicated enabled flag for server wallets

* wallet table now contains boolean column 'enabled'
* 'priority' is now a number everywhere
* use consistent order between how autowithdrawals are attempted and server wallets cards

* Fix onCanceled missing

* Fix typo

* Fix noisy changes in lib/validate

I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later.

This commit should make the changeset cleaner by removing noise.

* Split arguments into [value,] config, context

* Run lnbits url.replace in validate and sendPayment

* Remove unnecessary WALLETS_QUERY

* Generate wallet mutation from fields

* Generate wallet resolver from fields

* Fix import inconsistency between app and worker

* Use wallet.createInvoice for autowithdrawals

* Fix success autowithdrawal log

* Fix wallet security banner shown for server wallets

* Add autowithdrawal to lightning address

* Add optional wallet short name for logging

* Fix draggable

* Fix autowithdraw loop

* Add missing hints

* Add CLN autowithdrawal

* Detach wallets and delete logs on logout

* Remove Wallet in lib/constants

* Use inject function for resolvers and typeDefs

* Fix priority ignored when fetching enabled wallet

* Fix draggable false on first page load due to SSR

* Use touches instead of dnd on mobile

Browsers don't support drag events for touch devices.

To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove.

For now, this commit makes changing the order possible on touch devices with simple touches.

* Fix duplicate CLN error

* Fix autowithdraw priority order

* Fix error per invalid bip39 word

* Update LNC code

* remove LNC FIXMEs

Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic?

* also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments.

* setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81.

* Fix order if wallet with no priority exists

* Use common sort

* Add link to lnbits.com

* Add example wallet def

* Remove TODOs

TODO in components/wallet-logger.js was handled.
I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway.

* Remove console.log

* Toast priority save errors

* Fix leaking relay connections

* Remove 'tor or clearnet' hint for LN addresses

* Remove React dependency from wallet definitions

* Generate resolver name from walletField

* Move wallets into top level directory wallet/

* Put wallets into own folder

* Fix generateMutation

* remove resolverName property from wallet defs
* move function into lib/wallet
* use function in generateMutation on client to fix wrongly generated mutation

* Separate client and server imports by files

* wallets now consist of an index.js, a client.js and a server.js file
* client.js is imported on the client and contains the client portion
* server.js is imported on the server and contains the server porition
* both reexport index.js so everything in index.js can be shared by client and server

* every wallet contains a client.js file since they are all imported on the client to show the cards

* client.js of every wallet is reexported as an array in wallets/client.js
* server.js of every wallet is reexported as an array in wallets/server.js

FIXME: for some reason, worker does not properly import the default export of wallets/server.js

* Fix worker import of wallets/server

* Fix wallet.server usage

* I removed wallet.server in a previous commit
* the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js
* walletType and walletField are now set in index.js
* walletType is now used to determine if a wallet is stored on the server

* also included some formatting changes

* Fix w.default usage

Since package.json with { "type": "module" } was added, this is no longer needed.

* Fix id access in walletPrioritySort

* Fix autowithdrawal error log

* Generate validation schema for LNbits

* Generate validation schema for NWC

* Rename to torAllowed

* Generate validation schema for LNC

* Generate validation schema for LND

* Generate validation schema for LnAddr

* Remove stringTypes

* Generate validation schema for CLN

* Make clear that message belongs to test

* validate.message was used in tandem with validate.test
* it might be confused as the message if the validation for validate.type failed
* now validate.test can be a function or an object of { test, message } shape which matches Yup.test

* Remove validate.schema as a trap door

* make lnc work

* Return null if no wallet was found

* Revert code around schema generation

* Transform autowithdrawSchemaMembers into an object

* Rename schema to yupSchema

* Fix missing required for LNbits adminKey

* Support formik form-level validation

* Fix missing addWalletLog import

* Fix missing space after =

* fix merge conflict resolution mistake

* remove non-custodial* badges

* create guides for attaching wallets in sndev

* Use built-in formik validation or Yup schema but not both

* Rename: validate -> testConnectClient, testConnect -> testConnectServer

* make lnaddr autowithdraw work in dev

* move ATTACH docs to ./wallets and add lnaddr doc

* Fix missing rename: yupSchema -> fieldValidation

* Remove unused context

* Add documentation how to add wallets

---------

Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 17:51:46 -05:00

374 lines
11 KiB
JavaScript

import Link from 'next/link'
import { Button, Dropdown, Nav, Navbar } from 'react-bootstrap'
import styles from '../header.module.css'
import { useRouter } from 'next/router'
import BackArrow from '../../svgs/arrow-left-line.svg'
import { useCallback, useEffect, useState } from 'react'
import Price from '../price'
import SubSelect from '../sub-select'
import { USER_ID, BALANCE_LIMIT_MSATS } from '../../lib/constants'
import Head from 'next/head'
import NoteIcon from '../../svgs/notification-4-fill.svg'
import { useMe } from '../me'
import HiddenWalletSummary from '../hidden-wallet-summary'
import { abbrNum, msatsToSats } from '../../lib/format'
import { useServiceWorker } from '../serviceworker'
import { signOut } from 'next-auth/react'
import Hat from '../hat'
import { randInRange } from '../../lib/rand'
import { useLightning } from '../lightning'
import LightningIcon from '../../svgs/bolt.svg'
import SearchIcon from '../../svgs/search-line.svg'
import classNames from 'classnames'
import SnIcon from '@/svgs/sn.svg'
import { useHasNewNotes } from '../use-has-new-notes'
import { useWallets } from 'wallets'
export function Brand ({ className }) {
return (
<Link href='/' passHref legacyBehavior>
<Navbar.Brand className={classNames(styles.brand, className)}>
<SnIcon width={36} height={36} />
</Navbar.Brand>
</Link>
)
}
export function hasNavSelect ({ path, pathname }) {
return (
pathname.startsWith('/~') &&
!path.endsWith('/post') &&
!path.endsWith('/edit')
)
}
export function Back () {
const router = useRouter()
const [back, setBack] = useState(router.asPath !== '/')
useEffect(() => {
setBack(router.asPath !== '/' && (typeof window.navigation === 'undefined' || window.navigation.canGoBack === undefined || window?.navigation.canGoBack))
}, [router.asPath])
if (!back) return null
return (
<a
role='button' tabIndex='0' className='nav-link p-0 me-2' onClick={() => {
if (back) {
router.back()
} else {
router.push('/')
}
}}
>
<BackArrow className='theme me-1 me-md-2' width={24} height={24} />
</a>
)
}
export function BackOrBrand ({ className }) {
const router = useRouter()
const [back, setBack] = useState(router.asPath !== '/')
useEffect(() => {
setBack(router.asPath !== '/' && (typeof window.navigation === 'undefined' || window.navigation.canGoBack === undefined || window?.navigation.canGoBack))
}, [router.asPath])
return (
<div className='d-flex align-items-center'>
{back ? <Back /> : <Brand className={className} />}
</div>
)
}
export function SearchItem ({ prefix, className }) {
return (
<Link href='/search' passHref legacyBehavior>
<Nav.Link eventKey='search' className={className}>
<SearchIcon className='theme' width={22} height={28} />
</Nav.Link>
</Link>
)
}
export function NavPrice ({ className }) {
return (
<Nav.Item className={classNames(styles.price, className)}>
<Price className='nav-link text-monospace' />
</Nav.Item>
)
}
const PREPEND_SUBS = ['home']
const APPEND_SUBS = [{ label: '--------', items: ['create'] }]
export function NavSelect ({ sub: subName, className, size }) {
const sub = subName || 'home'
return (
<Nav.Item className={className}>
<SubSelect
sub={sub} prependSubs={PREPEND_SUBS} appendSubs={APPEND_SUBS} noForm
groupClassName='mb-0' size={size}
/>
</Nav.Item>
)
}
export function NavNotifications ({ className }) {
const hasNewNotes = useHasNewNotes()
return (
<>
<Head>
<link rel='shortcut icon' href={hasNewNotes ? '/favicon-notify.png' : '/favicon.png'} />
</Head>
<Link href='/notifications' passHref legacyBehavior>
<Nav.Link eventKey='notifications' className={classNames('position-relative', className)}>
<NoteIcon height={28} width={20} className='theme' />
{hasNewNotes &&
<span className={styles.notification}>
<span className='invisible'>{' '}</span>
</span>}
</Nav.Link>
</Link>
</>
)
}
export function WalletSummary () {
const me = useMe()
if (!me) return null
if (me.privates?.hideWalletBalance) {
return <HiddenWalletSummary abbreviate fixedWidth />
}
return `${abbrNum(me.privates?.sats)}`
}
export function NavWalletSummary ({ className }) {
const me = useMe()
const walletLimitReached = me?.privates?.sats >= msatsToSats(BALANCE_LIMIT_MSATS)
return (
<Nav.Item className={className}>
<Link href='/wallet' passHref legacyBehavior>
<Nav.Link eventKey='wallet' className={`${walletLimitReached ? 'text-warning' : 'text-success'} text-monospace px-0 text-nowrap`}>
<WalletSummary me={me} />
</Nav.Link>
</Link>
</Nav.Item>
)
}
export function MeDropdown ({ me, dropNavKey }) {
if (!me) return null
return (
<div className='position-relative'>
<Dropdown className={styles.dropdown} align='end'>
<Dropdown.Toggle className='nav-link nav-item fw-normal' id='profile' variant='custom'>
<Nav.Link eventKey={me.name} as='span' className='p-0'>
{`@${me.name}`}<Hat user={me} />
</Nav.Link>
</Dropdown.Toggle>
<Dropdown.Menu>
<Link href={'/' + me.name} passHref legacyBehavior>
<Dropdown.Item active={me.name === dropNavKey}>
profile
{me && !me.bioId &&
<div className='p-1 d-inline-block bg-secondary ms-1'>
<span className='invisible'>{' '}</span>
</div>}
</Dropdown.Item>
</Link>
<Link href={'/' + me.name + '/bookmarks'} passHref legacyBehavior>
<Dropdown.Item active={me.name + '/bookmarks' === dropNavKey}>bookmarks</Dropdown.Item>
</Link>
<Link href='/wallet' passHref legacyBehavior>
<Dropdown.Item eventKey='wallet'>wallet</Dropdown.Item>
</Link>
<Link href='/satistics?inc=invoice,withdrawal,stacked,spent' passHref legacyBehavior>
<Dropdown.Item eventKey='satistics'>satistics</Dropdown.Item>
</Link>
<Dropdown.Divider />
<Link href='/referrals/month' passHref legacyBehavior>
<Dropdown.Item eventKey='referrals'>referrals</Dropdown.Item>
</Link>
<Dropdown.Divider />
<div className='d-flex align-items-center'>
<Link href='/settings' passHref legacyBehavior>
<Dropdown.Item eventKey='settings'>settings</Dropdown.Item>
</Link>
</div>
<Dropdown.Divider />
<LogoutDropdownItem />
</Dropdown.Menu>
</Dropdown>
{!me.bioId &&
<span className='position-absolute p-1 bg-secondary' style={{ top: '5px', right: '0px' }}>
<span className='invisible'>{' '}</span>
</span>}
</div>
)
}
export function SignUpButton ({ className = 'py-0' }) {
const router = useRouter()
const handleLogin = useCallback(async pathname => await router.push({
pathname,
query: { callbackUrl: window.location.origin + router.asPath }
}), [router])
return (
<Button
className={classNames('align-items-center ps-2 pe-3', className)}
style={{ borderWidth: '2px', width: '112px' }}
id='signup'
onClick={() => handleLogin('/signup')}
>
<LightningIcon
width={17}
height={17}
className='me-1'
/>sign up
</Button>
)
}
export default function LoginButton ({ className }) {
const router = useRouter()
const handleLogin = useCallback(async pathname => await router.push({
pathname,
query: { callbackUrl: window.location.origin + router.asPath }
}), [router])
return (
<Button
className='align-items-center px-3 py-1 mb-2'
id='login'
style={{ borderWidth: '2px', width: '112px' }}
variant='outline-grey-darkmode'
onClick={() => handleLogin('/login')}
>
login
</Button>
)
}
export function LogoutDropdownItem () {
const { registration: swRegistration, togglePushSubscription } = useServiceWorker()
const wallets = useWallets()
return (
<Dropdown.Item
onClick={async () => {
// order is important because we need to be logged in to delete push subscription on server
const pushSubscription = await swRegistration?.pushManager.getSubscription()
if (pushSubscription) {
await togglePushSubscription().catch(console.error)
}
await wallets.resetClient().catch(console.error)
await signOut({ callbackUrl: '/' })
}}
>logout
</Dropdown.Item>
)
}
export function LoginButtons () {
return (
<>
<LoginButton />
<SignUpButton className='py-1' />
</>
)
}
export function AnonDropdown ({ path }) {
const strike = useLightning()
useEffect(() => {
if (!window.localStorage.getItem('striked')) {
const to = setTimeout(() => {
strike()
window.localStorage.setItem('striked', 'yep')
}, randInRange(3000, 10000))
return () => clearTimeout(to)
}
}, [])
return (
<div className='position-relative'>
<Dropdown className={styles.dropdown} align='end'>
<Dropdown.Toggle className='nav-link nav-item' id='profile' variant='custom'>
<Nav.Link eventKey='anon' as='span' className='p-0 fw-normal'>
@anon<Hat user={{ id: USER_ID.anon }} />
</Nav.Link>
</Dropdown.Toggle>
<Dropdown.Menu className='p-3'>
<LoginButtons />
</Dropdown.Menu>
</Dropdown>
</div>
)
}
export function Sorts ({ sub, prefix, className }) {
return (
<>
<Nav.Item className={className}>
<Link href={prefix + '/'} passHref legacyBehavior>
<Nav.Link eventKey='' className={styles.navLink}>hot</Nav.Link>
</Link>
</Nav.Item>
<Nav.Item className={className}>
<Link href={prefix + '/recent'} passHref legacyBehavior>
<Nav.Link eventKey='recent' className={styles.navLink}>recent</Nav.Link>
</Link>
</Nav.Item>
{/* <Nav.Item className={className}>
<Link href={prefix + '/random'} passHref legacyBehavior>
<Nav.Link eventKey='random' className={styles.navLink}>random</Nav.Link>
</Link>
</Nav.Item> */}
{sub !== 'jobs' &&
<Nav.Item className={className}>
<Link
href={{
pathname: '/~/top/[type]/[when]',
query: { type: 'posts', when: 'day', sub }
}} as={prefix + '/top/posts/day'} passHref legacyBehavior
>
<Nav.Link eventKey='top' className={styles.navLink}>top</Nav.Link>
</Link>
</Nav.Item>}
</>
)
}
export function PostItem ({ className, prefix }) {
return (
<Link href={prefix + '/post'} className={`${className} btn btn-md btn-primary py-md-1`}>
post
</Link>
)
}
export function MeCorner ({ dropNavKey, me, className }) {
return (
<div className={className}>
<NavNotifications />
<MeDropdown me={me} dropNavKey={dropNavKey} />
<NavWalletSummary className='d-inline-block' />
</div>
)
}
export function AnonCorner ({ dropNavKey, className }) {
return (
<div className={className}>
<AnonDropdown dropNavKey={dropNavKey} />
</div>
)
}