This commit is contained in:
armaniferrante 2021-07-13 00:03:09 -07:00
commit e066895b6b
No known key found for this signature in database
GPG Key ID: 58BEF301E91F7828
55 changed files with 23166 additions and 0 deletions

9
.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
node_modules/
build/
dist/
.DS_Store
*~
.idea
npm-debug.log*
yarn-debug.log*
yarn-error.log*

46
README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

73
package.json Normal file
View File

@ -0,0 +1,73 @@
{
"name": "@project-serum/stake-ui",
"version": "0.0.1-beta.3",
"private": true,
"homepage": ".",
"dependencies": {
"@material-ui/core": "^4.11.0",
"@material-ui/icons": "^4.9.1",
"@project-serum/anchor": "^0.4.4",
"@project-serum/common": "^0.0.1-beta.3",
"@project-serum/sol-wallet-adapter": "^0.2.0",
"@project-serum/tokens": "0.0.7",
"@solana/spl-token": "^0.1.6",
"@solana/spl-token-registry": "^0.2.41",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/chartist": "^0.11.0",
"@types/jest": "^26.0.15",
"@types/material-ui": "^0.21.8",
"@types/node": "^12.0.0",
"@types/react": "^16.9.53",
"@types/react-dom": "^16.9.8",
"@types/react-redux": "^7.1.11",
"@types/react-router-dom": "^5.1.6",
"@types/styled-components": "^5.1.7",
"chartist": "^0.11.4",
"eventemitter3": "^4.0.7",
"js-base64": "^3.6.0",
"notistack": "^1.0.1",
"react": "^17.0.1",
"react-chartist": "^0.14.3",
"react-dom": "^17.0.1",
"react-image": "^4.0.3",
"react-redux": "^7.2.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.1",
"redux": "^4.0.5",
"styled-components": "^5.2.1",
"typescript": "^4.0.5",
"web-vitals": "^0.2.4"
},
"scripts": {
"deploy:app": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
"test:ui": "react-scripts test",
"eject": "react-scripts eject",
"prettier:fix": "prettier src/** -w"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"eslint-config-react-app": "^6.0.0",
"gh-pages": "^3.1.0"
}
}

1
public/CNAME Normal file
View File

@ -0,0 +1 @@
stake.projectserum.com

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

43
public/index.html Normal file
View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Stake | Serum</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

15
public/manifest.json Normal file
View File

@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

3
public/robots.txt Normal file
View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

9
src/App.test.tsx Normal file
View File

@ -0,0 +1,9 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

59
src/App.tsx Normal file
View File

