Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add React Library #77

Merged
merged 9 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cool-zoos-rest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@fedimint/react': patch
---

Added an example project for developing the react package
5 changes: 5 additions & 0 deletions .changeset/empty-kings-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@fedimint/react': patch
---

Added useReceiveLightning and useSendlightning hooks
5 changes: 5 additions & 0 deletions .changeset/fifty-papayas-float.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@fedimint/react': patch
---

Introduced a bunch of helper hooks (useBalance, useFedimintWallet, useLightningInvoice, useOpenWallet)
5 changes: 5 additions & 0 deletions .changeset/soft-parrots-hear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@fedimint/react': patch
---

Introduces the `FedimintWalletContext` and `FedimintWalletProvider` to provide access to the FedimintWallet functions throughout your app.`
2 changes: 1 addition & 1 deletion examples/vite-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"dependencies": {
"@fedimint/core-web": "canary",
"react": "^18.3.1",
"react-dom": "^18.3.1"
"react-dom": ">=18.3.1"
},
"devDependencies": {
"@types/react": ">=18.3.11",
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"clean:deep": "rm -rf node_modules && pnpm run --r --parallel clean:deep",
"deps": "pnpx taze -r",
"dev": "pnpm build && pnpm dev:vite",
"dev:react": "pnpm --filter react dev",
"dev:vite": "pnpm --filter vite-core dev",
"dev:bare": "pnpm run --filter bare-js server",
"docs:dev": "pnpm run --filter docs docs:dev",
Expand Down
20 changes: 13 additions & 7 deletions packages/core-web/src/FedimintWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,19 @@ export class FedimintWallet {
throw new Error(
'The FedimintWallet is already open. You can only call `joinFederation` on closed clients.',
)
const response = await this._client.sendSingleMessage<{ success: boolean }>(
'join',
{ inviteCode, clientName },
)
if (response.success) {
this._isOpen = true
this._resolveOpen()
try {
const response = await this._client.sendSingleMessage<{
success: boolean
}>('join', { inviteCode, clientName })
if (response.success) {
this._isOpen = true
this._resolveOpen()
}

return response.success
} catch (e) {
logger.error('Error joining federation', e)
return false
}
}

Expand Down
37 changes: 37 additions & 0 deletions packages/react/lib/contexts/FedimintWalletContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { FedimintWallet } from '@fedimint/core-web'
import { createContext, createElement } from 'react'

let wallet: FedimintWallet

type FedimintWalletConfig = {
lazy?: boolean
debug?: boolean
}

export const setupFedimintWallet = (config: FedimintWalletConfig) => {
wallet = new FedimintWallet(!!config.lazy)
if (config.debug) {
wallet.setLogLevel('debug')
}
}

export const FedimintWalletContext = createContext<
{ wallet: FedimintWallet } | undefined
>(undefined)

export type FedimintWalletProviderProps = {}

export const FedimintWalletProvider = (
parameters: React.PropsWithChildren<FedimintWalletProviderProps>,
) => {
const { children } = parameters

if (!wallet)
throw new Error(
'You must call setupFedimintWallet() first. See the getting started guide.',
)

const props = { value: { wallet } }

return createElement(FedimintWalletContext.Provider, props, children)
}
7 changes: 7 additions & 0 deletions packages/react/lib/contexts/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {
FedimintWalletContext,
FedimintWalletProvider,
setupFedimintWallet,
} from './FedimintWalletContext'

export { FedimintWalletContext, FedimintWalletProvider, setupFedimintWallet }
13 changes: 13 additions & 0 deletions packages/react/lib/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useBalance } from './useBalance'
import { useOpenWallet } from './useOpenWallet'
import { useFedimintWallet } from './useFedimintWallet'
import { useReceiveLightning } from './useReceiveLightning'
import { useSendLightning } from './useSendLightning'

export {
useBalance,
useOpenWallet,
useFedimintWallet,
useReceiveLightning,
useSendLightning,
}
22 changes: 22 additions & 0 deletions packages/react/lib/hooks/useBalance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useEffect, useState } from 'react'
import { useFedimintWallet, useOpenWallet } from '.'

export const useBalance = () => {
const wallet = useFedimintWallet()
const { walletStatus } = useOpenWallet()
const [balance, setBalance] = useState<number>()

useEffect(() => {
if (walletStatus !== 'open') return

const unsubscribe = wallet.balance.subscribeBalance((balance) => {
setBalance(balance)
})

return () => {
unsubscribe()
}
}, [walletStatus])

return balance
}
12 changes: 12 additions & 0 deletions packages/react/lib/hooks/useFedimintWallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useContext } from 'react'
import { FedimintWalletContext } from '../contexts'

export const useFedimintWallet = () => {
const value = useContext(FedimintWalletContext)
if (!value?.wallet) {
throw new Error(
'useFedimintWallet must be used within a FedimintWalletProvider',
)
}
return value.wallet
}
42 changes: 42 additions & 0 deletions packages/react/lib/hooks/useOpenWallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useCallback, useEffect, useState } from 'react'
import { useFedimintWallet } from '.'

type WalletStatus = 'open' | 'closed' | 'opening'

export const useOpenWallet = () => {
const wallet = useFedimintWallet()
const [walletStatus, setWalletStatus] = useState<WalletStatus>()

const openWallet = useCallback(() => {
if (walletStatus === 'open') return

setWalletStatus('opening')
wallet.open().then((res) => {
setWalletStatus(res ? 'open' : 'closed')
})
}, [wallet])

const joinFederation = useCallback(
async (invite: string) => {
if (walletStatus === 'open') return

setWalletStatus('opening')

const res = await wallet.joinFederation(invite)
setWalletStatus(res ? 'open' : 'closed')
},
[wallet],
)

useEffect(() => {
wallet.waitForOpen().then(() => {
setWalletStatus('open')
})

return () => {
setWalletStatus('closed')
}
}, [wallet])

return { walletStatus, openWallet, joinFederation }
}
46 changes: 46 additions & 0 deletions packages/react/lib/hooks/useReceiveLightning.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { useCallback, useEffect, useState } from 'react'
import { useFedimintWallet, useOpenWallet } from '.'
import { LnReceiveState, type CreateBolt11Response } from '@fedimint/core-web'

export const useReceiveLightning = () => {
const wallet = useFedimintWallet()
const { walletStatus } = useOpenWallet()
const [invoice, setInvoice] = useState<CreateBolt11Response>()
const [invoiceReceiveState, setInvoiceReceiveState] =
useState<LnReceiveState>()
const [error, setError] = useState<string>()

const generateInvoice = useCallback(
async (amount: number, description: string) => {
if (walletStatus !== 'open') throw new Error('Wallet is not open')
const response = await wallet.lightning.createInvoice(amount, description)
setInvoice(response)
return response.invoice
},
[wallet, walletStatus],
)

useEffect(() => {
if (walletStatus !== 'open' || !invoice) return
const unsubscribe = wallet.lightning.subscribeLnReceive(
invoice.operation_id,
(state) => {
setInvoiceReceiveState(state)
},
(error) => {
setError(error)
},
)

return () => {
unsubscribe()
}
}, [walletStatus, invoice])

return {
generateInvoice,
bolt11: invoice?.invoice,
invoiceStatus: invoiceReceiveState,
error,
}
}
49 changes: 49 additions & 0 deletions packages/react/lib/hooks/useSendLightning.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { useCallback, useEffect, useState } from 'react'
import { useFedimintWallet, useOpenWallet } from '.'
import {
type LnPayState,
type OutgoingLightningPayment,
} from '@fedimint/core-web'

export const useSendLightning = () => {
const wallet = useFedimintWallet()
const { walletStatus } = useOpenWallet()
const [payment, setPayment] = useState<OutgoingLightningPayment>()
const [paymentState, setPaymentState] = useState<LnPayState>()
const [error, setError] = useState<string>()

const payInvoice = useCallback(
async (bolt11: string) => {
if (walletStatus !== 'open') throw new Error('Wallet is not open')
const response = await wallet.lightning.payInvoice(bolt11)
setPayment(response)
return response
},
[wallet, walletStatus],
)

useEffect(() => {
if (walletStatus !== 'open' || !payment) return
const unsubscribe = wallet.lightning.subscribeLnPay(
// @ts-ignore
payment.payment_type.lightning,
(state) => {
setPaymentState(state)
},
(error) => {
setError(error)
},
)

return () => {
unsubscribe()
}
}, [walletStatus, payment])

return {
payInvoice,
payment,
paymentStatus: paymentState,
paymentError: error,
}
}
2 changes: 2 additions & 0 deletions packages/react/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './hooks'
export * from './contexts'
11 changes: 11 additions & 0 deletions packages/react/lib/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { FedimintWallet } from '@fedimint/core-web'

let wallet: FedimintWallet | undefined

export const initFedimintReact = (lazy: boolean = false) => {
if (!lazy) {
wallet = new FedimintWallet(lazy)
}

return {}
}
23 changes: 19 additions & 4 deletions packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,38 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --p ./tsconfig.build.json && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"files": [
"dist"
],
"main": "./dist/fedimint-react.umd.cjs",
"module": "./dist/fedimint-react.js",
"exports": {
".": {
"import": "./dist/fedimint-react.js",
"require": "./dist/fedimint-react.umd.cjs"
}
},
"peerDependencies": {
"react": "^18.3.1",
"react-dom": ">=18.3.1"
"@fedimint/core-web": "workspace:*",
"react": "^18.3.1"
},
"devDependencies": {
"@types/react": ">=18.3.11",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^7.18.0",
"@typescript-eslint/parser": "^7.18.0",
"@vitejs/plugin-react": "^4.3.2",
"eslint": "^8.57.1",
"eslint": "^9.11.1",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.12",
"react-dom": ">=18.3.1",
"typescript": "^5.6.2",
"vite": "^5.4.8"
"vite": "^5.4.8",
"vite-plugin-dts": "^4.2.4",
"vite-plugin-wasm": "^3.3.0"
}
}
Loading
Loading