Skip to content

Commit

Permalink
get investment
Browse files Browse the repository at this point in the history
  • Loading branch information
onnovisser committed Dec 16, 2024
1 parent eb910e7 commit e85138c
Show file tree
Hide file tree
Showing 9 changed files with 205 additions and 17 deletions.
17 changes: 4 additions & 13 deletions sdk-consumer/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,22 @@
import { FabricProvider, centrifugeTheme } from '@centrifuge/fabric'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { WagmiProvider, useAccount } from 'wagmi'
import { WagmiProvider } from 'wagmi'
import { Invest } from './components/Invest'
import { TransactionProvider } from './components/Transactions/TransactionsProvider'
import { Account } from './components/account'
import { WalletOptions } from './components/wallet-options'
import { wagmiConfig } from './config/wagmiConfig'

const queryClient = new QueryClient()

function ConnectWallet() {
const { isConnected } = useAccount()
if (isConnected) return <Account />
return <WalletOptions />
}

function App() {
export function App() {
return (
<FabricProvider theme={centrifugeTheme}>
<TransactionProvider>
<WagmiProvider config={wagmiConfig}>
<QueryClientProvider client={queryClient}>
<ConnectWallet />
<Invest />
</QueryClientProvider>
</WagmiProvider>
</TransactionProvider>
</FabricProvider>
)
}

export default App
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useAccount, useDisconnect, useEnsName } from 'wagmi'
import { useAccountBalance } from '../hooks/useAccount'