@ -0,0 +1,59 @@
import React from 'react';
import { Provider } from 'react-redux';
import { HashRouter, Route } from 'react-router-dom';
import { SnackbarProvider } from 'notistack';
import { MuiThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import { unstable_createMuiStrictModeTheme as createMuiTheme } from '@material-ui/core/styles';
import { store } from './store';
import WalletProvider from './components/common/WalletProvider';
import BootstrapProvider from './components/common/BootstrapProvider';
import { TokenRegistryProvider } from './utils/tokens';
import Layout from './components/common/Layout';
import MyNodePage from './pages/MyNode';
import LockupPage from './pages/Lockup';
import MultisigPage, { MultisigInstancePage } from './pages/Multisig';
function App() {
const theme = createMuiTheme({
palette: {
background: {
default: 'rgb(255,255,255)',
},
},
typography: {
fontFamily: ['Source Sans Pro', 'sans-serif'].join(','),
},
overrides: {},
});
return (
<Provider store={store}>
<MuiThemeProvider theme={theme}>
<CssBaseline />
<SnackbarProvider maxSnack={5} autoHideDuration={8000}>
<TokenRegistryProvider>
<WalletProvider>
<BootstrapProvider>
<HashRouter basename={'/'}>
<Layout>
<Route exact path="/" component={MyNodePage} />
<Route exact path="/stake" component={MyNodePage} />
<Route exact path="/lockup" component={LockupPage} />
<Route exact path="/multisig" component={MultisigPage} />
<Route
exact
path="/multisig/:address"
component={MultisigInstancePage}
/>
</Layout>
</HashRouter>
</BootstrapProvider>
</WalletProvider>
</TokenRegistryProvider>
</SnackbarProvider>
</MuiThemeProvider>
</Provider>
);
}
export default App;

171
src/components/Me.tsx Normal file
View File

@ -0,0 +1,171 @@
import React from 'react';
import { useSelector } from 'react-redux';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Typography from '@material-ui/core/Typography';
import CircularProgress from '@material-ui/core/CircularProgress';
import { State as StoreState } from '../store/reducer';
import { toDisplay, toDisplayLabel } from '../utils/tokens';
export default function Me() {
const { member } = useSelector((state: StoreState) => {
return {
member: state.registry.member,
};
});
return (
<div style={{ display: 'flex', width: '100%' }}>
<div style={{ flex: 1, marginTop: '24px', marginBottom: '24px' }}>
{member && <MemberBalancesCard />}
</div>
</div>
);
}
// Assumes a member and all vaults is available in the store.
function MemberBalancesCard() {
const {
mint,
registrar,
vault,
vaultStake,
vaultPw,
spt,
lockedVault,
lockedVaultStake,
lockedVaultPw,
lockedSpt,
} = useSelector((state: StoreState) => {
const member = state.accounts[state.registry.member!.toString()];
const registrar = state.accounts[state.registry.registrar.toString()];
return {
registrar,
mint: state.accounts[registrar.mint.toString()],
vault: state.accounts[member.balances.vault],
vaultStake: state.accounts[member.balances.vaultStake],
vaultPw: state.accounts[member.balances.vaultPw],
spt: state.accounts[member.balances.spt],
lockedVault: state.accounts[member.balancesLocked.vault],
lockedVaultStake: state.accounts[member.balancesLocked.vaultStake],
lockedVaultPw: state.accounts[member.balancesLocked.vaultPw],
lockedSpt: state.accounts[member.balancesLocked.spt],
};
});
const tables = [
{
title: 'Main Balances',
description: 'Balances deposited directly from the connected wallet.',
rows: [
{
token: toDisplayLabel(registrar.mint),
balance: toDisplay(vault.amount, mint.decimals),
stake: toDisplay(vaultStake.amount, mint.decimals),
pending: toDisplay(vaultPw.amount, mint.decimals),
spt: toDisplay(spt.amount, 0),
},
],
},
{
title: 'Locked Balances',
description:
'Balances deposited from the lockup program. These funds are isolated from the Main Balances and may only be withdrawn back to the lockup program. At all times they are program controlled.',
rows: [
{
token: toDisplayLabel(registrar.mint),
balance: toDisplay(lockedVault.amount, mint.decimals),
stake: toDisplay(lockedVaultStake.amount, mint.decimals),
pending: toDisplay(lockedVaultPw.amount, mint.decimals),
spt: toDisplay(lockedSpt.amount, 0),
},
],
},
];
return (
<Card
style={{
marginBottom: '24px',
}}
>
<CardContent
style={{
marginTop: '24px',
position: 'relative',
paddingTop: 0,
paddingBottom: '16px',
}}
>
{tables.map(t => (
<BalanceTable
key={t.title}
title={t.title}
description={t.description}
rows={t.rows}
/>
))}
</CardContent>
</Card>
);
}
type BalanceTableProps = {
title: string;
description: string;
rows:
| null
| {
token: string;
balance: string;
stake: string;
pending: string;
spt: string;
}[];
};
function BalanceTable(props: BalanceTableProps) {
const { title, rows, description } = props;
return (
<div style={{ marginBottom: '16px' }}>
<Typography style={{ fontWeight: 'bold' }}>{title}</Typography>
<Typography color="textSecondary" style={{ fontSize: '14px' }}>
{description}
</Typography>
<TableContainer>
<Table>
<TableHead>
<TableRow>
<TableCell>Token</TableCell>
<TableCell align="right">Available</TableCell>
<TableCell align="right">Pending</TableCell>
<TableCell align="right">Staked</TableCell>
<TableCell align="right">Pool</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows === null ? (
<CircularProgress />
) : (
rows.map(row => (
<TableRow key={row.token}>
<TableCell component="th" scope="row">
{row.token}
</TableCell>
<TableCell align="right">{row.balance}</TableCell>
<TableCell align="right">{row.pending}</TableCell>
<TableCell align="right">{row.stake}</TableCell>
<TableCell align="right">{row.spt}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableContainer>
</div>
);
}

770
src/components/Stake.tsx Normal file
View File

@ -0,0 +1,770 @@
import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import BN from 'bn.js';
import { useSnackbar } from 'notistack';
import {
Account,
SYSVAR_RENT_PUBKEY,
SYSVAR_CLOCK_PUBKEY,
} from '@solana/web3.js';
import Table from '@material-ui/core/Table';
import TableHead from '@material-ui/core/TableHead';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
import CircularProgress from '@material-ui/core/CircularProgress';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import IconButton from '@material-ui/core/IconButton';
import CheckCircleIcon from '@material-ui/icons/CheckCircle';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardHeader from '@material-ui/core/CardHeader';
import FormControl from '@material-ui/core/FormControl';
import Typography from '@material-ui/core/Typography';
import { u64 } from '@solana/spl-token';
import { TokenInstructions } from '@project-serum/serum';
import { useWallet } from '../components/common/WalletProvider';
import { ViewTransactionOnExplorerButton } from '../components/common/Notification';
import { State as StoreState, ProgramAccount } from '../store/reducer';
import { ActionType } from '../store/actions';
import * as skin from '../skin';
import { toDisplay, toDisplayLabel } from '../utils/tokens';
import { memberSigner, registrarSigner } from '../utils/registry';
export default function Stake() {
const { registryClient } = useWallet();
const dispatch = useDispatch();
const { member, memberAccount, registrarAccount, registrar } = useSelector(
(state: StoreState) => {
const registrarAccount =
state.accounts[state.registry.registrar.toString()];
return {
member: state.registry.member,
memberAccount: state.registry.member
? state.accounts[state.registry.member.toString()]
: undefined,
registrarAccount: registrarAccount,
registrar: state.registry.registrar,
};
},
);
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const createPoolTokens = async (amount: number, isLocked: boolean) => {
enqueueSnackbar(
`Staking ${toDisplayLabel(registrarAccount.poolMint)} Pool tokens`,
{
variant: 'info',
},
);
const tx = await registryClient.rpc.stake(new u64(amount), isLocked, {
accounts: {
registrar,
rewardEventQ: registrarAccount.rewardEventQ,
poolMint: registrarAccount.poolMint,
member,
beneficiary: registryClient.provider.wallet.publicKey,
balances: memberAccount.balances,
balancesLocked: memberAccount.balancesLocked,
memberSigner: (
await memberSigner(registryClient.programId, registrar, member!)
).publicKey,
registrarSigner: (
await registrarSigner(registryClient.programId, registrar)
).publicKey,
clock: SYSVAR_CLOCK_PUBKEY,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
},
});
closeSnackbar();
enqueueSnackbar(`Staking complete`, {
variant: 'success',
action: <ViewTransactionOnExplorerButton signature={tx} />,
});
};
const redeemPoolTokens = async (amount: number, isLocked: boolean) => {
enqueueSnackbar(
`Unstaking ${amount} ${toDisplayLabel(
registrarAccount.poolMint,
)} Pool tokens`,
{
variant: 'info',
},
);
const pendingWithdrawal = new Account();
const tx = await registryClient.rpc.startUnstake(
new u64(amount),
isLocked,
{
accounts: {
registrar,
rewardEventQ: registrarAccount.rewardEventQ,
poolMint: registrarAccount.poolMint,
pendingWithdrawal: pendingWithdrawal.publicKey,
member,
beneficiary: registryClient.provider.wallet.publicKey,
balances: memberAccount.balances,
balancesLocked: memberAccount.balancesLocked,
memberSigner: (
await memberSigner(registryClient.programId, registrar, member!)
).publicKey,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
clock: SYSVAR_CLOCK_PUBKEY,
rent: SYSVAR_RENT_PUBKEY,
},
signers: [pendingWithdrawal],
instructions: [
await registryClient.account.pendingWithdrawal.createInstruction(
pendingWithdrawal,
),
],
},
);
const pwAccount = await registryClient.account.pendingWithdrawal(
pendingWithdrawal.publicKey,
);
dispatch({
type: ActionType.RegistryCreatePendingWithdrawal,
item: {
pendingWithdrawal: {
publicKey: pendingWithdrawal.publicKey,
account: pwAccount,
},
},
});
closeSnackbar();
enqueueSnackbar(`Stake transfer initiated`, {
variant: 'success',
action: <ViewTransactionOnExplorerButton signature={tx} />,
});
};
const createPool = async (shares: number, isLocked: boolean) => {
if (shares > 0) {
createPoolTokens(shares, isLocked).catch(err => {
console.error(err);
enqueueSnackbar(`Error staking: ${err.toString()}`, {
variant: 'error',
});
});
}
};
const redeemPool = async (shares: number, isLocked: boolean) => {
if (shares > 0) {
redeemPoolTokens(shares, isLocked).catch(err => {
console.error(err);
enqueueSnackbar(`Error unstaking: ${err.toString()}`, {
variant: 'error',
});
});
}
};
return (
<div style={{ width: '100%' }}>
<div style={{ display: 'flex', width: '100%' }}>
<div style={{ flex: 1, marginTop: '24px', marginBottom: '24px' }}>
<PoolCard
title={'Stake Pool'}
create={createPool}
redeem={redeemPool}
/>
</div>
<RedemptionList
style={{
marginBottom: '24px',
}}
/>
</div>
<AllPendingTransfers />
</div>
);
}
type PoolCardProps = {
title: string;
create: (shares: number, isLocked: boolean) => void;
redeem: (shares: number, isLocked: boolean) => void;
};
function PoolCard(props: PoolCardProps) {
const { title, create, redeem } = props;
const [poolAmount, setPoolAmount] = useState<null | number>(null);
const [isLocked, setIsLocked] = useState(false);
const { poolTokenMint, member, registrarAccount, mint } = useSelector(
(state: StoreState) => {
const registrarAccount =
state.accounts[state.registry.registrar.toString()];
const poolTokenMint = {
publicKey: registrarAccount.poolMint,
account: state.accounts[registrarAccount.poolMint.toString()],
};
return {
poolTokenMint,
member: state.registry.member,
registrarAccount,
mint: {
publicKey: registrarAccount.mint,
account: state.accounts[registrarAccount.mint.toString()],
},
};
},
);
const pricePerShare = toDisplay(
registrarAccount.stakeRate,
mint.account.decimals,
);
const cost = poolAmount
? toDisplay(
registrarAccount.stakeRate.mul(new BN(poolAmount)),
mint.account.decimals,
)
: 0;
return (
<Card
style={{
marginBottom: '24px',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<CardHeader
title={title}
subheader={poolTokenMint.publicKey.toString()}
/>
<div
style={{
paddingRight: '16px',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
}}
>
<Typography color="textSecondary"></Typography>
</div>
</div>
<CardContent>
<div
style={{
marginBottom: '16px',
}}
>
<Typography>
Please enter the amount of pool tokens you would like to purchase in
the form below. Upon pressing <b>stake</b> you will create new pool
tokens at a fixed price, adding to the amount of pool tokens
outstanding.
</Typography>
<br />
<Typography>
Unstaking works similarly, except one must incur an unbonding period
where funds will not be able to be retrieved until the unbonding
period ends. At the end of the unbonding period, click the blue
checkbox next to your pending transfer. If the checkbox is grey,
your unbonding period has not yet completed.
</Typography>
<br />
<Typography style={{ fontWeight: 'bold' }}>
Total pool tokens outstanding
</Typography>
<Typography>{poolTokenMint.account.supply.toString()}</Typography>
<Typography style={{ fontWeight: 'bold' }}>
Price per pool token
</Typography>
<Typography>{pricePerShare.toString()}</Typography>
<Typography style={{ fontWeight: 'bold' }}>
Your total cost
</Typography>
<Typography>
{cost} {toDisplayLabel(mint.publicKey)}
</Typography>
<Typography style={{ fontWeight: 'bold' }}>
Unbonding period (days)
</Typography>
<Typography>
{(
registrarAccount.withdrawalTimelock /
(60 * 60 * 24.0)
).toString()}
</Typography>
</div>
<div>
<div style={{ marginBottom: '10px' }}>
<FormControl>
<TextField
style={{ width: '100%' }}
label="Pool tokens"
type="number"
variant="outlined"
onChange={e => setPoolAmount(parseInt(e.target.value))}
/>
</FormControl>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div>
<Button
disabled={member === undefined}
color="primary"
variant="contained"
onClick={() => create(poolAmount as number, isLocked)}
>
Stake
</Button>
<Button
disabled={member === undefined}
color="secondary"
variant="contained"
style={{ marginLeft: '10px' }}
onClick={() => redeem(poolAmount as number, isLocked)}
>
Unstake
</Button>
</div>
<div>
<FormControlLabel
control={
<Switch
checked={isLocked}
onChange={() => setIsLocked(!isLocked)}
/>
}
labelPlacement={'start'}
label="Locked balances"
/>
</div>
</div>
</div>
</CardContent>
</Card>
);
}
type RedemptionListProps = {
style: any;
};
function RedemptionList(props: RedemptionListProps) {
const { registryClient } = useWallet();
const dispatch = useDispatch();
const { member, registrar, mint, pendingWithdrawals } = useSelector(
(state: StoreState) => {
const member = state.registry.member
? {
publicKey: state.registry.member,
account: state.accounts[state.registry.member.toString()],
}
: undefined;
const registrar = {
publicKey: state.registry.registrar!,
account: state.accounts[state.registry.registrar.toString()],
};
const mint = {
publicKey: registrar.account.mint,
account: state.accounts[registrar.account.mint.toString()],
};
const pendingWithdrawals =
state.registry.pendingWithdrawals === null
? null
: state.registry.pendingWithdrawals.map(pw => {
return {
publicKey: pw,
account: state.accounts[pw.toString()],
};
});
return {
member,
registrar,
mint,
pendingWithdrawals,
};
},
);
useEffect(() => {
if (!member) {
return;
}
if (pendingWithdrawals !== null) {
return;
}
// Only grab pending withdrawals for the current member account.
const filter = Buffer.concat([
registrar.publicKey.toBuffer(),
member.publicKey.toBuffer(),
]);
registryClient.account.pendingWithdrawal
.all(filter)
.then(pendingWithdrawals => {
dispatch({
type: ActionType.RegistrySetPendingWithdrawals,
item: {
pendingWithdrawals,
},
});
});
}, [
dispatch,
registrar,
member,
pendingWithdrawals,
registryClient.account.pendingWithdrawal,
]);
return (
<div style={props.style}>
<Card
style={{
marginLeft: '20px',
marginTop: '24px',
width: '294px',
}}
>
<CardContent
style={{
paddingLeft: 0,
paddingRight: 0,
paddingBottom: 0,
paddingTop: 0,
}}
>
<div
style={{
marginLeft: '24px',
marginTop: '24px',
marginRight: '24px',
borderBottom: 'solid 1pt #ccc',
paddingBottom: '12px',
}}
>
<Typography style={{}}>Your Pending Transfers</Typography>
<Typography style={{ fontSize: '12px' }} color="textSecondary">
Click the checkmark to complete a transfer on or after the "end"
date.
</Typography>
</div>
<div style={{ paddingLeft: '24px', paddingRight: '24px' }}>
{member && pendingWithdrawals === null ? (
<div style={{ paddingTop: '24px', marginBottom: '24px' }}>
<CircularProgress
style={{
display: 'block',
marginLeft: 'auto',
marginRight: 'auto',
}}
/>
</div>
) : pendingWithdrawals !== null && pendingWithdrawals.length > 0 ? (
pendingWithdrawals.map((pw, idx) => {
return (
<PendingStakeListItem
key={pw.publicKey.toString()}
isLast={idx === pendingWithdrawals.length - 1}
registrar={registrar}
pw={pw}
member={member!}
mint={mint}
/>
);
})
) : (
<div
style={{
paddingBottom: '24px',
paddingTop: '12px',
}}
>
<Typography color="textSecondary" style={{ fontSize: '14px' }}>
None found
</Typography>
</div>
)}
</div>
</CardContent>
</Card>
</div>
);
}
type PendingStakeListItemProps = {
isLast?: boolean;
registrar: ProgramAccount;
pw: ProgramAccount;
member: ProgramAccount;
mint: ProgramAccount;
};
function PendingStakeListItem(props: PendingStakeListItemProps) {
const { isLast, pw, member, registrar, mint } = props;
const sptLabel = (() => {
const isLocked = pw.account.locked;
const l = isLocked ? '(locked)' : '';
return `${toDisplay(
pw.account.amount,
mint.account.decimals,
)} ${toDisplayLabel(mint.publicKey)} ${l}`;
})();
return (
<div
style={{
paddingBottom: !isLast ? '12px' : '24px',
paddingTop: '12px',
borderBottom: 'solid 1pt #ccc',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
overflow: 'hidden',
}}
>
<div>
<Typography
style={{
whiteSpace: 'pre',
maxWidth: '195px',
overflow: 'hidden',
fontWeight: 'bold',
fontSize: '14px',
}}
>
{`${sptLabel}`}
</Typography>
</div>
<div>
<PendingWithdrawalButton
registrar={registrar}
member={member}
pendingWithdrawal={pw}
/>
</div>
</div>
<Typography style={{ fontSize: '14px' }}>
{`Start: ${new Date(
pw.account.startTs.toNumber() * 1000,
).toLocaleString()}`}
</Typography>
<Typography style={{ fontSize: '14px' }}>
{`End: ${new Date(
pw.account.endTs.toNumber() * 1000,
).toLocaleString()}`}
</Typography>
<Typography
color="textSecondary"
style={{
fontSize: '14px',
overflow: 'hidden',
}}
>
{pw.account.pool.toString()}
</Typography>
</div>
);
}
type PendingWithdrawalButtonProps = {
registrar: ProgramAccount;
pendingWithdrawal: ProgramAccount;
member: ProgramAccount;
};
function PendingWithdrawalButton(props: PendingWithdrawalButtonProps) {
const { pendingWithdrawal, member, registrar } = props;
const { registryClient } = useWallet();
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const dispatch = useDispatch();
const endPendingWithdrawal = async () => {
enqueueSnackbar(`Completing redemption`, {
variant: 'info',
});
const balances = pendingWithdrawal.account.locked
? member.account.balancesLocked
: member.account.balances;
const tx = await registryClient.rpc.endUnstake({
accounts: {
registrar: registrar.publicKey,
member: member.publicKey,
beneficiary: registryClient.provider.wallet.publicKey,
pendingWithdrawal: pendingWithdrawal.publicKey,
vault: balances.vault,
vaultPw: balances.vaultPw,
memberSigner: (
await memberSigner(
registryClient.programId,
registrar.publicKey,
member.publicKey,
)
).publicKey,
clock: SYSVAR_CLOCK_PUBKEY,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
},
});
const updatedPendingWithdrawal = {
publicKey: pendingWithdrawal.publicKey,
account: {
...pendingWithdrawal.account,
burned: true,
},
};
dispatch({
type: ActionType.RegistryUpdatePendingWithdrawal,
item: {
pendingWithdrawal: updatedPendingWithdrawal,
},
});
closeSnackbar();
enqueueSnackbar(`Stake transfer completed`, {
variant: 'success',
action: <ViewTransactionOnExplorerButton signature={tx} />,
});
};
let disabled = false;
let color = skin.instance().ready;
let onClick = async () =>
endPendingWithdrawal().catch(err => {
console.error(`Error completing transfer: ${err.toString()}`);
enqueueSnackbar(
`Error completing transfer. Wait for the transfer's timelock to end and try again.`,
{
variant: 'error',
},
);
});
if (pendingWithdrawal.account.burned) {
disabled = true;
color = skin.instance().active;
onClick = async () => {};
}
if (pendingWithdrawal.account.endTs.toNumber() > Date.now() / 1000) {
disabled = true;
color = skin.instance().notReady;
onClick = async () => {};
}
return (
<div
onClick={onClick}
style={{
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
}}
>
<IconButton disabled={disabled} style={{ width: '25px', height: '25px' }}>
<CheckCircleIcon style={{ color, fontSize: '20px' }} />
</IconButton>
</div>
);
}
function AllPendingTransfers() {
const { registryClient } = useWallet();
const { registrar, registrarAccount, mintAccount } = useSelector(
(state: StoreState) => {
const registrarAccount =
state.accounts[state.registry.registrar.toString()];
return {
registrar: state.registry.registrar,
registrarAccount,
mintAccount: state.accounts[registrarAccount.mint.toString()],
};
},
);
const [pendingTransfers, setPendingTransfers] = useState<null | any>(null);
useEffect(() => {
const fetchAll = async () => {
let transfers = await registryClient.account.pendingWithdrawal.all(
registrar.toBuffer(),
);
transfers = transfers
.filter((pw: any) => pw.account.burned === false)
.sort((a, b) => {
if (a.account.startTs < b.account.startTs) {
return 1;
} else if (a.account.startTs > b.account.startTs) {
return -1;
} else {
return 0;
}
});
setPendingTransfers(transfers);
};
fetchAll();
}, [registryClient, registrar]);
return (
<Card style={{ maxHeight: '900px', overflow: 'auto' }}>
<Typography
variant="h5"
style={{ padding: '16px', borderBottom: 'solid 1pt #ccc' }}
>
All pending transfers
</Typography>
{pendingTransfers !== null ? (
<Table>
<TableHead>
<TableRow>
<TableCell>Member Account</TableCell>
<TableCell>Amount</TableCell>
<TableCell>Pool</TableCell>
<TableCell>Locked</TableCell>
<TableCell>Start</TableCell>
<TableCell>End</TableCell>
</TableRow>
</TableHead>
<TableBody>
{pendingTransfers.map((pw: any) => (
<TableRow>
<TableCell>{pw.account.member.toString()}</TableCell>
<TableCell>
{toDisplay(
pw.account.amount.toString(),
mintAccount.decimals,
)}
</TableCell>
<TableCell>
{pw.account.amount.div(registrarAccount.stakeRate).toString()}
</TableCell>
<TableCell>{pw.account.locked.toString()}</TableCell>
<TableCell>
{new Date(pw.account.startTs.toNumber() * 1000).toString()}
</TableCell>
<TableCell>
{new Date(pw.account.endTs.toNumber() * 1000).toString()}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<div style={{ padding: '24px' }}>
<CircularProgress
style={{
display: 'block',
marginLeft: 'auto',
marginRight: 'auto',
}}
/>
</div>
)}
</Card>
);
}

View File

@ -0,0 +1,548 @@
import React, {
PropsWithChildren,
ReactNode,
useEffect,
useCallback,
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSnackbar } from 'notistack';
import { PublicKey } from '@solana/web3.js';
import {
token,
parseMintAccount,
parseTokenAccount,
} from '@project-serum/common';
import * as anchor from '@project-serum/anchor';
import { State as StoreState, ProgramAccount } from '../../store/reducer';
import { ActionType } from '../../store/actions';
import { useWallet } from './WalletProvider';
import { memberSeed } from '../../utils/registry';
// BootstrapProvider performs data fetching on application startup.
export default function BootstrapProvider(props: PropsWithChildren<ReactNode>) {
const { bootstrapTrigger, shutdownTrigger, network, registrar } = useSelector(
(state: StoreState) => {
return {
bootstrapTrigger: state.common.bootstrapTrigger,
shutdownTrigger: state.common.shutdownTrigger,
network: state.common.network,
registrar: state.registry.registrar,
};
},
);
const dispatch = useDispatch();
const { wallet, lockupClient, registryClient } = useWallet();
const { enqueueSnackbar } = useSnackbar();
// Entry point for bootstrapping all the data for the app.
const bootstrap = useCallback(async () => {
enqueueSnackbar(`Connecting to ${network.label}`, {
variant: 'info',
autoHideDuration: 2500,
});
dispatch({
type: ActionType.CommonAppWillBootstrap,
item: {},
});
let { registrars, members } = await refreshAccounts({
dispatch,
lockupClient,
registryClient,
network,
wallet,
});
// Temporary account store for the initial registrar switch.
const accountStore = Object.fromEntries(
new Map(registrars.map(r => [r.publicKey.toString(), r.account])),
);
members.forEach(m => {
accountStore[m.publicKey.toString()] = m.account;
});
await registrarSwitch(
registryClient,
accountStore,
dispatch,
registrar,
undefined,
);
dispatch({
type: ActionType.CommonAppDidBootstrap,
item: {},
});
enqueueSnackbar(`Connection established`, {
variant: 'success',
autoHideDuration: 2500,
});
}, [
dispatch,
enqueueSnackbar,
registryClient,
registrar,
lockupClient,
network,
wallet,
]);
const shutdown = useCallback(async () => {
wallet.disconnect();
dispatch({
type: ActionType.CommonDidShutdown,
item: {},
});
}, [dispatch, wallet]);
useEffect(() => {
if (bootstrapTrigger) {
bootstrap().catch(err => {
console.error(err);
enqueueSnackbar(`Error bootstrapping application: ${err.toString()}`, {
variant: 'error',
});
});
}
if (shutdownTrigger) {
shutdown().catch(err => {
console.error(err);
enqueueSnackbar(`Error shutting down application: ${err.toString()}`, {
variant: 'error',
});
});
}
}, [bootstrapTrigger, bootstrap, shutdownTrigger, shutdown, enqueueSnackbar]);
return <>{props.children}</>;
}
// Fetches and populates the redux store with all accounts needed for the app to start.
export async function refreshAccounts({
dispatch,
lockupClient,
registryClient,
network,
wallet,
}: any) {
// Fetch all staking instances.
const fetchRegistrars = async (): Promise<ProgramAccount[]> => {
const registrarAddresses: PublicKey[] = Object.values(network.registrars);
// All registrars.
const registrars: ProgramAccount[] = (
await anchor.utils.getMultipleAccounts(
registryClient.provider.connection,
registrarAddresses,
)
).map(raw => {
const account = registryClient.coder.accounts.decode(
'Registrar',
raw!.account.data,
);
return {
publicKey: raw!.publicKey,
account,
};
});
// Mint for each registrar.
const mints: ProgramAccount[] = (
await anchor.utils.getMultipleAccounts(
registryClient.provider.connection,
registrars.map(r => r.account.mint),
)
).map(raw => {
const account = parseMintAccount(raw!.account.data);
return {
publicKey: raw!.publicKey,
account,
};
});
// Reward queues for each registrar.
const rewardQs = (
await anchor.utils.getMultipleAccounts(
registryClient.provider.connection,
registrars.map(r => r.account.rewardEventQ),
)
).map(raw => {
const account = registryClient.coder.accounts.decode(
'RewardQueue',
raw!.account.data,
);
return {
publicKey: raw!.publicKey,
account,
};
});
// Add all the accounts to the store.
registrars
.concat(mints)
.concat(rewardQs)
.forEach(r => {
dispatch({
type: ActionType.AccountAdd,
item: {
account: r,
},
});
});
return registrars;
};
// Fetch the stake accounts for each staking instance (for the connected wallet).
const fetchMembers = async (
registrars: ProgramAccount[],
): Promise<ProgramAccount[]> => {
const members = await Promise.all(
registrars
.map((r: ProgramAccount) => r.publicKey)
.map((r: PublicKey) =>
memberSeed(r)
.then(seed =>
PublicKey.createWithSeed(
wallet.publicKey,
seed,
registryClient.programId,
),
)
.then(member => {
return {
memberPublicKey: member,
registrar: r,
};
}),
),
);
const memberAddresses: PublicKey[] = members.map(m => m.memberPublicKey);
const memberAccounts: ProgramAccount[] = (
await anchor.utils.getMultipleAccounts(
registryClient.provider.connection,
memberAddresses,
)
)
.filter(raw => raw !== null)
.map((raw: any) => {
const account = registryClient.coder.accounts.decode(
'Member',
raw!.account.data,
);
return {
publicKey: raw!.publicKey,
account,
};
});
// Get all accounts for all of our member accounts.
//
// Note: As the number of registrars grows, we'll probably want to move
// this fetch to be an on demand query, rather than on application
// bootstrap.
await Promise.all(
memberAccounts.map(memberAccount => {
return fetchAndDispatchMemberAccounts(
memberAccount,
dispatch,
registryClient.provider.connection,
);
}),
);
// Add all the member accounts to the store. Must be done *after* the
// active member's vaults.
memberAccounts.forEach(m => {
dispatch({
type: ActionType.AccountAdd,
item: {
account: m,
},
});
});
return memberAccounts;
};
// All mints for each staking instance (pool token and the token being staked).
const fetchMints = async (registrars: ProgramAccount[]) => {
const mintAddresses = registrars
.map(r => r.account.mint)
.concat(registrars.map(r => r.account.poolMint));
const mints = (
await anchor.utils.getMultipleAccounts(
registryClient.provider.connection,
mintAddresses,
)
).map(raw => {
const account = parseMintAccount(raw!.account.data);
return {
publicKey: raw!.publicKey,
account,
};
});
mints.forEach(m => {
dispatch({
type: ActionType.AccountAdd,
item: {
account: m,
},
});
});
};
// All token accounts owned by the current user.
const fetchOwnedTokenAccounts = async () => {
const ownedTokenAccounts = await token.getOwnedTokenAccounts(
lockupClient.provider.connection,
wallet.publicKey,
);
dispatch({
type: ActionType.CommonOwnedTokenAccountsSet,
item: {
ownedTokenAccounts,
},
});
};
// All vesting accounts owned by the current user.
const fetchVestingAccounts = async () => {
const vestingAccounts = await lockupClient.account.vesting.all(
wallet.publicKey.toBuffer(),
);
vestingAccounts.forEach((account: any) => {
dispatch({
type: ActionType.AccountAdd,
item: {
account,
},
});
});
dispatch({
type: ActionType.LockupSetVestings,
item: {
vestingAccounts: vestingAccounts.map(
(v: ProgramAccount) => v.publicKey,
),
},
});
};
const registrars = await fetchRegistrars();
const members = await fetchMembers(registrars);
await fetchMints(registrars);
await fetchOwnedTokenAccounts();
await fetchVestingAccounts();
return { registrars, members };
}
export async function registrarSwitch(
registryClient: any,
accounts: any,
dispatch: any,
newRegistrar: PublicKey,
oldRegistrar?: PublicKey,
) {
const oldMember = await (async (): Promise<ProgramAccount | undefined> => {
if (oldRegistrar === undefined) {
return undefined;
}
const oldMember = await PublicKey.createWithSeed(
registryClient.provider.wallet.publicKey,
await memberSeed(oldRegistrar),
registryClient.programId,
);
const oldMemberAccount = accounts[oldMember.toString()];
return oldMemberAccount !== undefined
? {
publicKey: oldMember,
account: oldMemberAccount,
}
: undefined;
})();
const newMember = await (async (): Promise<ProgramAccount | undefined> => {
const newMember = await PublicKey.createWithSeed(
registryClient.provider.wallet.publicKey,
await memberSeed(newRegistrar),
registryClient.programId,
);
const newMemberAccount = accounts[newMember.toString()];
return newMemberAccount
? {
publicKey: newMember,
account: newMemberAccount,
}
: undefined;
})();
await subscribeRegistrar(
registryClient,
accounts,
dispatch,
newRegistrar,
oldRegistrar,
);
if (newMember) {
unsubscribeMember(registryClient, oldMember);
subscribeMember(newMember, registryClient, dispatch);
}
// Perform the UI update.
dispatch({
type: ActionType.RegistrySetRegistrar,
item: {
registrar: newRegistrar,
member: newMember ? newMember.publicKey : undefined,
},
});
}
export async function subscribeRegistrar(
registryClient: any,
accounts: any,
dispatch: any,
newRegistrar: PublicKey,
oldRegistrar?: PublicKey,
) {
if (oldRegistrar) {
const oldRegistrarAccount = accounts[oldRegistrar.toString()];
registryClient.account.rewardQueue.unsubscribe(
oldRegistrarAccount.rewardEventQ,
);
// TODO: unsubscribe from the staking pool subscription.
}
const newRegistrarAccount = accounts[newRegistrar.toString()];
// Reward event queue sub.
const conn = registryClient.account.rewardQueue.subscribe(
newRegistrarAccount.rewardEventQ,
);
conn.on('change', (account: any) => {
dispatch({
type: ActionType.AccountUpdate,
item: {
account: {
publicKey: newRegistrarAccount.rewardEventQ,
account,
},
},
});
});
// Staking pool token sub.
// TODO: track these connections somewhere more organized.
registryClient.provider.connection.onAccountChange(
newRegistrarAccount.poolMint,
(acc: any) => {
const poolMint = parseMintAccount(acc.data);
dispatch({
type: ActionType.AccountUpdate,
item: {
account: {
publicKey: newRegistrarAccount.poolMint,
account: poolMint,
},
},
});
},
'recent',
);
}
export function subscribeMember(
newMember: ProgramAccount,
registryClient: any,
dispatch: any,
) {
// Subscribe to all member account updates.
registryClient.account.member
.subscribe(newMember.publicKey)
.on('change', (account: any) => {
dispatch({
type: ActionType.AccountUpdate,
item: {
account: {
publicKey: newMember.publicKey,
account,
},
},
});
});
// Subscription function, updating the redux store on every change
// to a token account.
//
// TODO: should track these subscriptions for unsubscribing on demand.
const createVaultSubscription = (address: PublicKey) => {
registryClient.provider.connection.onAccountChange(
address,
(acc: any) => {
const tokenAccount = parseTokenAccount(acc.data);
dispatch({
type: ActionType.AccountUpdate,
item: {
account: {
publicKey: address,
account: tokenAccount,
},
},
});
},
'recent',
);
};
// Subscribe to all the member's token vaults.
createVaultSubscription(newMember.account.balances.vault);
createVaultSubscription(newMember.account.balances.vaultStake);
createVaultSubscription(newMember.account.balances.vaultPw);
createVaultSubscription(newMember.account.balances.spt);
createVaultSubscription(newMember.account.balancesLocked.vault);
createVaultSubscription(newMember.account.balancesLocked.vaultStake);
createVaultSubscription(newMember.account.balancesLocked.vaultPw);
createVaultSubscription(newMember.account.balancesLocked.spt);
}
function unsubscribeMember(registryClient: any, newMember?: ProgramAccount) {
// todo
}
// Fetches all accounts for a member account and populates the store with them.
export async function fetchAndDispatchMemberAccounts(
memberAccount: ProgramAccount,
dispatch: any,
connection: any,
) {
let accounts = (
await anchor.utils.getMultipleAccounts(connection, [
memberAccount.account.balances.vault,
memberAccount.account.balances.vaultStake,
memberAccount.account.balances.vaultPw,
memberAccount.account.balances.spt,
memberAccount.account.balancesLocked.vault,
memberAccount.account.balancesLocked.vaultStake,
memberAccount.account.balancesLocked.vaultPw,
memberAccount.account.balancesLocked.spt,
])
)
.filter(raw => raw !== null)
.map((raw: any) => {
return {
publicKey: raw.publicKey,
account: parseTokenAccount(raw.account.data),
};
});
accounts.forEach(account => {
dispatch({
type: ActionType.AccountAdd,
item: {
account,
},
});
});
}

View File

@ -0,0 +1,75 @@
import React from 'react';
import Typography from '@material-ui/core/Typography';
import Link from '@material-ui/core/Link';
export default function Footer() {
return (
<div
style={{
zIndex: 99,
position: 'fixed',
width: '100%',
bottom: 0,
textAlign: 'center',
height: '30px',
backgroundColor: '#fbfbfb',
borderTop: 'solid 1pt #ccc',
display: 'flex',
justifyContent: 'space-between',
paddingLeft: '10px',
paddingRight: '10px',
}}
>
<div style={{ marginLeft: 'auto', marginRight: 'auto', display: 'flex' }}>
<FooterButton
href={
'https://github.com/project-serum/anchor/blob/master/examples/lockup/docs/staking.md'
}
label={'Technical Documentation'}
/>
<FooterButton
href={'https://github.com/project-serum/awesome-serum'}
label={'Developer Resources'}
/>
<FooterButton
href={'https://discord.com/channels/739225212658122886'}
label={'Discord'}
/>
<FooterButton href={'https://t.me/ProjectSerum'} label={'Telegram'} />
<FooterButton
href={'https://github.com/project-serum'}
label={'GitHub'}
/>
<FooterButton
href={'https://solanabeach.io/'}
label={'Solana Network'}
isEnd={true}
/>
</div>
</div>
);
}
type FooterButtonProps = {
label: string;
href: string;
isEnd?: boolean;
};
function FooterButton(props: FooterButtonProps) {
const { label, href, isEnd } = props;
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
marginRight: isEnd ? '' : '15px',
}}
>
<Link href={href} target="_blank" color="inherit">
<Typography style={{ fontSize: '14px' }}>{label}</Typography>
</Link>
</div>
);
}

View File

@ -0,0 +1,379 @@
import React, { useState, useEffect, ReactElement } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { useSnackbar } from 'notistack';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Select from '@material-ui/core/Select';
import Menu from '@material-ui/core/Menu';
import Link from '@material-ui/core/Link';
import Typography from '@material-ui/core/Typography';
import MenuItem from '@material-ui/core/MenuItem';
import IconButton from '@material-ui/core/IconButton';
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import Button from '@material-ui/core/Button';
import PersonIcon from '@material-ui/icons/Person';
import BubbleChartIcon from '@material-ui/icons/BubbleChart';
import RefreshIcon from '@material-ui/icons/Refresh';
import CircularProgress from '@material-ui/core/CircularProgress';
import { refreshAccounts } from './BootstrapProvider';
import { networks } from '../../store/config';
import {
State as StoreState,
ProgramAccount,
BootstrapState,
} from '../../store/reducer';
import { ActionType } from '../../store/actions';
import { useWallet } from './WalletProvider';
type HeaderProps = {
isAppReady: boolean;
member?: ProgramAccount;
};
export default function Header(props: HeaderProps) {
const { isAppReady } = props;
const { network } = useSelector((state: StoreState) => {
return {
network: state.common.network,
isAppReady:
state.common.isWalletConnected &&
state.common.bootstrapState === BootstrapState.Bootstrapped,
};
});
const dispatch = useDispatch();
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const { wallet, registryClient, lockupClient } = useWallet();
const [isRefreshing, setIsRefreshing] = useState(false);
return (
<AppBar
position="static"
style={{
background: '#ffffff',
color: '#272727',
boxShadow: 'none',
borderBottom: 'solid 1pt #ccc',
}}
>
<Toolbar>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
width: '100%',
}}
>
<div style={{ display: 'flex' }}>
<SerumLogoButton />
<BarButton label="Stake" hrefClient="/stake" />
<BarButton label="Lockup" hrefClient="/lockup" />
<BarButton label="Multisig" href="https://multisig.projectserum.com" />
<BarButton label="Trade" href="https://dex.projectserum.com" />
{network.srmFaucet && (
<BarButton
label="Faucet"
href="https://www.spl-token-ui.com/#/token-faucets"
/>
)}
</div>
<div
style={{
display: 'flex',
}}
>
<div
onClick={() => {
setIsRefreshing(true);
enqueueSnackbar(`Refreshing`, {
variant: 'info',
});
refreshAccounts({
dispatch,
lockupClient,
registryClient,
network,
wallet,
})
.then(() => {
setIsRefreshing(false);
closeSnackbar();
})
.catch(err => {
setIsRefreshing(false);
closeSnackbar();
enqueueSnackbar(`There was a problem refreshing: ${err}`, {
variant: 'error',
autoHideDuration: 2500,
});
});
}}
style={{
display: isAppReady ? 'block' : 'none',
justifyContent: 'center',
flexDirection: 'column',
marginRight: '10px',
}}
>
{isRefreshing ? (
<div
style={{
marginTop: '8px',
padding: '10px',
}}
>
<CircularProgress style={{ width: '24px', height: '24px' }} />
</div>
) : (
<div>
<IconButton>
<RefreshIcon />
</IconButton>
</div>
)}
</div>
<NetworkSelector />
<WalletConnectButton
style={{
display: isAppReady ? 'none' : '',
}}
/>
{isAppReady && <UserSelector />}
</div>
</div>
</Toolbar>
</AppBar>
);
}
function SerumLogoButton() {
const history = useHistory();
return (
<div style={{ display: 'flex' }} onClick={() => history.push('/')}>
<Button color="inherit">
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
}}
>
<img
style={{
display: 'block',
height: '35px',
}}
alt="Logo"
src="http://dex.projectserum.com/static/media/logo.49174c73.svg"
/>
</div>
</Button>
</div>
);
}
type BarButtonProps = {
label: string;
hrefClient?: string;
href?: string;
};
function BarButton(props: BarButtonProps) {
const history = useHistory();
const { label, href, hrefClient } = props;
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
}}
onClick={() => hrefClient && history.push(hrefClient)}
>
<Link
style={{ color: 'inherit', textDecoration: 'none' }}
href={href}
target="_blank"
>
<Button color="inherit">
<div
style={{
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
}}
>
<Typography style={{ fontSize: '15px' }}>{label}</Typography>
</div>
</Button>
</Link>
</div>
);
}
function NetworkSelector() {
const network = useSelector((state: StoreState) => {
return state.common.network;
});
const dispatch = useDispatch();
const [anchorEl, setAnchorEl] = useState(null);
const handleClose = () => {
setAnchorEl(null);
};
return (
<div
style={{
marginRight: '10px',
fontSize: '15px',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
}}
>
<Button
color="inherit"
onClick={e =>
setAnchorEl(
// @ts-ignore
e.currentTarget,
)
}
>
<BubbleChartIcon />
<Typography style={{ marginLeft: '5px', fontSize: '15px' }}>
{network.label}
</Typography>
</Button>
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleClose}
style={{
marginLeft: '12px',
color: 'white',
}}
>
{Object.keys(networks).map((n: string) => (
<MenuItem
key={n}
onClick={() => {
handleClose();
dispatch({
type: ActionType.CommonSetNetwork,
item: {
network: networks[n],
networkKey: n,
},
});
}}
>
<Typography>{networks[n].label}</Typography>
</MenuItem>
))}
</Menu>
</div>
);
}
function UserSelector() {
const { wallet } = useWallet();
return (
<Select
displayEmpty
renderValue={() => {
return (
<Typography style={{ overflow: 'hidden' }}>
{wallet.publicKey?.toString()}
</Typography>
);
}}
style={{
marginLeft: '12px',
width: '150px',
}}
onChange={e => {
if (e.target.value === 'disconnect') {
wallet.disconnect();
}
}}
>
<MenuItem value="disconnect">
<IconButton color="inherit">
<ExitToAppIcon />
<Typography style={{ marginLeft: '15px' }}>Disconnect</Typography>
</IconButton>
</MenuItem>
</Select>
);
}
type WalletConnectButtonProps = {
style?: any;
};
export function WalletConnectButton(
props: WalletConnectButtonProps,
): ReactElement {
const { showDisconnect } = useSelector((state: StoreState) => {
return {
showDisconnect: state.common.isWalletConnected,
};
});
const dispatch = useDispatch();
const { wallet, lockupClient } = useWallet();
const { enqueueSnackbar } = useSnackbar();
// Wallet connection event listeners.
useEffect(() => {
wallet.on('disconnect', () => {
enqueueSnackbar('Disconnected from wallet', {
variant: 'info',
autoHideDuration: 2500,
});
dispatch({
type: ActionType.CommonWalletDidDisconnect,
item: {},
});
dispatch({
type: ActionType.CommonTriggerShutdown,
item: {},
});
});
wallet.on('connect', async () => {
dispatch({
type: ActionType.CommonWalletDidConnect,
item: {},
});
dispatch({
type: ActionType.CommonTriggerBootstrap,
item: {},
});
});
}, [wallet, dispatch, enqueueSnackbar, lockupClient.provider.connection]);
return showDisconnect ? (
<Button
style={props.style}
color="inherit"
onClick={() => wallet.disconnect()}
>
<ExitToAppIcon />
<Typography style={{ marginLeft: '5px', fontSize: '15px' }}>
Disconnect
</Typography>
</Button>
) : (
<Button
style={props.style}
color="inherit"
onClick={() => wallet.connect()}
>
<PersonIcon />
<Typography style={{ marginLeft: '5px', fontSize: '15px' }}>
Connect wallet
</Typography>
</Button>
);
}

