Skip to content

Commit

Permalink
chore: add wallet example
Browse files Browse the repository at this point in the history
  • Loading branch information
iosh committed Sep 22, 2024
1 parent f484fe1 commit 26e03c0
Show file tree
Hide file tree
Showing 9 changed files with 234 additions and 1 deletion.
2 changes: 1 addition & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ The `examples/` directory is a growing & living folder, and open for contributio
- [ ] Watching Epoch
- Clients
- [x] Public (w/ HTTP, WebSocket, Fallback)
- [ ] Wallet – JSON-RPC Account (`window.fluent`)
- [x] Wallet – JSON-RPC Account (`window.fluent`)
- [ ] Wallet - JSON-RPC Account (WalletConnect v2)
- Contracts
- [ ] Deploying
Expand Down
3 changes: 3 additions & 0 deletions examples/client_wallet_fluent/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Client wallet fluent Example

[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github.com/iosh/cive/tree/main/examples/client_wallet_fluent)
14 changes: 14 additions & 0 deletions examples/client_wallet_fluent/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<h1 class="title has-text-centered">Wallet Client Example</h1>
<div class="container" id="app">Loading...</div>
<script type="module">
import './index.tsx';
</script>
</body>
</html>
9 changes: 9 additions & 0 deletions examples/client_wallet_fluent/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './src/App'
import 'bulma/css/bulma.css'
ReactDOM.createRoot(document.getElementById('app') as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
21 changes: 21 additions & 0 deletions examples/client_wallet_fluent/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "client_wallet_fluent",
"private": true,
"type": "module",
"scripts": {
"dev": "vite"
},
"dependencies": {
"bulma": "^1.0.2",
"cive": "latest",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.8",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"typescript": "^5.6.2",
"vite": "^5.4.4"
}
}
124 changes: 124 additions & 0 deletions examples/client_wallet_fluent/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import {
http,
type Address,
createPublicClient,
createWalletClient,
custom,
parseCFX,
SignMessageErrorType,
} from "cive";
import { mainnet, testnet } from "cive/chains";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import "cive/window";
import type { SendTransactionErrorType } from "../../../src/_types/actions/wallet/sendTransaction";

export default function App() {
const [account, setAccount] = useState<Address>();
const [transaction, setTransaction] = useState<string>();
const [signMessage, setSignMessage] = useState<string>();

const walletClient = useMemo(
() =>
createWalletClient({
chain: testnet,
transport: custom(window.fluent!),
}),
[]
);

const connect = useCallback(async () => {
const [address] = await walletClient.requestAddresses();
setAccount(address);
}, [walletClient]);

const handleSendTransaction = useCallback(async () => {
if (account) {
try {
const hash = await walletClient.sendTransaction({
account,
to: account,
value: parseCFX("0.01"),
});
setTransaction(`successful: ${hash}`);
} catch (error: unknown) {
const err = error as SendTransactionErrorType;
setTransaction(err.name);
}
}
}, [walletClient, account]);

const handleSignMessage = useCallback(async () => {
if (account) {
try {
const signature = await walletClient.signMessage({
account,
message: "hello world",
});
setSignMessage(`successful: ${signature}`);
} catch (error: unknown) {
const err = error as SignMessageErrorType;

setSignMessage(err.name);
}
}
}, [walletClient, account]);

const handleSwitchChain = useCallback(async () => {
if (account) {
await walletClient.switchChain({ id: testnet.id });
}
}, [walletClient, account]);
useEffect(() => {
window?.fluent?.on("accountsChanged", (accounts: Address[]) => {
if (accounts.length > 0) {
setAccount(accounts[0]);
} else {
setAccount(undefined);
}
});
window?.fluent?.on("disconnect", () => setAccount(undefined));
}, []);

return (
<div className="box">
<div>
<div className="column">
{account ? (
<div className="columns is-3 is-flex-direction-column">
<span>Account: {account}</span>
<div className="column">
<div className="is-flex is-align-items-center">
<button className="button" onClick={handleSendTransaction}>
Send Transaction(0.01 CFX to self)
</button>
<span className="is-size-5">result: {transaction}</span>
</div>
</div>

<div className="column">
<div className="is-flex is-align-items-center">
<button className="button" onClick={handleSwitchChain}>
Switch chain
</button>
</div>
</div>

<div className="column">
<div className="is-flex is-align-items-center">
<button className="button" onClick={handleSignMessage}>
Sign message (hello world)
</button>
<span className="is-size-5">result: {signMessage}</span>
</div>
</div>
</div>
) : (
<button className="button" onClick={connect}>
Connect Wallet
</button>
)}
</div>
</div>
</div>
);
}
24 changes: 24 additions & 0 deletions examples/client_wallet_fluent/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,

/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
7 changes: 7 additions & 0 deletions examples/client_wallet_fluent/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})
31 changes: 31 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 26e03c0

Please sign in to comment.