Skip to content

Commit

Permalink
Minor refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
pindaroso committed Oct 15, 2024
1 parent dbcf4ca commit d530392
Show file tree
Hide file tree
Showing 7 changed files with 117 additions and 108 deletions.
58 changes: 36 additions & 22 deletions packages/app/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,11 @@ import {
} from '@/components/ui/dropdown-menu'
import { Button } from '@/components/ui/button'
import { useWalletContext } from '@/components/providers/wallet'
import { Increment } from '@/components/buttons/increment'
import { Airdrop } from '@/components/buttons/airdrop'
import { Send } from '@/components/buttons/send'
import AirdropButton from '@/components/buttons/airdrop'
import SendButton from '@/components/buttons/send'
import CreateMintButton from '@/components/buttons/create-mint'
import CreateCounterButton from '@/components/buttons/create-counter'

import IncrementCounterButton from '@/components/buttons/increment-counter'
import { formatAddress } from '@/lib/utils'

const defaultNetwork =
Expand All @@ -49,11 +48,14 @@ export default function Home() {
const [network, setNetwork] = useState(defaultNetwork)
const [networkActive, setNetworkActive] = useState(false)
const [walletConnected, setWalletConnected] = useState(false)
const [route, setRoute] = useState<'cost' | 'counter' | 'mint' | 'faucet'>(
'cost'
)

useEffect(() => {
if (publicKey && !walletConnected) {
setWalletConnected(true)
toast.success('Wallet connected')
toast.success('Wallet Connected')
}
}, [publicKey])

Expand Down Expand Up @@ -90,11 +92,20 @@ export default function Home() {
<div className="flex flex-col min-h-screen">
<nav className="p-4">
<div className="flex justify-between items-center">
<h1 className="text-primary text-lg">Solana ZK Starter</h1>
<div className="flex items-center gap-6 text-zinc-700 dark:text-zinc-300 cursor-pointer">
<h1 className="text-primary text-lg">Solana ZK Starter</h1>
<div onClick={() => setRoute('cost')}>Cost Calculator</div>
<div onClick={() => setRoute('counter')}>Counter Program</div>
<div onClick={() => setRoute('mint')}>Mint</div>
<div onClick={() => setRoute('faucet')}>Faucet</div>
</div>
<div className="flex items-center">
{publicKey ? (
<>
<Button variant="ghost" className="mr-2">
<Button
variant="ghost"
className="mr-2 text-zinc-700 dark:text-zinc-300"
>
{balance !== null ? balance.toFixed(2) + ' SOL' : '-'}
</Button>
<div className="flex flex-row">
Expand Down Expand Up @@ -206,21 +217,24 @@ export default function Home() {
</nav>
<main className="flex-grow">
<div className="flex flex-col max-w-md mx-auto p-4 gap-2">
<div className="flex flex-col mt-2">
<Airdrop />
</div>
<div className="flex flex-col mt-2">
<Send />
</div>
<div className="flex flex-col mt-2">
<CreateMintButton />
</div>
<div className="flex flex-col mt-2">
<CreateCounterButton />
</div>
<div className="flex flex-col mt-2">
<Increment />
</div>
{route === 'cost' && (
<div className="flex flex-col mt-2 text-center">Coming Soon</div>
)}
{route === 'faucet' && (
<AirdropButton className="flex flex-col mt-2" />
)}
{route === 'mint' && (
<>
<SendButton className="flex flex-col mt-2" />
<CreateMintButton className="flex flex-col mt-2" />
</>
)}
{route === 'counter' && (
<>
<CreateCounterButton className="flex flex-col mt-2" />
<IncrementCounterButton className="flex flex-col mt-2" />
</>
)}
</div>
</main>
<footer className="p-4">
Expand Down
7 changes: 5 additions & 2 deletions packages/app/src/components/buttons/airdrop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import toast from 'react-hot-toast'
import { useWalletContext } from '@/components/providers/wallet'
import { Button } from '@/components/ui/button'

export const Airdrop: FC = () => {
export const AirdropButton: FC<{ className?: string }> = ({ className }) => {
const { publicKey } = useWallet()
const { endpoint } = useWalletContext()

Expand All @@ -17,15 +17,18 @@ export const Airdrop: FC = () => {
try {
const conn = createRpc(endpoint)
await confirmTx(conn, await conn.requestAirdrop(publicKey, 1e9))
toast.success('Airdrop Success')
} catch (error: any) {
console.error(error)
toast.error(`Airdrop Failed: ${error.message}`)
}
}, [publicKey, endpoint])

return (
<Button onClick={onClick} disabled={!publicKey}>
<Button onClick={onClick} disabled={!publicKey} className={className}>
Airdrop SOL
</Button>
)
}

export default AirdropButton
35 changes: 24 additions & 11 deletions packages/app/src/components/buttons/create-counter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
noopProgram,
accountCompressionProgram,
deriveAddress,
CompressedAccountWithMerkleContext,
createCompressedAccount,
} from '@lightprotocol/stateless.js'
import { keccak_256 } from '@noble/hashes/sha3'
import { WalletNotConnectedError } from '@solana/wallet-adapter-base'
Expand Down Expand Up @@ -42,7 +44,9 @@ export class ProgramNotInitializedError extends Error {
name = 'ProgramNotInitializedError'
}

export const CreateButton: FC = () => {
export const CreateCounterButton: FC<{ className?: string }> = ({
className,
}) => {
const { endpoint } = useWalletContext()
const { program } = useProgramContext()
const wallet = useAnchorWallet()
Expand All @@ -55,29 +59,38 @@ export const CreateButton: FC = () => {
// TODO: Adapt for devnet, testnet and mainnet
const rpc = createRpc()

const { addressTree, addressQueue } = defaultTestStateTreeAccounts()
const { addressTree, addressQueue, nullifierQueue } =
defaultTestStateTreeAccounts()

const seed = deriveAddressSeed(
[Buffer.from('counter'), wallet.publicKey.toBuffer()],
program.programId
)
const address = await deriveAddress(seed, addressTree)
const compressedAccount = createCompressedAccount(
wallet.publicKey,
bn(10),
undefined,
[10]
)

const selectedAccounts = [
const selectedAccounts: CompressedAccountWithMerkleContext[] = [
{
hash: bn(address.toBytes()),
tree: addressTree,
queue: addressQueue,
...compressedAccount,
readOnly: true,
merkleTree: addressTree,
nullifierQueue,
hash: [bn(address.toBytes()).toNumber()],
leafIndex: 0,
},
]

/*
* ERROR: Failed to get ValidityProof for compressed accounts 36439686636752871256271152024530679660001424812964160093210165672697738154: Record Not Found: Leaf nodes not found for hashes. Got 0 hashes. Expected 1.
*/
const { compressedProof, rootIndices } = await rpc.getValidityProof(
selectedAccounts.map(
({ hash }: { hash: BN; tree: PublicKey; queue: PublicKey }) => hash
)
selectedAccounts.map(({ hash }) => bn(hash[0])),
[bn(address.toBytes())]
)

// TODO: Add input?
Expand Down Expand Up @@ -137,10 +150,10 @@ export const CreateButton: FC = () => {
}, [wallet, endpoint, program])

return (
<Button onClick={onClick} disabled={!wallet}>
<Button onClick={onClick} disabled={!wallet} className={className}>
Create Counter
</Button>
)
}

export default CreateButton
export default CreateCounterButton
20 changes: 8 additions & 12 deletions packages/app/src/components/buttons/create-mint.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,34 @@ import { WalletNotConnectedError } from '@solana/wallet-adapter-base'
import toast from 'react-hot-toast'

import { useWalletContext } from '@/components/providers/wallet'
import { useProgramContext } from '@/components/providers/program'
import { Button } from '@/components/ui/button'
import { Signer } from '@solana/web3.js'

export const CreateMintButton: FC = () => {
const { publicKey } = useWallet()
export const CreateMintButton: FC<{ className?: string }> = ({ className }) => {
const { endpoint } = useWalletContext()
const { program } = useProgramContext()
const wallet = useAnchorWallet()

const onClick = useCallback(async () => {
if (!publicKey) throw new WalletNotConnectedError()
if (!wallet) throw new WalletNotConnectedError()

try {
// TODO: Adapt for devnet, testnet and mainnet
const rpc = createRpc()
const { mint, transactionSignature } = await createMint(
const rpc = createRpc(endpoint)
const { transactionSignature } = await createMint(
rpc,
wallet as unknown as Signer,
wallet as unknown as Signer, // TODO: Fix this
wallet.publicKey,
9
)

toast.success(`Tx Success: ${transactionSignature}`)
} catch (error) {
} catch (error: any) {
console.error(error)
toast.error(`Mint Creation Failed: ${error.message}`)
}
}, [publicKey, wallet])
}, [wallet, endpoint])

return (
<Button onClick={onClick} disabled={!publicKey}>
<Button onClick={onClick} disabled={!wallet} className={className}>
Create Mint
</Button>
)
Expand Down
34 changes: 34 additions & 0 deletions packages/app/src/components/buttons/increment-counter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { useWallet } from '@solana/wallet-adapter-react'
import { FC, useCallback } from 'react'
import { WalletNotConnectedError } from '@solana/wallet-adapter-base'
import toast from 'react-hot-toast'

import { useWalletContext } from '@/components/providers/wallet'
import { Button } from '@/components/ui/button'

export const IncrementCounterButton: FC<{ className?: string }> = ({
className,
}) => {
const { publicKey } = useWallet()
const { endpoint } = useWalletContext()

const onClick = useCallback(async () => {
if (!publicKey) throw new WalletNotConnectedError()

try {
// TODO: Implement
toast.error('Not Implemented')
} catch (error: any) {
console.error(error)
toast.error(`Increment Failed: ${error.message}`)
}
}, [publicKey, endpoint])

return (
<Button onClick={onClick} disabled={!publicKey} className={className}>
Increment Counter
</Button>
)
}

export default IncrementCounterButton
58 changes: 0 additions & 58 deletions packages/app/src/components/buttons/increment.tsx

This file was deleted.

13 changes: 10 additions & 3 deletions packages/app/src/components/buttons/send.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ import {
VersionedTransaction,
} from '@solana/web3.js'
import { WalletNotConnectedError } from '@solana/wallet-adapter-base'
import { useWalletContext } from '@/components/providers/wallet'
import toast from 'react-hot-toast'

import { useWalletContext } from '@/components/providers/wallet'
import { Button } from '@/components/ui/button'

export const Send: FC = () => {
export const SendButton: FC<{ className?: string }> = ({ className }) => {
const { publicKey, sendTransaction } = useWallet()

const { endpoint } = useWalletContext()
Expand Down Expand Up @@ -123,14 +124,20 @@ export const Send: FC = () => {
signature: signatureSend,
})

toast.success(
`Sent ${1e7} lamports to ${recipient.toBase58()} ! txId: https://explorer.solana.com/tx/${signatureSend}?cluster=custom`
)

console.log(
`Sent ${1e7} lamports to ${recipient.toBase58()} ! txId: https://explorer.solana.com/tx/${signatureSend}?cluster=custom`
)
}, [publicKey, sendTransaction, endpoint])

return (
<Button onClick={onClick} disabled={!publicKey}>
<Button onClick={onClick} disabled={!publicKey} className={className}>
Send Compressed SOL
</Button>
)
}

export default SendButton

0 comments on commit d530392

Please sign in to comment.