repo_id
stringclasses 563
values | file_path
stringlengths 40
166
| content
stringlengths 1
2.94M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/.eslintrc.json
|
{
"extends": [
"plugin:@nx/react-typescript",
"next",
"next/core-web-vitals",
"../.eslintrc.json"
],
"ignorePatterns": ["!**/*", ".next/**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {
"@next/next/no-html-link-for-pages": ["error", "web/pages"]
}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {
"@nx/enforce-module-boundaries": [
"error",
{
"allow": ["@/"]
}
]
}
}
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/react-query-provider.tsx
|
'use client';
import React, { ReactNode, useState } from 'react';
import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental';
import { QueryClientProvider, QueryClient } from '@tanstack/react-query';
export function ReactQueryProvider({ children }: { children: ReactNode }) {
const [client] = useState(new QueryClient());
return (
<QueryClientProvider client={client}>
<ReactQueryStreamedHydration>{children}</ReactQueryStreamedHydration>
</QueryClientProvider>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/global.css
|
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body {
height: 100%;
}
.wallet-adapter-button-trigger {
background: rgb(100, 26, 230) !important;
border-radius: 8px !important;
padding-left: 16px !important;
padding-right: 16px !important;
}
.wallet-adapter-dropdown-list,
.wallet-adapter-button {
font-family: inherit !important;
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/page.module.css
|
.page {
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/layout.tsx
|
import './global.css';
import { UiLayout } from '@/components/ui/ui-layout';
import { ClusterProvider } from '@/components/cluster/cluster-data-access';
import { SolanaProvider } from '@/components/solana/solana-provider';
import { ReactQueryProvider } from './react-query-provider';
export const metadata = {
title: 'voting-dapp',
description: 'Generated by create-solana-dapp',
};
const links: { label: string; path: string }[] = [
{ label: 'Account', path: '/account' },
{ label: 'Clusters', path: '/clusters' },
{ label: 'Counter Program', path: '/counter' },
];
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<ReactQueryProvider>
<ClusterProvider>
<SolanaProvider>
<UiLayout links={links}>{children}</UiLayout>
</SolanaProvider>
</ClusterProvider>
</ReactQueryProvider>
</body>
</html>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/page.tsx
|
import DashboardFeature from '@/components/dashboard/dashboard-feature';
export default function Page() {
return <DashboardFeature />;
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/clusters/page.tsx
|
import ClusterFeature from '@/components/cluster/cluster-feature';
export default function Page() {
return <ClusterFeature />;
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/api
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/api/vote/route.ts
|
import { ActionGetResponse, ActionPostRequest, ACTIONS_CORS_HEADERS, createPostResponse } from "@solana/actions";
import { Connection, PublicKey, Transaction } from "@solana/web3.js";
import { Voting } from "@/../anchor/target/types/voting";
import { BN, Program } from "@coral-xyz/anchor";
const IDL = require('@/../anchor/target/idl/voting.json');
export const OPTIONS = GET;
export async function GET(request: Request) {
const actionMetdata: ActionGetResponse = {
icon: "https://zestfulkitchen.com/wp-content/uploads/2021/09/Peanut-butter_hero_for-web-2.jpg",
title: "Vote for your favorite type of peanut butter!",
description: "Vote between crunchy and smooth peanut butter.",
label: "Vote",
links: {
actions: [
{
label: "Vote for Crunchy",
href: "/api/vote?candidate=Crunchy",
},
{
label: "Vote for Smooth",
href: "/api/vote?candidate=Smooth",
}
]
}
};
return Response.json(actionMetdata, { headers: ACTIONS_CORS_HEADERS});
}
export async function POST(request: Request) {
const url = new URL(request.url);
const candidate = url.searchParams.get("candidate");
if (candidate != "Crunchy" && candidate != "Smooth") {
return new Response("Invalid candidate", { status: 400, headers: ACTIONS_CORS_HEADERS });
}
const connection = new Connection("http://127.0.0.1:8899", "confirmed");
const program: Program<Voting> = new Program(IDL, {connection});
const body: ActionPostRequest = await request.json();
let voter;
try {
voter = new PublicKey(body.account);
} catch (error) {
return new Response("Invalid account", { status: 400, headers: ACTIONS_CORS_HEADERS });
}
const instruction = await program.methods
.vote(candidate, new BN(1))
.accounts({
signer: voter,
})
.instruction();
const blockhash = await connection.getLatestBlockhash();
const transaction = new Transaction({
feePayer: voter,
blockhash: blockhash.blockhash,
lastValidBlockHeight: blockhash.lastValidBlockHeight,
}).add(instruction);
const response = await createPostResponse({
fields: {
transaction: transaction
}
});
return Response.json(response, { headers: ACTIONS_CORS_HEADERS });
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/api
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/api/hello/route.ts
|
export async function GET(request: Request) {
return new Response('Hello, from API!');
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/counter/page.tsx
|
import CounterFeature from '@/components/counter/counter-feature';
export default function Page() {
return <CounterFeature />;
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/account/page.tsx
|
import AccountListFeature from '@/components/account/account-list-feature';
export default function Page() {
return <AccountListFeature />;
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/account
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/app/account/[address]/page.tsx
|
import AccountDetailFeature from '@/components/account/account-detail-feature';
export default function Page() {
return <AccountDetailFeature />;
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/ui/ui-layout.tsx
|
'use client';
import { WalletButton } from '../solana/solana-provider';
import * as React from 'react';
import { ReactNode, Suspense, useEffect, useRef } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { AccountChecker } from '../account/account-ui';
import {
ClusterChecker,
ClusterUiSelect,
ExplorerLink,
} from '../cluster/cluster-ui';
import toast, { Toaster } from 'react-hot-toast';
export function UiLayout({
children,
links,
}: {
children: ReactNode;
links: { label: string; path: string }[];
}) {
const pathname = usePathname();
return (
<div className="h-full flex flex-col">
<div className="navbar bg-base-300 text-neutral-content flex-col md:flex-row space-y-2 md:space-y-0">
<div className="flex-1">
<Link className="btn btn-ghost normal-case text-xl" href="/">
<img className="h-4 md:h-6" alt="Logo" src="/logo.png" />
</Link>
<ul className="menu menu-horizontal px-1 space-x-2">
{links.map(({ label, path }) => (
<li key={path}>
<Link
className={pathname.startsWith(path) ? 'active' : ''}
href={path}
>
{label}
</Link>
</li>
))}
</ul>
</div>
<div className="flex-none space-x-2">
<WalletButton />
<ClusterUiSelect />
</div>
</div>
<ClusterChecker>
<AccountChecker />
</ClusterChecker>
<div className="flex-grow mx-4 lg:mx-auto">
<Suspense
fallback={
<div className="text-center my-32">
<span className="loading loading-spinner loading-lg"></span>
</div>
}
>
{children}
</Suspense>
<Toaster position="bottom-right" />
</div>
<footer className="footer footer-center p-4 bg-base-300 text-base-content">
<aside>
<p>
Generated by{' '}
<a
className="link hover:text-white"
href="https://github.com/solana-developers/create-solana-dapp"
target="_blank"
rel="noopener noreferrer"
>
create-solana-dapp
</a>
</p>
</aside>
</footer>
</div>
);
}
export function AppModal({
children,
title,
hide,
show,
submit,
submitDisabled,
submitLabel,
}: {
children: ReactNode;
title: string;
hide: () => void;
show: boolean;
submit?: () => void;
submitDisabled?: boolean;
submitLabel?: string;
}) {
const dialogRef = useRef<HTMLDialogElement | null>(null);
useEffect(() => {
if (!dialogRef.current) return;
if (show) {
dialogRef.current.showModal();
} else {
dialogRef.current.close();
}
}, [show, dialogRef]);
return (
<dialog className="modal" ref={dialogRef}>
<div className="modal-box space-y-5">
<h3 className="font-bold text-lg">{title}</h3>
{children}
<div className="modal-action">
<div className="join space-x-2">
{submit ? (
<button
className="btn btn-xs lg:btn-md btn-primary"
onClick={submit}
disabled={submitDisabled}
>
{submitLabel || 'Save'}
</button>
) : null}
<button onClick={hide} className="btn">
Close
</button>
</div>
</div>
</div>
</dialog>
);
}
export function AppHero({
children,
title,
subtitle,
}: {
children?: ReactNode;
title: ReactNode;
subtitle: ReactNode;
}) {
return (
<div className="hero py-[64px]">
<div className="hero-content text-center">
<div className="max-w-2xl">
{typeof title === 'string' ? (
<h1 className="text-5xl font-bold">{title}</h1>
) : (
title
)}
{typeof subtitle === 'string' ? (
<p className="py-6">{subtitle}</p>
) : (
subtitle
)}
{children}
</div>
</div>
</div>
);
}
export function ellipsify(str = '', len = 4) {
if (str.length > 30) {
return (
str.substring(0, len) + '..' + str.substring(str.length - len, str.length)
);
}
return str;
}
export function useTransactionToast() {
return (signature: string) => {
toast.success(
<div className={'text-center'}>
<div className="text-lg">Transaction sent</div>
<ExplorerLink
path={`tx/${signature}`}
label={'View Transaction'}
className="btn btn-xs btn-primary"
/>
</div>
);
};
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/cluster/cluster-data-access.tsx
|
'use client';
import { clusterApiUrl, Connection } from '@solana/web3.js';
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import { createContext, ReactNode, useContext } from 'react';
import toast from 'react-hot-toast';
export interface Cluster {
name: string;
endpoint: string;
network?: ClusterNetwork;
active?: boolean;
}
export enum ClusterNetwork {
Mainnet = 'mainnet-beta',
Testnet = 'testnet',
Devnet = 'devnet',
Custom = 'custom',
}
// By default, we don't configure the mainnet-beta cluster
// The endpoint provided by clusterApiUrl('mainnet-beta') does not allow access from the browser due to CORS restrictions
// To use the mainnet-beta cluster, provide a custom endpoint
export const defaultClusters: Cluster[] = [
{
name: 'devnet',
endpoint: clusterApiUrl('devnet'),
network: ClusterNetwork.Devnet,
},
{ name: 'local', endpoint: 'http://localhost:8899' },
{
name: 'testnet',
endpoint: clusterApiUrl('testnet'),
network: ClusterNetwork.Testnet,
},
];
const clusterAtom = atomWithStorage<Cluster>(
'solana-cluster',
defaultClusters[0]
);
const clustersAtom = atomWithStorage<Cluster[]>(
'solana-clusters',
defaultClusters
);
const activeClustersAtom = atom<Cluster[]>((get) => {
const clusters = get(clustersAtom);
const cluster = get(clusterAtom);
return clusters.map((item) => ({
...item,
active: item.name === cluster.name,
}));
});
const activeClusterAtom = atom<Cluster>((get) => {
const clusters = get(activeClustersAtom);
return clusters.find((item) => item.active) || clusters[0];
});
export interface ClusterProviderContext {
cluster: Cluster;
clusters: Cluster[];
addCluster: (cluster: Cluster) => void;
deleteCluster: (cluster: Cluster) => void;
setCluster: (cluster: Cluster) => void;
getExplorerUrl(path: string): string;
}
const Context = createContext<ClusterProviderContext>(
{} as ClusterProviderContext
);
export function ClusterProvider({ children }: { children: ReactNode }) {
const cluster = useAtomValue(activeClusterAtom);
const clusters = useAtomValue(activeClustersAtom);
const setCluster = useSetAtom(clusterAtom);
const setClusters = useSetAtom(clustersAtom);
const value: ClusterProviderContext = {
cluster,
clusters: clusters.sort((a, b) => (a.name > b.name ? 1 : -1)),
addCluster: (cluster: Cluster) => {
try {
new Connection(cluster.endpoint);
setClusters([...clusters, cluster]);
} catch (err) {
toast.error(`${err}`);
}
},
deleteCluster: (cluster: Cluster) => {
setClusters(clusters.filter((item) => item.name !== cluster.name));
},
setCluster: (cluster: Cluster) => setCluster(cluster),
getExplorerUrl: (path: string) =>
`https://explorer.solana.com/${path}${getClusterUrlParam(cluster)}`,
};
return <Context.Provider value={value}>{children}</Context.Provider>;
}
export function useCluster() {
return useContext(Context);
}
function getClusterUrlParam(cluster: Cluster): string {
let suffix = '';
switch (cluster.network) {
case ClusterNetwork.Devnet:
suffix = 'devnet';
break;
case ClusterNetwork.Mainnet:
suffix = '';
break;
case ClusterNetwork.Testnet:
suffix = 'testnet';
break;
default:
suffix = `custom&customUrl=${encodeURIComponent(cluster.endpoint)}`;
break;
}
return suffix.length ? `?cluster=${suffix}` : '';
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/cluster/cluster-ui.tsx
|
'use client';
import { useConnection } from '@solana/wallet-adapter-react';
import { IconTrash } from '@tabler/icons-react';
import { useQuery } from '@tanstack/react-query';
import { ReactNode, useState } from 'react';
import { AppModal } from '../ui/ui-layout';
import { ClusterNetwork, useCluster } from './cluster-data-access';
import { Connection } from '@solana/web3.js';
export function ExplorerLink({
path,
label,
className,
}: {
path: string;
label: string;
className?: string;
}) {
const { getExplorerUrl } = useCluster();
return (
<a
href={getExplorerUrl(path)}
target="_blank"
rel="noopener noreferrer"
className={className ? className : `link font-mono`}
>
{label}
</a>
);
}
export function ClusterChecker({ children }: { children: ReactNode }) {
const { cluster } = useCluster();
const { connection } = useConnection();
const query = useQuery({
queryKey: ['version', { cluster, endpoint: connection.rpcEndpoint }],
queryFn: () => connection.getVersion(),
retry: 1,
});
if (query.isLoading) {
return null;
}
if (query.isError || !query.data) {
return (
<div className="alert alert-warning text-warning-content/80 rounded-none flex justify-center">
<span>
Error connecting to cluster <strong>{cluster.name}</strong>
</span>
<button
className="btn btn-xs btn-neutral"
onClick={() => query.refetch()}
>
Refresh
</button>
</div>
);
}
return children;
}
export function ClusterUiSelect() {
const { clusters, setCluster, cluster } = useCluster();
return (
<div className="dropdown dropdown-end">
<label tabIndex={0} className="btn btn-primary rounded-btn">
{cluster.name}
</label>
<ul
tabIndex={0}
className="menu dropdown-content z-[1] p-2 shadow bg-base-100 rounded-box w-52 mt-4"
>
{clusters.map((item) => (
<li key={item.name}>
<button
className={`btn btn-sm ${
item.active ? 'btn-primary' : 'btn-ghost'
}`}
onClick={() => setCluster(item)}
>
{item.name}
</button>
</li>
))}
</ul>
</div>
);
}
export function ClusterUiModal({
hideModal,
show,
}: {
hideModal: () => void;
show: boolean;
}) {
const { addCluster } = useCluster();
const [name, setName] = useState('');
const [network, setNetwork] = useState<ClusterNetwork | undefined>();
const [endpoint, setEndpoint] = useState('');
return (
<AppModal
title={'Add Cluster'}
hide={hideModal}
show={show}
submit={() => {
try {
new Connection(endpoint);
if (name) {
addCluster({ name, network, endpoint });
hideModal();
} else {
console.log('Invalid cluster name');
}
} catch {
console.log('Invalid cluster endpoint');
}
}}
submitLabel="Save"
>
<input
type="text"
placeholder="Name"
className="input input-bordered w-full"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="text"
placeholder="Endpoint"
className="input input-bordered w-full"
value={endpoint}
onChange={(e) => setEndpoint(e.target.value)}
/>
<select
className="select select-bordered w-full"
value={network}
onChange={(e) => setNetwork(e.target.value as ClusterNetwork)}
>
<option value={undefined}>Select a network</option>
<option value={ClusterNetwork.Devnet}>Devnet</option>
<option value={ClusterNetwork.Testnet}>Testnet</option>
<option value={ClusterNetwork.Mainnet}>Mainnet</option>
</select>
</AppModal>
);
}
export function ClusterUiTable() {
const { clusters, setCluster, deleteCluster } = useCluster();
return (
<div className="overflow-x-auto">
<table className="table border-4 border-separate border-base-300">
<thead>
<tr>
<th>Name/ Network / Endpoint</th>
<th className="text-center">Actions</th>
</tr>
</thead>
<tbody>
{clusters.map((item) => (
<tr key={item.name} className={item?.active ? 'bg-base-200' : ''}>
<td className="space-y-2">
<div className="whitespace-nowrap space-x-2">
<span className="text-xl">
{item?.active ? (
item.name
) : (
<button
title="Select cluster"
className="link link-secondary"
onClick={() => setCluster(item)}
>
{item.name}
</button>
)}
</span>
</div>
<span className="text-xs">
Network: {item.network ?? 'custom'}
</span>
<div className="whitespace-nowrap text-gray-500 text-xs">
{item.endpoint}
</div>
</td>
<td className="space-x-2 whitespace-nowrap text-center">
<button
disabled={item?.active}
className="btn btn-xs btn-default btn-outline"
onClick={() => {
if (!window.confirm('Are you sure?')) return;
deleteCluster(item);
}}
>
<IconTrash size={16} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/cluster/cluster-feature.tsx
|
'use client';
import { useState } from 'react';
import { AppHero } from '../ui/ui-layout';
import { ClusterUiModal } from './cluster-ui';
import { ClusterUiTable } from './cluster-ui';
export default function ClusterFeature() {
const [showModal, setShowModal] = useState(false);
return (
<div>
<AppHero
title="Clusters"
subtitle="Manage and select your Solana clusters"
>
<ClusterUiModal
show={showModal}
hideModal={() => setShowModal(false)}
/>
<button
className="btn btn-xs lg:btn-md btn-primary"
onClick={() => setShowModal(true)}
>
Add Cluster
</button>
</AppHero>
<ClusterUiTable />
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/solana/solana-provider.tsx
|
'use client';
import dynamic from 'next/dynamic';
import { AnchorProvider } from '@coral-xyz/anchor';
import { WalletError } from '@solana/wallet-adapter-base';
import {
AnchorWallet,
useConnection,
useWallet,
ConnectionProvider,
WalletProvider,
} from '@solana/wallet-adapter-react';
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui';
import { ReactNode, useCallback, useMemo } from 'react';
import { useCluster } from '../cluster/cluster-data-access';
require('@solana/wallet-adapter-react-ui/styles.css');
export const WalletButton = dynamic(
async () =>
(await import('@solana/wallet-adapter-react-ui')).WalletMultiButton,
{ ssr: false }
);
export function SolanaProvider({ children }: { children: ReactNode }) {
const { cluster } = useCluster();
const endpoint = useMemo(() => cluster.endpoint, [cluster]);
const onError = useCallback((error: WalletError) => {
console.error(error);
}, []);
return (
<ConnectionProvider endpoint={endpoint}>
<WalletProvider wallets={[]} onError={onError} autoConnect={true}>
<WalletModalProvider>{children}</WalletModalProvider>
</WalletProvider>
</ConnectionProvider>
);
}
export function useAnchorProvider() {
const { connection } = useConnection();
const wallet = useWallet();
return new AnchorProvider(connection, wallet as AnchorWallet, {
commitment: 'confirmed',
});
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/dashboard/dashboard-feature.tsx
|
'use client';
import { AppHero } from '../ui/ui-layout';
const links: { label: string; href: string }[] = [
{ label: 'Solana Docs', href: 'https://docs.solana.com/' },
{ label: 'Solana Faucet', href: 'https://faucet.solana.com/' },
{ label: 'Solana Cookbook', href: 'https://solanacookbook.com/' },
{ label: 'Solana Stack Overflow', href: 'https://solana.stackexchange.com/' },
{
label: 'Solana Developers GitHub',
href: 'https://github.com/solana-developers/',
},
];
export default function DashboardFeature() {
return (
<div>
<AppHero title="gm" subtitle="Say hi to your new Solana dApp." />
<div className="max-w-xl mx-auto py-6 sm:px-6 lg:px-8 text-center">
<div className="space-y-2">
<p>Here are some helpful links to get you started.</p>
{links.map((link, index) => (
<div key={index}>
<a
href={link.href}
className="link"
target="_blank"
rel="noopener noreferrer"
>
{link.label}
</a>
</div>
))}
</div>
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/counter/counter-data-access.tsx
|
'use client';
import { getCounterProgram, getCounterProgramId } from '@voting-dapp/anchor';
import { Program } from '@coral-xyz/anchor';
import { useConnection } from '@solana/wallet-adapter-react';
import { Cluster, Keypair, PublicKey } from '@solana/web3.js';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
import toast from 'react-hot-toast';
import { useCluster } from '../cluster/cluster-data-access';
import { useAnchorProvider } from '../solana/solana-provider';
import { useTransactionToast } from '../ui/ui-layout';
export function useCounterProgram() {
const { connection } = useConnection();
const { cluster } = useCluster();
const transactionToast = useTransactionToast();
const provider = useAnchorProvider();
const programId = useMemo(
() => getCounterProgramId(cluster.network as Cluster),
[cluster]
);
const program = getCounterProgram(provider);
const accounts = useQuery({
queryKey: ['counter', 'all', { cluster }],
queryFn: () => program.account.counter.all(),
});
const getProgramAccount = useQuery({
queryKey: ['get-program-account', { cluster }],
queryFn: () => connection.getParsedAccountInfo(programId),
});
const initialize = useMutation({
mutationKey: ['counter', 'initialize', { cluster }],
mutationFn: (keypair: Keypair) =>
program.methods
.initialize()
.accounts({ counter: keypair.publicKey })
.signers([keypair])
.rpc(),
onSuccess: (signature) => {
transactionToast(signature);
return accounts.refetch();
},
onError: () => toast.error('Failed to initialize account'),
});
return {
program,
programId,
accounts,
getProgramAccount,
initialize,
};
}
export function useCounterProgramAccount({ account }: { account: PublicKey }) {
const { cluster } = useCluster();
const transactionToast = useTransactionToast();
const { program, accounts } = useCounterProgram();
const accountQuery = useQuery({
queryKey: ['counter', 'fetch', { cluster, account }],
queryFn: () => program.account.counter.fetch(account),
});
const closeMutation = useMutation({
mutationKey: ['counter', 'close', { cluster, account }],
mutationFn: () =>
program.methods.close().accounts({ counter: account }).rpc(),
onSuccess: (tx) => {
transactionToast(tx);
return accounts.refetch();
},
});
const decrementMutation = useMutation({
mutationKey: ['counter', 'decrement', { cluster, account }],
mutationFn: () =>
program.methods.decrement().accounts({ counter: account }).rpc(),
onSuccess: (tx) => {
transactionToast(tx);
return accountQuery.refetch();
},
});
const incrementMutation = useMutation({
mutationKey: ['counter', 'increment', { cluster, account }],
mutationFn: () =>
program.methods.increment().accounts({ counter: account }).rpc(),
onSuccess: (tx) => {
transactionToast(tx);
return accountQuery.refetch();
},
});
const setMutation = useMutation({
mutationKey: ['counter', 'set', { cluster, account }],
mutationFn: (value: number) =>
program.methods.set(value).accounts({ counter: account }).rpc(),
onSuccess: (tx) => {
transactionToast(tx);
return accountQuery.refetch();
},
});
return {
accountQuery,
closeMutation,
decrementMutation,
incrementMutation,
setMutation,
};
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/counter/counter-feature.tsx
|
'use client';
import { useWallet } from '@solana/wallet-adapter-react';
import { WalletButton } from '../solana/solana-provider';
import { AppHero, ellipsify } from '../ui/ui-layout';
import { ExplorerLink } from '../cluster/cluster-ui';
import { useCounterProgram } from './counter-data-access';
import { CounterCreate, CounterList } from './counter-ui';
export default function CounterFeature() {
const { publicKey } = useWallet();
const { programId } = useCounterProgram();
return publicKey ? (
<div>
<AppHero
title="Counter"
subtitle={
'Create a new account by clicking the "Create" button. The state of a account is stored on-chain and can be manipulated by calling the program\'s methods (increment, decrement, set, and close).'
}
>
<p className="mb-6">
<ExplorerLink
path={`account/${programId}`}
label={ellipsify(programId.toString())}
/>
</p>
<CounterCreate />
</AppHero>
<CounterList />
</div>
) : (
<div className="max-w-4xl mx-auto">
<div className="hero py-[64px]">
<div className="hero-content text-center">
<WalletButton />
</div>
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/counter/counter-ui.tsx
|
'use client';
import { Keypair, PublicKey } from '@solana/web3.js';
import { useMemo } from 'react';
import { ellipsify } from '../ui/ui-layout';
import { ExplorerLink } from '../cluster/cluster-ui';
import {
useCounterProgram,
useCounterProgramAccount,
} from './counter-data-access';
export function CounterCreate() {
const { initialize } = useCounterProgram();
return (
<button
className="btn btn-xs lg:btn-md btn-primary"
onClick={() => initialize.mutateAsync(Keypair.generate())}
disabled={initialize.isPending}
>
Create {initialize.isPending && '...'}
</button>
);
}
export function CounterList() {
const { accounts, getProgramAccount } = useCounterProgram();
if (getProgramAccount.isLoading) {
return <span className="loading loading-spinner loading-lg"></span>;
}
if (!getProgramAccount.data?.value) {
return (
<div className="alert alert-info flex justify-center">
<span>
Program account not found. Make sure you have deployed the program and
are on the correct cluster.
</span>
</div>
);
}
return (
<div className={'space-y-6'}>
{accounts.isLoading ? (
<span className="loading loading-spinner loading-lg"></span>
) : accounts.data?.length ? (
<div className="grid md:grid-cols-2 gap-4">
{accounts.data?.map((account) => (
<CounterCard
key={account.publicKey.toString()}
account={account.publicKey}
/>
))}
</div>
) : (
<div className="text-center">
<h2 className={'text-2xl'}>No accounts</h2>
No accounts found. Create one above to get started.
</div>
)}
</div>
);
}
function CounterCard({ account }: { account: PublicKey }) {
const {
accountQuery,
incrementMutation,
setMutation,
decrementMutation,
closeMutation,
} = useCounterProgramAccount({ account });
const count = useMemo(
() => accountQuery.data?.count ?? 0,
[accountQuery.data?.count]
);
return accountQuery.isLoading ? (
<span className="loading loading-spinner loading-lg"></span>
) : (
<div className="card card-bordered border-base-300 border-4 text-neutral-content">
<div className="card-body items-center text-center">
<div className="space-y-6">
<h2
className="card-title justify-center text-3xl cursor-pointer"
onClick={() => accountQuery.refetch()}
>
{count}
</h2>
<div className="card-actions justify-around">
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => incrementMutation.mutateAsync()}
disabled={incrementMutation.isPending}
>
Increment
</button>
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => {
const value = window.prompt(
'Set value to:',
count.toString() ?? '0'
);
if (
!value ||
parseInt(value) === count ||
isNaN(parseInt(value))
) {
return;
}
return setMutation.mutateAsync(parseInt(value));
}}
disabled={setMutation.isPending}
>
Set
</button>
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => decrementMutation.mutateAsync()}
disabled={decrementMutation.isPending}
>
Decrement
</button>
</div>
<div className="text-center space-y-4">
<p>
<ExplorerLink
path={`account/${account}`}
label={ellipsify(account.toString())}
/>
</p>
<button
className="btn btn-xs btn-secondary btn-outline"
onClick={() => {
if (
!window.confirm(
'Are you sure you want to close this account?'
)
) {
return;
}
return closeMutation.mutateAsync();
}}
disabled={closeMutation.isPending}
>
Close
</button>
</div>
</div>
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/account/account-data-access.tsx
|
'use client';
import { useConnection, useWallet } from '@solana/wallet-adapter-react';
import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token';
import {
Connection,
LAMPORTS_PER_SOL,
PublicKey,
SystemProgram,
TransactionMessage,
TransactionSignature,
VersionedTransaction,
} from '@solana/web3.js';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { useTransactionToast } from '../ui/ui-layout';
export function useGetBalance({ address }: { address: PublicKey }) {
const { connection } = useConnection();
return useQuery({
queryKey: ['get-balance', { endpoint: connection.rpcEndpoint, address }],
queryFn: () => connection.getBalance(address),
});
}
export function useGetSignatures({ address }: { address: PublicKey }) {
const { connection } = useConnection();
return useQuery({
queryKey: ['get-signatures', { endpoint: connection.rpcEndpoint, address }],
queryFn: () => connection.getConfirmedSignaturesForAddress2(address),
});
}
export function useGetTokenAccounts({ address }: { address: PublicKey }) {
const { connection } = useConnection();
return useQuery({
queryKey: [
'get-token-accounts',
{ endpoint: connection.rpcEndpoint, address },
],
queryFn: async () => {
const [tokenAccounts, token2022Accounts] = await Promise.all([
connection.getParsedTokenAccountsByOwner(address, {
programId: TOKEN_PROGRAM_ID,
}),
connection.getParsedTokenAccountsByOwner(address, {
programId: TOKEN_2022_PROGRAM_ID,
}),
]);
return [...tokenAccounts.value, ...token2022Accounts.value];
},
});
}
export function useTransferSol({ address }: { address: PublicKey }) {
const { connection } = useConnection();
const transactionToast = useTransactionToast();
const wallet = useWallet();
const client = useQueryClient();
return useMutation({
mutationKey: [
'transfer-sol',
{ endpoint: connection.rpcEndpoint, address },
],
mutationFn: async (input: { destination: PublicKey; amount: number }) => {
let signature: TransactionSignature = '';
try {
const { transaction, latestBlockhash } = await createTransaction({
publicKey: address,
destination: input.destination,
amount: input.amount,
connection,
});
// Send transaction and await for signature
signature = await wallet.sendTransaction(transaction, connection);
// Send transaction and await for signature
await connection.confirmTransaction(
{ signature, ...latestBlockhash },
'confirmed'
);
console.log(signature);
return signature;
} catch (error: unknown) {
console.log('error', `Transaction failed! ${error}`, signature);
return;
}
},
onSuccess: (signature) => {
if (signature) {
transactionToast(signature);
}
return Promise.all([
client.invalidateQueries({
queryKey: [
'get-balance',
{ endpoint: connection.rpcEndpoint, address },
],
}),
client.invalidateQueries({
queryKey: [
'get-signatures',
{ endpoint: connection.rpcEndpoint, address },
],
}),
]);
},
onError: (error) => {
toast.error(`Transaction failed! ${error}`);
},
});
}
export function useRequestAirdrop({ address }: { address: PublicKey }) {
const { connection } = useConnection();
const transactionToast = useTransactionToast();
const client = useQueryClient();
return useMutation({
mutationKey: ['airdrop', { endpoint: connection.rpcEndpoint, address }],
mutationFn: async (amount: number = 1) => {
const [latestBlockhash, signature] = await Promise.all([
connection.getLatestBlockhash(),
connection.requestAirdrop(address, amount * LAMPORTS_PER_SOL),
]);
await connection.confirmTransaction(
{ signature, ...latestBlockhash },
'confirmed'
);
return signature;
},
onSuccess: (signature) => {
transactionToast(signature);
return Promise.all([
client.invalidateQueries({
queryKey: [
'get-balance',
{ endpoint: connection.rpcEndpoint, address },
],
}),
client.invalidateQueries({
queryKey: [
'get-signatures',
{ endpoint: connection.rpcEndpoint, address },
],
}),
]);
},
});
}
async function createTransaction({
publicKey,
destination,
amount,
connection,
}: {
publicKey: PublicKey;
destination: PublicKey;
amount: number;
connection: Connection;
}): Promise<{
transaction: VersionedTransaction;
latestBlockhash: { blockhash: string; lastValidBlockHeight: number };
}> {
// Get the latest blockhash to use in our transaction
const latestBlockhash = await connection.getLatestBlockhash();
// Create instructions to send, in this case a simple transfer
const instructions = [
SystemProgram.transfer({
fromPubkey: publicKey,
toPubkey: destination,
lamports: amount * LAMPORTS_PER_SOL,
}),
];
// Create a new TransactionMessage with version and compile it to legacy
const messageLegacy = new TransactionMessage({
payerKey: publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions,
}).compileToLegacyMessage();
// Create a new VersionedTransaction which supports legacy and v0
const transaction = new VersionedTransaction(messageLegacy);
return {
transaction,
latestBlockhash,
};
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/account/account-ui.tsx
|
'use client';
import { useWallet } from '@solana/wallet-adapter-react';
import { LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';
import { IconRefresh } from '@tabler/icons-react';
import { useQueryClient } from '@tanstack/react-query';
import { useMemo, useState } from 'react';
import { AppModal, ellipsify } from '../ui/ui-layout';
import { useCluster } from '../cluster/cluster-data-access';
import { ExplorerLink } from '../cluster/cluster-ui';
import {
useGetBalance,
useGetSignatures,
useGetTokenAccounts,
useRequestAirdrop,
useTransferSol,
} from './account-data-access';
export function AccountBalance({ address }: { address: PublicKey }) {
const query = useGetBalance({ address });
return (
<div>
<h1
className="text-5xl font-bold cursor-pointer"
onClick={() => query.refetch()}
>
{query.data ? <BalanceSol balance={query.data} /> : '...'} SOL
</h1>
</div>
);
}
export function AccountChecker() {
const { publicKey } = useWallet();
if (!publicKey) {
return null;
}
return <AccountBalanceCheck address={publicKey} />;
}
export function AccountBalanceCheck({ address }: { address: PublicKey }) {
const { cluster } = useCluster();
const mutation = useRequestAirdrop({ address });
const query = useGetBalance({ address });
if (query.isLoading) {
return null;
}
if (query.isError || !query.data) {
return (
<div className="alert alert-warning text-warning-content/80 rounded-none flex justify-center">
<span>
You are connected to <strong>{cluster.name}</strong> but your account
is not found on this cluster.
</span>
<button
className="btn btn-xs btn-neutral"
onClick={() =>
mutation.mutateAsync(1).catch((err) => console.log(err))
}
>
Request Airdrop
</button>
</div>
);
}
return null;
}
export function AccountButtons({ address }: { address: PublicKey }) {
const wallet = useWallet();
const { cluster } = useCluster();
const [showAirdropModal, setShowAirdropModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showSendModal, setShowSendModal] = useState(false);
return (
<div>
<ModalAirdrop
hide={() => setShowAirdropModal(false)}
address={address}
show={showAirdropModal}
/>
<ModalReceive
address={address}
show={showReceiveModal}
hide={() => setShowReceiveModal(false)}
/>
<ModalSend
address={address}
show={showSendModal}
hide={() => setShowSendModal(false)}
/>
<div className="space-x-2">
<button
disabled={cluster.network?.includes('mainnet')}
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => setShowAirdropModal(true)}
>
Airdrop
</button>
<button
disabled={wallet.publicKey?.toString() !== address.toString()}
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => setShowSendModal(true)}
>
Send
</button>
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => setShowReceiveModal(true)}
>
Receive
</button>
</div>
</div>
);
}
export function AccountTokens({ address }: { address: PublicKey }) {
const [showAll, setShowAll] = useState(false);
const query = useGetTokenAccounts({ address });
const client = useQueryClient();
const items = useMemo(() => {
if (showAll) return query.data;
return query.data?.slice(0, 5);
}, [query.data, showAll]);
return (
<div className="space-y-2">
<div className="justify-between">
<div className="flex justify-between">
<h2 className="text-2xl font-bold">Token Accounts</h2>
<div className="space-x-2">
{query.isLoading ? (
<span className="loading loading-spinner"></span>
) : (
<button
className="btn btn-sm btn-outline"
onClick={async () => {
await query.refetch();
await client.invalidateQueries({
queryKey: ['getTokenAccountBalance'],
});
}}
>
<IconRefresh size={16} />
</button>
)}
</div>
</div>
</div>
{query.isError && (
<pre className="alert alert-error">
Error: {query.error?.message.toString()}
</pre>
)}
{query.isSuccess && (
<div>
{query.data.length === 0 ? (
<div>No token accounts found.</div>
) : (
<table className="table border-4 rounded-lg border-separate border-base-300">
<thead>
<tr>
<th>Public Key</th>
<th>Mint</th>
<th className="text-right">Balance</th>
</tr>
</thead>
<tbody>
{items?.map(({ account, pubkey }) => (
<tr key={pubkey.toString()}>
<td>
<div className="flex space-x-2">
<span className="font-mono">
<ExplorerLink
label={ellipsify(pubkey.toString())}
path={`account/${pubkey.toString()}`}
/>
</span>
</div>
</td>
<td>
<div className="flex space-x-2">
<span className="font-mono">
<ExplorerLink
label={ellipsify(account.data.parsed.info.mint)}
path={`account/${account.data.parsed.info.mint.toString()}`}
/>
</span>
</div>
</td>
<td className="text-right">
<span className="font-mono">
{account.data.parsed.info.tokenAmount.uiAmount}
</span>
</td>
</tr>
))}
{(query.data?.length ?? 0) > 5 && (
<tr>
<td colSpan={4} className="text-center">
<button
className="btn btn-xs btn-outline"
onClick={() => setShowAll(!showAll)}
>
{showAll ? 'Show Less' : 'Show All'}
</button>
</td>
</tr>
)}
</tbody>
</table>
)}
</div>
)}
</div>
);
}
export function AccountTransactions({ address }: { address: PublicKey }) {
const query = useGetSignatures({ address });
const [showAll, setShowAll] = useState(false);
const items = useMemo(() => {
if (showAll) return query.data;
return query.data?.slice(0, 5);
}, [query.data, showAll]);
return (
<div className="space-y-2">
<div className="flex justify-between">
<h2 className="text-2xl font-bold">Transaction History</h2>
<div className="space-x-2">
{query.isLoading ? (
<span className="loading loading-spinner"></span>
) : (
<button
className="btn btn-sm btn-outline"
onClick={() => query.refetch()}
>
<IconRefresh size={16} />
</button>
)}
</div>
</div>
{query.isError && (
<pre className="alert alert-error">
Error: {query.error?.message.toString()}
</pre>
)}
{query.isSuccess && (
<div>
{query.data.length === 0 ? (
<div>No transactions found.</div>
) : (
<table className="table border-4 rounded-lg border-separate border-base-300">
<thead>
<tr>
<th>Signature</th>
<th className="text-right">Slot</th>
<th>Block Time</th>
<th className="text-right">Status</th>
</tr>
</thead>
<tbody>
{items?.map((item) => (
<tr key={item.signature}>
<th className="font-mono">
<ExplorerLink
path={`tx/${item.signature}`}
label={ellipsify(item.signature, 8)}
/>
</th>
<td className="font-mono text-right">
<ExplorerLink
path={`block/${item.slot}`}
label={item.slot.toString()}
/>
</td>
<td>
{new Date((item.blockTime ?? 0) * 1000).toISOString()}
</td>
<td className="text-right">
{item.err ? (
<div
className="badge badge-error"
title={JSON.stringify(item.err)}
>
Failed
</div>
) : (
<div className="badge badge-success">Success</div>
)}
</td>
</tr>
))}
{(query.data?.length ?? 0) > 5 && (
<tr>
<td colSpan={4} className="text-center">
<button
className="btn btn-xs btn-outline"
onClick={() => setShowAll(!showAll)}
>
{showAll ? 'Show Less' : 'Show All'}
</button>
</td>
</tr>
)}
</tbody>
</table>
)}
</div>
)}
</div>
);
}
function BalanceSol({ balance }: { balance: number }) {
return (
<span>{Math.round((balance / LAMPORTS_PER_SOL) * 100000) / 100000}</span>
);
}
function ModalReceive({
hide,
show,
address,
}: {
hide: () => void;
show: boolean;
address: PublicKey;
}) {
return (
<AppModal title="Receive" hide={hide} show={show}>
<p>Receive assets by sending them to your public key:</p>
<code>{address.toString()}</code>
</AppModal>
);
}
function ModalAirdrop({
hide,
show,
address,
}: {
hide: () => void;
show: boolean;
address: PublicKey;
}) {
const mutation = useRequestAirdrop({ address });
const [amount, setAmount] = useState('2');
return (
<AppModal
hide={hide}
show={show}
title="Airdrop"
submitDisabled={!amount || mutation.isPending}
submitLabel="Request Airdrop"
submit={() => mutation.mutateAsync(parseFloat(amount)).then(() => hide())}
>
<input
disabled={mutation.isPending}
type="number"
step="any"
min="1"
placeholder="Amount"
className="input input-bordered w-full"
value={amount}
onChange={(e) => setAmount(e.target.value)}
/>
</AppModal>
);
}
function ModalSend({
hide,
show,
address,
}: {
hide: () => void;
show: boolean;
address: PublicKey;
}) {
const wallet = useWallet();
const mutation = useTransferSol({ address });
const [destination, setDestination] = useState('');
const [amount, setAmount] = useState('1');
if (!address || !wallet.sendTransaction) {
return <div>Wallet not connected</div>;
}
return (
<AppModal
hide={hide}
show={show}
title="Send"
submitDisabled={!destination || !amount || mutation.isPending}
submitLabel="Send"
submit={() => {
mutation
.mutateAsync({
destination: new PublicKey(destination),
amount: parseFloat(amount),
})
.then(() => hide());
}}
>
<input
disabled={mutation.isPending}
type="text"
placeholder="Destination"
className="input input-bordered w-full"
value={destination}
onChange={(e) => setDestination(e.target.value)}
/>
<input
disabled={mutation.isPending}
type="number"
step="any"
min="1"
placeholder="Amount"
className="input input-bordered w-full"
value={amount}
onChange={(e) => setAmount(e.target.value)}
/>
</AppModal>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/account/account-detail-feature.tsx
|
'use client';
import { PublicKey } from '@solana/web3.js';
import { useMemo } from 'react';
import { useParams } from 'next/navigation';
import { ExplorerLink } from '../cluster/cluster-ui';
import { AppHero, ellipsify } from '../ui/ui-layout';
import {
AccountBalance,
AccountButtons,
AccountTokens,
AccountTransactions,
} from './account-ui';
export default function AccountDetailFeature() {
const params = useParams();
const address = useMemo(() => {
if (!params.address) {
return;
}
try {
return new PublicKey(params.address);
} catch (e) {
console.log(`Invalid public key`, e);
}
}, [params]);
if (!address) {
return <div>Error loading account</div>;
}
return (
<div>
<AppHero
title={<AccountBalance address={address} />}
subtitle={
<div className="my-4">
<ExplorerLink
path={`account/${address}`}
label={ellipsify(address.toString())}
/>
</div>
}
>
<div className="my-4">
<AccountButtons address={address} />
</div>
</AppHero>
<div className="space-y-8">
<AccountTokens address={address} />
<AccountTransactions address={address} />
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/web/components/account/account-list-feature.tsx
|
'use client';
import { useWallet } from '@solana/wallet-adapter-react';
import { WalletButton } from '../solana/solana-provider';
import { redirect } from 'next/navigation';
export default function AccountListFeature() {
const { publicKey } = useWallet();
if (publicKey) {
return redirect(`/account/${publicKey.toString()}`);
}
return (
<div className="hero py-[64px]">
<div className="hero-content text-center">
<WalletButton />
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/Cargo.toml
|
[workspace]
members = ["programs/*"]
resolver = "2"
[profile.release]
overflow-checks = true
lto = "fat"
codegen-units = 1
[profile.release.build-override]
opt-level = 3
incremental = false
codegen-units = 1
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/project.json
|
{
"name": "anchor",
"$schema": "../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "anchor/src",
"projectType": "library",
"tags": [],
"targets": {
"build": {
"executor": "@nx/rollup:rollup",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/anchor",
"main": "anchor/src/index.ts",
"tsConfig": "anchor/tsconfig.lib.json",
"assets": [],
"project": "anchor/package.json",
"compiler": "swc",
"format": ["cjs", "esm"]
}
},
"lint": {
"executor": "@nx/eslint:lint"
},
"test": {
"executor": "nx:run-commands",
"options": {
"cwd": "anchor",
"commands": ["anchor test"],
"parallel": false
}
},
"anchor": {
"executor": "nx:run-commands",
"options": {
"cwd": "anchor",
"commands": ["anchor"],
"parallel": false
}
},
"localnet": {
"executor": "nx:run-commands",
"options": {
"cwd": "anchor",
"commands": ["anchor localnet"],
"parallel": false
}
},
"jest": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "anchor/jest.config.ts"
}
}
}
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/.swcrc
|
{
"jsc": {
"target": "es2017",
"parser": {
"syntax": "typescript",
"decorators": true,
"dynamicImport": true
},
"transform": {
"decoratorMetadata": true,
"legacyDecorator": true
},
"keepClassNames": true,
"externalHelpers": true,
"loose": true
},
"module": {
"type": "es6"
},
"sourceMaps": true,
"exclude": [
"jest.config.ts",
".*\\.spec.tsx?$",
".*\\.test.tsx?$",
"./src/jest-setup.ts$",
"./**/jest-setup.ts$",
".*.js$"
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/Anchor.toml
|
[toolchain]
[features]
seeds = false
skip-lint = false
[programs.localnet]
voting = "6RMzzoy8iRv9a6ATQbxva3p5GCLFtBukjVN195aBNmQ8"
[registry]
url = "https://api.apr.dev"
[provider]
cluster = "Localnet"
wallet = "~/.config/solana/id.json"
[scripts]
test = "../node_modules/.bin/nx run anchor:jest"
[test]
startup_wait = 5000
shutdown_wait = 2000
upgradeable = false
[test.validator]
bind_address = "127.0.0.1"
ledger = ".anchor/test-ledger"
rpc_port = 8899
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/package.json
|
{
"name": "@voting-dapp/anchor",
"version": "0.0.1",
"dependencies": {
"@coral-xyz/anchor": "^0.30.0",
"@solana/web3.js": "1.91.9",
"anchor-bankrun": "^0.4.0",
"solana-bankrun": "^0.2.0"
},
"main": "./index.cjs",
"module": "./index.js",
"private": true
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/tsconfig.json
|
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"module": "commonjs"
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/tsconfig.lib.json
|
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../dist/out-tsc",
"declaration": true,
"types": ["node"],
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true
},
"include": ["src/**/*.ts"],
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/.eslintrc.json
|
{
"extends": ["../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.json"],
"parser": "jsonc-eslint-parser",
"rules": {
"@nx/dependency-checks": [
"error",
{
"ignoredFiles": ["{projectRoot}/rollup.config.{js,ts,mjs,mts}"]
}
]
}
}
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/tsconfig.spec.json
|
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/jest.config.ts
|
/* eslint-disable */
import { readFileSync } from 'fs';
// Reading the SWC compilation config and remove the "exclude"
// for the test files to be compiled by SWC
const { exclude: _, ...swcJestConfig } = JSON.parse(
readFileSync(`${__dirname}/.swcrc`, 'utf-8')
);
// disable .swcrc look-up by SWC core because we're passing in swcJestConfig ourselves.
// If we do not disable this, SWC Core will read .swcrc and won't transform our test files due to "exclude"
if (swcJestConfig.swcrc === undefined) {
swcJestConfig.swcrc = false;
}
// Uncomment if using global setup/teardown files being transformed via swc
// https://nx.dev/packages/jest/documents/overview#global-setup/teardown-with-nx-libraries
// jest needs EsModule Interop to find the default exported setup/teardown functions
// swcJestConfig.module.noInterop = false;
export default {
displayName: 'anchor',
preset: '../jest.preset.js',
transform: {
'^.+\\.[tj]s$': ['@swc/jest', swcJestConfig],
},
moduleFileExtensions: ['ts', 'js', 'html'],
testEnvironment: '',
coverageDirectory: '../coverage/anchor',
};
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/migrations/deploy.ts
|
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.
import * as anchor from '@coral-xyz/anchor';
module.exports = async function (provider) {
// Configure client to use the provider.
anchor.setProvider(provider);
// Add your deploy script here.
};
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/tests/voting.spec.ts
|
import { PartialAccounts } from './../node_modules/@coral-xyz/anchor/dist/cjs/program/namespace/methods.d';
import * as anchor from '@coral-xyz/anchor';
import { Program } from '@coral-xyz/anchor';
import { Keypair, PublicKey, SystemProgram } from '@solana/web3.js';
import { Voting } from '../target/types/voting';
import { startAnchor } from "solana-bankrun";
import { BankrunProvider } from "anchor-bankrun";
const IDL = require('../target/idl/voting.json');
const votingAddress = new PublicKey("6RMzzoy8iRv9a6ATQbxva3p5GCLFtBukjVN195aBNmQ8");
describe('Voting', () => {
let context;
let provider;
let votingProgram;
//anchor.setProvider(anchor.AnchorProvider.env());
//let votingProgram = anchor.workspace.Voting as Program<Voting>;
beforeAll(async () => {
context = await startAnchor("", [{name: "voting", programId: votingAddress}], []);
provider = new BankrunProvider(context);
votingProgram = new Program<Voting>(
IDL,
provider,
);
})
it('Initialize Poll', async () => {
await votingProgram.methods.initializePoll(
new anchor.BN(1),
"What is your favorite type of peanut butter?",
new anchor.BN(0),
new anchor.BN(1821246480),
).rpc();
const [pollAddress] = PublicKey.findProgramAddressSync(
[new anchor.BN(1).toArrayLike(Buffer, 'le', 8)],
votingAddress,
)
const poll = await votingProgram.account.poll.fetch(pollAddress);
console.log(poll);
expect(poll.pollId.toNumber()).toEqual(1);
expect(poll.description).toEqual("What is your favorite type of peanut butter?");
expect(poll.pollStart.toNumber()).toBeLessThan(poll.pollEnd.toNumber());
});
it("initialize candidate", async() => {
await votingProgram.methods.initializeCandidate(
"Smooth",
new anchor.BN(1),
).rpc();
await votingProgram.methods.initializeCandidate(
"Crunchy",
new anchor.BN(1),
).rpc();
const [crunchyAddress] = PublicKey.findProgramAddressSync(
[new anchor.BN(1).toArrayLike(Buffer, 'le', 8), Buffer.from("Crunchy")],
votingAddress,
);
const crunchyCandidate = await votingProgram.account.candidate.fetch(crunchyAddress);
console.log(crunchyCandidate);
expect(crunchyCandidate.candidateVotes.toNumber()).toEqual(0);
const [smoothAddress] = PublicKey.findProgramAddressSync(
[new anchor.BN(1).toArrayLike(Buffer, 'le', 8), Buffer.from("Smooth")],
votingAddress,
);
const smoothCandidate = await votingProgram.account.candidate.fetch(smoothAddress);
console.log(smoothCandidate);
expect(smoothCandidate.candidateVotes.toNumber()).toEqual(0);
});
it("vote", async() => {
await votingProgram.methods
.vote(
"Smooth",
new anchor.BN(1)
).rpc()
const [smoothAddress] = PublicKey.findProgramAddressSync(
[new anchor.BN(1).toArrayLike(Buffer, 'le', 8), Buffer.from("Smooth")],
votingAddress,
);
const smoothCandidate = await votingProgram.account.candidate.fetch(smoothAddress);
console.log(smoothCandidate);
expect(smoothCandidate.candidateVotes.toNumber()).toEqual(1);
});
});
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/programs
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/programs/voting/Cargo.toml
|
[package]
name = "voting"
version = "0.1.0"
description = "Created with Anchor"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
name = "voting"
[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
default = []
idl-build = ["anchor-lang/idl-build"]
[dependencies]
anchor-lang = "0.30.1"
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/programs
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/programs/voting/Xargo.toml
|
[target.bpfel-unknown-unknown.dependencies.std]
features = []
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/programs/voting
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/programs/voting/src/lib.rs
|
#![allow(clippy::result_large_err)]
use anchor_lang::prelude::*;
declare_id!("6RMzzoy8iRv9a6ATQbxva3p5GCLFtBukjVN195aBNmQ8");
#[program]
pub mod voting {
use super::*;
pub fn initialize_poll(ctx: Context<InitializePoll>,
poll_id: u64,
description: String,
poll_start: u64,
poll_end: u64) -> Result<()> {
let poll = &mut ctx.accounts.poll;
poll.poll_id = poll_id;
poll.description = description;
poll.poll_start = poll_start;
poll.poll_end = poll_end;
poll.candidate_amount = 0;
Ok(())
}
pub fn initialize_candidate(ctx: Context<InitializeCandidate>,
candidate_name: String,
_poll_id: u64) -> Result<()> {
let candidate = &mut ctx.accounts.candidate;
let poll = &mut ctx.accounts.poll;
poll.candidate_amount += 1;
candidate.candidate_name = candidate_name;
candidate.candidate_votes = 0;
Ok(())
}
pub fn vote(ctx: Context<Vote>, _candidate_name: String, _poll_id: u64) -> Result<()> {
let candidate = &mut ctx.accounts.candidate;
candidate.candidate_votes += 1;
msg!("Voted for candidate: {}", candidate.candidate_name);
msg!("Votes: {}", candidate.candidate_votes);
Ok(())
}
}
#[derive(Accounts)]
#[instruction(candidate_name: String, poll_id: u64)]
pub struct Vote<'info> {
pub signer: Signer<'info>,
#[account(
seeds = [poll_id.to_le_bytes().as_ref()],
bump
)]
pub poll: Account<'info, Poll>,
#[account(
mut,
seeds = [poll_id.to_le_bytes().as_ref(), candidate_name.as_bytes()],
bump
)]
pub candidate: Account<'info, Candidate>,
}
#[derive(Accounts)]
#[instruction(candidate_name: String, poll_id: u64)]
pub struct InitializeCandidate<'info> {
#[account(mut)]
pub signer: Signer<'info>,
#[account(
mut,
seeds = [poll_id.to_le_bytes().as_ref()],
bump
)]
pub poll: Account<'info, Poll>,
#[account(
init,
payer = signer,
space = 8 + Candidate::INIT_SPACE,
seeds = [poll_id.to_le_bytes().as_ref(), candidate_name.as_bytes()],
bump
)]
pub candidate: Account<'info, Candidate>,
pub system_program: Program<'info, System>,
}
#[account]
#[derive(InitSpace)]
pub struct Candidate {
#[max_len(32)]
pub candidate_name: String,
pub candidate_votes: u64,
}
#[derive(Accounts)]
#[instruction(poll_id: u64)]
pub struct InitializePoll<'info> {
#[account(mut)]
pub signer: Signer<'info>,
#[account(
init,
payer = signer,
space = 8 + Poll::INIT_SPACE,
seeds = [poll_id.to_le_bytes().as_ref()],
bump
)]
pub poll: Account<'info, Poll>,
pub system_program: Program<'info, System>,
}
#[account]
#[derive(InitSpace)]
pub struct Poll {
pub poll_id: u64,
#[max_len(280)]
pub description: String,
pub poll_start: u64,
pub poll_end: u64,
pub candidate_amount: u64,
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/src/index.ts
|
// This file was generated by preset-anchor. Programs are exported from this file.
export * from './counter-exports';
| 0
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor
|
solana_public_repos/developer-bootcamp-2024/project-3-blinks/anchor/src/counter-exports.ts
|
// Here we export some useful types and functions for interacting with the Anchor program.
import { AnchorProvider, Program } from '@coral-xyz/anchor';
import { Cluster, PublicKey } from '@solana/web3.js';
import CounterIDL from '../target/idl/counter.json';
import type { Counter } from '../target/types/counter';
// Re-export the generated IDL and type
export { Counter, CounterIDL };
// The programId is imported from the program IDL.
export const COUNTER_PROGRAM_ID = new PublicKey(CounterIDL.address);
// This is a helper function to get the Counter Anchor program.
export function getCounterProgram(provider: AnchorProvider) {
return new Program(CounterIDL as Counter, provider);
}
// This is a helper function to get the program ID for the Counter program depending on the cluster.
export function getCounterProgramId(cluster: Cluster) {
switch (cluster) {
case 'devnet':
case 'testnet':
// This is the program ID for the Counter program on devnet and testnet.
return new PublicKey('CounNZdmsQmWh7uVngV9FXW2dZ6zAgbJyYsvBpqbykg');
case 'mainnet-beta':
default:
return COUNTER_PROGRAM_ID;
}
}
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/jest.preset.js
|
const nxPreset = require('@nx/jest/preset').default;
module.exports = { ...nxPreset };
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/nx.json
|
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"defaultBase": "master",
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/.eslintrc.json",
"!{projectRoot}/eslint.config.js",
"!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/jest.config.[jt]s",
"!{projectRoot}/src/test-setup.[jt]s",
"!{projectRoot}/test-setup.[jt]s"
],
"sharedGlobals": []
},
"targetDefaults": {
"@nx/next:build": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
},
"@nx/eslint:lint": {
"cache": true,
"inputs": [
"default",
"{workspaceRoot}/.eslintrc.json",
"{workspaceRoot}/.eslintignore",
"{workspaceRoot}/eslint.config.js"
]
},
"@nx/rollup:rollup": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
},
"@nx/jest:jest": {
"cache": true,
"inputs": ["default", "^production", "{workspaceRoot}/jest.preset.js"],
"options": {
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
}
},
"generators": {
"@nx/next": {
"application": {
"style": "css",
"linter": "eslint"
}
}
}
}
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/LICENSE
|
MIT License
Copyright (c) 2024 jacobcreech
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.
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/vercel.json
|
{
"buildCommand": "npm run build",
"outputDirectory": "dist/web/.next"
}
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/tsconfig.base.json
|
{
"compileOnSave": false,
"compilerOptions": {
"rootDir": ".",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es2015",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"baseUrl": ".",
"paths": {
"@/*": ["./web/*"],
"@voting-dapp/anchor": ["anchor/src/index.ts"]
}
},
"exclude": ["node_modules", "tmp"]
}
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/package.json
|
{
"name": "@voting-dapp/source",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"anchor": "nx run anchor:anchor",
"anchor-build": "nx run anchor:anchor build",
"anchor-localnet": "nx run anchor:anchor localnet",
"anchor-test": "nx run anchor:anchor test",
"feature": "nx generate @solana-developers/preset-react:feature",
"build": "nx build web",
"dev": "nx serve web"
},
"private": true,
"dependencies": {
"@coral-xyz/anchor": "^0.30.0",
"@solana-developers/preset-next": "3.0.1",
"@solana/actions": "^1.2.0",
"@solana/spl-token": "0.4.6",
"@solana/wallet-adapter-base": "^0.9.23",
"@solana/wallet-adapter-react": "^0.15.35",
"@solana/wallet-adapter-react-ui": "^0.9.35",
"@solana/web3.js": "1.91.9",
"@tabler/icons-react": "3.5.0",
"@tailwindcss/typography": "0.5.13",
"@tanstack/react-query": "5.40.0",
"@tanstack/react-query-next-experimental": "5.40.0",
"bs58": "5.0.0",
"buffer": "6.0.3",
"daisyui": "4.11.1",
"encoding": "0.1.13",
"jotai": "2.8.3",
"next": "14.0.4",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-hot-toast": "2.4.1",
"tslib": "^2.3.0"
},
"devDependencies": {
"@nx/eslint": "19.0.0",
"@nx/eslint-plugin": "19.0.0",
"@nx/jest": "19.0.0",
"@nx/js": "19.0.0",
"@nx/next": "19.0.0",
"@nx/rollup": "19.0.0",
"@nx/workspace": "19.0.0",
"@swc-node/register": "~1.8.0",
"@swc/cli": "~0.3.12",
"@swc/core": "~1.3.85",
"@swc/helpers": "~0.5.2",
"@swc/jest": "0.2.20",
"@types/jest": "^29.4.0",
"@types/node": "18.16.9",
"@types/react": "18.3.1",
"@types/react-dom": "18.3.0",
"@typescript-eslint/eslint-plugin": "^7.3.0",
"@typescript-eslint/parser": "^7.3.0",
"autoprefixer": "10.4.13",
"eslint": "~8.57.0",
"eslint-config-next": "14.0.4",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-import": "2.27.5",
"eslint-plugin-jsx-a11y": "6.7.1",
"eslint-plugin-react": "7.32.2",
"eslint-plugin-react-hooks": "4.6.0",
"jest": "^29.4.1",
"jest-environment-jsdom": "^29.4.1",
"nx": "19.0.0",
"postcss": "8.4.21",
"prettier": "^2.6.2",
"tailwindcss": "3.2.7",
"ts-jest": "^29.1.0",
"ts-node": "10.9.1",
"typescript": "~5.4.2"
}
}
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/jest.config.ts
|
import { getJestProjectsAsync } from '@nx/jest';
export default async () => ({
projects: await getJestProjectsAsync(),
});
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/tailwind.config.js
|
const { createGlobPatternsForDependencies } = require('@nx/react/tailwind');
const { join } = require('path');
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
join(
__dirname,
'{src,pages,components,app}/**/*!(*.stories|*.spec).{ts,tsx,html}'
),
...createGlobPatternsForDependencies(__dirname),
],
theme: {
extend: {},
},
plugins: [require('daisyui')],
};
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/project.json
|
{
"name": "web",
"$schema": "../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "web",
"projectType": "application",
"tags": [],
"targets": {
"build": {
"executor": "@nx/next:build",
"outputs": ["{options.outputPath}"],
"defaultConfiguration": "production",
"options": {
"outputPath": "dist/web"
},
"configurations": {
"development": {
"outputPath": "web"
},
"production": {}
}
},
"serve": {
"executor": "@nx/next:server",
"defaultConfiguration": "development",
"options": {
"buildTarget": "web:build",
"dev": true,
"port": 3000
},
"configurations": {
"development": {
"buildTarget": "web:build:development",
"dev": true
},
"production": {
"buildTarget": "web:build:production",
"dev": false
}
}
},
"export": {
"executor": "@nx/next:export",
"options": {
"buildTarget": "web:build:production"
}
},
"lint": {
"executor": "@nx/eslint:lint"
}
}
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/next.config.js
|
//@ts-check
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { composePlugins, withNx } = require('@nx/next');
/**
* @type {import('@nx/next/plugins/with-nx').WithNxOptions}
**/
const nextConfig = {
webpack: (config) => {
config.externals = [
...(config.externals || []),
'bigint',
'node-gyp-build',
];
return config;
},
nx: {
// Set this to true if you would like to use SVGR
// See: https://github.com/gregberge/svgr
svgr: false,
},
};
const plugins = [
// Add more Next.js plugins to this list if needed.
withNx,
];
module.exports = composePlugins(...plugins)(nextConfig);
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/next-env.d.ts
|
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/tsconfig.json
|
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"jsx": "preserve",
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"resolveJsonModule": true,
"isolatedModules": true,
"incremental": true,
"plugins": [
{
"name": "next"
}
]
},
"include": [
"**/*.ts",
"**/*.tsx",
"**/*.js",
"**/*.jsx",
"../web/.next/types/**/*.ts",
"../dist/web/.next/types/**/*.ts",
"next-env.d.ts",
".next/types/**/*.ts"
],
"exclude": ["node_modules", "jest.config.ts", "**/*.spec.ts", "**/*.test.ts"]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/index.d.ts
|
/* eslint-disable @typescript-eslint/no-explicit-any */
declare module '*.svg' {
const content: any;
export const ReactComponent: any;
export default content;
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/postcss.config.js
|
const { join } = require('path');
// Note: If you use library-specific PostCSS/Tailwind configuration then you should remove the `postcssConfig` build
// option from your application's configuration (i.e. project.json).
//
// See: https://nx.dev/guides/using-tailwind-css-in-react#step-4:-applying-configuration-to-libraries
module.exports = {
plugins: {
tailwindcss: {
config: join(__dirname, 'tailwind.config.js'),
},
autoprefixer: {},
},
};
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/.eslintrc.json
|
{
"extends": [
"plugin:@nx/react-typescript",
"next",
"next/core-web-vitals",
"../.eslintrc.json"
],
"ignorePatterns": ["!**/*", ".next/**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {
"@next/next/no-html-link-for-pages": ["error", "web/pages"]
}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {
"@nx/enforce-module-boundaries": [
"error",
{
"allow": ["@/"]
}
]
}
}
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/app/react-query-provider.tsx
|
'use client';
import React, { ReactNode, useState } from 'react';
import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental';
import { QueryClientProvider, QueryClient } from '@tanstack/react-query';
export function ReactQueryProvider({ children }: { children: ReactNode }) {
const [client] = useState(new QueryClient());
return (
<QueryClientProvider client={client}>
<ReactQueryStreamedHydration>{children}</ReactQueryStreamedHydration>
</QueryClientProvider>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/app/global.css
|
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body {
height: 100%;
}
.wallet-adapter-button-trigger {
background: rgb(100, 26, 230) !important;
border-radius: 8px !important;
padding-left: 16px !important;
padding-right: 16px !important;
}
.wallet-adapter-dropdown-list,
.wallet-adapter-button {
font-family: inherit !important;
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/app/page.module.css
|
.page {
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/app/layout.tsx
|
import './global.css';
import { UiLayout } from '@/components/ui/ui-layout';
import { ClusterProvider } from '@/components/cluster/cluster-data-access';
import { SolanaProvider } from '@/components/solana/solana-provider';
import { ReactQueryProvider } from './react-query-provider';
export const metadata = {
title: 'voting-dapp',
description: 'Generated by create-solana-dapp',
};
const links: { label: string; path: string }[] = [
];
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<ReactQueryProvider>
<ClusterProvider>
<SolanaProvider>
<UiLayout links={links}>{children}</UiLayout>
</SolanaProvider>
</ClusterProvider>
</ReactQueryProvider>
</body>
</html>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/app/page.tsx
|
import VotingFeature from '@/components/voting/voting-feature';
export default function Page() {
return <VotingFeature />;
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/app/api
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/app/api/vote/route.ts
|
import { ActionGetResponse, ActionPostRequest, ACTIONS_CORS_HEADERS, createPostResponse } from "@solana/actions";
import { Connection, PublicKey, Transaction } from "@solana/web3.js";
import { Voting } from "@/../anchor/target/types/voting";
import { BN, Program } from "@coral-xyz/anchor";
const IDL = require('@/../anchor/target/idl/voting.json');
export const OPTIONS = GET;
export async function GET(request: Request) {
const actionMetdata: ActionGetResponse = {
icon: "https://zestfulkitchen.com/wp-content/uploads/2021/09/Peanut-butter_hero_for-web-2.jpg",
title: "Vote for your favorite type of peanut butter!",
description: "Vote between crunchy and smooth peanut butter.",
label: "Vote",
links: {
actions: [
{
label: "Vote for Crunchy",
href: "/api/vote?candidate=Crunchy",
},
{
label: "Vote for Smooth",
href: "/api/vote?candidate=Smooth",
}
]
}
};
return Response.json(actionMetdata, { headers: ACTIONS_CORS_HEADERS});
}
export async function POST(request: Request) {
const url = new URL(request.url);
const candidate = url.searchParams.get("candidate");
if (candidate != "Crunchy" && candidate != "Smooth") {
return new Response("Invalid candidate", { status: 400, headers: ACTIONS_CORS_HEADERS });
}
const connection = new Connection("http://127.0.0.1:8899", "confirmed");
const program: Program<Voting> = new Program(IDL, {connection});
const body: ActionPostRequest = await request.json();
let voter;
try {
voter = new PublicKey(body.account);
} catch (error) {
return new Response("Invalid account", { status: 400, headers: ACTIONS_CORS_HEADERS });
}
const instruction = await program.methods
.vote(candidate, new BN(1))
.accounts({
signer: voter,
})
.instruction();
const blockhash = await connection.getLatestBlockhash();
const transaction = new Transaction({
feePayer: voter,
blockhash: blockhash.blockhash,
lastValidBlockHeight: blockhash.lastValidBlockHeight,
}).add(instruction);
const response = await createPostResponse({
fields: {
transaction: transaction
}
});
return Response.json(response, { headers: ACTIONS_CORS_HEADERS });
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/app/api
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/app/api/hello/route.ts
|
export async function GET(request: Request) {
return new Response('Hello, from API!');
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/ui/ui-layout.tsx
|
'use client';
import { WalletButton } from '../solana/solana-provider';
import * as React from 'react';
import { ReactNode, Suspense, useEffect, useRef } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { AccountChecker } from '../account/account-ui';
import {
ClusterChecker,
ClusterUiSelect,
ExplorerLink,
} from '../cluster/cluster-ui';
import toast, { Toaster } from 'react-hot-toast';
export function UiLayout({
children,
links,
}: {
children: ReactNode;
links: { label: string; path: string }[];
}) {
const pathname = usePathname();
return (
<div className="h-full flex flex-col">
<div className="navbar bg-base-300 text-neutral-content flex-col md:flex-row space-y-2 md:space-y-0">
<div className="flex-1">
<Link className="btn btn-ghost normal-case text-xl" href="/">
<img className="h-4 md:h-6" alt="Logo" src="/logo.png" />
</Link>
<ul className="menu menu-horizontal px-1 space-x-2">
{links.map(({ label, path }) => (
<li key={path}>
<Link
className={pathname.startsWith(path) ? 'active' : ''}
href={path}
>
{label}
</Link>
</li>
))}
</ul>
</div>
<div className="flex-none space-x-2">
<WalletButton />
<ClusterUiSelect />
</div>
</div>
<ClusterChecker>
<AccountChecker />
</ClusterChecker>
<div className="flex-grow mx-4 lg:mx-auto">
<Suspense
fallback={
<div className="text-center my-32">
<span className="loading loading-spinner loading-lg"></span>
</div>
}
>
{children}
</Suspense>
<Toaster position="bottom-right" />
</div>
<footer className="footer footer-center p-4 bg-base-300 text-base-content">
<aside>
<p>
Generated by{' '}
<a
className="link hover:text-white"
href="https://github.com/solana-developers/create-solana-dapp"
target="_blank"
rel="noopener noreferrer"
>
create-solana-dapp
</a>
</p>
</aside>
</footer>
</div>
);
}
export function AppModal({
children,
title,
hide,
show,
submit,
submitDisabled,
submitLabel,
}: {
children: ReactNode;
title: string;
hide: () => void;
show: boolean;
submit?: () => void;
submitDisabled?: boolean;
submitLabel?: string;
}) {
const dialogRef = useRef<HTMLDialogElement | null>(null);
useEffect(() => {
if (!dialogRef.current) return;
if (show) {
dialogRef.current.showModal();
} else {
dialogRef.current.close();
}
}, [show, dialogRef]);
return (
<dialog className="modal" ref={dialogRef}>
<div className="modal-box space-y-5">
<h3 className="font-bold text-lg">{title}</h3>
{children}
<div className="modal-action">
<div className="join space-x-2">
{submit ? (
<button
className="btn btn-xs lg:btn-md btn-primary"
onClick={submit}
disabled={submitDisabled}
>
{submitLabel || 'Save'}
</button>
) : null}
<button onClick={hide} className="btn">
Close
</button>
</div>
</div>
</div>
</dialog>
);
}
export function AppHero({
children,
title,
subtitle,
}: {
children?: ReactNode;
title: ReactNode;
subtitle: ReactNode;
}) {
return (
<div className="hero py-[32px]">
<div className="hero-content text-center">
<div className="max-w-2xl">
{typeof title === 'string' ? (
<h1 className="text-5xl font-bold">{title}</h1>
) : (
title
)}
{typeof subtitle === 'string' ? (
<p className="py-6">{subtitle}</p>
) : (
subtitle
)}
{children}
</div>
</div>
</div>
);
}
export function ellipsify(str = '', len = 4) {
if (str.length > 30) {
return (
str.substring(0, len) + '..' + str.substring(str.length - len, str.length)
);
}
return str;
}
export function useTransactionToast() {
return (signature: string) => {
toast.success(
<div className={'text-center'}>
<div className="text-lg">Transaction sent</div>
<ExplorerLink
path={`tx/${signature}`}
label={'View Transaction'}
className="btn btn-xs btn-primary"
/>
</div>
);
};
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/cluster/cluster-data-access.tsx
|
'use client';
import { clusterApiUrl, Connection } from '@solana/web3.js';
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import { createContext, ReactNode, useContext } from 'react';
import toast from 'react-hot-toast';
export interface Cluster {
name: string;
endpoint: string;
network?: ClusterNetwork;
active?: boolean;
}
export enum ClusterNetwork {
Mainnet = 'mainnet-beta',
Testnet = 'testnet',
Devnet = 'devnet',
Custom = 'custom',
}
// By default, we don't configure the mainnet-beta cluster
// The endpoint provided by clusterApiUrl('mainnet-beta') does not allow access from the browser due to CORS restrictions
// To use the mainnet-beta cluster, provide a custom endpoint
export const defaultClusters: Cluster[] = [
{
name: 'devnet',
endpoint: clusterApiUrl('devnet'),
network: ClusterNetwork.Devnet,
},
{ name: 'local', endpoint: 'http://localhost:8899' },
{
name: 'testnet',
endpoint: clusterApiUrl('testnet'),
network: ClusterNetwork.Testnet,
},
];
const clusterAtom = atomWithStorage<Cluster>(
'solana-cluster',
defaultClusters[0]
);
const clustersAtom = atomWithStorage<Cluster[]>(
'solana-clusters',
defaultClusters
);
const activeClustersAtom = atom<Cluster[]>((get) => {
const clusters = get(clustersAtom);
const cluster = get(clusterAtom);
return clusters.map((item) => ({
...item,
active: item.name === cluster.name,
}));
});
const activeClusterAtom = atom<Cluster>((get) => {
const clusters = get(activeClustersAtom);
return clusters.find((item) => item.active) || clusters[0];
});
export interface ClusterProviderContext {
cluster: Cluster;
clusters: Cluster[];
addCluster: (cluster: Cluster) => void;
deleteCluster: (cluster: Cluster) => void;
setCluster: (cluster: Cluster) => void;
getExplorerUrl(path: string): string;
}
const Context = createContext<ClusterProviderContext>(
{} as ClusterProviderContext
);
export function ClusterProvider({ children }: { children: ReactNode }) {
const cluster = useAtomValue(activeClusterAtom);
const clusters = useAtomValue(activeClustersAtom);
const setCluster = useSetAtom(clusterAtom);
const setClusters = useSetAtom(clustersAtom);
const value: ClusterProviderContext = {
cluster,
clusters: clusters.sort((a, b) => (a.name > b.name ? 1 : -1)),
addCluster: (cluster: Cluster) => {
try {
new Connection(cluster.endpoint);
setClusters([...clusters, cluster]);
} catch (err) {
toast.error(`${err}`);
}
},
deleteCluster: (cluster: Cluster) => {
setClusters(clusters.filter((item) => item.name !== cluster.name));
},
setCluster: (cluster: Cluster) => setCluster(cluster),
getExplorerUrl: (path: string) =>
`https://explorer.solana.com/${path}${getClusterUrlParam(cluster)}`,
};
return <Context.Provider value={value}>{children}</Context.Provider>;
}
export function useCluster() {
return useContext(Context);
}
function getClusterUrlParam(cluster: Cluster): string {
let suffix = '';
switch (cluster.network) {
case ClusterNetwork.Devnet:
suffix = 'devnet';
break;
case ClusterNetwork.Mainnet:
suffix = '';
break;
case ClusterNetwork.Testnet:
suffix = 'testnet';
break;
default:
suffix = `custom&customUrl=${encodeURIComponent(cluster.endpoint)}`;
break;
}
return suffix.length ? `?cluster=${suffix}` : '';
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/cluster/cluster-ui.tsx
|
'use client';
import { useConnection } from '@solana/wallet-adapter-react';
import { IconTrash } from '@tabler/icons-react';
import { useQuery } from '@tanstack/react-query';
import { ReactNode, useState } from 'react';
import { AppModal } from '../ui/ui-layout';
import { ClusterNetwork, useCluster } from './cluster-data-access';
import { Connection } from '@solana/web3.js';
export function ExplorerLink({
path,
label,
className,
}: {
path: string;
label: string;
className?: string;
}) {
const { getExplorerUrl } = useCluster();
return (
<a
href={getExplorerUrl(path)}
target="_blank"
rel="noopener noreferrer"
className={className ? className : `link font-mono`}
>
{label}
</a>
);
}
export function ClusterChecker({ children }: { children: ReactNode }) {
const { cluster } = useCluster();
const { connection } = useConnection();
const query = useQuery({
queryKey: ['version', { cluster, endpoint: connection.rpcEndpoint }],
queryFn: () => connection.getVersion(),
retry: 1,
});
if (query.isLoading) {
return null;
}
if (query.isError || !query.data) {
return (
<div className="alert alert-warning text-warning-content/80 rounded-none flex justify-center">
<span>
Error connecting to cluster <strong>{cluster.name}</strong>
</span>
<button
className="btn btn-xs btn-neutral"
onClick={() => query.refetch()}
>
Refresh
</button>
</div>
);
}
return children;
}
export function ClusterUiSelect() {
const { clusters, setCluster, cluster } = useCluster();
return (
<div className="dropdown dropdown-end">
<label tabIndex={0} className="btn btn-primary rounded-btn">
{cluster.name}
</label>
<ul
tabIndex={0}
className="menu dropdown-content z-[1] p-2 shadow bg-base-100 rounded-box w-52 mt-4"
>
{clusters.map((item) => (
<li key={item.name}>
<button
className={`btn btn-sm ${
item.active ? 'btn-primary' : 'btn-ghost'
}`}
onClick={() => setCluster(item)}
>
{item.name}
</button>
</li>
))}
</ul>
</div>
);
}
export function ClusterUiModal({
hideModal,
show,
}: {
hideModal: () => void;
show: boolean;
}) {
const { addCluster } = useCluster();
const [name, setName] = useState('');
const [network, setNetwork] = useState<ClusterNetwork | undefined>();
const [endpoint, setEndpoint] = useState('');
return (
<AppModal
title={'Add Cluster'}
hide={hideModal}
show={show}
submit={() => {
try {
new Connection(endpoint);
if (name) {
addCluster({ name, network, endpoint });
hideModal();
} else {
console.log('Invalid cluster name');
}
} catch {
console.log('Invalid cluster endpoint');
}
}}
submitLabel="Save"
>
<input
type="text"
placeholder="Name"
className="input input-bordered w-full"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="text"
placeholder="Endpoint"
className="input input-bordered w-full"
value={endpoint}
onChange={(e) => setEndpoint(e.target.value)}
/>
<select
className="select select-bordered w-full"
value={network}
onChange={(e) => setNetwork(e.target.value as ClusterNetwork)}
>
<option value={undefined}>Select a network</option>
<option value={ClusterNetwork.Devnet}>Devnet</option>
<option value={ClusterNetwork.Testnet}>Testnet</option>
<option value={ClusterNetwork.Mainnet}>Mainnet</option>
</select>
</AppModal>
);
}
export function ClusterUiTable() {
const { clusters, setCluster, deleteCluster } = useCluster();
return (
<div className="overflow-x-auto">
<table className="table border-4 border-separate border-base-300">
<thead>
<tr>
<th>Name/ Network / Endpoint</th>
<th className="text-center">Actions</th>
</tr>
</thead>
<tbody>
{clusters.map((item) => (
<tr key={item.name} className={item?.active ? 'bg-base-200' : ''}>
<td className="space-y-2">
<div className="whitespace-nowrap space-x-2">
<span className="text-xl">
{item?.active ? (
item.name
) : (
<button
title="Select cluster"
className="link link-secondary"
onClick={() => setCluster(item)}
>
{item.name}
</button>
)}
</span>
</div>
<span className="text-xs">
Network: {item.network ?? 'custom'}
</span>
<div className="whitespace-nowrap text-gray-500 text-xs">
{item.endpoint}
</div>
</td>
<td className="space-x-2 whitespace-nowrap text-center">
<button
disabled={item?.active}
className="btn btn-xs btn-default btn-outline"
onClick={() => {
if (!window.confirm('Are you sure?')) return;
deleteCluster(item);
}}
>
<IconTrash size={16} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/cluster/cluster-feature.tsx
|
'use client';
import { useState } from 'react';
import { AppHero } from '../ui/ui-layout';
import { ClusterUiModal } from './cluster-ui';
import { ClusterUiTable } from './cluster-ui';
export default function ClusterFeature() {
const [showModal, setShowModal] = useState(false);
return (
<div>
<AppHero
title="Clusters"
subtitle="Manage and select your Solana clusters"
>
<ClusterUiModal
show={showModal}
hideModal={() => setShowModal(false)}
/>
<button
className="btn btn-xs lg:btn-md btn-primary"
onClick={() => setShowModal(true)}
>
Add Cluster
</button>
</AppHero>
<ClusterUiTable />
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/voting/voting-data-access.tsx
|
'use client';
import { getVotingProgram, getVotingProgramId } from '@voting-dapp/anchor';
import { Program, BN } from '@coral-xyz/anchor';
import { useConnection } from '@solana/wallet-adapter-react';
import { Cluster, PublicKey } from '@solana/web3.js';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
import toast from 'react-hot-toast';
import { useCluster } from '../cluster/cluster-data-access';
import { useAnchorProvider } from '../solana/solana-provider';
import { useTransactionToast } from '../ui/ui-layout';
export function useVotingProgramCandidateAccount({ account }: { account: PublicKey }) {
const { cluster } = useCluster();
const provider = useAnchorProvider();
const program = getVotingProgram(provider);
const transactionToast = useTransactionToast();
const candidateQuery = useQuery({
queryKey: ['candidate', { cluster, account }],
queryFn: () => program.account.candidate.fetch(account),
});
const vote = useMutation({
mutationKey: ['voting', 'vote', { cluster }],
mutationFn: (candidate: string) =>
program.methods.vote(
candidate,
new BN(1),
).rpc(),
onSuccess: (signature) => {
transactionToast(signature);
return candidateQuery.refetch();
},
onError: () => toast.error('Failed to vote for candidate'),
});
return {
candidateQuery,
vote
}
}
export function useVotingProgram() {
const { connection } = useConnection();
const { cluster } = useCluster();
const transactionToast = useTransactionToast();
const provider = useAnchorProvider();
const programId = useMemo(
() => getVotingProgramId(cluster.network as Cluster),
[cluster]
);
const program = getVotingProgram(provider);
const accounts = useQuery({
queryKey: ['voting', 'all', { cluster }],
queryFn: () => program.account.candidate.all(),
});
const polls = useQuery({
queryKey: ['polls', 'all', { cluster }],
queryFn: () => program.account.poll.all(),
});
const candidates = useQuery({
queryKey: ['candidates', 'all', { cluster }],
queryFn: () => program.account.candidate.all(),
});
const getProgramAccount = useQuery({
queryKey: ['get-program-account', { cluster }],
queryFn: () => connection.getParsedAccountInfo(programId),
});
const vote = useMutation({
mutationKey: ['voting', 'vote', { cluster }],
mutationFn: (candidate: string) =>
program.methods.vote(
candidate,
new BN(1),
).rpc(),
onSuccess: (signature) => {
transactionToast(signature);
return accounts.refetch();
},
onError: () => toast.error('Failed to vote for candidate'),
});
return {
program,
programId,
accounts,
polls,
getProgramAccount,
vote,
candidates
};
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/voting/voting-feature.tsx
|
'use client';
import { useWallet } from '@solana/wallet-adapter-react';
import { WalletButton } from '../solana/solana-provider';
import { AppHero, ellipsify } from '../ui/ui-layout';
import { ExplorerLink } from '../cluster/cluster-ui';
import { useVotingProgram } from './voting-data-access';
import { CandidateList, VotingCreate } from './voting-ui';
export default function VotingFeature() {
const { publicKey } = useWallet();
const { programId } = useVotingProgram();
return publicKey ? (
<div>
<AppHero
title="Voting Application"
subtitle={
'A simple voting application on Solana'
}
>
</AppHero>
<CandidateList />
</div>
) : (
<div className="max-w-4xl mx-auto">
<div className="hero py-[64px]">
<div className="hero-content text-center">
<WalletButton />
</div>
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/voting/voting-ui.tsx
|
'use client';
import { ellipsify } from '../ui/ui-layout';
import { ExplorerLink } from '../cluster/cluster-ui';
import {
useVotingProgram,
useVotingProgramCandidateAccount,
} from './voting-data-access';
import { useEffect, useMemo, useState } from 'react';
import { PublicKey } from '@solana/web3.js';
export function CandidateList() {
const { candidates, getProgramAccount } = useVotingProgram();
if (getProgramAccount.isLoading) {
return <span className="loading loading-spinner loading-lg"></span>;
}
return (
<div>
{candidates.isLoading ? (
<span className="loading loading-spinner loading-lg"></span>
) : candidates.data?.length ? (
<div className="grid md:grid-cols-2 gap-4">
{candidates.data?.map((account) => (
<div key={account.publicKey.toString()}>
<CandidateCard
key={account.publicKey.toString()}
votes={account.account.candidateVotes}
name={account.account.candidateName}
account={account.publicKey}
/>
</div>
))}
</div>
) : (
<div className="text-center">
<h2 className={'text-2xl'}>No accounts</h2>
No accounts found. Create one above to get started.
</div>
)}
</div>
)
}
function CandidateCard({ account }:
{ votes: number, name: string, account: PublicKey }) {
const {
candidateQuery,
vote,
} = useVotingProgramCandidateAccount({ account });
const [name, setName] = useState('');
const [votes, setVotes] = useState(0);
useEffect(() => {
if (candidateQuery.data) {
setName(candidateQuery.data.candidateName ?? '');
setVotes(candidateQuery.data.candidateVotes ?? 0);
}
}, [candidateQuery.data]);
return (
<div className="card card-bordered border-base-300 border-4 text-neutral-content">
<div className="card-body items-center text-center">
<div className="space-y-6">
<h2
className="card-title justify-center text-3xl cursor-pointer"
onClick={() => candidateQuery.refetch()}
>
{name}
</h2>
<p>{votes.toString()} votes</p>
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => vote.mutateAsync(name)}
disabled={vote.isPending}
>
Vote
</button>
</div>
</div>
</div>
);
}
/*export function VotingList() {
const { accounts, getProgramAccount } = useVotingProgram();
if (getProgramAccount.isLoading) {
return <span className="loading loading-spinner loading-lg"></span>;
}
if (!getProgramAccount.data?.value) {
return (
<div className="alert alert-info flex justify-center">
<span>
Program account not found. Make sure you have deployed the program and
are on the correct cluster.
</span>
</div>
);
}
return (
<div className={'space-y-6'}>
{accounts.isLoading ? (
<span className="loading loading-spinner loading-lg"></span>
) : accounts.data?.length ? (
<div className="grid md:grid-cols-2 gap-4">
{accounts.data?.map((account) => (
<VotingCard
key={account.publicKey.toString()}
account={account.publicKey}
/>
))}
</div>
) : (
<div className="text-center">
<h2 className={'text-2xl'}>No accounts</h2>
No accounts found. Create one above to get started.
</div>
)}
</div>
);
}
/*function VotingCard({ account }: { account: PublicKey }) {
const {
accountQuery,
incrementMutation,
setMutation,
decrementMutation,
closeMutation,
} = useVotingProgram({ account });
const count = useMemo(
() => accountQuery.data?.count ?? 0,
[accountQuery.data?.count]
);
return accountQuery.isLoading ? (
<span className="loading loading-spinner loading-lg"></span>
) : (
<div className="card card-bordered border-base-300 border-4 text-neutral-content">
<div className="card-body items-center text-center">
<div className="space-y-6">
<h2
className="card-title justify-center text-3xl cursor-pointer"
onClick={() => accountQuery.refetch()}
>
{count}
</h2>
<div className="card-actions justify-around">
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => incrementMutation.mutateAsync()}
disabled={incrementMutation.isPending}
>
Increment
</button>
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => {
const value = window.prompt(
'Set value to:',
count.toString() ?? '0'
);
if (
!value ||
parseInt(value) === count ||
isNaN(parseInt(value))
) {
return;
}
return setMutation.mutateAsync(parseInt(value));
}}
disabled={setMutation.isPending}
>
Set
</button>
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => decrementMutation.mutateAsync()}
disabled={decrementMutation.isPending}
>
Decrement
</button>
</div>
<div className="text-center space-y-4">
<p>
<ExplorerLink
path={`account/${account}`}
label={ellipsify(account.toString())}
/>
</p>
<button
className="btn btn-xs btn-secondary btn-outline"
onClick={() => {
if (
!window.confirm(
'Are you sure you want to close this account?'
)
) {
return;
}
return closeMutation.mutateAsync();
}}
disabled={closeMutation.isPending}
>
Close
</button>
</div>
</div>
</div>
</div>
);
}*/
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/solana/solana-provider.tsx
|
'use client';
import dynamic from 'next/dynamic';
import { AnchorProvider } from '@coral-xyz/anchor';
import { WalletError } from '@solana/wallet-adapter-base';
import {
AnchorWallet,
useConnection,
useWallet,
ConnectionProvider,
WalletProvider,
} from '@solana/wallet-adapter-react';
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui';
import { ReactNode, useCallback, useMemo } from 'react';
import { useCluster } from '../cluster/cluster-data-access';
require('@solana/wallet-adapter-react-ui/styles.css');
export const WalletButton = dynamic(
async () =>
(await import('@solana/wallet-adapter-react-ui')).WalletMultiButton,
{ ssr: false }
);
export function SolanaProvider({ children }: { children: ReactNode }) {
const { cluster } = useCluster();
const endpoint = useMemo(() => cluster.endpoint, [cluster]);
const onError = useCallback((error: WalletError) => {
console.error(error);
}, []);
return (
<ConnectionProvider endpoint={endpoint}>
<WalletProvider wallets={[]} onError={onError} autoConnect={true}>
<WalletModalProvider>{children}</WalletModalProvider>
</WalletProvider>
</ConnectionProvider>
);
}
export function useAnchorProvider() {
const { connection } = useConnection();
const wallet = useWallet();
return new AnchorProvider(connection, wallet as AnchorWallet, {
commitment: 'confirmed',
});
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/dashboard/dashboard-feature.tsx
|
'use client';
import { AppHero } from '../ui/ui-layout';
const links: { label: string; href: string }[] = [
{ label: 'Solana Docs', href: 'https://docs.solana.com/' },
{ label: 'Solana Faucet', href: 'https://faucet.solana.com/' },
{ label: 'Solana Cookbook', href: 'https://solanacookbook.com/' },
{ label: 'Solana Stack Overflow', href: 'https://solana.stackexchange.com/' },
{
label: 'Solana Developers GitHub',
href: 'https://github.com/solana-developers/',
},
];
export default function DashboardFeature() {
return (
<div>
<AppHero title="gm" subtitle="Say hi to your new Solana dApp." />
<div className="max-w-xl mx-auto py-6 sm:px-6 lg:px-8 text-center">
<div className="space-y-2">
<p>Here are some helpful links to get you started.</p>
{links.map((link, index) => (
<div key={index}>
<a
href={link.href}
className="link"
target="_blank"
rel="noopener noreferrer"
>
{link.label}
</a>
</div>
))}
</div>
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/counter/counter-data-access.tsx
|
'use client';
import { getCounterProgram, getCounterProgramId } from '@voting-dapp/anchor';
import { Program } from '@coral-xyz/anchor';
import { useConnection } from '@solana/wallet-adapter-react';
import { Cluster, Keypair, PublicKey } from '@solana/web3.js';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
import toast from 'react-hot-toast';
import { useCluster } from '../cluster/cluster-data-access';
import { useAnchorProvider } from '../solana/solana-provider';
import { useTransactionToast } from '../ui/ui-layout';
export function useCounterProgram() {
const { connection } = useConnection();
const { cluster } = useCluster();
const transactionToast = useTransactionToast();
const provider = useAnchorProvider();
const programId = useMemo(
() => getCounterProgramId(cluster.network as Cluster),
[cluster]
);
const program = getCounterProgram(provider);
const accounts = useQuery({
queryKey: ['counter', 'all', { cluster }],
queryFn: () => program.account.counter.all(),
});
const getProgramAccount = useQuery({
queryKey: ['get-program-account', { cluster }],
queryFn: () => connection.getParsedAccountInfo(programId),
});
const initialize = useMutation({
mutationKey: ['counter', 'initialize', { cluster }],
mutationFn: (keypair: Keypair) =>
program.methods
.initialize()
.accounts({ counter: keypair.publicKey })
.signers([keypair])
.rpc(),
onSuccess: (signature) => {
transactionToast(signature);
return accounts.refetch();
},
onError: () => toast.error('Failed to initialize account'),
});
return {
program,
programId,
accounts,
getProgramAccount,
initialize,
};
}
export function useCounterProgramAccount({ account }: { account: PublicKey }) {
const { cluster } = useCluster();
const transactionToast = useTransactionToast();
const { program, accounts } = useCounterProgram();
const accountQuery = useQuery({
queryKey: ['counter', 'fetch', { cluster, account }],
queryFn: () => program.account.counter.fetch(account),
});
const closeMutation = useMutation({
mutationKey: ['counter', 'close', { cluster, account }],
mutationFn: () =>
program.methods.close().accounts({ counter: account }).rpc(),
onSuccess: (tx) => {
transactionToast(tx);
return accounts.refetch();
},
});
const decrementMutation = useMutation({
mutationKey: ['counter', 'decrement', { cluster, account }],
mutationFn: () =>
program.methods.decrement().accounts({ counter: account }).rpc(),
onSuccess: (tx) => {
transactionToast(tx);
return accountQuery.refetch();
},
});
const incrementMutation = useMutation({
mutationKey: ['counter', 'increment', { cluster, account }],
mutationFn: () =>
program.methods.increment().accounts({ counter: account }).rpc(),
onSuccess: (tx) => {
transactionToast(tx);
return accountQuery.refetch();
},
});
const setMutation = useMutation({
mutationKey: ['counter', 'set', { cluster, account }],
mutationFn: (value: number) =>
program.methods.set(value).accounts({ counter: account }).rpc(),
onSuccess: (tx) => {
transactionToast(tx);
return accountQuery.refetch();
},
});
return {
accountQuery,
closeMutation,
decrementMutation,
incrementMutation,
setMutation,
};
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/counter/counter-feature.tsx
|
'use client';
import { useWallet } from '@solana/wallet-adapter-react';
import { WalletButton } from '../solana/solana-provider';
import { AppHero, ellipsify } from '../ui/ui-layout';
import { ExplorerLink } from '../cluster/cluster-ui';
import { useCounterProgram } from './counter-data-access';
import { CounterCreate, CounterList } from './counter-ui';
export default function CounterFeature() {
const { publicKey } = useWallet();
const { programId } = useCounterProgram();
return publicKey ? (
<div>
<AppHero
title="Counter"
subtitle={
'Create a new account by clicking the "Create" button. The state of a account is stored on-chain and can be manipulated by calling the program\'s methods (increment, decrement, set, and close).'
}
>
<p className="mb-6">
<ExplorerLink
path={`account/${programId}`}
label={ellipsify(programId.toString())}
/>
</p>
<CounterCreate />
</AppHero>
<CounterList />
</div>
) : (
<div className="max-w-4xl mx-auto">
<div className="hero py-[64px]">
<div className="hero-content text-center">
<WalletButton />
</div>
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/counter/counter-ui.tsx
|
'use client';
import { Keypair, PublicKey } from '@solana/web3.js';
import { useMemo } from 'react';
import { ellipsify } from '../ui/ui-layout';
import { ExplorerLink } from '../cluster/cluster-ui';
import {
useCounterProgram,
useCounterProgramAccount,
} from './counter-data-access';
export function CounterCreate() {
const { initialize } = useCounterProgram();
return (
<button
className="btn btn-xs lg:btn-md btn-primary"
onClick={() => initialize.mutateAsync(Keypair.generate())}
disabled={initialize.isPending}
>
Create {initialize.isPending && '...'}
</button>
);
}
export function CounterList() {
const { accounts, getProgramAccount } = useCounterProgram();
if (getProgramAccount.isLoading) {
return <span className="loading loading-spinner loading-lg"></span>;
}
if (!getProgramAccount.data?.value) {
return (
<div className="alert alert-info flex justify-center">
<span>
Program account not found. Make sure you have deployed the program and
are on the correct cluster.
</span>
</div>
);
}
return (
<div className={'space-y-6'}>
{accounts.isLoading ? (
<span className="loading loading-spinner loading-lg"></span>
) : accounts.data?.length ? (
<div className="grid md:grid-cols-2 gap-4">
{accounts.data?.map((account) => (
<CounterCard
key={account.publicKey.toString()}
account={account.publicKey}
/>
))}
</div>
) : (
<div className="text-center">
<h2 className={'text-2xl'}>No accounts</h2>
No accounts found. Create one above to get started.
</div>
)}
</div>
);
}
function CounterCard({ account }: { account: PublicKey }) {
const {
accountQuery,
incrementMutation,
setMutation,
decrementMutation,
closeMutation,
} = useCounterProgramAccount({ account });
const count = useMemo(
() => accountQuery.data?.count ?? 0,
[accountQuery.data?.count]
);
return accountQuery.isLoading ? (
<span className="loading loading-spinner loading-lg"></span>
) : (
<div className="card card-bordered border-base-300 border-4 text-neutral-content">
<div className="card-body items-center text-center">
<div className="space-y-6">
<h2
className="card-title justify-center text-3xl cursor-pointer"
onClick={() => accountQuery.refetch()}
>
{count}
</h2>
<div className="card-actions justify-around">
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => incrementMutation.mutateAsync()}
disabled={incrementMutation.isPending}
>
Increment
</button>
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => {
const value = window.prompt(
'Set value to:',
count.toString() ?? '0'
);
if (
!value ||
parseInt(value) === count ||
isNaN(parseInt(value))
) {
return;
}
return setMutation.mutateAsync(parseInt(value));
}}
disabled={setMutation.isPending}
>
Set
</button>
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => decrementMutation.mutateAsync()}
disabled={decrementMutation.isPending}
>
Decrement
</button>
</div>
<div className="text-center space-y-4">
<p>
<ExplorerLink
path={`account/${account}`}
label={ellipsify(account.toString())}
/>
</p>
<button
className="btn btn-xs btn-secondary btn-outline"
onClick={() => {
if (
!window.confirm(
'Are you sure you want to close this account?'
)
) {
return;
}
return closeMutation.mutateAsync();
}}
disabled={closeMutation.isPending}
>
Close
</button>
</div>
</div>
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/account/account-data-access.tsx
|
'use client';
import { useConnection, useWallet } from '@solana/wallet-adapter-react';
import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token';
import {
Connection,
LAMPORTS_PER_SOL,
PublicKey,
SystemProgram,
TransactionMessage,
TransactionSignature,
VersionedTransaction,
} from '@solana/web3.js';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { useTransactionToast } from '../ui/ui-layout';
export function useGetBalance({ address }: { address: PublicKey }) {
const { connection } = useConnection();
return useQuery({
queryKey: ['get-balance', { endpoint: connection.rpcEndpoint, address }],
queryFn: () => connection.getBalance(address),
});
}
export function useGetSignatures({ address }: { address: PublicKey }) {
const { connection } = useConnection();
return useQuery({
queryKey: ['get-signatures', { endpoint: connection.rpcEndpoint, address }],
queryFn: () => connection.getConfirmedSignaturesForAddress2(address),
});
}
export function useGetTokenAccounts({ address }: { address: PublicKey }) {
const { connection } = useConnection();
return useQuery({
queryKey: [
'get-token-accounts',
{ endpoint: connection.rpcEndpoint, address },
],
queryFn: async () => {
const [tokenAccounts, token2022Accounts] = await Promise.all([
connection.getParsedTokenAccountsByOwner(address, {
programId: TOKEN_PROGRAM_ID,
}),
connection.getParsedTokenAccountsByOwner(address, {
programId: TOKEN_2022_PROGRAM_ID,
}),
]);
return [...tokenAccounts.value, ...token2022Accounts.value];
},
});
}
export function useTransferSol({ address }: { address: PublicKey }) {
const { connection } = useConnection();
const transactionToast = useTransactionToast();
const wallet = useWallet();
const client = useQueryClient();
return useMutation({
mutationKey: [
'transfer-sol',
{ endpoint: connection.rpcEndpoint, address },
],
mutationFn: async (input: { destination: PublicKey; amount: number }) => {
let signature: TransactionSignature = '';
try {
const { transaction, latestBlockhash } = await createTransaction({
publicKey: address,
destination: input.destination,
amount: input.amount,
connection,
});
// Send transaction and await for signature
signature = await wallet.sendTransaction(transaction, connection);
// Send transaction and await for signature
await connection.confirmTransaction(
{ signature, ...latestBlockhash },
'confirmed'
);
console.log(signature);
return signature;
} catch (error: unknown) {
console.log('error', `Transaction failed! ${error}`, signature);
return;
}
},
onSuccess: (signature) => {
if (signature) {
transactionToast(signature);
}
return Promise.all([
client.invalidateQueries({
queryKey: [
'get-balance',
{ endpoint: connection.rpcEndpoint, address },
],
}),
client.invalidateQueries({
queryKey: [
'get-signatures',
{ endpoint: connection.rpcEndpoint, address },
],
}),
]);
},
onError: (error) => {
toast.error(`Transaction failed! ${error}`);
},
});
}
export function useRequestAirdrop({ address }: { address: PublicKey }) {
const { connection } = useConnection();
const transactionToast = useTransactionToast();
const client = useQueryClient();
return useMutation({
mutationKey: ['airdrop', { endpoint: connection.rpcEndpoint, address }],
mutationFn: async (amount: number = 1) => {
const [latestBlockhash, signature] = await Promise.all([
connection.getLatestBlockhash(),
connection.requestAirdrop(address, amount * LAMPORTS_PER_SOL),
]);
await connection.confirmTransaction(
{ signature, ...latestBlockhash },
'confirmed'
);
return signature;
},
onSuccess: (signature) => {
transactionToast(signature);
return Promise.all([
client.invalidateQueries({
queryKey: [
'get-balance',
{ endpoint: connection.rpcEndpoint, address },
],
}),
client.invalidateQueries({
queryKey: [
'get-signatures',
{ endpoint: connection.rpcEndpoint, address },
],
}),
]);
},
});
}
async function createTransaction({
publicKey,
destination,
amount,
connection,
}: {
publicKey: PublicKey;
destination: PublicKey;
amount: number;
connection: Connection;
}): Promise<{
transaction: VersionedTransaction;
latestBlockhash: { blockhash: string; lastValidBlockHeight: number };
}> {
// Get the latest blockhash to use in our transaction
const latestBlockhash = await connection.getLatestBlockhash();
// Create instructions to send, in this case a simple transfer
const instructions = [
SystemProgram.transfer({
fromPubkey: publicKey,
toPubkey: destination,
lamports: amount * LAMPORTS_PER_SOL,
}),
];
// Create a new TransactionMessage with version and compile it to legacy
const messageLegacy = new TransactionMessage({
payerKey: publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions,
}).compileToLegacyMessage();
// Create a new VersionedTransaction which supports legacy and v0
const transaction = new VersionedTransaction(messageLegacy);
return {
transaction,
latestBlockhash,
};
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/account/account-ui.tsx
|
'use client';
import { useWallet } from '@solana/wallet-adapter-react';
import { LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';
import { IconRefresh } from '@tabler/icons-react';
import { useQueryClient } from '@tanstack/react-query';
import { useMemo, useState } from 'react';
import { AppModal, ellipsify } from '../ui/ui-layout';
import { useCluster } from '../cluster/cluster-data-access';
import { ExplorerLink } from '../cluster/cluster-ui';
import {
useGetBalance,
useGetSignatures,
useGetTokenAccounts,
useRequestAirdrop,
useTransferSol,
} from './account-data-access';
export function AccountBalance({ address }: { address: PublicKey }) {
const query = useGetBalance({ address });
return (
<div>
<h1
className="text-5xl font-bold cursor-pointer"
onClick={() => query.refetch()}
>
{query.data ? <BalanceSol balance={query.data} /> : '...'} SOL
</h1>
</div>
);
}
export function AccountChecker() {
const { publicKey } = useWallet();
if (!publicKey) {
return null;
}
return <AccountBalanceCheck address={publicKey} />;
}
export function AccountBalanceCheck({ address }: { address: PublicKey }) {
const { cluster } = useCluster();
const mutation = useRequestAirdrop({ address });
const query = useGetBalance({ address });
if (query.isLoading) {
return null;
}
if (query.isError || !query.data) {
return (
<div className="alert alert-warning text-warning-content/80 rounded-none flex justify-center">
<span>
You are connected to <strong>{cluster.name}</strong> but your account
is not found on this cluster.
</span>
<button
className="btn btn-xs btn-neutral"
onClick={() =>
mutation.mutateAsync(1).catch((err) => console.log(err))
}
>
Request Airdrop
</button>
</div>
);
}
return null;
}
export function AccountButtons({ address }: { address: PublicKey }) {
const wallet = useWallet();
const { cluster } = useCluster();
const [showAirdropModal, setShowAirdropModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showSendModal, setShowSendModal] = useState(false);
return (
<div>
<ModalAirdrop
hide={() => setShowAirdropModal(false)}
address={address}
show={showAirdropModal}
/>
<ModalReceive
address={address}
show={showReceiveModal}
hide={() => setShowReceiveModal(false)}
/>
<ModalSend
address={address}
show={showSendModal}
hide={() => setShowSendModal(false)}
/>
<div className="space-x-2">
<button
disabled={cluster.network?.includes('mainnet')}
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => setShowAirdropModal(true)}
>
Airdrop
</button>
<button
disabled={wallet.publicKey?.toString() !== address.toString()}
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => setShowSendModal(true)}
>
Send
</button>
<button
className="btn btn-xs lg:btn-md btn-outline"
onClick={() => setShowReceiveModal(true)}
>
Receive
</button>
</div>
</div>
);
}
export function AccountTokens({ address }: { address: PublicKey }) {
const [showAll, setShowAll] = useState(false);
const query = useGetTokenAccounts({ address });
const client = useQueryClient();
const items = useMemo(() => {
if (showAll) return query.data;
return query.data?.slice(0, 5);
}, [query.data, showAll]);
return (
<div className="space-y-2">
<div className="justify-between">
<div className="flex justify-between">
<h2 className="text-2xl font-bold">Token Accounts</h2>
<div className="space-x-2">
{query.isLoading ? (
<span className="loading loading-spinner"></span>
) : (
<button
className="btn btn-sm btn-outline"
onClick={async () => {
await query.refetch();
await client.invalidateQueries({
queryKey: ['getTokenAccountBalance'],
});
}}
>
<IconRefresh size={16} />
</button>
)}
</div>
</div>
</div>
{query.isError && (
<pre className="alert alert-error">
Error: {query.error?.message.toString()}
</pre>
)}
{query.isSuccess && (
<div>
{query.data.length === 0 ? (
<div>No token accounts found.</div>
) : (
<table className="table border-4 rounded-lg border-separate border-base-300">
<thead>
<tr>
<th>Public Key</th>
<th>Mint</th>
<th className="text-right">Balance</th>
</tr>
</thead>
<tbody>
{items?.map(({ account, pubkey }) => (
<tr key={pubkey.toString()}>
<td>
<div className="flex space-x-2">
<span className="font-mono">
<ExplorerLink
label={ellipsify(pubkey.toString())}
path={`account/${pubkey.toString()}`}
/>
</span>
</div>
</td>
<td>
<div className="flex space-x-2">
<span className="font-mono">
<ExplorerLink
label={ellipsify(account.data.parsed.info.mint)}
path={`account/${account.data.parsed.info.mint.toString()}`}
/>
</span>
</div>
</td>
<td className="text-right">
<span className="font-mono">
{account.data.parsed.info.tokenAmount.uiAmount}
</span>
</td>
</tr>
))}
{(query.data?.length ?? 0) > 5 && (
<tr>
<td colSpan={4} className="text-center">
<button
className="btn btn-xs btn-outline"
onClick={() => setShowAll(!showAll)}
>
{showAll ? 'Show Less' : 'Show All'}
</button>
</td>
</tr>
)}
</tbody>
</table>
)}
</div>
)}
</div>
);
}
export function AccountTransactions({ address }: { address: PublicKey }) {
const query = useGetSignatures({ address });
const [showAll, setShowAll] = useState(false);
const items = useMemo(() => {
if (showAll) return query.data;
return query.data?.slice(0, 5);
}, [query.data, showAll]);
return (
<div className="space-y-2">
<div className="flex justify-between">
<h2 className="text-2xl font-bold">Transaction History</h2>
<div className="space-x-2">
{query.isLoading ? (
<span className="loading loading-spinner"></span>
) : (
<button
className="btn btn-sm btn-outline"
onClick={() => query.refetch()}
>
<IconRefresh size={16} />
</button>
)}
</div>
</div>
{query.isError && (
<pre className="alert alert-error">
Error: {query.error?.message.toString()}
</pre>
)}
{query.isSuccess && (
<div>
{query.data.length === 0 ? (
<div>No transactions found.</div>
) : (
<table className="table border-4 rounded-lg border-separate border-base-300">
<thead>
<tr>
<th>Signature</th>
<th className="text-right">Slot</th>
<th>Block Time</th>
<th className="text-right">Status</th>
</tr>
</thead>
<tbody>
{items?.map((item) => (
<tr key={item.signature}>
<th className="font-mono">
<ExplorerLink
path={`tx/${item.signature}`}
label={ellipsify(item.signature, 8)}
/>
</th>
<td className="font-mono text-right">
<ExplorerLink
path={`block/${item.slot}`}
label={item.slot.toString()}
/>
</td>
<td>
{new Date((item.blockTime ?? 0) * 1000).toISOString()}
</td>
<td className="text-right">
{item.err ? (
<div
className="badge badge-error"
title={JSON.stringify(item.err)}
>
Failed
</div>
) : (
<div className="badge badge-success">Success</div>
)}
</td>
</tr>
))}
{(query.data?.length ?? 0) > 5 && (
<tr>
<td colSpan={4} className="text-center">
<button
className="btn btn-xs btn-outline"
onClick={() => setShowAll(!showAll)}
>
{showAll ? 'Show Less' : 'Show All'}
</button>
</td>
</tr>
)}
</tbody>
</table>
)}
</div>
)}
</div>
);
}
function BalanceSol({ balance }: { balance: number }) {
return (
<span>{Math.round((balance / LAMPORTS_PER_SOL) * 100000) / 100000}</span>
);
}
function ModalReceive({
hide,
show,
address,
}: {
hide: () => void;
show: boolean;
address: PublicKey;
}) {
return (
<AppModal title="Receive" hide={hide} show={show}>
<p>Receive assets by sending them to your public key:</p>
<code>{address.toString()}</code>
</AppModal>
);
}
function ModalAirdrop({
hide,
show,
address,
}: {
hide: () => void;
show: boolean;
address: PublicKey;
}) {
const mutation = useRequestAirdrop({ address });
const [amount, setAmount] = useState('2');
return (
<AppModal
hide={hide}
show={show}
title="Airdrop"
submitDisabled={!amount || mutation.isPending}
submitLabel="Request Airdrop"
submit={() => mutation.mutateAsync(parseFloat(amount)).then(() => hide())}
>
<input
disabled={mutation.isPending}
type="number"
step="any"
min="1"
placeholder="Amount"
className="input input-bordered w-full"
value={amount}
onChange={(e) => setAmount(e.target.value)}
/>
</AppModal>
);
}
function ModalSend({
hide,
show,
address,
}: {
hide: () => void;
show: boolean;
address: PublicKey;
}) {
const wallet = useWallet();
const mutation = useTransferSol({ address });
const [destination, setDestination] = useState('');
const [amount, setAmount] = useState('1');
if (!address || !wallet.sendTransaction) {
return <div>Wallet not connected</div>;
}
return (
<AppModal
hide={hide}
show={show}
title="Send"
submitDisabled={!destination || !amount || mutation.isPending}
submitLabel="Send"
submit={() => {
mutation
.mutateAsync({
destination: new PublicKey(destination),
amount: parseFloat(amount),
})
.then(() => hide());
}}
>
<input
disabled={mutation.isPending}
type="text"
placeholder="Destination"
className="input input-bordered w-full"
value={destination}
onChange={(e) => setDestination(e.target.value)}
/>
<input
disabled={mutation.isPending}
type="number"
step="any"
min="1"
placeholder="Amount"
className="input input-bordered w-full"
value={amount}
onChange={(e) => setAmount(e.target.value)}
/>
</AppModal>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/account/account-detail-feature.tsx
|
'use client';
import { PublicKey } from '@solana/web3.js';
import { useMemo } from 'react';
import { useParams } from 'next/navigation';
import { ExplorerLink } from '../cluster/cluster-ui';
import { AppHero, ellipsify } from '../ui/ui-layout';
import {
AccountBalance,
AccountButtons,
AccountTokens,
AccountTransactions,
} from './account-ui';
export default function AccountDetailFeature() {
const params = useParams();
const address = useMemo(() => {
if (!params.address) {
return;
}
try {
return new PublicKey(params.address);
} catch (e) {
console.log(`Invalid public key`, e);
}
}, [params]);
if (!address) {
return <div>Error loading account</div>;
}
return (
<div>
<AppHero
title={<AccountBalance address={address} />}
subtitle={
<div className="my-4">
<ExplorerLink
path={`account/${address}`}
label={ellipsify(address.toString())}
/>
</div>
}
>
<div className="my-4">
<AccountButtons address={address} />
</div>
</AppHero>
<div className="space-y-8">
<AccountTokens address={address} />
<AccountTransactions address={address} />
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/web/components/account/account-list-feature.tsx
|
'use client';
import { useWallet } from '@solana/wallet-adapter-react';
import { WalletButton } from '../solana/solana-provider';
import { redirect } from 'next/navigation';
export default function AccountListFeature() {
const { publicKey } = useWallet();
if (publicKey) {
return redirect(`/account/${publicKey.toString()}`);
}
return (
<div className="hero py-[64px]">
<div className="hero-content text-center">
<WalletButton />
</div>
</div>
);
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/Cargo.toml
|
[workspace]
members = ["programs/*"]
resolver = "2"
[profile.release]
overflow-checks = true
lto = "fat"
codegen-units = 1
[profile.release.build-override]
opt-level = 3
incremental = false
codegen-units = 1
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/project.json
|
{
"name": "anchor",
"$schema": "../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "anchor/src",
"projectType": "library",
"tags": [],
"targets": {
"build": {
"executor": "@nx/rollup:rollup",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/anchor",
"main": "anchor/src/index.ts",
"tsConfig": "anchor/tsconfig.lib.json",
"assets": [],
"project": "anchor/package.json",
"compiler": "swc",
"format": ["cjs", "esm"]
}
},
"lint": {
"executor": "@nx/eslint:lint"
},
"test": {
"executor": "nx:run-commands",
"options": {
"cwd": "anchor",
"commands": ["anchor test"],
"parallel": false
}
},
"anchor": {
"executor": "nx:run-commands",
"options": {
"cwd": "anchor",
"commands": ["anchor"],
"parallel": false
}
},
"localnet": {
"executor": "nx:run-commands",
"options": {
"cwd": "anchor",
"commands": ["anchor localnet"],
"parallel": false
}
},
"jest": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "anchor/jest.config.ts"
}
}
}
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/.swcrc
|
{
"jsc": {
"target": "es2017",
"parser": {
"syntax": "typescript",
"decorators": true,
"dynamicImport": true
},
"transform": {
"decoratorMetadata": true,
"legacyDecorator": true
},
"keepClassNames": true,
"externalHelpers": true,
"loose": true
},
"module": {
"type": "es6"
},
"sourceMaps": true,
"exclude": [
"jest.config.ts",
".*\\.spec.tsx?$",
".*\\.test.tsx?$",
"./src/jest-setup.ts$",
"./**/jest-setup.ts$",
".*.js$"
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/Anchor.toml
|
[toolchain]
[features]
seeds = false
skip-lint = false
[programs.localnet]
voting = "HDxHrQL4N5GaBo19UjEF3sypkrGiDijjuGyQXBNhnrKB"
[registry]
url = "https://api.apr.dev"
[provider]
cluster = "Localnet"
wallet = "~/.config/solana/id.json"
[scripts]
test = "../node_modules/.bin/nx run anchor:jest"
[test]
startup_wait = 5000
shutdown_wait = 2000
upgradeable = false
[test.validator]
bind_address = "127.0.0.1"
ledger = ".anchor/test-ledger"
rpc_port = 8899
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/package.json
|
{
"name": "@voting-dapp/anchor",
"version": "0.0.1",
"dependencies": {
"@coral-xyz/anchor": "^0.30.0",
"@solana/web3.js": "1.91.9",
"anchor-bankrun": "^0.4.0"
},
"main": "./index.cjs",
"module": "./index.js",
"private": true
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/tsconfig.json
|
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"module": "commonjs"
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/tsconfig.lib.json
|
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../dist/out-tsc",
"declaration": true,
"types": ["node"],
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true
},
"include": ["src/**/*.ts"],
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/.eslintrc.json
|
{
"extends": ["../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.json"],
"parser": "jsonc-eslint-parser",
"rules": {
"@nx/dependency-checks": [
"error",
{
"ignoredFiles": ["{projectRoot}/rollup.config.{js,ts,mjs,mts}"]
}
]
}
}
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/tsconfig.spec.json
|
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/jest.config.ts
|
/* eslint-disable */
import { readFileSync } from 'fs';
// Reading the SWC compilation config and remove the "exclude"
// for the test files to be compiled by SWC
const { exclude: _, ...swcJestConfig } = JSON.parse(
readFileSync(`${__dirname}/.swcrc`, 'utf-8')
);
// disable .swcrc look-up by SWC core because we're passing in swcJestConfig ourselves.
// If we do not disable this, SWC Core will read .swcrc and won't transform our test files due to "exclude"
if (swcJestConfig.swcrc === undefined) {
swcJestConfig.swcrc = false;
}
// Uncomment if using global setup/teardown files being transformed via swc
// https://nx.dev/packages/jest/documents/overview#global-setup/teardown-with-nx-libraries
// jest needs EsModule Interop to find the default exported setup/teardown functions
// swcJestConfig.module.noInterop = false;
export default {
displayName: 'anchor',
preset: '../jest.preset.js',
transform: {
'^.+\\.[tj]s$': ['@swc/jest', swcJestConfig],
},
moduleFileExtensions: ['ts', 'js', 'html'],
testEnvironment: '',
coverageDirectory: '../coverage/anchor',
};
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/migrations/deploy.ts
|
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.
import * as anchor from '@coral-xyz/anchor';
module.exports = async function (provider) {
// Configure client to use the provider.
anchor.setProvider(provider);
// Add your deploy script here.
};
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/tests/voting.spec.ts
|
import { PartialAccounts } from '@coral-xyz/anchor/dist/cjs/program/namespace/methods';
import * as anchor from '@coral-xyz/anchor';
import { Program } from '@coral-xyz/anchor';
import { Keypair, PublicKey, SystemProgram } from '@solana/web3.js';
import { Voting } from '../target/types/voting';
import { startAnchor } from "solana-bankrun";
import { BankrunProvider } from "anchor-bankrun";
const IDL = require('../target/idl/voting.json');
const votingAddress = new PublicKey("HDxHrQL4N5GaBo19UjEF3sypkrGiDijjuGyQXBNhnrKB");
describe('Voting', () => {
let context;
let provider;
//let votingProgram;
anchor.setProvider(anchor.AnchorProvider.env());
let votingProgram = anchor.workspace.Voting as Program<Voting>;
/*beforeAll(async () => {
context = await startAnchor("", [{name: "voting", programId: votingAddress}], []);
provider = new BankrunProvider(context);
votingProgram = new Program<Voting>(
IDL,
provider,
);
})*/
it('Initialize Poll', async () => {
await votingProgram.methods.initializePoll(
new anchor.BN(1),
"What is your favorite type of peanut butter?",
new anchor.BN(0),
new anchor.BN(1821246480),
).rpc();
const [pollAddress] = PublicKey.findProgramAddressSync(
[new anchor.BN(1).toArrayLike(Buffer, 'le', 8)],
votingAddress,
)
const poll = await votingProgram.account.poll.fetch(pollAddress);
console.log(poll);
expect(poll.pollId.toNumber()).toEqual(1);
expect(poll.description).toEqual("What is your favorite type of peanut butter?");
expect(poll.pollStart.toNumber()).toBeLessThan(poll.pollEnd.toNumber());
});
it("initialize candidate", async() => {
await votingProgram.methods.initializeCandidate(
"Smooth",
new anchor.BN(1),
).rpc();
await votingProgram.methods.initializeCandidate(
"Crunchy",
new anchor.BN(1),
).rpc();
const [crunchyAddress] = PublicKey.findProgramAddressSync(
[new anchor.BN(1).toArrayLike(Buffer, 'le', 8), Buffer.from("Crunchy")],
votingAddress,
);
const crunchyCandidate = await votingProgram.account.candidate.fetch(crunchyAddress);
console.log(crunchyCandidate);
expect(crunchyCandidate.candidateVotes.toNumber()).toEqual(0);
const [smoothAddress] = PublicKey.findProgramAddressSync(
[new anchor.BN(1).toArrayLike(Buffer, 'le', 8), Buffer.from("Smooth")],
votingAddress,
);
const smoothCandidate = await votingProgram.account.candidate.fetch(smoothAddress);
console.log(smoothCandidate);
expect(smoothCandidate.candidateVotes.toNumber()).toEqual(0);
});
it("vote", async() => {
await votingProgram.methods
.vote(
"Smooth",
new anchor.BN(1)
).rpc()
const [smoothAddress] = PublicKey.findProgramAddressSync(
[new anchor.BN(1).toArrayLike(Buffer, 'le', 8), Buffer.from("Smooth")],
votingAddress,
);
const smoothCandidate = await votingProgram.account.candidate.fetch(smoothAddress);
console.log(smoothCandidate);
expect(smoothCandidate.candidateVotes.toNumber()).toEqual(1);
});
});
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/programs
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/programs/voting/Cargo.toml
|
[package]
name = "voting"
version = "0.1.0"
description = "Created with Anchor"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
name = "voting"
[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
default = []
idl-build = ["anchor-lang/idl-build"]
[dependencies]
anchor-lang = "0.30.1"
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/programs
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/programs/voting/Xargo.toml
|
[target.bpfel-unknown-unknown.dependencies.std]
features = []
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/programs/voting
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/programs/voting/src/lib.rs
|
#![allow(clippy::result_large_err)]
use anchor_lang::prelude::*;
declare_id!("HDxHrQL4N5GaBo19UjEF3sypkrGiDijjuGyQXBNhnrKB");
#[program]
pub mod voting {
use super::*;
pub fn initialize_poll(ctx: Context<InitializePoll>,
poll_id: u64,
description: String,
poll_start: u64,
poll_end: u64) -> Result<()> {
let poll = &mut ctx.accounts.poll;
poll.poll_id = poll_id;
poll.description = description;
poll.poll_start = poll_start;
poll.poll_end = poll_end;
poll.candidate_amount = 0;
Ok(())
}
pub fn initialize_candidate(ctx: Context<InitializeCandidate>,
candidate_name: String,
_poll_id: u64) -> Result<()> {
let candidate = &mut ctx.accounts.candidate;
let poll = &mut ctx.accounts.poll;
poll.candidate_amount += 1;
candidate.candidate_name = candidate_name;
candidate.candidate_votes = 0;
Ok(())
}
pub fn vote(ctx: Context<Vote>, _candidate_name: String, _poll_id: u64) -> Result<()> {
let candidate = &mut ctx.accounts.candidate;
candidate.candidate_votes += 1;
msg!("Voted for candidate: {}", candidate.candidate_name);
msg!("Votes: {}", candidate.candidate_votes);
Ok(())
}
}
#[derive(Accounts)]
#[instruction(candidate_name: String, poll_id: u64)]
pub struct Vote<'info> {
pub signer: Signer<'info>,
#[account(
seeds = [poll_id.to_le_bytes().as_ref()],
bump
)]
pub poll: Account<'info, Poll>,
#[account(
mut,
seeds = [poll_id.to_le_bytes().as_ref(), candidate_name.as_bytes()],
bump
)]
pub candidate: Account<'info, Candidate>,
}
#[derive(Accounts)]
#[instruction(candidate_name: String, poll_id: u64)]
pub struct InitializeCandidate<'info> {
#[account(mut)]
pub signer: Signer<'info>,
#[account(
mut,
seeds = [poll_id.to_le_bytes().as_ref()],
bump
)]
pub poll: Account<'info, Poll>,
#[account(
init,
payer = signer,
space = 8 + Candidate::INIT_SPACE,
seeds = [poll_id.to_le_bytes().as_ref(), candidate_name.as_bytes()],
bump
)]
pub candidate: Account<'info, Candidate>,
pub system_program: Program<'info, System>,
}
#[account]
#[derive(InitSpace)]
pub struct Candidate {
#[max_len(32)]
pub candidate_name: String,
pub candidate_votes: u64,
}
#[derive(Accounts)]
#[instruction(poll_id: u64)]
pub struct InitializePoll<'info> {
#[account(mut)]
pub signer: Signer<'info>,
#[account(
init,
payer = signer,
space = 8 + Poll::INIT_SPACE,
seeds = [poll_id.to_le_bytes().as_ref()],
bump
)]
pub poll: Account<'info, Poll>,
pub system_program: Program<'info, System>,
}
#[account]
#[derive(InitSpace)]
pub struct Poll {
pub poll_id: u64,
#[max_len(280)]
pub description: String,
pub poll_start: u64,
pub poll_end: u64,
pub candidate_amount: u64,
}
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/src/index.ts
|
// This file was generated by preset-anchor. Programs are exported from this file.
export * from './voting-exports';
| 0
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor
|
solana_public_repos/developer-bootcamp-2024/project-13-getting-to-production/anchor/src/voting-exports.ts
|
// Here we export some useful types and functions for interacting with the Anchor program.
import { AnchorProvider, Program } from '@coral-xyz/anchor';
import { Cluster, PublicKey } from '@solana/web3.js';
import VotingIDL from '../target/idl/voting.json';
import type { Voting } from '../target/types/voting';
// Re-export the generated IDL and type
export { Voting, VotingIDL };
// The programId is imported from the program IDL.
export const VOTING_PROGRAM_ID = new PublicKey(VotingIDL.address);
// This is a helper function to get the Voting Anchor program.
export function getVotingProgram(provider: AnchorProvider) {
return new Program(VotingIDL as Voting, provider);
}
// This is a helper function to get the program ID for the Voting program depending on the cluster.
export function getVotingProgramId(cluster: Cluster) {
switch (cluster) {
case 'devnet':
case 'testnet':
case 'mainnet-beta':
default:
return VOTING_PROGRAM_ID;
}
}
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-10-lending/Cargo.toml
|
[workspace]
members = [
"programs/*"
]
resolver = "2"
[profile.release]
overflow-checks = true
lto = "fat"
codegen-units = 1
[profile.release.build-override]
opt-level = 3
incremental = false
codegen-units = 1
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-10-lending/.prettierignore
|
.anchor
.DS_Store
target
node_modules
dist
build
test-ledger
| 0
|
solana_public_repos/developer-bootcamp-2024
|
solana_public_repos/developer-bootcamp-2024/project-10-lending/Anchor.toml
|
[toolchain]
[features]
resolution = true
skip-lint = false
[programs.localnet]
lending = "CdZeD33fXsAHfZYS8jdxg4qHgXYJwBQ1Bv6GJyETtLST"
[registry]
url = "https://api.apr.dev"
[provider]
cluster = "Localnet"
wallet = "~/.config/solana/id.json"
[scripts]
test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.