export function Account() {
export function Invest() {
const { address } = useAccount()
const { disconnect } = useDisconnect()
const { data: ensName } = useEnsName({ address })
Expand Down
70 changes: 70 additions & 0 deletions sdk-consumer/src/components/ConnectionGuard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { Button, IconChevronDown, Menu, MenuItem, MenuItemGroup, Popover, Stack, Text } from '@centrifuge/fabric'
import { ReactNode } from 'react'
import { useAccount, useChains, useSwitchChain } from 'wagmi'
import { WalletOptions } from './WalletOptions'

type Props = {
networks: number[]
children: ReactNode
message?: string
}

export function ConnectionGuard({ networks, children, message = 'Unsupported network.' }: Props) {
const { switchChain } = useSwitchChain()
const chains = useChains()
function getName(chainId: number) {
const chain = chains.find((c) => c.id === chainId)
return chain?.name || chainId.toString()
}

const { isConnected, chainId } = useAccount()

if (!isConnected) {
return (
<Stack gap={2} pb={3}>
<Text variant="body3">Connect to continue</Text>
<WalletOptions />
</Stack>
)
}
if (chainId && networks.includes(chainId)) {
return <>{children}</>
}

return (
<Stack gap={2} pb={3}>
<Text variant="body3">{message}</Text>
{networks.length === 1 ? (
<Button onClick={() => switchChain({ chainId: networks[0] })}>Switch to {getName(networks[0])}</Button>
) : (
<Popover
renderTrigger={(props, ref, state) => (
<Stack ref={ref} width="100%" alignItems="stretch">
<Button iconRight={IconChevronDown} active={state.isOpen} {...props}>
Switch network
</Button>
</Stack>
)}
renderContent={(props, ref, state) => (
<div {...props} ref={ref}>
<Menu>
<MenuItemGroup>
{networks.map((network) => (
<MenuItem
label={getName(network)}
onClick={() => {
state.close()
switchChain({ chainId: network })
}}
key={network}
/>
))}
</MenuItemGroup>
</Menu>
</div>
)}
/>
)}
</Stack>
)
}
41 changes: 41 additions & 0 deletions sdk-consumer/src/components/Invest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useAccount, useDisconnect, useEnsName } from 'wagmi'
import { useAccountBalance } from '../hooks/useAccount'
import { useActiveNetworks, useVaults } from '../hooks/usePool'
import { ConnectionGuard } from './ConnectionGuard'

const poolId = '2779829532'
const trancheId = '0xac6bffc5fd68f7772ceddec7b0a316ca'

export function Invest() {
const { data: networks } = useActiveNetworks(poolId)
console.log('active networks', networks)
return (
<ConnectionGuard networks={networks?.map((n) => n.chainId) || []}>
<InvestInner />
</ConnectionGuard>
)
}

function InvestInner() {
const { address } = useAccount()
const { disconnect } = useDisconnect()
const { data: ensName } = useEnsName({ address })
const { data: balance, error, retry, isError } = useAccountBalance()
const { data: vaults } = useVaults(poolId, trancheId, 11155111)

return (
<div>
{address && <div>{ensName ? `${ensName} (${address})` : address}</div>}
<h1>Your balance is {balance?.toFloat() ?? 'Loading...'}</h1>
{error ? (
<div>
Error {isError && 'fatal'}
<button type="button" onClick={() => retry()}>
Retry
</button>
</div>
) : null}
<button onClick={() => disconnect()}>Disconnect</button>
</div>
)
}
5 changes: 3 additions & 2 deletions sdk-consumer/src/config/wagmiConfig.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { createConfig, http } from 'wagmi'
import { sepolia } from 'wagmi/chains'
import { baseSepolia, sepolia } from 'wagmi/chains'
import { injected } from 'wagmi/connectors'

export const wagmiConfig = createConfig({
chains: [sepolia],
chains: [sepolia, baseSepolia],
connectors: [injected()],
transports: {
[sepolia.id]: http(),
[baseSepolia.id]: http(),
},
})
74 changes: 74 additions & 0 deletions sdk-consumer/src/hooks/useCentrifugeTransaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { OperationConfirmedStatus, Transaction } from '@centrifuge/sdk'
import * as React from 'react'
import { lastValueFrom, tap } from 'rxjs'
import { useTransactions } from '../components/Transactions/TransactionsProvider'
import { useVaults } from './usePool'

export type CentrifugeTransactionOptions = {
onSuccess?: (args: any[], result: OperationConfirmedStatus) => void
onError?: (error: any) => void
}

function Comp() {
const { data: vaults } = useVaults('2779829532', '0xac6bffc5fd68f7772ceddec7b0a316ca', 11155111)
const { execute, isLoading } = useCentrifugeTransaction()

async function submit() {
const vault = vaults?.[0]!
execute(vault.increaseInvestOrder(100))
}
}

export function useCentrifugeTransaction() {
const { updateTransaction, addTransaction } = useTransactions()
const [status, setStatus] = React.useState<'idle' | 'loading' | 'success' | 'error'>()

async function execute(observable: Transaction) {
setStatus('loading')
let lastId = ''
try {
const lastResult = await lastValueFrom(
observable.pipe(
tap((result) => {
switch (result.type) {
case 'SigningTransaction':
lastId = Math.random().toString(36).slice(2)
addTransaction({
id: lastId,
title: result.title,
status: 'unconfirmed',
})
break
case 'TransactionPending':
updateTransaction(lastId, {
status: 'pending',
})
break
case 'TransactionConfirmed':
updateTransaction(lastId, {
status: 'succeeded',
result: result.receipt,
})
}
})
)
)
return (lastResult as OperationConfirmedStatus).receipt
} catch (e) {
if (lastId) {
updateTransaction(lastId, {
status: 'failed',
error: e,
})
setStatus('error')
}
throw e
}
}

return {
execute,
reset: () => setStatus('idle'),
isLoading: status === 'loading',
}
}
11 changes: 11 additions & 0 deletions sdk-consumer/src/hooks/usePool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ function usePools() {
return pools
}

export function useActiveNetworks(poolId: string) {
const pool = usePools().find((p) => p.id === poolId)
const networks$ = useMemo(() => {
console.log('getActiveNetworks $$', pool)
return pool?.activeNetworks()
}, [pool])
return useCentrifugeQuery(networks$)
}

export function useVaults(poolId: string, trancheId: string, chainId: number) {
const pool = usePools().find((p) => p.id === poolId)
const vaults$ = useMemo(
Expand All @@ -20,3 +29,5 @@ export function useVaults(poolId: string, trancheId: string, chainId: number) {
)
return useCentrifugeQuery(vaults$)
}

export function useVaultInvestment() {}
2 changes: 1 addition & 1 deletion sdk-consumer/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import { App } from './App.tsx'

createRoot(document.getElementById('root')!).render(
<StrictMode>
Expand Down

0 comments on commit e85138c

Please sign in to comment.