View File

@ -0,0 +1,196 @@
import React, { useState, PropsWithChildren } from 'react';
import { useSelector } from 'react-redux';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import LinearProgress from '@material-ui/core/LinearProgress';
import Button from '@material-ui/core/Button';
import { State as StoreState, BootstrapState } from '../../store/reducer';
import Header from './Header';
import Footer from './Footer';
type Props = {};
export default function Layout(props: PropsWithChildren<Props>) {
const { isAppReady } = useSelector((state: StoreState) => {
return {
isAppReady:
state.common.isWalletConnected &&
state.common.bootstrapState === BootstrapState.Bootstrapped,
};
});
const [refresh, setRefresh] = useState(false);
return (
<div
style={{
display: 'flex',
minHeight: '100vh',
flexDirection: 'column',
backgroundColor: 'rgb(251, 251, 251)',
}}
>
<div
style={{
position: 'fixed',
width: '100%',
zIndex: 99,
}}
>
<RiskBar />
<Header isAppReady={isAppReady} />
</div>
<div
style={{
width: '100%',
marginTop: '94px',
flex: 1,
display: 'flex',
marginBottom: '30px', // Compensates for the fixed position footer.
}}
>
{window.localStorage.getItem('consent') ? (
!isAppReady ? (
<DisconnectedSplash />
) : (
<div style={{ width: '100%' }}>{props.children}</div>
)
) : (
<RiskDisclosureForm
onConsent={() => {
window.localStorage.setItem('consent', 'true');
setRefresh(!refresh);
}}
/>
)}
</div>
<Footer />
</div>
);
}
function RiskBar() {
return (
<div
style={{
color: '#fff',
backgroundColor: 'rgb(39, 39, 39)',
height: '30px',
textAlign: 'center',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
height: '100%',
}}
>
<Typography style={{ fontSize: '14px' }}>
Stake is unaudited software. Use at your own risk.
</Typography>
</div>
</div>
);
}
const useStyles = makeStyles(theme => ({
root: {
width: '100%',
'& > * + *': {
marginTop: theme.spacing(2),
},
},
}));
function RiskDisclosureForm({ onConsent }: { onConsent: () => void }) {
return (
<div
style={{
flex: '1',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
textAlign: 'center',
}}
>
<div style={{ width: '100%', display: 'flex' }}>
<div
style={{ display: 'flex', marginLeft: 'auto', marginRight: 'auto' }}
>
<Typography
style={{ marginBottom: '16px', maxWidth: '1000px' }}
color="textSecondary"
variant="h4"
>
No statement or warranty is provided in relation to the utility of
this program, the safety of its code or its suitability for your
use, and by using it, you agree to bear any risk associated with
such potential vulnerabilities, including, but not limited to the
potential loss of tokens.
</Typography>
</div>
</div>
<div style={{ display: 'flex', marginLeft: 'auto', marginRight: 'auto' }}>
<Button variant="contained" color="primary" onClick={onConsent}>
I agree
</Button>
</div>
</div>
);
}
function DisconnectedSplash() {
const classes = useStyles();
const { network, isDisconnected } = useSelector((state: StoreState) => {
return {
network: state.common.network,
isDisconnected: !state.common.isWalletConnected,
};
});
return (
<div
style={{
flex: '1',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
textAlign: 'center',
}}
>
<div style={{ width: '100%', display: 'flex' }}>
{isDisconnected ? (
<div
style={{ display: 'flex', marginLeft: 'auto', marginRight: 'auto' }}
>
<Typography
style={{ marginLeft: '24px' }}
color="textSecondary"
variant="h4"
>
Disconnected
</Typography>
</div>
) : (
<div style={{ width: '100%' }}>
<div style={{ width: '100%' }} className={classes.root}>
<div>
<Typography variant="h5">
{`Connecting to ${network.label}...`}
</Typography>
</div>
<div
style={{
marginLeft: 'auto',
marginRight: 'auto',
width: '300px',
}}
>
<LinearProgress style={{ width: '100%' }} />
</div>
</div>
</div>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,832 @@
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useSnackbar } from 'notistack';
import BN from 'bn.js';
import styled from 'styled-components';
import LockIcon from '@material-ui/icons/Lock';
import Container from '@material-ui/core/Container';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import { TransitionProps } from '@material-ui/core/transitions';
import ArrowDownwardIcon from '@material-ui/icons/ArrowDownward';
import ArrowUpwardIcon from '@material-ui/icons/ArrowUpward';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import FormControl from '@material-ui/core/FormControl';
import Slide from '@material-ui/core/Slide';
import FormHelperText from '@material-ui/core/FormHelperText';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import { Account, SYSVAR_RENT_PUBKEY, PublicKey, SystemProgram } from '@solana/web3.js';
import { TokenInstructions } from '@project-serum/serum';
import { getTokenAccount } from '@project-serum/common';
import { useWallet } from '../../components/common/WalletProvider';
import OwnedTokenAccountsSelect from '../../components/common/OwnedTokenAccountsSelect';
import { ViewTransactionOnExplorerButton } from '../../components/common/Notification';
import RegistrarSelect from './RegistrarSelect';
import { State as StoreState, ProgramAccount } from '../../store/reducer';
import { ActionType } from '../../store/actions';
import * as bootstrap from './BootstrapProvider';
import Me from '../Me';
import {
memberSigner,
memberSeed,
createBalanceSandbox,
} from '../../utils/registry';
import { vestingSigner } from '../../utils/lockup';
import Stake from '../Stake';
import Rewards from '../rewards/Rewards';
import VestingAccountsSelect from './VestingAccountsSelect';
import { toDisplayLabel, fromDisplay } from '../../utils/tokens';
enum TabModel {
Me,
Stake,
Rewards,
Lockup,
}
export default function MyNode() {
const [tab, setTab] = useState(TabModel.Me);
return (
<div>
<MyNodeBanner setTab={setTab} />
<Container fixed maxWidth="md" style={{ flex: 1, display: 'flex' }}>
{tab === TabModel.Me && <Me />}
{tab === TabModel.Stake && <Stake />}
{tab === TabModel.Rewards && <Rewards />}
</Container>
</div>
);
}
type MyNodeBannerProps = {
setTab: (t: TabModel) => void;
};
function MyNodeBanner(props: MyNodeBannerProps) {
const [tab, setTab] = useState(TabModel.Me);
const { member, registrar, registrarAccount } = useSelector(
(state: StoreState) => {
return {
member: state.registry.member,
registrar: state.registry.registrar,
registrarAccount: state.accounts[state.registry.registrar.toString()],
};
},
);
const [showDepositDialog, setShowDepositDialog] = useState(false);
const [showWithdrawDialog, setShowWithdrawDialog] = useState(false);
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const { wallet, registryClient } = useWallet();
const dispatch = useDispatch();
const createStakeAccount = async () => {
enqueueSnackbar('Creating stake account', {
variant: 'info',
});
const seed = await memberSeed(registrar);
const member = await PublicKey.createWithSeed(
wallet.publicKey!,
seed,
registryClient.programId,
);
const { publicKey, nonce } = await memberSigner(
registryClient.programId,
registrar,
member,
);
const memberSignerPublicKey = publicKey;
const [mainTx, balances] = await createBalanceSandbox(
registryClient.provider,
registrarAccount,
memberSignerPublicKey,
);
const [lockedTx, balancesLocked] = await createBalanceSandbox(
registryClient.provider,
registrarAccount,
memberSignerPublicKey,
);
const tx = registryClient.transaction.createMember(nonce, {
accounts: {
registrar: registrar,
member: member,
beneficiary: wallet.publicKey,
memberSigner: memberSignerPublicKey,
balances,
balancesLocked,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
rent: SYSVAR_RENT_PUBKEY,
},
instructions: [
SystemProgram.createAccountWithSeed({
fromPubkey: wallet.publicKey!,
newAccountPubkey: member,
basePubkey: wallet.publicKey!,
seed,
lamports: await registryClient.provider.connection.getMinimumBalanceForRentExemption(
registryClient.account.member.size,
),
space: registryClient.account.member.size,
programId: registryClient.programId,
}),
],
});
const signers: Account[] = [];
const allTxs = [mainTx, lockedTx, { tx, signers }];
// @ts-ignore
let txSigs = await registryClient.provider.sendAll(allTxs, {
commitment: 'recent',
preflightCommitment: 'recent',
skipPreflight: true,
});
console.log('Accounts created with transactions:', txSigs);
const memberAccount = await registryClient.account.member(member);
const memberProgramAccount = {
publicKey: member,
account: memberAccount,
};
// Add the new member to the store.
dispatch({
type: ActionType.AccountAdd,
item: {
account: memberProgramAccount,
},
});
// Populate the store with all of the member's accounts.
await bootstrap.fetchAndDispatchMemberAccounts(
memberProgramAccount,
dispatch,
registryClient.provider.connection,
);
// Subscribe to any updates to the member.
bootstrap.subscribeMember(memberProgramAccount, registryClient, dispatch);
// Tell the UI that our member is ready.
dispatch({
type: ActionType.RegistrySetMember,
item: {
member,
},
});
closeSnackbar();
enqueueSnackbar(`Stake account created ${member.toString()}`, {
variant: 'success',
});
};
const HoverSpan = styled.span`
:hover {
cursor: pointer;
}
`;
return (
<>
<div
style={{
backgroundColor: '#fff',
paddingTop: '24px',
borderBottom: 'solid 1pt #ccc',
}}
>
<Container
fixed
maxWidth="md"
style={{
height: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div>
<Typography variant="h4" style={{ marginBottom: '10px' }}>
My Stake
</Typography>
</div>
<div
style={{
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
}}
>
<RegistrarSelect />
</div>
</div>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
}}
>
<div>
<Typography>
{member !== undefined ? (
member.toString()
) : (
<>
Account not found. Please{' '}
<HoverSpan
onClick={() => {
createStakeAccount().catch(err => {
console.error(err);
enqueueSnackbar(
`Error creating stake account: ${err.toString()}`,
{
variant: 'error',
},
);
});
}}
style={{
color: 'black',
fontWeight: 'bold',
textDecoration: 'underline',
}}
>
create
</HoverSpan>{' '}
a stake account.
</>
)}
</Typography>
</div>
<div>
<div>
<Button
disabled={member === undefined}
onClick={() => setShowDepositDialog(true)}
variant="outlined"
color="primary"
style={{ marginRight: '10px' }}
>
<ArrowDownwardIcon style={{ fontSize: '20px' }} />
<Typography style={{ marginLeft: '5px', marginRight: '5px' }}>
Deposit
</Typography>
</Button>
<Button
disabled={member === undefined}
variant="outlined"
color="primary"
onClick={() => setShowWithdrawDialog(true)}
>
<ArrowUpwardIcon style={{ fontSize: '20px' }} />
<Typography style={{ marginLeft: '5px', marginRight: '5px' }}>
Withdraw
</Typography>
</Button>
</div>
</div>
</div>
</Container>
<div
style={{
maxWidth: '960px',
marginLeft: 'auto',
marginRight: 'auto',
paddingLeft: '24px',
paddingRight: '24px',
marginTop: '10px',
}}
>
<Tabs
value={tab}
onChange={(_e, t) => {
setTab(t);
props.setTab(t);
}}
>
<Tab value={TabModel.Me} label="Me" />
<Tab value={TabModel.Stake} label="Stake" />
<Tab value={TabModel.Rewards} label="Rewards" />
</Tabs>
</div>
</div>
{member !== undefined && (
<>
<DepositDialog
open={showDepositDialog}
onClose={() => setShowDepositDialog(false)}
/>
<WithdrawDialog
open={showWithdrawDialog}
onClose={() => setShowWithdrawDialog(false)}
/>
</>
)}
</>
);
}
type DepositDialogProps = {
open: boolean;
onClose: () => void;
};
function DepositDialog(props: DepositDialogProps) {
const { open, onClose } = props;
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const { registryClient, lockupClient } = useWallet();
const dispatch = useDispatch();
const {
registrar,
member,
memberAccount,
mintAccount,
accounts,
} = useSelector((state: StoreState) => {
let memberAccount = undefined;
if (state.registry.member) {
memberAccount = state.accounts[state.registry.member.toString()];
}
const registrarAccount =
state.accounts[state.registry.registrar.toString()];
const registrar: ProgramAccount = {
publicKey: state.registry.registrar,
account: registrarAccount,
};
return {
registrar,
memberAccount,
member: state.registry.member,
mintAccount: state.accounts[registrar.account.mint.toString()],
accounts: state.accounts,
};
});
return (
<TransferDialog
deposit={true}
title={'Deposit'}
contextText={'Select the amount to deposit'}
open={open}
onClose={onClose}
onTransfer={async (
from: PublicKey,
displayAmount: number,
isLocked: boolean,
) => {
const amount = fromDisplay(displayAmount, mintAccount.decimals);
enqueueSnackbar(
`Depositing ${displayAmount} ${toDisplayLabel(
registrar.account.mint,
)} from ${from.toString()}`,
{
variant: 'info',
},
);
const tx = await (async () => {
if (isLocked) {
const relayData = registryClient.coder.instruction.encode(
'deposit_locked',
{
amount,
},
);
const vesting = accounts[from.toString()];
const _memberSigner = (
await memberSigner(
registryClient.programId,
registrar.publicKey,
member!,
)
).publicKey;
const _vestingSigner = (
await vestingSigner(lockupClient.programId, from)
).publicKey;
const relayAccounts = [
{
// @ts-ignore
pubkey: await registryClient.state.address(),
isWritable: false,
isSigner: false,
},
{
pubkey: registrar.publicKey,
isWritable: false,
isSigner: false,
},
{ pubkey: member!, isWritable: false, isSigner: false },
{
pubkey: registryClient.provider.wallet.publicKey,
isWritable: false,
isSigner: true,
},
];
const tx = await lockupClient.rpc.whitelistWithdraw(
relayData,
amount,
{
accounts: {
transfer: {
// @ts-ignore
lockup: await lockupClient.state.address(),
beneficiary: registryClient.provider.wallet.publicKey,
whitelistedProgram: registryClient.programId,
vesting: from,
vault: vesting.vault,
vestingSigner: _vestingSigner,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
whitelistedProgramVault: memberAccount.balancesLocked.vault,
whitelistedProgramVaultAuthority: _memberSigner,
},
},
remainingAccounts: relayAccounts,
},
);
// Update the store with the updated account.
const updatedVestingAccount = await lockupClient.account.vesting(
from,
);
dispatch({
type: ActionType.LockupUpdateVesting,
item: {
vesting: {
publicKey: from,
account: updatedVestingAccount,
},
},
});
return tx;
} else {
const tx = await registryClient.rpc.deposit(amount, {
accounts: {
depositor: from,
depositorAuthority: registryClient.provider.wallet.publicKey,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
vault: memberAccount.balances.vault,
beneficiary: registryClient.provider.wallet.publicKey,
member: member,
},
});
const tokenAccount = await getTokenAccount(
registryClient.provider,
from,
);
dispatch({
type: ActionType.CommonOwnedTokenAccountsUpdate,
item: {
account: {
publicKey: from,
account: tokenAccount,
},
},
});
return tx;
}
})();
closeSnackbar();
enqueueSnackbar(`Deposit complete`, {
variant: 'success',
action: <ViewTransactionOnExplorerButton signature={tx as string} />,
});
onClose();
}}
/>
);
}
type WithdrawDialogProps = DepositDialogProps;
function WithdrawDialog(props: WithdrawDialogProps) {
const { open, onClose } = props;
const { registryClient, lockupClient } = useWallet();
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const dispatch = useDispatch();
const {
registrar,
registrarAccount,
member,
memberAccount,
mintAccount,
accounts,
} = useSelector((state: StoreState) => {
let memberAccount = undefined;
if (state.registry.member) {
memberAccount = state.accounts[state.registry.member.toString()];
}
const registrarAccount =
state.accounts[state.registry.registrar.toString()];
return {
registrar: state.registry.registrar,
registrarAccount,
member: state.registry.member,
memberAccount,
mintAccount: state.accounts[registrarAccount.mint.toString()],
accounts: state.accounts,
};
});
return (
<TransferDialog
title={'Withdraw'}
contextText={'Select the amount to withdraw'}
open={open}
onClose={onClose}
onTransfer={async (
from: PublicKey,
displayAmount: number,
isLocked: boolean,
) => {
const amount = fromDisplay(displayAmount, mintAccount.decimals);
enqueueSnackbar(
`Withdrawing ${displayAmount} ${toDisplayLabel(
registrarAccount.mint,
)} to ${from.toString()}`,
{
variant: 'info',
},
);
const tx = await (async () => {
const _memberSigner = await memberSigner(
registryClient.programId,
registrar,
member!,
);
if (isLocked) {
const relayData = registryClient.coder.instruction.encode(
'withdraw_locked',
{
amount,
},
);
const vesting = accounts[from.toString()];
const _memberSigner = (
await memberSigner(registryClient.programId, registrar, member!)
).publicKey;
const _vestingSigner = (
await vestingSigner(lockupClient.programId, from)
).publicKey;
const relayAccounts = [
{
// @ts-ignore
pubkey: await registryClient.state.address(),
isWritable: false,
isSigner: false,
},
{ pubkey: registrar, isWritable: false, isSigner: false },
{ pubkey: member!, isWritable: false, isSigner: false },
{
pubkey: registryClient.provider.wallet.publicKey,
isWritable: false,
isSigner: true,
},
];
const tx = await lockupClient.rpc.whitelistDeposit(relayData, {
accounts: {
transfer: {
// @ts-ignore
lockup: await lockupClient.state.address(),
beneficiary: registryClient.provider.wallet.publicKey,
whitelistedProgram: registryClient.programId,
vesting: from,
vault: vesting.vault,
vestingSigner: _vestingSigner,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
whitelistedProgramVault: memberAccount.balancesLocked.vault,
whitelistedProgramVaultAuthority: _memberSigner,
},
},
remainingAccounts: relayAccounts,
});
// Update the store with the updated account.
const updatedVestingAccount = await lockupClient.account.vesting(
from,
);
dispatch({
type: ActionType.LockupUpdateVesting,
item: {
vesting: {
publicKey: from,
account: updatedVestingAccount,
},
},
});
return tx;
} else {
const tx = await registryClient.rpc.withdraw(amount, {
accounts: {
registrar,
member,
beneficiary: registryClient.provider.wallet.publicKey,
vault: memberAccount.balances.vault,
memberSigner: _memberSigner.publicKey,
depositor: from,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
},
});
const tokenAccount = await getTokenAccount(
registryClient.provider,
from,
);
dispatch({
type: ActionType.CommonOwnedTokenAccountsUpdate,
item: {
account: {
publicKey: from,
account: tokenAccount,
},
},
});
return tx;
}
})();
closeSnackbar();
enqueueSnackbar(`Withdraw complete`, {
variant: 'success',
action: <ViewTransactionOnExplorerButton signature={tx as string} />,
});
onClose();
}}
/>
);
}
type TransferDialogProps = {
title: string;
contextText: string;
open: boolean;
deposit?: boolean;
onClose: () => void;
onTransfer: (
from: PublicKey,
amount: number,
isLocked: boolean,
) => Promise<void>;
};
function TransferDialog(props: TransferDialogProps) {
const { mint, mintAccount } = useSelector((state: StoreState) => {
const registrar = state.accounts[state.registry.registrar.toString()];
const mint = registrar ? registrar.mint : undefined;
return {
mint,
mintAccount: state.accounts[registrar.mint.toString()],
};
});
const { enqueueSnackbar } = useSnackbar();
const { open, onClose, onTransfer, title, contextText, deposit } = props;
const [displayAmount, setDisplayAmount] = useState<null | number>(null);
const [from, setFrom] = useState<null | PublicKey>(null);
const [vesting, setVesting] = useState<null | PublicKey>(null);
const [maxDisplayAmount, setMaxDisplayAmount] = useState<null | number>(null);
const [isLocked, setIsLocked] = useState(false);
const submitBtnDisabled =
(isLocked ? !vesting : !from) ||
!displayAmount ||
!maxDisplayAmount ||
displayAmount > maxDisplayAmount;
return (
<div>
<Dialog
open={open}
TransitionComponent={Transition}
keepMounted
onClose={onClose}
fullWidth
>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<DialogTitle>{title}</DialogTitle>
<div style={{ display: 'flex', paddingRight: '24px' }}>
<div
style={{
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
}}
>
<LockIcon />
</div>
<FormControlLabel
style={{ marginLeft: '0px', marginRight: '0px' }}
control={
<Switch
checked={isLocked}
onChange={() => setIsLocked(!isLocked)}
/>
}
label=""
/>
</div>
</div>
<DialogContent>
<div style={{ display: 'flex' }}>
<div style={{ flex: 1 }}>
<TextField
style={{ width: '100%' }}
id="outlined-number"
label="Amount"
type="number"
InputLabelProps={{
shrink: true,
}}
variant="outlined"
onChange={e =>
setDisplayAmount(parseFloat(e.target.value) as number)
}
InputProps={{
inputProps: { min: 0, max: maxDisplayAmount ?? 0 },
}}
/>
<FormHelperText>{contextText}</FormHelperText>
</div>
</div>
<FormControl fullWidth>
{!isLocked ? (
<>
<OwnedTokenAccountsSelect
variant="outlined"
decimals={mintAccount.decimals}
mint={mint}
onChange={(f: PublicKey, _maxDisplayAmount: BN) => {
setFrom(f);
// TODO: set an actual limit for the withdrawal UI (i.e.
// what's currently in the vault). Currently not
// done since we dont' have websocket connections
// for each of the users accounts. However we
// still use the "max" amount for display vesting
// accounts.
setMaxDisplayAmount(2 ** 53);
}}
/>
<FormHelperText>
Token account to transfer to/from
</FormHelperText>
</>
) : (
<>
<VestingAccountsSelect
variant="outlined"
mint={mint}
decimals={mintAccount.decimals}
deposit={deposit}
onChange={(v: PublicKey, maxDisplayAmount: BN) => {
setVesting(v);
setMaxDisplayAmount(maxDisplayAmount.toNumber());
}}
/>
<FormHelperText>
Vesting account to transfer to/from your <b>locked</b>{' '}
balances
</FormHelperText>
</>
)}
</FormControl>
</DialogContent>
<DialogActions>
<Button onClick={onClose} color="primary">
Cancel
</Button>
<Button
//@ts-ignore
onClick={() => {
onTransfer(
isLocked ? vesting! : from!,
displayAmount!,
isLocked,
).catch(err => {
console.error(err);
enqueueSnackbar(`Error transferring funds: ${err.toString()}`, {
variant: 'error',
});
});
}}
color="primary"
disabled={submitBtnDisabled}
>
{title}
</Button>
</DialogActions>
</Dialog>
</div>
);
}
const Transition = React.forwardRef(function Transition(
props: TransitionProps & { children?: React.ReactElement<any, any> },
ref: React.Ref<unknown>,
) {
return <Slide direction="up" ref={ref} {...props} />;
});

View File

@ -0,0 +1,53 @@
import React from 'react';
import { useSelector } from 'react-redux';
import Button from '@material-ui/core/Button';
import { TransactionSignature } from '@solana/web3.js';
import { State as StoreState } from '../../store/reducer';
type Props = {
signature: string;
};
export async function withTx(
snack: any,
beforeLabel: string,
afterLabel: string,
execTx: () => Promise<TransactionSignature>,
) {
snack.enqueueSnackbar(beforeLabel, {
variant: 'info',
});
try {
let tx = await execTx();
snack.closeSnackbar();
snack.enqueueSnackbar(afterLabel, {
variant: 'success',
action: <ViewTransactionOnExplorerButton signature={tx} />,
});
} catch (err) {
snack.enqueueSnackbar(`Error: ${err.toString()}`, {
variant: 'error',
});
}
}
export function ViewTransactionOnExplorerButton(props: Props) {
const { signature } = props;
const { explorerClusterSuffix } = useSelector((state: StoreState) => {
return {
explorerClusterSuffix: state.common.network.explorerClusterSuffix,
};
});
const urlSuffix = `?cluster=${explorerClusterSuffix}`;
return (
<Button
color="inherit"
component="a"
target="_blank"
rel="noopener"
href={`https://explorer.solana.com/tx/${signature}` + urlSuffix}
>
View on Solana Explorer
</Button>
);
}

View File

@ -0,0 +1,75 @@
import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import BN from 'bn.js';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import { PublicKey } from '@solana/web3.js';
import { State as StoreState } from '../../store/reducer';
import { toDisplay } from '../../utils/tokens';
type Props = {
style?: any;
mint?: PublicKey | null;
decimals?: number;
variant?: 'outlined' | 'standard';
onChange: (from: PublicKey, maxAmount: BN) => void;
};
export default function OwnedTokenAccountsSelect(p: Props) {
const { mint, decimals, variant, onChange, style } = p;
const ownedTokenAccounts = useSelector((state: StoreState) => {
if (!mint) {
return [];
}
return state.common.ownedTokenAccounts.filter(
ota => ota.account.mint.toString() === mint.toString(),
);
});
const [fromAccount, setFromAccount] = useState('');
return (
<Select
style={style}
variant={variant}
fullWidth
value={fromAccount}
onChange={e => {
const pk = e.target.value as string;
setFromAccount(pk);
const pubkey = new PublicKey(pk);
const token = ownedTokenAccounts
.filter(ota => ota.publicKey.equals(pubkey))
.pop();
onChange(pubkey, new BN(token!.account.amount));
}}
>
{ownedTokenAccounts.length === 0 ? (
<MenuItem value={''}>No token accounts found</MenuItem>
) : (
ownedTokenAccounts.map(ownedTokenAccount => {
return (
<MenuItem value={ownedTokenAccount.publicKey.toString()}>
<div
style={{
width: '100%',
display: 'flex',
justifyContent: 'space-between',
overflow: 'hidden',
}}
>
<div>{`${ownedTokenAccount.publicKey}`}</div>
{decimals && (
<div style={{ float: 'right', color: '#ccc' }}>{`${toDisplay(
ownedTokenAccount.account.amount,
decimals ?? 0,
)}`}</div>
)}
</div>
</MenuItem>
);
})
)}
</Select>
);
}

View File

@ -0,0 +1,163 @@
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import { TokenInfo } from '@solana/spl-token-registry';
import { useTokenInfos } from '../../utils/tokens';
import { State as StoreState, ProgramAccount } from '../../store/reducer';
import { Network } from '../../store/config';
import * as bootstrap from './BootstrapProvider';
import { useWallet } from './WalletProvider';
export function activeRegistrar(
state: StoreState,
): { label: string; programAccount: any } {
const registrars = Object.keys(state.common.network.registrars)
.map(registrar => {
let entry: [string, ProgramAccount] = [
registrar,
{
publicKey: state.common.network.registrars[registrar],
account:
state.accounts[
state.common.network.registrars[registrar].toString()
],
},
];
return entry;
})
.filter(r => r[1].account !== undefined);
const selectedRegistrar: any = registrars
.filter(([r, acc]) => acc.publicKey.equals(state.registry.registrar))
.map(([r, acc]) => {
return {
label: r,
programAccount: acc,
};
})
.pop();
return selectedRegistrar;
}
export default function RegistrarSelect() {
const { registryClient } = useWallet();
const { registrars, selectedRegistrar, accounts, network } = useSelector(
(state: StoreState) => {
const registrars = Object.keys(state.common.network.registrars)
.map(registrar => {
let entry: [string, ProgramAccount] = [
registrar,
{
publicKey: state.common.network.registrars[registrar],
account:
state.accounts[
state.common.network.registrars[registrar].toString()
],
},
];
return entry;
})
.filter(r => r[1].account !== undefined);
const selectedRegistrar: any = registrars
.filter(([r, acc]) => acc.publicKey.equals(state.registry.registrar))
.map(([r, acc]) => {
return {
label: r,
programAccount: acc,
};
})
.pop();
return {
network: state.common.network,
accounts: state.accounts,
registrars,
selectedRegistrar,
};
},
);
const dispatch = useDispatch();
const tokenInfos = useTokenInfos();
return (
<Select
style={{ width: '294px', height: '36px' }}
variant={'outlined'}
fullWidth
value={selectedRegistrar.label}
onChange={async e => {
const registrar: ProgramAccount = registrars
.filter(([r, acc]) => r === e.target.value)
.map(([r, acc]) => acc)
.pop()!;
bootstrap.registrarSwitch(
registryClient,
accounts,
dispatch,
registrar!.publicKey, // New.
selectedRegistrar.programAccount.publicKey, // Old.
);
}}
>
{registrars.length === 0 ? (
<MenuItem value={'_loading'}>Loading registrars...</MenuItem>
) : (
registrars.map(([label, registrar]) => {
return (
<MenuItem key={label} value={label}>
<div style={{ display: 'flex' }}>
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
}}
>
{getImage(tokenInfos.get(registrar.account.mint.toString()))}
</div>
<div
style={{
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
}}
>
{`${registrarToDisplayLabel(registrar, network)}`}
</div>
</div>
</MenuItem>
);
})
)}
</Select>
);
}
function registrarToDisplayLabel(
registrar: ProgramAccount,
network: Network,
): string {
const entry = Object.keys(network.registrars)
.filter(r => network.registrars[r].equals(registrar.publicKey))
.pop();
if (entry !== undefined) {
return entry.toUpperCase();
}
return registrar.publicKey.toString();
}
export function getImage(token?: TokenInfo, style?: any) {
if (token) {
return (
<img
alt="Token Icon"
style={style ?? { marginRight: '10px', height: '25px' }}
src={token.logoURI}
/>
);
} else {
return <div style={{ marginLeft: '32px' }}></div>;
}
}

View File

@ -0,0 +1,28 @@
import React from 'react';
export default function Scroll(props: any) {
return (
<div
style={{
position: 'relative',
overflowY: 'scroll',
flex: 1,
}}
>
<div
style={{
position: 'absolute',
top: '0',
left: '0',
right: '0',
maxHeight: '100%',
minHeight: '100%',
display: 'flex',
flexDirection: 'column',
}}
>
{props.children}
</div>
</div>
);
}

View File

@ -0,0 +1,77 @@
import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import BN from 'bn.js';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import { PublicKey } from '@solana/web3.js';
import { State as StoreState, ProgramAccount } from '../../store/reducer';
import { toDisplay } from '../../utils/tokens';
type Props = {
style?: any;
mint?: PublicKey | null;
decimals: number;
variant?: 'outlined' | 'standard';
onChange: (from: PublicKey, maxAmount: BN) => void;
deposit?: boolean;
};
export default function VestingAccountsSelect(p: Props) {
const { mint, decimals, variant, onChange, style, deposit } = p;
const vestings: ProgramAccount[] = useSelector((state: StoreState) => {
if (!mint) {
return [];
}
return state.lockup.vestings
.map(v => {
return { publicKey: v, account: state.accounts[v.toString()] };
})
.filter(v => v.account.mint.equals(mint));
});
const [fromAccount, setFromAccount] = useState('');
return (
<Select
style={style}
variant={variant}
fullWidth
value={fromAccount}
onChange={e => {
const pk = e.target.value as string;
setFromAccount(pk);
const pubkey = new PublicKey(pk);
const v = vestings.filter(v => v.publicKey.equals(pubkey)).pop();
onChange(pubkey, availableAmount(v!, deposit));
}}
>
{vestings.length === 0 ? (
<MenuItem value={''}>No vesting accounts found</MenuItem>
) : (
vestings.map(v => {
return (
<MenuItem value={v.publicKey.toString()}>
<div
style={{
width: '100%',
display: 'flex',
justifyContent: 'space-between',
}}
>
<div>{`${v.publicKey.toString()}`}</div>
<div style={{ float: 'right', color: '#ccc' }}>{`${toDisplay(
availableAmount(v, deposit),
decimals,
)}`}</div>
</div>
</MenuItem>
);
})
)}
</Select>
);
}
function availableAmount(v: ProgramAccount, deposit?: boolean): BN {
return deposit
? v.account.outstanding.sub(v.account.whitelistOwned)
: v.account.whitelistOwned;
}

View File

@ -0,0 +1,93 @@
import React, {
PropsWithChildren,
ReactElement,
ReactNode,
useMemo,
useContext,
} from 'react';
import { useSelector } from 'react-redux';
import { Connection, ConfirmOptions } from '@solana/web3.js';
// @ts-ignore
import Wallet from '@project-serum/sol-wallet-adapter';
import { Provider } from '@project-serum/common';
import { Program } from '@project-serum/anchor';
import { State as StoreState } from '../../store/reducer';
import LockupIdl from '../../idl/lockup';
import RegistryIdl from '../../idl/registry';
import MultisigIdl from '../../idl/multisig';
export function useWallet(): WalletContextValues {
const w = useContext(WalletContext);
if (!w) {
throw new Error('Missing wallet context');
}
return w;
}
const WalletContext = React.createContext<null | WalletContextValues>(null);
type WalletContextValues = {
wallet: Wallet;
lockupClient: Program;
registryClient: Program;
multisigClient: Program;
};
export default function WalletProvider(
props: PropsWithChildren<ReactNode>,
): ReactElement {
const { walletProvider, network } = useSelector((state: StoreState) => {
return {
walletProvider: state.common.walletProvider,
network: state.common.network,
};
});
const {
wallet,
lockupClient,
registryClient,
multisigClient,
} = useMemo(() => {
const opts: ConfirmOptions = {
preflightCommitment: 'recent',
commitment: 'recent',
};
const connection = new Connection(network.url, opts.preflightCommitment);
const wallet = new Wallet(walletProvider, network.url);
// @ts-ignore
const provider = new Provider(connection, wallet, opts);
const lockupClient = new Program(
LockupIdl,
network.lockupProgramId,
provider,
);
const registryClient = new Program(
RegistryIdl,
network.registryProgramId,
provider,
);
const multisigClient = new Program(
MultisigIdl,
network.multisigProgramId,
provider,
);
return {
wallet,
lockupClient,
registryClient,
multisigClient,
};
}, [walletProvider, network]);
return (
<WalletContext.Provider
value={{ wallet, lockupClient, registryClient, multisigClient }}
>
{props.children}
</WalletContext.Provider>
);
}

View File

@ -0,0 +1,401 @@
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSnackbar } from 'notistack';
import BN from 'bn.js';
import {
Account,
PublicKey,
SystemProgram,
SYSVAR_RENT_PUBKEY,
SYSVAR_CLOCK_PUBKEY,
} from '@solana/web3.js';
import { TokenInstructions } from '@project-serum/serum';
import { createTokenAccountInstrs } from '@project-serum/common';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/Select';
import FormHelperText from '@material-ui/core/FormHelperText';
import MenuItem from '@material-ui/core/MenuItem';
import Typography from '@material-ui/core/Typography';
import CircularProgress from '@material-ui/core/CircularProgress';
import DialogContent from '@material-ui/core/DialogContent';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogActions from '@material-ui/core/DialogActions';
import { State as StoreState } from '../../store/reducer';
import { ActionType } from '../../store/actions';
import { useWallet } from '../../components/common/WalletProvider';
import OwnedTokenAccountsSelect from '../../components/common/OwnedTokenAccountsSelect';
import { fromDisplay } from '../../utils/tokens';
import { vestingSigner } from '../../utils/lockup';
import { ViewTransactionOnExplorerButton } from '../common/Notification';
export default function NewVestingButton() {
const [open, setOpen] = useState(false);
return (
<>
<div onClick={() => setOpen(true)}>
<Button variant="contained" color="secondary">
New
</Button>
</div>
<NewVestingDialog open={open} onClose={() => setOpen(false)} />
</>
);
}
type NewVestingDialogProps = {
open: boolean;
onClose: () => void;
};
function NewVestingDialog(props: NewVestingDialogProps) {
const { open, onClose } = props;
const { network, accounts } = useSelector((state: StoreState) => {
return {
network: state.common.network,
accounts: state.accounts,
};
});
const defaultStartDate = new Date().toString();
const defaultStartTs = new Date(defaultStartDate).getTime() / 1000;
const defaultEndDate = '2027-01-01T12:00';
const defaultEndTs = new Date(defaultEndDate).getTime() / 1000;
const [beneficiary, setBeneficiary] = useState('');
const isValidBeneficiary = (() => {
try {
new PublicKey(beneficiary);
return true;
} catch (_) {
return false;
}
})();
const displayBeneficiaryError = !isValidBeneficiary && beneficiary !== '';
const [fromAccount, setFromAccount] = useState<null | PublicKey>(null);
const [startTimestamp, setStartTimestamp] = useState(defaultStartTs);
const [timestamp, setTimestamp] = useState(defaultEndTs);
const [periodCount, setPeriodCount] = useState(7);
const [displayAmount, setDisplayAmount] = useState<null | number>(null);
const { lockupClient } = useWallet();
const [isLoading, setIsLoading] = useState(false);
const [mint, setMint] = useState<null | PublicKey>(null);
const { enqueueSnackbar } = useSnackbar();
const dispatch = useDispatch();
const submitBtnEnabled =
mint !== null &&
fromAccount !== null &&
isValidBeneficiary &&
displayAmount !== null;
const createVestingClickHandler = async () => {
setIsLoading(true);
try {
const beneficiaryPublicKey = new PublicKey(beneficiary);
const beneficiaryAccount = await lockupClient.provider.connection.getAccountInfo(
beneficiaryPublicKey,
);
if (beneficiaryAccount === null) {
enqueueSnackbar('Unable to validate given beneficiary.', {
variant: 'error',
});
setIsLoading(false);
return;
}
if (!beneficiaryAccount.owner.equals(SystemProgram.programId)) {
enqueueSnackbar(
'The beneficiary must be owned by the System Program.',
{
variant: 'error',
},
);
setIsLoading(false);
return;
}
enqueueSnackbar('Creating vesting acount...', {
variant: 'info',
});
const mintAccount = accounts[mint!.toString()];
let amount = mintAccount
? fromDisplay(displayAmount!, mintAccount.decimals)
: new BN(displayAmount!);
const vesting = new Account();
const vestingVault = new Account();
const _vestingSigner = await vestingSigner(
lockupClient.programId,
vesting.publicKey,
);
let tx = await lockupClient.rpc.createVesting(
beneficiaryPublicKey,
amount,
_vestingSigner.nonce,
new BN(startTimestamp),
new BN(timestamp),
new BN(periodCount),
null,
{
accounts: {
vesting: vesting.publicKey,
vault: vestingVault.publicKey,
depositor: fromAccount,
depositorAuthority: lockupClient.provider.wallet.publicKey,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
rent: SYSVAR_RENT_PUBKEY,
clock: SYSVAR_CLOCK_PUBKEY,
},
signers: [vesting, vestingVault],
instructions: [
await lockupClient.account.vesting.createInstruction(vesting),
...(await createTokenAccountInstrs(
lockupClient.provider,
vestingVault.publicKey,
mint!,
_vestingSigner.publicKey,
)),
],
},
);
// Only add to the local store if the lockup belongs to the current user.
if (beneficiaryPublicKey.equals(lockupClient.provider.wallet.publicKey)) {
const vestingAccount = await lockupClient.account.vesting(
vesting.publicKey,
);
dispatch({
type: ActionType.LockupCreateVesting,
item: {
vesting: {
publicKey: vesting.publicKey,
account: vestingAccount,
},
},
});
}
enqueueSnackbar(`Vesting account created`, {
variant: 'success',
action: <ViewTransactionOnExplorerButton signature={tx} />,
});
onClose();
} catch (err) {
enqueueSnackbar(`Error creating vesting account: ${err.toString()}`, {
variant: 'error',
});
}
setIsLoading(false);
};
return (
<Dialog open={open} onClose={onClose} fullWidth maxWidth="md">
<DialogTitle>
<Typography variant="h4" component="h2">
New Vesting Account
</Typography>
</DialogTitle>
<DialogContent>
<div>
{isLoading && (
<div
style={{
width: '40px',
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: '24px',
}}
>
<CircularProgress
style={{ marginLeft: 'auto', marginRight: 'auto' }}
/>
</div>
)}
<div style={{ display: 'flex', width: '100%' }}>
<div>
<FormControl variant="outlined" style={{ width: '200px' }}>
<InputLabel>Mint</InputLabel>
<Select
value={mint ? mint!.toString() : ''}
onChange={e =>
setMint(new PublicKey(e.target.value as string))
}
>
{Object.keys(network.mints).map(m => (
<MenuItem value={network.mints[m].toString()}>
{m.toUpperCase()}
</MenuItem>
))}
{/*<MenuItem value="custom">Custom</MenuItem>*/}
</Select>
</FormControl>
</div>
{false && (
<div style={{ flex: 1, marginLeft: '10px' }}>
<TextField
fullWidth
label="Custom mint"
value={mint ? mint!.toString() : ''}
onChange={e => setMint(new PublicKey(e.target.value))}
/>
<FormHelperText>Mint of the token to lockup</FormHelperText>
</div>
)}
</div>
<div>
<div style={{ display: 'flex', width: '100%' }}>
<div style={{ flex: 1 }}>
<FormControl fullWidth>
<InputLabel>From</InputLabel>
<OwnedTokenAccountsSelect
mint={mint}
onChange={(f: PublicKey) => setFromAccount(f)}
/>
<FormHelperText>Token account to send from</FormHelperText>
</FormControl>
</div>
</div>
</div>
<div style={{ marginTop: '24px' }}>
<TextField
fullWidth
error={displayBeneficiaryError}
helperText={displayBeneficiaryError && 'Invalid beneficiary'}
label="Beneficiary"
value={beneficiary}
onChange={e => setBeneficiary(e.target.value)}
/>
<FormHelperText>Owner of the new vesting account</FormHelperText>
</div>
<div
style={{
marginTop: '24px',
}}
>
{false && (
<FormHelperText style={{ color: 'blue' }}>
Note: Amounts for custom mints (i.e., not SRM/MSRM) are in their
raw, non-decimal form. Make sure to convert before entering into
the fields here. For example, if a token has 6 decimals, then
multiply your desired amount by 10^6.
</FormHelperText>
)}
<TextField
fullWidth
label="Amount"
type="number"
value={displayAmount}
InputProps={{ inputProps: { min: 0 } }}
onChange={e => setDisplayAmount(parseFloat(e.target.value))}
/>
<FormHelperText>
Amount to deposit into the vesting account
</FormHelperText>
</div>
<div
style={{
marginTop: '24px',
display: 'flex',
}}
>
<div style={{ flex: 1, marginRight: '10px' }}>
<TextField
fullWidth
label="Start date"
type="datetime-local"
defaultValue={defaultStartDate}
InputLabelProps={{
shrink: true,
}}
onChange={e => {
const d = new Date(e.target.value);
setStartTimestamp(d.getTime() / 1000);
}}
/>
<FormHelperText>Date when vesting begins</FormHelperText>
</div>
<div>
<TextField
disabled
fullWidth
label="Unix Timestamp"
value={startTimestamp}
/>
</div>
</div>
<div
style={{
marginTop: '24px',
display: 'flex',
}}
>
<div style={{ flex: 1, marginRight: '10px' }}>
<TextField
fullWidth
label="End date"
type="datetime-local"
defaultValue={defaultEndDate}
InputLabelProps={{
shrink: true,
}}
onChange={e => {
const d = new Date(e.target.value);
setTimestamp(d.getTime() / 1000);
}}
/>
<FormHelperText>Date when all tokens are vested</FormHelperText>
</div>
<div>
<TextField
disabled
fullWidth
label="Unix Timestamp"
value={timestamp}
/>
</div>
</div>
<div
style={{
marginTop: '24px',
}}
>
<FormControl fullWidth>
<TextField
id="outlined-number"
label="Period Count"
type="number"
InputLabelProps={{
shrink: true,
}}
variant="outlined"
value={periodCount}
onChange={e =>
setPeriodCount(parseInt(e.target.value) as number)
}
InputProps={{ inputProps: { min: 1 } }}
/>
<FormHelperText>Number of vesting periods</FormHelperText>
</FormControl>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Cancel</Button>
<Button
variant="contained"
type="submit"
color="primary"
disabled={!submitBtnEnabled || isLoading}
onClick={() => createVestingClickHandler()}
>
Create
</Button>
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,441 @@
import React, { useState, useEffect } from 'react';
import ChartistGraph from 'react-chartist';
import { useDispatch, useSelector } from 'react-redux';
import BN from 'bn.js';
import { useSnackbar } from 'notistack';
import { FixedScaleAxis, IChartOptions, Interpolation } from 'chartist';
import CircularProgress from '@material-ui/core/CircularProgress';
import Card from '@material-ui/core/Card';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Link from '@material-ui/core/Link';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
import Collapse from '@material-ui/core/Collapse';
import { PublicKey, SYSVAR_CLOCK_PUBKEY } from '@solana/web3.js';
import { TokenInstructions } from '@project-serum/serum';
import { ProgramAccount, State as StoreState } from '../../store/reducer';
import { Network } from '../../store/config';
import { useWallet } from '../common/WalletProvider';
import OwnedTokenAccountsSelect from '../../components/common/OwnedTokenAccountsSelect';
import { withTx } from '../../components/common/Notification';
import { ActionType } from '../../store/actions';
import { getImage } from '../../components/common/RegistrarSelect';
import { useTokenInfos, toDisplay, toDisplayLabel } from '../../utils/tokens';
import {
vestingSigner,
availableForWithdrawal as _availableForWithdrawal,
} from '../../utils/lockup';
type VestingAccountCardProps = {
network: Network;
vesting: ProgramAccount;
};
export default function VestingAccountCard(props: VestingAccountCardProps) {
const { vesting, network } = props;
const { lockupClient, registryClient } = useWallet();
const { enqueueSnackbar } = useSnackbar();
const tokenInfos = useTokenInfos();
const dispatch = useDispatch();
const { accounts, member, mintAccount } = useSelector((state: StoreState) => {
return {
accounts: state.accounts,
member: state.registry.member
? {
publicKey: state.registry.member,
account: state.accounts[state.registry.member.toString()],
}
: undefined,
mintAccount: state.accounts[vesting.account.mint.toString()],
};
});
const [expanded, setExpanded] = useState(false);
const [hover, setHover] = useState(false);
// Whitelisted mints only for now.
const isCustomMint = false;
let mint = accounts[vesting.account.mint.toString()];
const displayFn = mint
? (input: BN) => {
return toDisplay(input, mint.decimals);
}
: (input: BN) => input.toString();
const outstandingLabel = `${displayFn(
vesting.account.outstanding,
)} ${toDisplayLabel(vesting.account.mint)}`;
const startTs = vesting.account.startTs;
const endTs = vesting.account.endTs;
const tsOverflow = endTs.sub(startTs).mod(vesting.account.periodCount);
const shiftedStartTs = startTs.sub(tsOverflow);
const period = endTs.sub(shiftedStartTs).div(vesting.account.periodCount);
// Make the horizontal axis evenly spaced.
//
// Vesting dates assuming we stretch the start date back in time (so that the
// periods are of even length).
const vestingDates = [
...Array(vesting.account.periodCount.toNumber() + 1),
].map((_, idx) => {
return formatDate(
new Date((shiftedStartTs.toNumber() + idx * period.toNumber()) * 1000),
);
});
// Now push the start window forward to the real start date, making the first period shorter.
vestingDates[0] = formatDate(new Date(startTs.toNumber() * 1000));
// Now do the same thing on the vertical axis.
const rewardOverflow = vesting.account.startBalance.mod(
vesting.account.periodCount,
);
const rewardPerPeriod = vesting.account.startBalance
.sub(rewardOverflow)
.div(vesting.account.periodCount)
.toNumber();
const cumulativeVesting = [...Array(vestingDates.length)].map(() => 0);
cumulativeVesting[1] = rewardPerPeriod + rewardOverflow.toNumber();
for (let k = 2; k < cumulativeVesting.length; k += 1) {
cumulativeVesting[k] = cumulativeVesting[k - 1] + rewardPerPeriod;
}
const startLabel = formatDate(
new Date(vesting.account.startTs.toNumber() * 1000),
);
const endLabel = formatDate(
new Date(vesting.account.endTs.toNumber() * 1000),
);
const urlSuffix = `?cluster=${network.explorerClusterSuffix}`;
const [
availableForWithdrawal,
setAvailableForWithdrawal,
] = useState<null | BN>(null);
const [withdrawalAccount, setWithdrawalAccount] = useState<null | PublicKey>(
null,
);
useEffect(() => {
_availableForWithdrawal(lockupClient, vesting.publicKey)
.then((amount: BN) => {
setAvailableForWithdrawal(amount);
})
.catch((err: any) => {
console.error(err);
enqueueSnackbar(
`Error fetching available for withdrawal: ${err.toString()}`,
{
variant: 'error',
},
);
});
}, [lockupClient, vesting, enqueueSnackbar]);
const snack = useSnackbar();
const withdrawEnabled =
withdrawalAccount !== null &&
availableForWithdrawal !== null &&
availableForWithdrawal.gtn(0);
const withdraw = async () => {
await withTx(
snack,
'Withdrawing locked tokens',
'Tokens unlocked',
async () => {
const remainingAccounts = (() => {
if (vesting.account.realizor) {
if (!member) {
// Should never be thrown.
throw new Error('Member account not found');
}
return [
{
pubkey: registryClient.programId,
isSigner: false,
isWritable: false,
},
{ pubkey: member.publicKey, isSigner: false, isWritable: false },
{
pubkey: member.account.balances.spt,
isSigner: false,
isWritable: false,
},
{
pubkey: member.account.balancesLocked.spt,
isSigner: false,
isWritable: false,
},
];
} else {
return undefined;
}
})();
const tx = await lockupClient.rpc.withdraw(availableForWithdrawal!, {
accounts: {
vesting: vesting.publicKey,
beneficiary: lockupClient.provider.wallet.publicKey,
token: withdrawalAccount!,
vault: vesting.account.vault,
vestingSigner: (
await vestingSigner(lockupClient.programId, vesting.publicKey)
).publicKey,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
clock: SYSVAR_CLOCK_PUBKEY,
},
remainingAccounts,
});
const newVesting = await lockupClient.account.vesting(
vesting.publicKey,
);
dispatch({
type: ActionType.LockupUpdateVesting,
item: {
vesting: {
publicKey: vesting.publicKey,
account: newVesting,
},
},
});
return tx;
},
);
};
const rows = [
{
field: 'Projected unlock',
value:
availableForWithdrawal === null
? null
: displayFn(availableForWithdrawal!),
},
{
field: 'Locked outstanding',
value: displayFn(vesting.account.outstanding),
},
{
field: 'Current balance',
value: displayFn(
vesting.account.outstanding.sub(vesting.account.whitelistOwned),
),
},
{ field: 'Initial lockup', value: displayFn(vesting.account.startBalance) },
{
field: 'Amount unlocked',
value: displayFn(
vesting.account.startBalance.sub(vesting.account.outstanding),
),
},
{
field: 'Whitelist owned',
value: displayFn(vesting.account.whitelistOwned),
},
{ field: 'Period count', value: vesting.account.periodCount.toString() },
{
field: 'Start timestamp',
value: `${new Date(
vesting.account.startTs.toNumber() * 1000,
).toLocaleString()} (${vesting.account.startTs.toString()})`,
},
{
field: 'End timestamp',
value: `${new Date(
vesting.account.endTs.toNumber() * 1000,
).toLocaleString()} (${vesting.account.endTs.toString()})`,
},
{ field: 'Vault', value: vesting.account.vault.toString() },
{
field: 'Realizer program',
value: vesting.account.realizor
? vesting.account.realizor.program.toString()
: 'None',
},
{
field: 'Realizer metadata',
value: vesting.account.realizor
? vesting.account.realizor.metadata.toString()
: 'None',
},
{
field: 'Grantor',
value: vesting.account.grantor.toString(),
},
];
return (
<Card
key={vesting.publicKey.toString()}
onMouseOver={() => setHover(true)}
onMouseOut={() => setHover(false)}
style={{
marginTop: '24px',
cursor: hover ? 'pointer' : 'default',
}}
>
<CardContent style={{ paddingBottom: '16px' }}>
<ListItem onClick={() => setExpanded(!expanded)}>
<div
style={{
width: '100%',
display: 'flex',
justifyContent: 'space-between',
}}
>
<ListItemIcon>
{getImage(tokenInfos.get(vesting.account.mint.toString()), {
marginRight: '16px',
width: '56px',
})}
</ListItemIcon>
<ListItemText
primary={
<Link
href={
`https://explorer.solana.com/account/${vesting.publicKey.toBase58()}` +
urlSuffix
}
target="_blank"
rel="noopener"
>
{vesting.publicKey.toString()}
</Link>
}
secondary={`${startLabel}, ${endLabel} | ${vesting.account.periodCount.toNumber()} periods`}
/>
<div
style={{
marginTop: '6px',
color: 'rgba(0, 0, 0, 0.54)',
display: 'flex',
justifyContent: 'space-between',
flexDirection: 'column',
maxWidth: '200px',
}}
>
<Typography
style={{ overflow: 'hidden', whiteSpace: 'nowrap' }}
variant="body1"
>
{outstandingLabel}
</Typography>
</div>
</div>
</ListItem>
<Collapse in={expanded} timeout="auto" unmountOnExit>
<Typography></Typography>
{vestingDates.length <= 15 ? (
<ChartistGraph
data={{
labels: vestingDates,
series: [cumulativeVesting],
}}
options={
{
axisY: {
type: FixedScaleAxis,
low: 0,
high: cumulativeVesting[cumulativeVesting.length - 1],
ticks: cumulativeVesting,
},
lineSmooth: Interpolation.step(),
height: 400,
} as IChartOptions
}
type={'Line'}
/>
) : (
<div style={{ textAlign: 'center', fontWeight: 'bold' }}>
{/* TOOD: graphs for vesting accounts with a lot of periods. */}A
graph isn't available for this account.
</div>
)}
<div>
{isCustomMint && (
<div
style={{
padding: '15px',
}}
>
<b>
Note: custom mints (i.e. not SRM/MSRM) display raw token
amounts without decimals.
</b>
</div>
)}
<Table>
<TableBody>
{rows.map(r => {
return (
<TableRow>
<TableCell>{r.field}</TableCell>
<TableCell align="right">
{r.value === null ? (
<CircularProgress
style={{
height: '20px',
width: '20px',
padding: 0,
}}
/>
) : (
r.value
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
<div style={{ display: 'flex', marginTop: '15px' }}>
<OwnedTokenAccountsSelect
decimals={mintAccount ? mintAccount.decimals : undefined}
mint={vesting.account.mint}
onChange={(f: PublicKey) => setWithdrawalAccount(f)}
/>
<div style={{ marginLeft: '20px', width: '191px' }}>
<Button
style={{ fontSize: '12px' }}
color="primary"
disabled={!withdrawEnabled}
variant="contained"
onClick={() =>
withdraw().catch(err => {
let msg = err.toString();
if (
msg &&
msg.split('custom program error: 0x78').length === 2
) {
msg = 'Unrealized rewards. Please unstake';
}
enqueueSnackbar(
`Error withdrawing from vesting account: ${err.toString()}`,
{
variant: 'error',
},
);
})
}
>
Unlock tokens
</Button>
</div>
</div>
</div>
</Collapse>
</CardContent>
</Card>
);
}
// TODO: locale format without minutes, hours, seconds?
function formatDate(d: Date): string {
return `${d.getMonth() + 1}/${d.getDate()}/${d.getFullYear()}`;
}

View File

@ -0,0 +1,109 @@
import React from 'react';
import { useSelector } from 'react-redux';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import ListItem from '@material-ui/core/ListItem';
import Container from '@material-ui/core/Container';
import List from '@material-ui/core/List';
import { useWallet } from '../../components/common/WalletProvider';
import { State as StoreState } from '../../store/reducer';
import NewVestingButton from './NewVesting';
import VestingAccountCard from './VestingAccountCard';
export default function Vestings() {
const { wallet } = useWallet();
const { vestingAccounts, network } = useSelector((state: StoreState) => {
return {
vestingAccounts: state.lockup.vestings.map(v => {
return {
publicKey: v,
account: state.accounts[v.toString()],
};
}),
network: state.common.network,
};
});
return (
<Container fixed maxWidth="md">
<div style={{ width: '100%' }}>
<div style={{ marginTop: '24px', marginBottom: '24px' }}>
<link
rel="stylesheet"
href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css"
/>
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
{wallet.publicKey && (
<div
style={{
display: 'flex',
justifyContent: 'space-between',
marginBottom: '24px',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
}}
>
<Typography
style={{
fontSize: '20px',
fontWeight: 'bold',
}}
>
Projected Unlocks
</Typography>
</div>
<div>
<NewVestingButton />
</div>
</div>
)}
<Typography color="textSecondary">
In addition to a vesting schedule, locked token accounts are subject
to an application dependent
<b> realization condition</b>, determining if and when locked tokens
are given to a user. For example, in the case of locked staking
rewards, locked tokens become realized in the event of unstaking. If
one never unstakes, one never receives locked token rewards.
</Typography>
<List
disablePadding
style={{ marginLeft: 'auto', marginRight: 'auto' }}
>
{vestingAccounts.map(v => (
<VestingAccountCard network={network} vesting={v} />
))}
{vestingAccounts.length === 0 && (
<Card
style={{
marginTop: '24px',
}}
>
<CardContent>
<ListItem>
<div
style={{
width: '100%',
display: 'flex',
justifyContent: 'space-between',
}}
>
<Typography color="textSecondary" variant="h6">
No vesting accounts found
</Typography>
</div>
</ListItem>
</CardContent>
</Card>
)}
</List>
</div>
</div>
</Container>
);
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,200 @@
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSnackbar } from 'notistack';
import Button from '@material-ui/core/Button';
import {
Account,
PublicKey,
SYSVAR_RENT_PUBKEY,
SYSVAR_CLOCK_PUBKEY,
} from '@solana/web3.js';
import { TokenInstructions } from '@project-serum/serum';
import { createTokenAccountInstrs } from '@project-serum/common';
import { useWallet } from '../../components/common/WalletProvider';
import * as notification from '../common/Notification';
import OwnedTokenAccountsSelect from '../common/OwnedTokenAccountsSelect';
import { RewardListItemViewModel } from './RewardsList';
import { ActionType } from '../../store/actions';
import { State as StoreState } from '../../store/reducer';
import { vendorSigner } from '../../utils/registry';
import { vestingSigner } from '../../utils/lockup';
type ClaimRewardButtonProps = {
rli: RewardListItemViewModel;
};
export default function ClaimRewardButton(props: ClaimRewardButtonProps) {
const { registryClient, lockupClient } = useWallet();
const { member, registrar } = useSelector((state: StoreState) => {
const registrar = {
publicKey: state.registry.registrar,
account: state.accounts[state.registry.registrar.toString()],
};
const member = state.registry.member
? {
publicKey: state.registry.member,
account: state.accounts[state.registry.member.toString()],
}
: undefined;
return {
registrar,
member,
};
});
const { rli } = props;
const dispatch = useDispatch();
const snack = useSnackbar();
const [token, setToken] = useState<null | PublicKey>(null);
// On click.
const clickHandler = async (): Promise<void> => {
notification.withTx(
snack,
`Processing vendor reward ${rli!.vendor!.publicKey.toString()}`,
'Reward processed',
async () => {
const vendor = await registryClient.account.rewardVendor(
rli.vendor!.publicKey,
);
const _vendorSigner = await vendorSigner(
registryClient.programId,
registrar.publicKey,
rli.vendor!.publicKey,
);
if (rli!.reward.locked) {
const vendoredVesting = new Account();
const vendoredVestingVault = new Account();
const vendoredVestingSigner = await vestingSigner(
lockupClient.programId,
vendoredVesting.publicKey,
);
const remainingAccounts = lockupClient.instruction.createVesting
.accounts({
vesting: vendoredVesting.publicKey,
vault: vendoredVestingVault.publicKey,
depositor: vendor.vault,
depositorAuthority: _vendorSigner.publicKey,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
rent: SYSVAR_RENT_PUBKEY,
clock: SYSVAR_CLOCK_PUBKEY,
})
// Change the signer status on the vendor signer since it's signed by the program, not the
// client.
.map((meta: any) =>
meta.pubkey.equals(_vendorSigner.publicKey)
? { ...meta, isSigner: false }
: meta,
);
const tx = await registryClient.rpc.claimRewardLocked(
vendoredVestingSigner.nonce,
{
accounts: {
// @ts-ignore
registry: await registryClient.state.address(),
lockupProgram: lockupClient.programId,
cmn: {
registrar: registrar.publicKey,
member: member!.publicKey,
beneficiary: registryClient.provider.wallet.publicKey,
balances: member!.account.balances,
balancesLocked: member!.account.balancesLocked,
vendor: rli.vendor!.publicKey,
vault: rli.vendor!.account.vault,
vendorSigner: _vendorSigner.publicKey,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
clock: SYSVAR_CLOCK_PUBKEY,
},
},
remainingAccounts,
signers: [vendoredVesting, vendoredVestingVault],
instructions: [
await lockupClient.account.vesting.createInstruction(
vendoredVesting,
),
...(await createTokenAccountInstrs(
registryClient.provider,
vendoredVestingVault.publicKey,
rli.vendor!.account.mint,
vendoredVestingSigner.publicKey,
)),
],
},
);
// Refetch the vesting accounts to update the UI with the new reward.
const vestingAccounts = await lockupClient.account.vesting.all(
registryClient.provider.wallet.publicKey.toBuffer(),
);
vestingAccounts.forEach(account => {
dispatch({
type: ActionType.AccountAdd,
item: {
account,
},
});
});
dispatch({
type: ActionType.LockupSetVestings,
item: {
vestingAccounts: vestingAccounts.map(v => v.publicKey),
},
});
return tx;
} else {
return await registryClient.rpc.claimReward({
accounts: {
to: token,
cmn: {
registrar: registrar.publicKey,
member: member!.publicKey,
beneficiary: registryClient.provider.wallet.publicKey,
balances: member!.account.balances,
balancesLocked: member!.account.balancesLocked,
vendor: rli.vendor!.publicKey,
vault: vendor.vault,
vendorSigner: _vendorSigner.publicKey,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
clock: SYSVAR_CLOCK_PUBKEY,
},
},
});
}
},
);
};
return (
<>
{!rli.reward.locked && (
<div>
<OwnedTokenAccountsSelect
style={{ width: '400px', height: '100%' }}
mint={rli.vendor.account.mint}
onChange={(f: PublicKey) => setToken(f)}
/>
</div>
)}
<div style={{ marginLeft: '10px', marginRight: '10px' }}>
<Button
disabled={rli.reward.unlockedAlloc && token === null}
variant="contained"
color="primary"
onClick={() =>
clickHandler().catch(err => {
console.error(err);
snack.enqueueSnackbar(
`Error ending pending redemption: ${err.toString()}`,
{
variant: 'error',
},
);
})
}
>
Process Reward
</Button>
</div>
</>
);
}

View File

@ -0,0 +1,541 @@
import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import BN from 'bn.js';
import { useSnackbar } from 'notistack';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import Button from '@material-ui/core/Button';
import Tabs from '@material-ui/core/Tabs';
import MenuItem from '@material-ui/core/MenuItem';
import Tab from '@material-ui/core/Tab';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/Select';
import * as serumCmn from '@project-serum/common';
import { TokenInstructions } from '@project-serum/serum';
import {
Account,
PublicKey,
SYSVAR_CLOCK_PUBKEY,
SYSVAR_RENT_PUBKEY,
} from '@solana/web3.js';
import { useWallet } from '../../components/common/WalletProvider';
import { State as StoreState } from '../../store/reducer';
import OwnedTokenAccountsSelect from '../common/OwnedTokenAccountsSelect';
import * as notification from '../common/Notification';
import { fromDisplay } from '../../utils/tokens';
import { Network } from '../../store/config';
import { activeRegistrar } from '../common/RegistrarSelect';
export default function DropRewardButton() {
const [showDialog, setShowDialog] = useState(false);
return (
<>
<div onClick={() => setShowDialog(true)}>
<Button variant="contained" color="secondary">
Drop Rewards
</Button>
</div>
<DropRewardDialog
open={showDialog}
onClose={() => setShowDialog(false)}
/>
</>
);
}
enum RewardTypeViewModel {
Unlocked,
Locked,
}
type DropRewardsDialogProps = {
open: boolean;
onClose: () => void;
};
function DropRewardDialog(props: DropRewardsDialogProps) {
const { open, onClose } = props;
const { selectedRegistrar } = useSelector((state: StoreState) => {
return {
selectedRegistrar: activeRegistrar(state),
};
});
const [rewardTypeTab, setRewardTypeTab] = useState(
RewardTypeViewModel.Unlocked,
);
return (
<Dialog open={open} onClose={onClose} fullWidth maxWidth="md">
<DialogTitle>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<Typography variant="h4" component="h2">
{`Drop Rewards on ${selectedRegistrar.label.toUpperCase()} Stakers`}
</Typography>
</div>
</DialogTitle>
<DialogContent>
<Tabs value={rewardTypeTab} onChange={(_e, t) => setRewardTypeTab(t)}>
<Tab value={RewardTypeViewModel.Unlocked} label="Unlocked" />
<Tab value={RewardTypeViewModel.Locked} label="Locked" />
</Tabs>
{rewardTypeTab === RewardTypeViewModel.Unlocked && (
<DropUnlockedForm onClose={onClose} />
)}
{rewardTypeTab === RewardTypeViewModel.Locked && (
<DropLockedForm onClose={onClose} />
)}
</DialogContent>
</Dialog>
);
}
type DropUnlockedFormProps = {
onClose: () => void;
};
function DropUnlockedForm(props: DropUnlockedFormProps) {
const { onClose } = props;
const snack = useSnackbar();
const { registryClient } = useWallet();
const { network, registrar, accounts } = useSelector((state: StoreState) => {
return {
network: state.common.network,
registrar: {
publicKey: state.registry.registrar,
account: state.accounts[state.registry.registrar.toString()],
},
accounts: state.accounts,
};
});
const [rewardDisplayAmount, setRewardDisplayAmount] = useState<null | number>(
null,
);
const [expiryTs, setExpiryTs] = useState<null | number>(null);
const [depositor, setDepositor] = useState<null | PublicKey>(null);
const [mint, setMint] = useState<null | string>(null);
const isSendEnabled =
mint !== null &&
depositor !== null &&
rewardDisplayAmount !== null &&
rewardDisplayAmount >= 100 &&
expiryTs !== null;
const sendUnlockedReward = async () => {
await notification.withTx(
snack,
'Dropping unlocked reward...',
'Unlocked reward dropped',
async () => {
let mintAccount = accounts[network.mints[mint!].toString()];
if (!mintAccount) {
mintAccount = await serumCmn.getMintInfo(
registryClient.provider,
network.mints[mint!],
);
}
const lockedRewardAmount = fromDisplay(
rewardDisplayAmount!,
mintAccount.decimals,
);
const rewardKind = { unlocked: {} };
const vendor = new Account();
const vendorVault = new Account();
const [vendorSigner, nonce] = await PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), vendor.publicKey.toBuffer()],
registryClient.programId,
);
return await registryClient.rpc.dropReward(
rewardKind,
lockedRewardAmount,
new BN(expiryTs!),
registryClient.provider.wallet.publicKey,
nonce,
{
accounts: {
registrar: registrar.publicKey,
rewardEventQ: registrar.account.rewardEventQ,
poolMint: registrar.account.poolMint,
vendor: vendor.publicKey,
vendorVault: vendorVault.publicKey,
depositor,
depositorAuthority: registryClient.provider.wallet.publicKey,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
clock: SYSVAR_CLOCK_PUBKEY,
rent: SYSVAR_RENT_PUBKEY,
},
signers: [vendorVault, vendor],
instructions: [
...(await serumCmn.createTokenAccountInstrs(
registryClient.provider,
vendorVault.publicKey,
network.mints[mint!],
vendorSigner,
)),
await registryClient.account.rewardVendor.createInstruction(
vendor,
),
],
},
);
},
);
onClose();
};
const onClick = () => {
sendUnlockedReward().catch(err => {
console.error(err);
snack.enqueueSnackbar(
`Error dropping unlocked reward: ${err.toString()}`,
{
variant: 'error',
},
);
});
};
return (
<DropVendorForm
network={network}
mint={mint}
setMint={setMint}
setDepositor={setDepositor}
setRewardDisplayAmount={setRewardDisplayAmount}
expiryTs={expiryTs}
setExpiryTs={setExpiryTs}
onCancel={onClose}
onClick={onClick}
isSendEnabled={isSendEnabled}
/>
);
}
type DropLockedFormProps = DropUnlockedFormProps;
function DropLockedForm(props: DropLockedFormProps) {
const { onClose } = props;
const snack = useSnackbar();
const { registryClient } = useWallet();
const { network, registrar, accounts } = useSelector((state: StoreState) => {
return {
network: state.common.network,
registrar: {
publicKey: state.registry.registrar,
account: state.accounts[state.registry.registrar.toString()],
},
accounts: state.accounts,
};
});
const [rewardDisplayAmount, setRewardDisplayAmount] = useState<null | number>(
null,
);
const [startTs, setStartTs] = useState<null | number>(null);
const [endTs, setEndTs] = useState<null | number>(null);
const [expiryTs, setExpiryTs] = useState<null | number>(null);
const [depositor, setDepositor] = useState<null | PublicKey>(null);
const [mint, setMint] = useState<null | string>(null);
const [periodCount, setPeriodCount] = useState(7);
const isSendEnabled =
startTs !== null &&
endTs !== null &&
mint !== null &&
depositor !== null &&
rewardDisplayAmount !== null &&
rewardDisplayAmount >= 100 &&
expiryTs !== null;
const sendLockedRewards = async () => {
await notification.withTx(
snack,
'Dropping locked reward...',
'Locked reward dropped',
async () => {
const rewardKind = {
locked: {
startTs: new BN(startTs!),
endTs: new BN(endTs!),
periodCount: new BN(periodCount),
},
};
const vendor = new Account();
const vendorVault = new Account();
const [vendorSigner, nonce] = await PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), vendor.publicKey.toBuffer()],
registryClient.programId,
);
let mintAccount = accounts[network.mints[mint!].toString()];
const rewardAmount = fromDisplay(
rewardDisplayAmount!,
mintAccount.decimals,
);
return await registryClient.rpc.dropReward(
rewardKind,
rewardAmount,
new BN(expiryTs!),
registryClient.provider.wallet.publicKey,
nonce,
{
accounts: {
registrar: registrar.publicKey,
rewardEventQ: registrar.account.rewardEventQ,
poolMint: registrar.account.poolMint,
vendor: vendor.publicKey,
vendorVault: vendorVault.publicKey,
depositor,
depositorAuthority: registryClient.provider.wallet.publicKey,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
clock: SYSVAR_CLOCK_PUBKEY,
rent: SYSVAR_RENT_PUBKEY,
},
signers: [vendorVault, vendor],
instructions: [
...(await serumCmn.createTokenAccountInstrs(
registryClient.provider,
vendorVault.publicKey,
network.mints[mint!],
vendorSigner,
)),
await registryClient.account.rewardVendor.createInstruction(
vendor,
),
],
},
);
},
);
onClose();
};
const onClick = () => {
sendLockedRewards().catch(err => {
snack.enqueueSnackbar(`Error dropping locked reward: ${err.toString()}`, {
variant: 'error',
});
});
};
return (
<DropVendorForm
network={network}
mint={mint}
setMint={setMint}
setDepositor={setDepositor}
setRewardDisplayAmount={setRewardDisplayAmount}
setStartTs={setStartTs}
setEndTs={setEndTs}
periodCount={periodCount}
setPeriodCount={setPeriodCount}
expiryTs={expiryTs}
setExpiryTs={setExpiryTs}
onCancel={onClose}
onClick={onClick}
isSendEnabled={isSendEnabled}
/>
);
}
type DropVendorFormProps = {
network: Network;
mint: string | null;
setMint: (mintLabel: string) => void;
setDepositor: (pk: PublicKey) => void;
setRewardDisplayAmount: (n: number) => void;
setStartTs?: (n: number) => void;
setEndTs?: (n: number) => void;
periodCount?: number;
setPeriodCount?: (p: number) => void;
expiryTs: number | null;
setExpiryTs: (ts: number) => void;
onCancel: () => void;
onClick: () => void;
isSendEnabled: boolean;
};
function DropVendorForm(props: DropVendorFormProps) {
const {
network,
mint,
setDepositor,
setMint,
setRewardDisplayAmount,
setStartTs,
setEndTs,
periodCount,
setPeriodCount,
expiryTs,
setExpiryTs,
onCancel,
onClick,
isSendEnabled,
} = props;
const mintOptions: { label: string; publicKey: PublicKey }[] = Object.keys(
network.mints,
).map(label => {
return {
label,
publicKey: network.mints[label],
};
});
return (
<>
<div>
<div style={{ display: 'flex', marginTop: '10px' }}>
<div style={{ flex: 1 }}>
<OwnedTokenAccountsSelect
style={{ height: '100%' }}
mint={mint === null ? undefined : network.mints[mint]}
onChange={(f: PublicKey) => setDepositor(f)}
/>
<FormHelperText>Account to send from</FormHelperText>
</div>
<div>
<FormControl
variant="outlined"
style={{ width: '200px', marginLeft: '10px', marginTop: '10px' }}
>
<InputLabel>Mint</InputLabel>
<Select
value={mint}
onChange={e => setMint(e.target.value as string)}
label="Mint"
>
{mintOptions.map(m => (
<MenuItem value={m.label}>{m.label.toUpperCase()}</MenuItem>
))}
</Select>
</FormControl>
</div>
<div>
<TextField
style={{ marginLeft: '10px', marginTop: '10px' }}
id="outlined-number"
label="Amount"
type="number"
InputLabelProps={{
shrink: true,
}}
variant="outlined"
onChange={e =>
setRewardDisplayAmount(parseFloat(e.target.value) as number)
}
InputProps={{ inputProps: { min: 0 } }}
/>
</div>
</div>
{setEndTs !== undefined && setStartTs !== undefined && (
<>
<div style={{ display: 'flex', marginTop: '37px' }}>
<div style={{ flex: 1 }}>
<TextField
fullWidth
label="Start date"
type="datetime-local"
InputLabelProps={{
shrink: true,
}}
onChange={e => {
const d = new Date(e.target.value);
setStartTs(d.getTime() / 1000);
}}
/>
<FormHelperText>Date vesting begins</FormHelperText>
</div>
</div>
<div style={{ flex: 1, marginTop: '20px' }}>
<TextField
fullWidth
label="End date"
type="datetime-local"
InputLabelProps={{
shrink: true,
}}
onChange={e => {
const d = new Date(e.target.value);
setEndTs(d.getTime() / 1000);
}}
/>
<FormHelperText>
Date the vesting account is fully vested
</FormHelperText>
</div>
<div>
<FormControl fullWidth>
<TextField
style={{ marginTop: '37px' }}
id="outlined-number"
label="Period Count"
type="number"
InputLabelProps={{
shrink: true,
}}
variant="outlined"
value={periodCount}
onChange={e =>
setPeriodCount!(parseInt(e.target.value) as number)
}
InputProps={{ inputProps: { min: 1 } }}
/>
</FormControl>
</div>
</>
)}
<div style={{ marginTop: '37px', display: 'flex' }}>
<div
style={{
flex: 1,
height: '100%',
marginRight: '10px',
}}
>
<TextField
fullWidth
label="Expiry date"
type="datetime-local"
InputLabelProps={{
shrink: true,
}}
onChange={e => {
const d = new Date(e.target.value);
setExpiryTs(d.getTime() / 1000);
}}
/>
<FormHelperText>
Date after which the account owner dropping rewards can withdraw
all unclaimed rewards.
</FormHelperText>
</div>
<div style={{ marginTop: '26px' }}>
<TextField
style={{ height: '100%' }}
disabled
placeholder="Expiry Unix timestamp"
fullWidth
value={expiryTs}
/>
</div>
</div>
</div>
<DialogActions>
<Button onClick={onCancel}>Cancel</Button>
<Button
onClick={onClick}
type="submit"
color="primary"
disabled={!isSendEnabled}
>
Send
</Button>
</DialogActions>
</>
);
}

View File

@ -0,0 +1,139 @@
import React, { useEffect, useMemo } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useSnackbar } from 'notistack';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import * as anchor from '@project-serum/anchor';
import { useWallet } from '../../components/common/WalletProvider';
import { State as StoreState } from '../../store/reducer';
import { ActionType } from '../../store/actions';
import RewardsList, { RewardListItemViewModel } from './RewardsList';
import DropRewardButton from './DropRewardButton';
import ClaimRewardButton from './ClaimRewardButton';
import { rewardEvents } from '../../utils/registry';
export default function Rewards() {
const { registryClient } = useWallet();
const dispatch = useDispatch();
const snack = useSnackbar();
const ctx = useSelector((state: StoreState) => {
const registrar = state.accounts[state.registry.registrar.toString()];
const rewardEventQueue = {
publicKey: registrar.rewardEventQ,
account: state.accounts[registrar.rewardEventQ.toString()],
};
return {
accounts: state.accounts,
rewardEventQueue,
member: state.registry.member
? {
publicKey: state.registry.member,
account: state.accounts[state.registry.member.toString()],
}
: undefined,
network: state.common.network,
};
});
const { rewardEventQueue } = ctx;
const events = useMemo(() => rewardEvents(rewardEventQueue.account), [
rewardEventQueue.account,
]);
useEffect(() => {
(async () => {
// TODO: need to chop up the calls here, for reward vendors > 100 entires.
const accounts = await anchor.utils.getMultipleAccounts(
registryClient.provider.connection,
events.map(m => m.vendor),
);
accounts.forEach(a => {
if (a === null) {
snack.enqueueSnackbar(`RPC node returned invalid vendor account`, {
variant: 'error',
});
return;
}
const account = registryClient.coder.accounts.decode(
'RewardVendor',
a.account.data,
);
dispatch({
type: ActionType.AccountAdd,
item: {
account: { publicKey: a.publicKey, account },
},
});
});
})();
}, [
events,
dispatch,
snack,
registryClient.coder.accounts,
registryClient.provider.connection,
]);
// All rewards to display.
const rewards = events
.map((m: any) => RewardListItemViewModel.fromMessage(ctx, m))
.reverse();
// Next reward to claim.
let nextReward = null;
if (rewards.filter(r => r === null).length === 0) {
nextReward = rewards
.filter(r => r!.needsClaim)
.sort((a, b) =>
a!.cursor < b!.cursor ? -1 : a!.cursor > b!.cursor ? 1 : 0,
)
.shift();
}
return (
<div style={{ width: '100%', marginTop: '24px' }}>
{nextReward && (
<Card style={{ marginBottom: '24px' }}>
<CardContent>
<Typography variant="h6">
You were staked during a previous reward. To prove eligibility,
click the "Process" button until you've processed <b>all</b>{' '}
eligible rewards. For unlocked rewards, don't forget to select the
address you wish to send your stake reward to.
</Typography>
</CardContent>
</Card>
)}
<div
style={{
marginBottom: '10px',
display: 'flex',
justifyContent: 'space-between',
}}
>
<Typography style={{ fontWeight: 'bold', fontSize: '20px' }}>
Reward History
</Typography>
<div style={{ display: 'flex' }}>
{nextReward && <ClaimRewardButton rli={nextReward} />}
{localStorage.getItem('private') && <DropRewardButton />}
</div>
</div>
<div style={{ marginBottom: '16px' }}>
<Typography>
When rewards are dropped, one must prove one was staked during the
time of drop. This means sending a transaction to the staking program
to <b>process</b> the reward. For <b>unlocked</b> rewards, select the
token address to transfer the reward to. For <b>locked</b> rewards, a
locked vesting account will be created and realized to the staker upon
unstaking. See the Lockup tab.
</Typography>
</div>
<Paper>
<RewardsList rewards={rewards} />
</Paper>
</div>
);
}

View File

@ -0,0 +1,280 @@
import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import { useSnackbar } from 'notistack';
import CircularProgress from '@material-ui/core/CircularProgress';
import LockIcon from '@material-ui/icons/Lock';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Collapse from '@material-ui/core/Collapse';
import ExpandLess from '@material-ui/icons/ExpandLess';
import ExpandMore from '@material-ui/icons/ExpandMore';
import Button from '@material-ui/core/Button';
import { PublicKey, SYSVAR_CLOCK_PUBKEY } from '@solana/web3.js';
import { TokenInstructions } from '@project-serum/serum';
import OwnedTokenAccountsSelect from '../../components/common/OwnedTokenAccountsSelect';
import { useWallet } from '../../components/common/WalletProvider';
import { toDisplay } from '../../utils/tokens';
import { ProgramAccount } from '../../store/reducer';
import { Network } from '../../store/config';
import { State as StoreState } from '../../store/reducer';
import { ViewTransactionOnExplorerButton } from '../../components/common/Notification';
type RewardsListProps = {
rewards: (RewardListItemViewModel | null)[];
};
export default function RewardsList(props: RewardsListProps) {
const { rewards } = props;
let loading = false;
rewards.forEach(r => {
if (r === null) {
loading = true;
}
});
return (
<List>
{loading ? (
<CircularProgress
style={{
display: 'block',
marginLeft: 'auto',
marginRight: 'auto',
}}
/>
) : rewards.length > 0 ? (
rewards
.filter(r => r!.vendor.account.expired === false)
.map(r => {
return <RewardListItem rli={r as RewardListItemViewModel} />;
})
) : (
<ListItem>
<ListItemText primary={'No rewards found'} />
</ListItem>
)}
</List>
);
}
type RewardListItemProps = {
rli: RewardListItemViewModel;
};
function RewardListItem(props: RewardListItemProps) {
const { rli } = props;
const [open, setOpen] = useState(false);
const dateLabel = new Date(
rli.vendor!.account.startTs.toNumber() * 1000,
).toLocaleString();
let fromLabel = `Dropped by ${rli.vendor.account.from.toString()} | ${dateLabel}`;
return (
<>
<ListItem button onClick={() => setOpen(open => !open)}>
<LockIcon
style={{
visibility: rli.reward.locked ? 'visible' : 'hidden',
marginRight: '16px',
}}
/>
<ListItemText
primary={
<div
style={{
display: 'flex',
justifyContent: 'space-between',
color: rli.needsClaim ? '#54a15e' : '',
}}
>
<div>{`${toDisplay(
rli.vendor.account.total,
rli.mint!.account.decimals,
)} ${rli.mint!.publicKey}`}</div>
</div>
}
secondary={fromLabel}
/>
{open ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
{rli.vendor === undefined ? (
<CircularProgress />
) : (
<RewardListItemDetails vendor={rli.vendor!} />
)}
</Collapse>
</>
);
}
type RewardListItemDetailsProps = {
vendor: ProgramAccount;
};
function RewardListItemDetails(props: RewardListItemDetailsProps) {
let { vendor } = props;
const { registryClient } = useWallet();
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const { vendorMint, registrar } = useSelector((state: StoreState) => {
return {
registrar: state.registry.registrar,
vendorMint: state.accounts[vendor.account.mint.toString()],
};
});
const [
expiryReceiverToken,
setExpiryReceiverToken,
] = useState<null | PublicKey>(null);
const expire = async () => {
enqueueSnackbar('Expiring reward', {
variant: 'info',
});
const vendorSigner = await PublicKey.createProgramAddress(
[
registrar.toBuffer(),
vendor.publicKey.toBuffer(),
Buffer.from([vendor.account.nonce]),
],
registryClient.programId,
);
const tx = await registryClient.rpc.expireReward({
accounts: {
registrar,
vendor: vendor.publicKey,
vault: vendor.account.vault,
vendorSigner,
expiryReceiver: vendor.account.expiryReceiver,
expiryReceiverToken,
tokenProgram: TokenInstructions.TOKEN_PROGRAM_ID,
clock: SYSVAR_CLOCK_PUBKEY,
},
});
closeSnackbar();
enqueueSnackbar(`Reward expired`, {
variant: 'success',
action: <ViewTransactionOnExplorerButton signature={tx as string} />,
});
};
return (
<div
style={{
marginLeft: '56px',
}}
>
<div>Vendor</div>
<ul>
<li>Address {vendor.publicKey.toString()}</li>
<li>Vault: {vendor.account.vault.toString()}</li>
<li>Mint: {vendor.account.mint.toString()}</li>
<li>
Pool token supply snapshot:{' '}
{vendor.account.poolTokenSupply.toString()}
</li>
<li>
Expiry:{' '}
{new Date(
vendor.account.expiryTs.toNumber() * 1000,
).toLocaleDateString()}
{` (${vendor.account.expiryTs.toNumber()})`}
</li>
<li>Expiry receiver: {vendor.account.expiryReceiver.toString()}</li>
<li>Expired: {vendor.account.expired.toString()}</li>
<li>
Reward queue cursor: {vendor.account.rewardEventQCursor.toString()}
</li>
</ul>
{(vendor.account.expiryTs.toNumber() <= Date.now()/1000) && registryClient.provider.wallet.publicKey.equals(vendor.account.expiryReceiver) && (
<div style={{ display: 'flex', flexDirection: 'row-reverse' }}>
<Button
color="primary"
variant="outlined"
onClick={expire}
style={{ marginRight: '24px' }}
>
Expire
</Button>
<div style={{ flex: 1, marginRight: '24px' }}>
<OwnedTokenAccountsSelect
variant="outlined"
decimals={vendorMint.decimals}
mint={vendor.account.mint}
onChange={(f: PublicKey) => {
setExpiryReceiverToken(f);
}}
/>
</div>
</div>
)}
</div>
);
}
export class RewardListItemViewModel {
constructor(
readonly reward: any,
readonly cursor: number,
readonly needsClaim: boolean,
readonly mint: ProgramAccount,
readonly vendor: ProgramAccount,
) {}
static fromMessage(ctx: Context, event: any): RewardListItemViewModel | null {
let needsClaim = false;
const vendor = ctx.accounts[event.vendor.toString()];
if (vendor === undefined) {
return null;
}
const mint = {
publicKey: vendor.mint,
account: ctx.accounts[vendor.mint.toString()],
};
if (ctx.member !== undefined) {
// Must own shares of the reward's target pool.
const sptAccount =
ctx.accounts[ctx.member.account.balances.spt.toString()];
const lockedSptAccount =
ctx.accounts[ctx.member.account.balancesLocked.spt.toString()];
const ownsPoolShares = sptAccount.amount + lockedSptAccount.amount > 0;
// Must not have claimed the reward yet.
const notYetClaimed =
vendor.rewardEventQCursor >= ctx.member.account.rewardsCursor;
// Must have staked before the reward was dropped.
const isEligible = ctx.member.account.lastStakeTs < vendor.startTs;
// Must not have let the reward expire.
const expired = vendor.expired;
needsClaim = ownsPoolShares && notYetClaimed && isEligible && !expired;
}
const vendorProgramAccount = {
publicKey: event.vendor,
account: vendor,
};
return new RewardListItemViewModel(
event,
vendor.rewardEventQCursor,
needsClaim,
mint,
vendorProgramAccount,
);
}
}
type Context = {
accounts: any;
rewardEventQueue: ProgramAccount;
member?: ProgramAccount;
network: Network;
};

552
src/idl/lockup.ts Normal file
View File

@ -0,0 +1,552 @@
import { Idl } from '@project-serum/anchor';
const idl: Idl = {
version: '0.0.0',
name: 'lockup',
instructions: [
{
name: 'createVesting',
accounts: [
{
name: 'vesting',
isMut: true,
isSigner: false,
},
{
name: 'vault',
isMut: true,
isSigner: false,
},
{
name: 'depositor',
isMut: true,
isSigner: false,
},
{
name: 'depositorAuthority',
isMut: false,
isSigner: true,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'beneficiary',
type: 'publicKey',
},
{
name: 'depositAmount',
type: 'u64',
},
{
name: 'nonce',
type: 'u8',
},
{
name: 'startTs',
type: 'i64',
},
{
name: 'endTs',
type: 'i64',
},
{
name: 'periodCount',
type: 'u64',
},
{
name: 'realizor',
type: {
option: {
defined: 'Realizor',
},
},
},
],
},
{
name: 'withdraw',
accounts: [
{
name: 'vesting',
isMut: true,
isSigner: false,
},
{
name: 'beneficiary',
isMut: false,
isSigner: true,
},
{
name: 'vault',
isMut: true,
isSigner: false,
},
{
name: 'vestingSigner',
isMut: false,
isSigner: false,
},
{
name: 'token',
isMut: true,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'amount',
type: 'u64',
},
],
},
{
name: 'whitelistWithdraw',
accounts: [
{
name: 'transfer',
accounts: [
{
name: 'lockup',
isMut: false,
isSigner: false,
},
{
name: 'beneficiary',
isMut: false,
isSigner: true,
},
{
name: 'whitelistedProgram',
isMut: false,
isSigner: false,
},
{
name: 'vesting',
isMut: true,
isSigner: false,
},
{
name: 'vault',
isMut: true,
isSigner: false,
},
{
name: 'vestingSigner',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
{
name: 'whitelistedProgramVault',
isMut: true,
isSigner: false,
},
{
name: 'whitelistedProgramVaultAuthority',
isMut: false,
isSigner: false,
},
],
},
],
args: [
{
name: 'instructionData',
type: 'bytes',
},
{
name: 'amount',
type: 'u64',
},
],
},
{
name: 'whitelistDeposit',
accounts: [
{
name: 'transfer',
accounts: [
{
name: 'lockup',
isMut: false,
isSigner: false,
},
{
name: 'beneficiary',
isMut: false,
isSigner: true,
},
{
name: 'whitelistedProgram',
isMut: false,
isSigner: false,
},
{
name: 'vesting',
isMut: true,
isSigner: false,
},
{
name: 'vault',
isMut: true,
isSigner: false,
},
{
name: 'vestingSigner',
isMut: false,
isSigner: false,
},
{
name: 'tokenProgram',
isMut: false,
isSigner: false,
},
{
name: 'whitelistedProgramVault',
isMut: true,
isSigner: false,
},
{
name: 'whitelistedProgramVaultAuthority',
isMut: false,
isSigner: false,
},
],
},
],
args: [
{
name: 'instructionData',
type: 'bytes',
},
],
},
{
name: 'availableForWithdrawal',
accounts: [
{
name: 'vesting',
isMut: false,
isSigner: false,
},
{
name: 'clock',
isMut: false,
isSigner: false,
},
],
args: [],
},
],
state: {
struct: {
name: 'Lockup',
type: {
kind: 'struct',
fields: [
{
name: 'authority',
type: 'publicKey',
},
{
name: 'whitelist',
type: {
vec: {
defined: 'WhitelistEntry',
},
},
},
],
},
},
methods: [
{
name: 'new',
accounts: [
{
name: 'authority',
isMut: false,
isSigner: true,
},
],
args: [],
},
{
name: 'whitelistAdd',
accounts: [
{
name: 'authority',
isMut: false,
isSigner: true,
},
],
args: [
{
name: 'entry',
type: {
defined: 'WhitelistEntry',
},
},
],
},
{
name: 'whitelistDelete',
accounts: [
{
name: 'authority',
isMut: false,
isSigner: true,
},
],
args: [
{
name: 'entry',
type: {
defined: 'WhitelistEntry',
},
},
],
},
{
name: 'setAuthority',
accounts: [
{
name: 'authority',
isMut: false,
isSigner: true,
},
],
args: [
{
name: 'newAuthority',
type: 'publicKey',
},
],
},
],
},
accounts: [
{
name: 'Vesting',
type: {
kind: 'struct',
fields: [
{
name: 'beneficiary',
type: 'publicKey',
},
{
name: 'mint',
type: 'publicKey',
},
{
name: 'vault',
type: 'publicKey',
},
{
name: 'grantor',
type: 'publicKey',
},
{
name: 'outstanding',
type: 'u64',
},
{
name: 'startBalance',
type: 'u64',
},
{
name: 'createdTs',
type: 'i64',
},
{
name: 'startTs',
type: 'i64',
},
{
name: 'endTs',
type: 'i64',
},
{
name: 'periodCount',
type: 'u64',
},
{
name: 'whitelistOwned',
type: 'u64',
},
{
name: 'nonce',
type: 'u8',
},
{
name: 'realizor',
type: {
option: {
defined: 'Realizor',
},
},
},
],
},
},
],
types: [
{
name: 'Realizor',
type: {
kind: 'struct',
fields: [
{
name: 'program',
type: 'publicKey',
},
{
name: 'metadata',
type: 'publicKey',
},
],
},
},
{
name: 'WhitelistEntry',
type: {
kind: 'struct',
fields: [
{
name: 'programId',
type: 'publicKey',
},
],
},
},
],
errors: [
{
code: 100,
name: 'InvalidTimestamp',
msg: 'Vesting end must be greater than the current unix timestamp.',
},
{
code: 101,
name: 'InvalidPeriod',
msg: 'The number of vesting periods must be greater than zero.',
},
{
code: 102,
name: 'InvalidDepositAmount',
msg: 'The vesting deposit amount must be greater than zero.',
},
{
code: 103,
name: 'InvalidWhitelistEntry',
msg: 'The Whitelist entry is not a valid program address.',
},
{
code: 104,
name: 'InvalidProgramAddress',
msg: 'Invalid program address. Did you provide the correct nonce?',
},
{
code: 105,
name: 'InvalidVaultOwner',
msg: 'Invalid vault owner.',
},
{
code: 106,
name: 'InvalidVaultAmount',
msg: 'Vault amount must be zero.',
},
{
code: 107,
name: 'InsufficientWithdrawalBalance',
msg: 'Insufficient withdrawal balance.',
},
{
code: 108,
name: 'WhitelistFull',
msg: 'Whitelist is full',
},
{
code: 109,
name: 'WhitelistEntryAlreadyExists',
msg: 'Whitelist entry already exists',
},
{
code: 110,
name: 'InsufficientWhitelistDepositAmount',
msg: 'Balance must go up when performing a whitelist deposit',
},
{
code: 111,
name: 'WhitelistDepositOverflow',
msg: 'Cannot deposit more than withdrawn',
},
{
code: 112,
name: 'WhitelistWithdrawLimit',
msg: 'Tried to withdraw over the specified limit',
},
{
code: 113,
name: 'WhitelistEntryNotFound',
msg: 'Whitelist entry not found.',
},
{
code: 114,
name: 'Unauthorized',
msg: 'You do not have sufficient permissions to perform this action.',
},
{
code: 115,
name: 'UnableToWithdrawWhileStaked',
msg: 'You are unable to realize projected rewards until unstaking.',
},
{
code: 116,
name: 'InvalidLockRealizor',
msg: "The given lock realizor doesn't match the vesting account.",
},
{
code: 117,
name: 'UnrealizedVesting',
msg: 'You have not realized this vesting account.',
},
{
code: 118,
name: 'InvalidSchedule',
msg: 'Invalid vesting schedule given.',
},
],
};
export default idl;

299
src/idl/multisig.ts Normal file
View File

@ -0,0 +1,299 @@
import { Idl } from '@project-serum/anchor';
const idl: Idl = {
version: '0.0.0',
name: 'multisig',
instructions: [
{
name: 'createMultisig',
accounts: [
{
name: 'multisig',
isMut: true,
isSigner: false,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'owners',
type: {
vec: 'publicKey',
},
},
{
name: 'threshold',
type: 'u64',
},
{
name: 'nonce',
type: 'u8',
},
],
},
{
name: 'createTransaction',
accounts: [
{
name: 'multisig',
isMut: false,
isSigner: false,
},
{
name: 'transaction',
isMut: true,
isSigner: false,
},
{
name: 'proposer',
isMut: false,
isSigner: true,
},
{
name: 'rent',
isMut: false,
isSigner: false,
},
],
args: [
{
name: 'pid',
type: 'publicKey',
},
{
name: 'accs',
type: {
vec: {
defined: 'TransactionAccount',
},
},
},
{
name: 'data',
type: 'bytes',
},
],
},
{
name: 'approve',
accounts: [
{
name: 'multisig',
isMut: false,
isSigner: false,
},
{
name: 'transaction',
isMut: true,
isSigner: false,
},
{
name: 'owner',
isMut: false,
isSigner: true,
},
],
args: [],
},
{
name: 'setOwners',
accounts: [
{
name: 'multisig',
isMut: true,
isSigner: false,
},
{
name: 'multisigSigner',
isMut: false,
isSigner: true,
},
],
args: [
{
name: 'owners',
type: {
vec: 'publicKey',
},
},
],
},
{
name: 'changeThreshold',
accounts: [
{
name: 'multisig',
isMut: true,
isSigner: false,
},
{
name: 'multisigSigner',
isMut: false,
isSigner: true,
},
],
args: [
{
name: 'threshold',
type: 'u64',
},
],
},
{
name: 'executeTransaction',
accounts: [
{
name: 'multisig',
isMut: false,
isSigner: false,
},
{
name: 'multisigSigner',
isMut: false,
isSigner: false,
},
{
name: 'transaction',
isMut: true,
isSigner: false,
},
],
args: [],
},
],
accounts: [
{
name: 'Multisig',
type: {
kind: 'struct',
fields: [
{
name: 'owners',
type: {
vec: 'publicKey',
},
},
{
name: 'threshold',
type: 'u64',
},
{
name: 'nonce',
type: 'u8',
},
{
name: 'ownerSetSeqno',
type: 'u32',
},
],
},
},
{
name: 'Transaction',
type: {
kind: 'struct',
fields: [
{
name: 'multisig',
type: 'publicKey',
},
{
name: 'programId',
type: 'publicKey',
},
{
name: 'accounts',
type: {
vec: {
defined: 'TransactionAccount',
},
},
},
{
name: 'data',
type: 'bytes',
},
{
name: 'signers',
type: {
vec: 'bool',
},
},
{
name: 'didExecute',
type: 'bool',
},
{
name: 'ownerSetSeqno',
type: 'u32',
},
],
},
},
],
types: [
{
name: 'TransactionAccount',
type: {
kind: 'struct',
fields: [
{
name: 'pubkey',
type: 'publicKey',
},
{
name: 'isSigner',
type: 'bool',
},
{
name: 'isWritable',
type: 'bool',
},
],
},
},
],
errors: [
{
code: 100,
name: 'InvalidOwner',
msg: 'The given owner is not part of this multisig.',
},
{
code: 101,
name: 'NotEnoughSigners',
msg: 'Not enough owners signed this transaction.',
},
{
code: 102,
name: 'TransactionAlreadySigned',
msg: 'Cannot delete a transaction that has been signed by an owner.',
},
{
code: 103,
name: 'Overflow',
msg: 'Overflow when adding.',
},
{
code: 104,
name: 'UnableToDelete',
msg: 'Cannot delete a transaction the owner did not create.',
},
{
code: 105,
name: 'AlreadyExecuted',
msg: 'The given transaction has already been executed.',
},
{
code: 106,
name: 'InvalidThreshold',
msg: 'Threshold must be less than or equal to the number of owners.',
},
],
};
export default idl;

1488
src/idl/registry.ts Normal file

File diff suppressed because it is too large Load Diff

13
src/index.css Normal file
View File

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

17
src/index.tsx Normal file
View File

@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'),
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

6
src/pages/Lockup.tsx Normal file
View File

@ -0,0 +1,6 @@
import React from 'react';
import Vestings from '../components/lockups/Vestings';
export default function LockupPage() {
return <Vestings />;
}

21
src/pages/Multisig.tsx Normal file
View File

@ -0,0 +1,21 @@
import React from 'react';
import { useHistory, useLocation } from 'react-router';
import Multisig from '../components/multisig/Multisig';
import { PublicKey } from '@solana/web3.js';
export default function MultisigPage() {
return <Multisig />;
}
export function MultisigInstancePage() {
const history = useHistory();
const location = useLocation();
const path = location.pathname.split('/');
if (path.length !== 3) {
history.push(`/multisig`);
return <></>;
} else {
const multisig = new PublicKey(path[2]);
return <Multisig multisig={multisig} />;
}
}

6
src/pages/MyNode.tsx Normal file
View File

@ -0,0 +1,6 @@
import React from 'react';
import MyNode from '../components/common/MyNode';
export default function MyNodePage() {
return <MyNode />;
}

1
src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

15
src/reportWebVitals.ts Normal file
View File

@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

5
src/setupTests.ts Normal file
View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

19
src/skin/index.ts Normal file
View File

@ -0,0 +1,19 @@
type Skin = {
active: string;
ready: string;
inactive: string;
notReady: string;
deactivating: string;
};
const _skin: Skin = {
active: '#43a047',
ready: '#3f51b5',
notReady: '#ccc',
inactive: 'red',
deactivating: 'rgb(255, 121, 42)',
};
export function instance(): Skin {
return _skin;
}

36
src/store/actions.ts Normal file
View File

@ -0,0 +1,36 @@
export type Action = {
type: ActionType;
item: any;
};
export enum ActionType {
// Common.
CommonTriggerBootstrap,
CommonAppWillBootstrap,
CommonAppDidBootstrap,
CommonTriggerShutdown,
CommonDidShutdown,
CommonWalletDidConnect,
CommonWalletDidDisconnect,
CommonWalletSetProvider,
CommonSetNetwork,
CommonOwnedTokenAccountsSet,
CommonOwnedTokenAccountsUpdate,
CommonWalletReset,
// Lockup.
LockupSetVestings,
LockupUpdateVesting,
LockupCreateVesting,
// Registry.
RegistrySetMember,
RegistrySetRegistrar,
RegistrySetPendingWithdrawals,
RegistryCreatePendingWithdrawal,
RegistryUpdatePendingWithdrawal,
// Accounts.
AccountAdd,
AccountUpdate,
}

114
src/store/config.ts Normal file
View File

@ -0,0 +1,114 @@
import { PublicKey } from '@solana/web3.js';
type Networks = { [label: string]: Network };
export type Network = {
// Cluster.
label: string;
url: string;
explorerClusterSuffix: string;
// Faucets.
srmFaucet: PublicKey | null;
msrmFaucet: PublicKey | null;
// Programs.
registryProgramId: PublicKey;
lockupProgramId: PublicKey;
multisigProgramId: PublicKey;
// Staking instances.
registrars: { [token: string]: PublicKey };
// Whitelisted token mints.
mints: { [token: string]: PublicKey };
};
export const networks: Networks = {
mainnet: {
// Cluster.
label: 'Mainnet Beta',
url: 'https://api.mainnet-beta.solana.com',
//url: 'https://api.mainnet-beta.solana.com',
explorerClusterSuffix: '',
srmFaucet: null,
msrmFaucet: null,
registryProgramId: new PublicKey(
'GrAkKfEpTKQuVHG2Y97Y2FF4i7y7Q5AHLK94JBy7Y5yv',
),
lockupProgramId: new PublicKey(
'6ebQNeTPZ1j7k3TtkCCtEPRvG7GQsucQrZ7sSEDQi9Ks',
),
multisigProgramId: new PublicKey(
'3S6ALMCGVib4X3vVR3CLpm2K6Ng5qbWFYMTo5jfxWcEq',
),
registrars: {
srm: new PublicKey('5vJRzKtcp4fJxqmR7qzajkaKSiAb6aT9grRsaZKXU222'),
msrm: new PublicKey('7uURiX2DwCpRuMFebKSkFtX9v5GK1Cd8nWLL8tyoyxZY'),
fida: new PublicKey('5C2ayX1E2SJ5kKEmDCA9ue9eeo3EPR34QFrhyzbbs3qh'),
},
mints: {
srm: new PublicKey('SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt'),
msrm: new PublicKey('MSRMcoVyrFxnSgo5uXwone5SKcGhT1KEJMFEkMEWf9L'),
fida: new PublicKey('EchesyfXePKdLtoiZSL8pBe8Myagyy8ZRqsACNCFGnvp'),
},
},
devnet: {
// Cluster.
label: 'Devnet',
url: 'https://devnet.solana.com',
explorerClusterSuffix: 'devnet',
srmFaucet: null,
msrmFaucet: null,
multisigProgramId: new PublicKey(
'9z7Pq56To96qbVLzuBcf47Lc7u8uUWZh6k5rhcaTsDjz',
),
registryProgramId: new PublicKey(
'65aMavjMw3EhmWKVCkGn1Uj2SqZ3XY4coJhYM1BVJTHw',
),
lockupProgramId: new PublicKey(
'bRGMWZz4mzJ8NG8csn5QNTbJDv2973QSvppbfcAboje',
),
registrars: {
token1: new PublicKey('EqbwcuvPWLZ5fav58HrieHmJEqTm6RPu5bmn5bBQJ3mu'),
token2: new PublicKey('2rDWuS6yVFQ3jYx1nQq7gs3HgzWLJcUwm9sTUBWuXuyK'),
},
mints: {
token1: new PublicKey('Ep6ASaHQ4gKiN3gWNRKYttZEQ7b82seMk9HWc5JNBJZP'),
token2: new PublicKey('5vWxJthWbCFuNSZj1qcP9WoU8E6UG3DUfeAoPvYoN8PQ'),
},
},
// Fill in with your local cluster addresses.
localhost: {
// Cluster.
label: 'Localhost',
url: 'http://localhost:8899',
explorerClusterSuffix: 'localhost',
srmFaucet: null,
msrmFaucet: null,
multisigProgramId: new PublicKey(
'9z7Pq56To96qbVLzuBcf47Lc7u8uUWZh6k5rhcaTsDjz',
),
registryProgramId: new PublicKey(
'A3ukM9swAsTqVC6g5Zy9FsWXofe5f2JhXMEfzenNf9Q7',
),
lockupProgramId: new PublicKey(
'2z65xTKJDM4iJBVz5aXtNrWfQvKGgNJvnqY1GL2mkimu',
),
registrars: {
token1: new PublicKey('Fwi5pie2VgWTDUSRNkca1HdFCke5r3v3mY83JbxtC3CJ'),
token2: new PublicKey('9kCGBWgHzGGChvmAsmu5jrXwEShZfLxKRTmKdxEpFUBr'),
},
mints: {
token1: new PublicKey('2aE1pietadYMeDtdqKayS4SVo9W4xtC3U7SN4iGWCVcX'),
token2: new PublicKey('Cgan7PWyBH6Z7JNA6f9kDYgwBMZBxRexpdd29PJgnqah'),
},
},
};

4
src/store/index.ts Normal file
View File

@ -0,0 +1,4 @@
import { createStore } from 'redux';
import reducer from './reducer';
export const store = createStore(reducer);

196
src/store/reducer.ts Normal file
View File

@ -0,0 +1,196 @@
import { PublicKey } from '@solana/web3.js';
import { AccountInfo as TokenAccount } from '@solana/spl-token';
import { ProgramAccount as CommonProgramAccount } from '@project-serum/common';
import { Action, ActionType } from './actions';
import { networks, Network } from './config';
export enum BootstrapState {
NeedsBootstrap,
IsBootstrapping,
Bootstrapped,
}
export default function reducer(
state: State = initialState,
action: Action,
): State {
let newState = {
common: { ...state.common },
lockup: { ...state.lockup },
registry: { ...state.registry },
accounts: { ...state.accounts },
};
switch (action.type) {
// Common.
case ActionType.CommonAppWillBootstrap:
newState.common.bootstrapState = BootstrapState.IsBootstrapping;
newState.common.bootstrapTrigger = false;
return newState;
case ActionType.CommonAppDidBootstrap:
newState.common.bootstrapState = BootstrapState.Bootstrapped;
return newState;
case ActionType.CommonWalletSetProvider:
newState.common.walletProvider = action.item.walletProvider;
return newState;
case ActionType.CommonWalletDidConnect:
newState.common.isWalletConnected = true;
return newState;
case ActionType.CommonWalletDidDisconnect:
newState.common.isWalletConnected = false;
return newState;
case ActionType.CommonSetNetwork:
if (newState.common.network.label !== action.item.network.label) {
newState.common.network = action.item.network;
newState.common.bootstrapState = BootstrapState.NeedsBootstrap;
newState.common.shutdownTrigger = true;
const network = networks[action.item.networkKey];
newState.registry.registrar = Object.values(network.registrars)[0];
}
return newState;
case ActionType.CommonTriggerBootstrap:
newState.common.bootstrapState = BootstrapState.NeedsBootstrap;
newState.common.bootstrapTrigger = true;
return newState;
case ActionType.CommonTriggerShutdown:
newState.common.bootstrapState = BootstrapState.NeedsBootstrap;
newState.common.shutdownTrigger = true;
return newState;
case ActionType.CommonDidShutdown:
// Reset everything except network and registrar.
let s = {
...initialState,
};
s.common.network = newState.common.network;
s.registry.registrar = newState.registry.registrar;
return s;
case ActionType.CommonOwnedTokenAccountsSet:
newState.common.ownedTokenAccounts = action.item.ownedTokenAccounts;
return newState;
case ActionType.CommonOwnedTokenAccountsUpdate:
newState.common.ownedTokenAccounts = newState.common.ownedTokenAccounts.map(
programAccount => {
if (programAccount.publicKey.equals(action.item.account.publicKey)) {
return action.item.account;
} else {
return programAccount;
}
},
);
return newState;
// Lockup.
case ActionType.LockupSetVestings:
newState.lockup.vestings = action.item.vestingAccounts;
return newState;
case ActionType.LockupUpdateVesting:
newState.accounts[action.item.vesting.publicKey.toString()] =
action.item.vesting.account;
return newState;
case ActionType.LockupCreateVesting:
newState.lockup.vestings.unshift(action.item.vesting.publicKey);
newState.accounts[action.item.vesting.publicKey.toString()] =
action.item.vesting.account;
return newState;
// Registry.
case ActionType.RegistrySetMember:
// This should only be called on member creation. All other member
// member switches should route through `RegistrySetMember`.
newState.registry.member = action.item.member;
return newState;
case ActionType.RegistrySetRegistrar:
newState.registry.registrar = action.item.registrar;
newState.registry.member = action.item.member;
newState.registry.pendingWithdrawals = null;
return newState;
case ActionType.RegistrySetPendingWithdrawals:
action.item.pendingWithdrawals.forEach((pw: any) => {
newState.accounts[pw.publicKey.toString()] = pw.account;
});
newState.registry.pendingWithdrawals = action.item.pendingWithdrawals.map(
(pw: any) => pw.publicKey,
);
return newState;
case ActionType.RegistryCreatePendingWithdrawal:
newState.accounts[action.item.pendingWithdrawal.publicKey.toString()] =
action.item.pendingWithdrawal.account;
if (newState.registry.pendingWithdrawals === null) {
newState.registry.pendingWithdrawals = [];
}
newState.registry.pendingWithdrawals.unshift(
action.item.pendingWithdrawal.publicKey,
);
return newState;
case ActionType.RegistryUpdatePendingWithdrawal:
newState.accounts[action.item.pendingWithdrawal.publicKey.toString()] =
action.item.pendingWithdrawal.account;
return newState;
case ActionType.AccountAdd:
newState.accounts[action.item.account.publicKey.toString()] =
action.item.account.account;
return newState;
case ActionType.AccountUpdate:
newState.accounts[action.item.account.publicKey.toString()] =
action.item.account.account;
return newState;
default:
return newState;
}
}
export type State = {
common: CommonState;
lockup: LockupState;
registry: RegistryState;
accounts: { [pubkey: string]: any };
};
export type CommonState = {
walletProvider?: string;
isWalletConnected: boolean;
bootstrapTrigger: boolean;
bootstrapState: BootstrapState;
shutdownTrigger: boolean;
network: Network;
ownedTokenAccounts: ProgramAccount<TokenAccount>[];
};
export type LockupState = {
vestings: PublicKey[];
};
// All state associated with a single instance of a staking registrar.
export type RegistryState = {
registrar: PublicKey;
member?: PublicKey;
pendingWithdrawals: PublicKey[] | null;
};
export const initialState: State = {
common: {
bootstrapTrigger: false,
shutdownTrigger: false,
isWalletConnected: false,
walletProvider: 'https://www.sollet.io',
bootstrapState: BootstrapState.NeedsBootstrap,
network: networks.mainnet,
ownedTokenAccounts: [],
},
lockup: {
vestings: [],
},
registry: {
pendingWithdrawals: null,
registrar: networks.mainnet.registrars.srm,
},
accounts: {},
};
export type AsyncData<T> = {
isReady: boolean;
data?: T;
};
// Re-export.
export type ProgramAccount<T = any> = CommonProgramAccount<T>;

33
src/utils/idl.ts Normal file
View File

@ -0,0 +1,33 @@
import { struct, Layout } from 'buffer-layout';
import { rustEnum } from '@project-serum/borsh';
// Simplified since we only use the SetBuffer variant.
export type IdlInstruction =
| Create
| CreateBuffer
| Write
| SetBuffer
| SetAuthority;
type Create = {};
type CreateBuffer = {};
type Write = {};
type SetBuffer = {};
type SetAuthority = {};
const IDL_INSTRUCTION_LAYOUT: Layout<IdlInstruction> = rustEnum([
struct([], 'create'),
struct([], 'createBuffer'),
struct([], 'write'),
struct([], 'setBuffer'),
struct([], 'setAuthority'),
]);
export function encodeInstruction(i: IdlInstruction): Buffer {
const buffer = Buffer.alloc(1000); // TODO: use a tighter buffer.
const len = IDL_INSTRUCTION_LAYOUT.encode(i, buffer);
return Buffer.concat([IDL_TAG, buffer.slice(0, len)]);
}
// Reverse for little endian.
export const IDL_TAG = Buffer.from('0a69e9a778bcf440', 'hex').reverse();

43
src/utils/loader.ts Normal file
View File

@ -0,0 +1,43 @@
import { struct, Layout } from 'buffer-layout';
import { publicKey, rustEnum } from '@project-serum/borsh';
// Simplified since we only use the Upgrade variant.
export type UpgradeableLoaderInstruction =
| InitializeBuffer
| Write
| DeployWithMaxDataLen
| Upgrade
| SetAuthority;
type InitializeBuffer = {};
type Write = {};
type DeployWithMaxDataLen = {};
type Upgrade = {};
type SetAuthority = {};
const UPGRADEABLE_LOADER_INSTRUCTION_LAYOUT: Layout<UpgradeableLoaderInstruction> = rustEnum(
[
struct([], 'initalizeBufer'),
struct([], 'write'),
struct([], 'deployWithMaxDataLen'),
struct([], 'upgrade'),
struct([], 'setAuthority'),
],
);
export function encodeInstruction(i: UpgradeableLoaderInstruction): Buffer {
const buffer = Buffer.alloc(1000); // TODO: use a tighter buffer.
const len = UPGRADEABLE_LOADER_INSTRUCTION_LAYOUT.encode(i, buffer);
return buffer.slice(0, len);
}
const UPGRADEABLE_LOADER_STATE_LAYOUT: Layout<any> = rustEnum([
struct([], 'uninitialized'),
struct([], 'buffer'),
struct([publicKey('programdataAddress')], 'program'),
struct([], 'programData'),
]);
export function decodeState(data: Buffer): any {
return UPGRADEABLE_LOADER_STATE_LAYOUT.decode(data);
}

42
src/utils/lockup.ts Normal file
View File

@ -0,0 +1,42 @@
import { PublicKey, SYSVAR_CLOCK_PUBKEY } from '@solana/web3.js';
import * as anchor from '@project-serum/anchor';
import { simulateTransaction } from '@project-serum/common';
export async function vestingSigner(
programId: PublicKey,
vesting: PublicKey,
): Promise<{ publicKey: PublicKey; nonce: number }> {
const [publicKey, nonce] = await anchor.web3.PublicKey.findProgramAddress(
[vesting.toBuffer()],
programId,
);
return {
publicKey,
nonce,
};
}
// Simulates the `availableForWithdrawal` instruction to funnel out a the
// emitted log data (as a hack to get a return value).
export async function availableForWithdrawal(
lockupClient: anchor.Program,
vesting: PublicKey,
): Promise<anchor.BN> {
let tx = lockupClient.transaction.availableForWithdrawal({
accounts: {
vesting,
clock: SYSVAR_CLOCK_PUBKEY,
},
});
tx.setSigners(...[lockupClient.provider.wallet.publicKey]);
let resp = await simulateTransaction(
lockupClient.provider.connection,
tx,
'recent',
);
if (resp.value.err) {
throw new Error(`RPC error: ${resp.value.err.toString()}`);
}
let log = resp.value.logs![1].slice('Program log: '.length);
return new anchor.BN(JSON.parse(log).result);
}

133
src/utils/registry.ts Normal file
View File

@ -0,0 +1,133 @@
import { Transaction, PublicKey, Account } from '@solana/web3.js';
import * as serumCmn from '@project-serum/common';
import * as anchor from '@project-serum/anchor';
export async function registrarSigner(
programId: PublicKey,
registrar: PublicKey,
): Promise<{ publicKey: PublicKey; nonce: number }> {
const [publicKey, nonce] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.toBuffer()],
programId,
);
return {
publicKey,
nonce,
};
}
export async function memberSigner(
programId: PublicKey,
registrar: PublicKey,
member: PublicKey,
): Promise<{ publicKey: PublicKey; nonce: number }> {
const [publicKey, nonce] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.toBuffer(), member.toBuffer()],
programId,
);
return {
publicKey,
nonce,
};
}
export async function vendorSigner(
programId: PublicKey,
registrar: PublicKey,
vendor: PublicKey,
): Promise<{ publicKey: PublicKey; nonce: number }> {
const [publicKey, nonce] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.toBuffer(), vendor.toBuffer()],
programId,
);
return {
publicKey,
nonce,
};
}
// Returns the seed used to derive a member address. This is not necessary, but
// a UX convenience. Each member address is a deterministic function of the
// program, beneficiary, and this (constant) seed.
export async function memberSeed(registrar: PublicKey): Promise<string> {
const seed = await anchor.utils.sha256(`${registrar.toString()}:Member`);
// The max length of seeds allowed by Solana is 32.
return seed.slice(0, 32);
}
// Creates all the SPL otken vaults needed for constructing a `Member` account.
export async function createBalanceSandbox(
provider: serumCmn.Provider,
r: any,
registrySigner: PublicKey,
) {
const spt = new Account();
const vault = new Account();
const vaultStake = new Account();
const vaultPw = new Account();
const lamports = await provider.connection.getMinimumBalanceForRentExemption(
165,
);
const createSptIx = await serumCmn.createTokenAccountInstrs(
provider,
spt.publicKey,
r.poolMint,
registrySigner,
lamports,
);
const createVaultIx = await serumCmn.createTokenAccountInstrs(
provider,
vault.publicKey,
r.mint,
registrySigner,
lamports,
);
const createVaultStakeIx = await serumCmn.createTokenAccountInstrs(
provider,
vaultStake.publicKey,
r.mint,
registrySigner,
lamports,
);
const createVaultPwIx = await serumCmn.createTokenAccountInstrs(
provider,
vaultPw.publicKey,
r.mint,
registrySigner,
lamports,
);
let tx0 = new Transaction();
tx0.add(
...createSptIx,
...createVaultIx,
...createVaultStakeIx,
...createVaultPwIx,
);
let signers0 = [spt, vault, vaultStake, vaultPw];
const tx = { tx: tx0, signers: signers0 };
return [
tx,
{
spt: spt.publicKey,
vault: vault.publicKey,
vaultStake: vaultStake.publicKey,
vaultPw: vaultPw.publicKey,
},
];
}
// Returns all events in the reward queue.
export function rewardEvents(rewardQ: any): any[] {
let events = [];
let tail = rewardQ.tail;
while (tail < rewardQ.head) {
let idx = tail % rewardQ.events.length;
events.push(rewardQ.events[idx]);
tail += 1;
}
return events;
}

