Skip to content

Commit

Permalink
An example React app that exercises the new @solana/web3.js and the…
Browse files Browse the repository at this point in the history
… new Wallet Standard wallet adapter in `@solana/react` (#2817)
  • Loading branch information
steveluscher authored Jun 25, 2024
1 parent 17b0b99 commit fbcf1fd
Show file tree
Hide file tree
Showing 43 changed files with 3,825 additions and 270 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Publish Legacy Documentation
name: Publish GitHub Pages

on:
workflow_dispatch:
Expand All @@ -18,7 +18,7 @@ env:
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}

jobs:
compile-docs-and-publish:
compile-github-pages-and-publish:
runs-on: ubuntu-latest
steps:
- name: Checkout
Expand All @@ -27,11 +27,17 @@ jobs:
- name: Install Dependencies
uses: ./.github/workflows/actions/install-dependencies

- name: Compile Documentation
run: pnpm turbo run compile:docs --concurrency=100% --filter=@solana/web3.js
- name: Compile
run: pnpm turbo run compile:ghpages --concurrency=100%

- name: Deploy Documentation to Github Pages
- name: Assemble deploy directory
run: |
mkdir -p .ghpages-deploy
cp -r ./packages/library-legacy/doc/* .ghpages-deploy
cp -r ./examples/react-app/dist/ .ghpages-deploy/example/
- name: Deploy to Github Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./packages/library-legacy/doc
publish_dir: .ghpages-deploy
3 changes: 3 additions & 0 deletions .github/workflows/pull-requests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ jobs:
- name: Build & Test
run: pnpm build

- name: Build GitHub Pages
run: pnpm turbo run compile:ghpages --concurrency=100%

- name: Stop Test Validator
if: always() && steps.start-test-validator.outcome == 'success'
run: kill ${{ steps.start-test-validator.outputs.pid }}
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,6 @@ yarn-error.log*
# `solana-test-validator`
.agave/
test-ledger/

# GitHub Pages deploy directory
.ghpages-deploy
10 changes: 10 additions & 0 deletions examples/react-app/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: ['../../.eslintrc.js', '@solana/eslint-config-solana/react'],
ignorePatterns: ['dist', '.eslintrc.cjs'],
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
},
};
24 changes: 24 additions & 0 deletions examples/react-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
20 changes: 20 additions & 0 deletions examples/react-app/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright (c) 2023 Solana Labs, Inc

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
44 changes: 44 additions & 0 deletions examples/react-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# @solana/example-react-app

This is an example of how to use `@solana/web3.js` and `@solana/react` to build a React web application.

The latest version of this code is automatically deployed to https://solana-labs.github.io/solana-web3.js/example/

## Features

- Connects to browser wallets that support the Wallet Standard; one or more at a time
- Fetches and subscribes to the balance of the selected wallet
- Allows you to sign an arbitrary message using a wallet account
- Allows you to make a transfer from the selected wallet to any other connected wallet

## Developing

Start a server in development mode.

```shell
pnpm install
pnpm turbo compile:js compile:typedefs
pnpm dev
```

Press <kbd>o</kbd> + <kbd>Enter</kbd> to open the app in a browser. Edits to the source code will automatically reload the app.

## Building for deployment

Build a static bundle and HTML for deployment to a webserver.

```shell
pnpm install
pnpm turbo build
```

The contents of the `dist/` directory can now be uploaded to a webserver.

## Enabling Mainnet-Beta

Access to this cluster is typically blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) rules, so it is disabled in the example app by default. To enable it, start the server or compile the application with the `REACT_EXAMPLE_APP_ENABLE_MAINNET` environment variable set to `"true"`.

```shell
REACT_EXAMPLE_APP_ENABLE_MAINNET=true pnpm dev
REACT_EXAMPLE_APP_ENABLE_MAINNET=true pnpm build
```
13 changes: 13 additions & 0 deletions examples/react-app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/solanaLogoMark.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Solana React Example App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
36 changes: 36 additions & 0 deletions examples/react-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "@solana/example-react-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/themes": "^3.0.5",
"@solana-program/system": "^0.3.2",
"@solana/react": "workspace:*",
"@solana/web3.js": "workspace:@solana/web3.js-experimental@*",
"@wallet-standard/core": "pre",
"@wallet-standard/react": "pre",
"react": "^18.3.0",
"react-dom": "^18.3.0",
"react-error-boundary": "^4.0.13",
"swr": "^2.2.5"
},
"devDependencies": {
"@solana/wallet-standard-features": "^1.2.0",
"@types/react": "^18.3",
"@types/react-dom": "^18.3",
"@typescript-eslint/eslint-plugin": "^7.13.1",
"@typescript-eslint/parser": "^7.13.1",
"@vitejs/plugin-react-swc": "^3.7.0",
"eslint-plugin-react-refresh": "^0.4.7",
"vite": "^5.3.1"
}
}
13 changes: 13 additions & 0 deletions examples/react-app/public/solanaLogoMark.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 50 additions & 0 deletions examples/react-app/src/components/Balance.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { ExclamationTriangleIcon } from '@radix-ui/react-icons';
import { Text, Tooltip } from '@radix-ui/themes';
import { address } from '@solana/web3.js';
import type { UiWalletAccount } from '@wallet-standard/react';
import { useContext, useMemo } from 'react';
import useSWRSubscription from 'swr/subscription';

import { ChainContext } from '../context/ChainContext';
import { RpcContext } from '../context/RpcContext';
import { getErrorMessage } from '../errors';
import { balanceSubscribe } from '../functions/balance';
import { ErrorDialog } from './ErrorDialog';

type Props = Readonly<{
account: UiWalletAccount;
}>;

export function Balance({ account }: Props) {
const { chain } = useContext(ChainContext);
const { rpc, rpcSubscriptions } = useContext(RpcContext);
const subscribe = useMemo(() => balanceSubscribe.bind(null, rpc, rpcSubscriptions), [rpc, rpcSubscriptions]);
const { data: lamports, error } = useSWRSubscription({ address: address(account.address), chain }, subscribe);
if (error) {
return (
<>
<ErrorDialog
error={error}
key={`${account.address}:${chain}`}
title="Failed to fetch account balance"
/>
<Text>
<Tooltip content={`Could not fetch balance: ${getErrorMessage(error, 'Unknown reason')}`}>
<ExclamationTriangleIcon
color="red"
style={{ height: 16, verticalAlign: 'text-bottom', width: 16 }}
/>
</Tooltip>
</Text>
</>
);
} else if (lamports == null) {
return <Text>&ndash;</Text>;
} else {
const formattedSolValue = new Intl.NumberFormat(undefined, { maximumFractionDigits: 5 }).format(
// @ts-expect-error This format string is 100% allowed now.
`${lamports}E-9`,
);
return <Text>{`${formattedSolValue} \u25CE`}</Text>;
}
}
102 changes: 102 additions & 0 deletions examples/react-app/src/components/BaseSignMessageFeaturePanel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { Pencil1Icon } from '@radix-ui/react-icons';
import { Blockquote, Box, Button, Code, DataList, Dialog, Flex, TextField } from '@radix-ui/themes';
import { getBase64Decoder } from '@solana/web3.js';
import type { ReadonlyUint8Array } from '@wallet-standard/core';
import type { SyntheticEvent } from 'react';
import { useRef, useState } from 'react';

import { ErrorDialog } from '../components/ErrorDialog';

type Props = Readonly<{
signMessage(message: ReadonlyUint8Array): Promise<ReadonlyUint8Array>;
}>;

export function BaseSignMessageFeaturePanel({ signMessage }: Props) {
const { current: NO_ERROR } = useRef(Symbol());
const [isSigningMessage, setIsSigningMessage] = useState(false);
const [error, setError] = useState<unknown | typeof NO_ERROR>(NO_ERROR);
const [lastSignature, setLastSignature] = useState<ReadonlyUint8Array | undefined>();
const [text, setText] = useState<string>();
return (
<Flex asChild gap="2" direction={{ initial: 'column', sm: 'row' }} style={{ width: '100%' }}>
<form
onSubmit={async e => {
e.preventDefault();
setError(NO_ERROR);
setIsSigningMessage(true);
try {
const signature = await signMessage(new TextEncoder().encode(text));
setLastSignature(signature);
} catch (e) {
setLastSignature(undefined);
setError(e);
} finally {
setIsSigningMessage(false);
}
}}
>
<Box flexGrow="1">
<TextField.Root
placeholder="Write a message to sign"
onChange={(e: SyntheticEvent<HTMLInputElement>) => setText(e.currentTarget.value)}
value={text}
>
<TextField.Slot>
<Pencil1Icon />
</TextField.Slot>
</TextField.Root>
</Box>
<Dialog.Root
open={!!lastSignature}
onOpenChange={open => {
if (!open) {
setLastSignature(undefined);
}
}}
>
<Dialog.Trigger>
<Button
color={error ? undefined : 'red'}
disabled={!text}
loading={isSigningMessage}
type="submit"
>
Sign Message
</Button>
</Dialog.Trigger>
{lastSignature ? (
<Dialog.Content
onClick={e => {
e.stopPropagation();
}}
>
<Dialog.Title>You Signed a Message!</Dialog.Title>
<DataList.Root orientation={{ initial: 'vertical', sm: 'horizontal' }}>
<DataList.Item>
<DataList.Label minWidth="88px">Message</DataList.Label>
<DataList.Value>
<Blockquote>{text}</Blockquote>
</DataList.Value>
</DataList.Item>
<DataList.Item>
<DataList.Label minWidth="88px">Signature</DataList.Label>
<DataList.Value>
<Code truncate>{getBase64Decoder().decode(lastSignature)}</Code>
</DataList.Value>
</DataList.Item>
</DataList.Root>
<Flex gap="3" mt="4" justify="end">
<Dialog.Close>
<Button>Cool!</Button>
</Dialog.Close>
</Flex>
</Dialog.Content>
) : null}
</Dialog.Root>
{error !== NO_ERROR ? (
<ErrorDialog error={error} onClose={() => setError(NO_ERROR)} title="Failed to sign message" />
) : null}
</form>
</Flex>
);
}
Loading

0 comments on commit fbcf1fd

Please sign in to comment.