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

Sdk playground #2522

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"simulation-tests",
"onboarding-api",
"faucet-api",
"pinning-api"
"pinning-api",
"sdk-consumer"
],
"devDependencies": {
"@types/bn.js": "^5.1.1",
Expand Down
24 changes: 24 additions & 0 deletions sdk-consumer/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
1 change: 1 addition & 0 deletions sdk-consumer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<!-- TO ADD -->
28 changes: 28 additions & 0 deletions sdk-consumer/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'

export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
)
12 changes: 12 additions & 0 deletions sdk-consumer/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Centrifuge SDK playground</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
38 changes: 38 additions & 0 deletions sdk-consumer/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "sdk-consumer",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@centrifuge/fabric": "workspace:*",
"@centrifuge/sdk": "0.0.0-alpha.0",
"@talismn/wagmi-connector": "^0.3.1",
"@tanstack/react-query": "^5.59.16",
"@wagmi/core": "^2.15.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"rxjs": "^7.8.1",
"viem": "^2.21.54",
"wagmi": "^2.13.3"
},
"devDependencies": {
"@eslint/js": "^9.13.0",
"@types/node": "^22.8.2",
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
"eslint": "^9.13.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.13",
"globals": "^15.11.0",
"typescript": "~5.6.2",
"typescript-eslint": "^8.10.0",
"vite": "^5.4.9"
}
}
1 change: 1 addition & 0 deletions sdk-consumer/public/vite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 22 additions & 0 deletions sdk-consumer/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { FabricProvider, centrifugeTheme } from '@centrifuge/fabric'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { WagmiProvider } from 'wagmi'
import { Invest } from './components/Invest'
import { TransactionProvider } from './components/Transactions/TransactionsProvider'
import { wagmiConfig } from './config/wagmiConfig'

const queryClient = new QueryClient()

export function App() {
return (
<FabricProvider theme={centrifugeTheme}>
<TransactionProvider>
<WagmiProvider config={wagmiConfig}>
<QueryClientProvider client={queryClient}>
<Invest />
</QueryClientProvider>
</WagmiProvider>
</TransactionProvider>
</FabricProvider>
)
}
2 changes: 2 additions & 0 deletions sdk-consumer/src/centrifuge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import Centrifuge from '@centrifuge/sdk'
export const centrifuge = new Centrifuge({ environment: 'demo' })
17 changes: 17 additions & 0 deletions sdk-consumer/src/components/Connected.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useAccount, useDisconnect, useEnsName } from 'wagmi'
import { useAccountBalance } from '../hooks/useAccount'

export function Invest() {
const { address } = useAccount()
const { disconnect } = useDisconnect()
const { data: ensName } = useEnsName({ address })
const { data: balance } = useAccountBalance()

return (
<div>
{address && <div>{ensName ? `${ensName} (${address})` : address}</div>}
<h1>Your balance is {balance?.toFloat() ?? 'Loading...'}</h1>
<button onClick={() => disconnect()}>Disconnect</button>
</div>
)
}
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>
)
}
104 changes: 104 additions & 0 deletions sdk-consumer/src/components/Invest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { Button, Card, CurrencyInput, Shelf, Spinner, Stack, Text } from '@centrifuge/fabric'
import { PoolNetwork, Vault } from '@centrifuge/sdk'
import { useEffect, useRef, useState } from 'react'
import { useAccount } from 'wagmi'
import { useCentrifugeTransaction } from '../hooks/useCentrifugeTransaction'
import { useActiveNetworks, useVaultInvestment, useVaults } from '../hooks/usePool'
import { ConnectionGuard } from './ConnectionGuard'

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

export function Invest() {
const { data: networks, isLoading } = useActiveNetworks(poolId)
const ref = useRef<PoolNetwork[]>()
if ((networks?.length ?? 0) > (ref.current?.length ?? 0)) {
ref.current = networks
}
return (
<Card maxWidth={400} mx="auto" p={2} backgroundColor="backgroundSecondary">
<Stack gap={2}>
{isLoading ? (
<Shelf justifyContent="center">
<Spinner />
</Shelf>
) : (
<>
<Text variant="heading1">Invest</Text>
<ConnectionGuard networks={ref.current?.map((n) => n.chainId) || []}>
<InvestInner />
</ConnectionGuard>
</>
)}
</Stack>
</Card>
)
}

function InvestInner() {
const { address } = useAccount()
const { data: vaults } = useVaults(poolId, trancheId, 11155111)
const { execute: executeClaim, isLoading: isClaiming } = useCentrifugeTransaction()
const { execute: executeInvest, isLoading: isInvesting } = useCentrifugeTransaction()
const [selectedVault, setVault] = useState<Vault>()
const [amount, setAmount] = useState<number | ''>(0)

useEffect(() => {
if (vaults?.length && (!selectedVault || !vaults.includes(selectedVault))) {
setVault(vaults[0])
}
}, [vaults])

function submit() {
if (!selectedVault || !amount) return
executeInvest(selectedVault.increaseInvestOrder(amount))
}

function claim() {
if (!selectedVault) return
executeClaim(selectedVault.claim())
}

const { data: investment } = useVaultInvestment(selectedVault, address)

return (
<>
{investment?.isAllowedToInvest === false && (
<Text variant="body2" color="statusCritical">
You are not allowed to invest in this vault
</Text>
)}
{investment?.pendingInvestCurrency.gt(0n) && (
<Text variant="body2" color="statusWarning">
You have a pending investment of {investment.pendingInvestCurrency.toFloat().toFixed(2)}{' '}
{investment.investmentCurrency.symbol}
</Text>
)}
{(investment?.claimableInvestShares.gt(0n) || investment?.claimableCancelInvestCurrency.gt(0n)) && (
<Stack gap={1}>
<Text variant="body2" color="statusWarning">
You have claimable shares or pending cancelation
</Text>
<Button loading={isClaiming} onClick={claim} small>
Claim
</Button>
</Stack>
)}
<CurrencyInput
value={amount}
onChange={(value) => setAmount(value)}
label="Amount"
currency={investment?.investmentCurrency.symbol}
secondaryLabel={`${investment?.investmentCurrencyBalance.toFloat().toFixed(2)} balance`}
disabled={
investment?.isAllowedToInvest === false ||
investment?.claimableInvestShares.gt(0n) ||
investment?.claimableCancelInvestCurrency.gt(0n)
}
/>
<Button onClick={submit} disabled={!amount} loading={isInvesting}>
Invest
</Button>
</>
)
}
Loading
Loading