66
src/utils/tokens.tsx Normal file
View File

@ -0,0 +1,66 @@
import React, {
ReactNode,
PropsWithChildren,
useContext,
useState,
useEffect,
} from 'react';
import BN from 'bn.js';
import { PublicKey } from '@solana/web3.js';
import { TokenListProvider, TokenInfo } from '@solana/spl-token-registry';
import { networks } from '../store/config';
const TokenListContext = React.createContext<TokenListContextValues>({
tokenMap: new Map(),
});
type TokenListContextValues = {
tokenMap: Map<string, TokenInfo>;
};
export function useTokenInfos(): Map<string, TokenInfo> {
const { tokenMap } = useContext<TokenListContextValues>(TokenListContext);
return tokenMap;
}
export function TokenRegistryProvider(props: PropsWithChildren<ReactNode>) {
const [tokenMap, setTokenMap] = useState<Map<string, TokenInfo>>(new Map());
useEffect(() => {
new TokenListProvider().resolve().then(tokens => {
const tokenList = tokens.filterByClusterSlug('mainnet-beta').getList();
setTokenMap(
tokenList.reduce((map, item) => {
map.set(item.address, item);
return map;
}, new Map()),
);
});
}, [setTokenMap]);
return (
<TokenListContext.Provider value={{ tokenMap }}>
{props.children}
</TokenListContext.Provider>
);
}
export function fromDisplay(amount: number, decimals: number): BN {
return new BN(amount * 10 ** decimals);
}
export function toDisplay(amount: BN | number, decimals: number): string {
if (amount instanceof BN) {
amount = amount.toNumber();
}
return (amount / 10 ** decimals).toString();
}
export function toDisplayLabel(mint: PublicKey): string {
let whitelistedMint = Object.keys(networks.mainnet.mints)
.filter(label => networks.mainnet.mints[label].equals(mint))
.pop();
if (whitelistedMint) {
return whitelistedMint.toUpperCase();
}
return mint.toString();
}

27
tsconfig.json Normal file
View File

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"typeRoots": ["./types/"]
},
"include": [
"src"
]
}

87
types/buffer-layout/index.d.ts vendored Normal file
View File

@ -0,0 +1,87 @@
declare module 'buffer-layout' {
// TODO: remove `any`.
export class Layout<T = any> {
span: number;
property?: string;
constructor(span: number, property?: string);
decode(b: Buffer, offset?: number): T;
encode(src: T, b: Buffer, offset?: number): number;
getSpan(b: Buffer, offset?: number): number;
replicate(name: string): this;
}
// TODO: remove any.
export class Structure<T = any> extends Layout<T> {
span: any;
}
export function greedy(
elementSpan?: number,
property?: string,
): Layout<number>;
export function offset<T>(
layout: Layout<T>,
offset?: number,
property?: string,
): Layout<T>;
export function u8(property?: string): Layout<number>;
export function u16(property?: string): Layout<number>;
export function u24(property?: string): Layout<number>;
export function u32(property?: string): Layout<number>;
export function u40(property?: string): Layout<number>;
export function u48(property?: string): Layout<number>;
export function nu64(property?: string): Layout<number>;
export function u16be(property?: string): Layout<number>;
export function u24be(property?: string): Layout<number>;
export function u32be(property?: string): Layout<number>;
export function u40be(property?: string): Layout<number>;
export function u48be(property?: string): Layout<number>;
export function nu64be(property?: string): Layout<number>;
export function s8(property?: string): Layout<number>;
export function s16(property?: string): Layout<number>;
export function s24(property?: string): Layout<number>;
export function s32(property?: string): Layout<number>;
export function s40(property?: string): Layout<number>;
export function s48(property?: string): Layout<number>;
export function ns64(property?: string): Layout<number>;
export function s16be(property?: string): Layout<number>;
export function s24be(property?: string): Layout<number>;
export function s32be(property?: string): Layout<number>;
export function s40be(property?: string): Layout<number>;
export function s48be(property?: string): Layout<number>;
export function ns64be(property?: string): Layout<number>;
export function f32(property?: string): Layout<number>;
export function f32be(property?: string): Layout<number>;
export function f64(property?: string): Layout<number>;
export function f64be(property?: string): Layout<number>;
export function struct<T>(
fields: Layout<any>[],
property?: string,
decodePrefixes?: boolean,
): Layout<T>;
export function bits(
word: Layout<number>,
msb?: boolean,
property?: string,
): any;
export function seq<T>(
elementLayout: Layout<T>,
count: number | Layout<number>,
property?: string,
): Layout<T[]>;
export function union(
discr: Layout<any>,
defaultLayout?: any,
property?: string,
): any;
export function unionLayoutDiscriminator(
layout: Layout<any>,
property?: string,
): any;
export function blob(
length: number | Layout<number>,
property?: string,
): Layout<Buffer>;
export function cstr(property?: string): Layout<string>;
export function utf8(maxSpan: number, property?: string): Layout<string>;
}

12740
yarn.lock Normal file

File diff suppressed because it is too large Load Diff