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-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/ui/button.tsx
import * as React from "react"; import { Slot } from "@radix-ui/react-slot"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const buttonVariants = cva( "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50", { variants: { variant: { default: "bg-primary text-primary-foreground hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90", outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-10 px-4 py-2", sm: "h-9 rounded-md px-3", lg: "h-11 rounded-md px-8", icon: "h-10 w-10", }, }, defaultVariants: { variant: "default", size: "default", }, }, ); export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> { asChild?: boolean; } const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button"; return ( <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} /> ); }, ); Button.displayName = "Button"; export { Button, buttonVariants };
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/ui/toggle.tsx
"use client" import * as React from "react" import * as TogglePrimitive from "@radix-ui/react-toggle" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const toggleVariants = cva( "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground", { variants: { variant: { default: "bg-transparent", outline: "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground", }, size: { default: "h-10 px-3", sm: "h-9 px-2.5", lg: "h-11 px-5", }, }, defaultVariants: { variant: "default", size: "default", }, } ) const Toggle = React.forwardRef< React.ElementRef<typeof TogglePrimitive.Root>, React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants> >(({ className, variant, size, ...props }, ref) => ( <TogglePrimitive.Root ref={ref} className={cn(toggleVariants({ variant, size, className }))} {...props} /> )) Toggle.displayName = TogglePrimitive.Root.displayName export { Toggle, toggleVariants }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/ui/toast.tsx
"use client" import * as React from "react" import * as ToastPrimitives from "@radix-ui/react-toast" import { cva, type VariantProps } from "class-variance-authority" import { X } from "lucide-react" import { cn } from "@/lib/utils" const ToastProvider = ToastPrimitives.Provider const ToastViewport = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Viewport>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport> >(({ className, ...props }, ref) => ( <ToastPrimitives.Viewport ref={ref} className={cn( "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]", className )} {...props} /> )) ToastViewport.displayName = ToastPrimitives.Viewport.displayName const toastVariants = cva( "group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", { variants: { variant: { default: "border bg-background text-foreground", destructive: "destructive group border-destructive bg-destructive text-destructive-foreground", }, }, defaultVariants: { variant: "default", }, } ) const Toast = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Root>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants> >(({ className, variant, ...props }, ref) => { return ( <ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props} /> ) }) Toast.displayName = ToastPrimitives.Root.displayName const ToastAction = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Action>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action> >(({ className, ...props }, ref) => ( <ToastPrimitives.Action ref={ref} className={cn( "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive", className )} {...props} /> )) ToastAction.displayName = ToastPrimitives.Action.displayName const ToastClose = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Close>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close> >(({ className, ...props }, ref) => ( <ToastPrimitives.Close ref={ref} className={cn( "absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600", className )} toast-close="" {...props} > <X className="h-4 w-4" /> </ToastPrimitives.Close> )) ToastClose.displayName = ToastPrimitives.Close.displayName const ToastTitle = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Title>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title> >(({ className, ...props }, ref) => ( <ToastPrimitives.Title ref={ref} className={cn("text-sm font-semibold", className)} {...props} /> )) ToastTitle.displayName = ToastPrimitives.Title.displayName const ToastDescription = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Description>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description> >(({ className, ...props }, ref) => ( <ToastPrimitives.Description ref={ref} className={cn("text-sm opacity-90", className)} {...props} /> )) ToastDescription.displayName = ToastPrimitives.Description.displayName type ToastProps = React.ComponentPropsWithoutRef<typeof Toast> type ToastActionElement = React.ReactElement<typeof ToastAction> export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction, }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/ui/checkbox.tsx
"use client" import * as React from "react" import * as CheckboxPrimitive from "@radix-ui/react-checkbox" import { Check } from "lucide-react" import { cn } from "@/lib/utils" const Checkbox = React.forwardRef< React.ElementRef<typeof CheckboxPrimitive.Root>, React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root> >(({ className, ...props }, ref) => ( <CheckboxPrimitive.Root ref={ref} className={cn( "peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground", className )} {...props} > <CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")} > <Check className="h-4 w-4" /> </CheckboxPrimitive.Indicator> </CheckboxPrimitive.Root> )) Checkbox.displayName = CheckboxPrimitive.Root.displayName export { Checkbox }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/ui/select.tsx
"use client" import * as React from "react" import * as SelectPrimitive from "@radix-ui/react-select" import { Check, ChevronDown, ChevronUp } from "lucide-react" import { cn } from "@/lib/utils" const Select = SelectPrimitive.Root const SelectGroup = SelectPrimitive.Group const SelectValue = SelectPrimitive.Value const SelectTrigger = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Trigger>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger> >(({ className, children, ...props }, ref) => ( <SelectPrimitive.Trigger ref={ref} className={cn( "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1", className )} {...props} > {children} <SelectPrimitive.Icon asChild> <ChevronDown className="h-4 w-4 opacity-50" /> </SelectPrimitive.Icon> </SelectPrimitive.Trigger> )) SelectTrigger.displayName = SelectPrimitive.Trigger.displayName const SelectScrollUpButton = React.forwardRef< React.ElementRef<typeof SelectPrimitive.ScrollUpButton>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton> >(({ className, ...props }, ref) => ( <SelectPrimitive.ScrollUpButton ref={ref} className={cn( "flex cursor-default items-center justify-center py-1", className )} {...props} > <ChevronUp className="h-4 w-4" /> </SelectPrimitive.ScrollUpButton> )) SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName const SelectScrollDownButton = React.forwardRef< React.ElementRef<typeof SelectPrimitive.ScrollDownButton>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton> >(({ className, ...props }, ref) => ( <SelectPrimitive.ScrollDownButton ref={ref} className={cn( "flex cursor-default items-center justify-center py-1", className )} {...props} > <ChevronDown className="h-4 w-4" /> </SelectPrimitive.ScrollDownButton> )) SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName const SelectContent = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Content>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> >(({ className, children, position = "popper", ...props }, ref) => ( <SelectPrimitive.Portal> <SelectPrimitive.Content ref={ref} className={cn( "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", position === "popper" && "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", className )} position={position} {...props} > <SelectScrollUpButton /> <SelectPrimitive.Viewport className={cn( "p-1", position === "popper" && "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]" )} > {children} </SelectPrimitive.Viewport> <SelectScrollDownButton /> </SelectPrimitive.Content> </SelectPrimitive.Portal> )) SelectContent.displayName = SelectPrimitive.Content.displayName const SelectLabel = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Label>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label> >(({ className, ...props }, ref) => ( <SelectPrimitive.Label ref={ref} className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)} {...props} /> )) SelectLabel.displayName = SelectPrimitive.Label.displayName const SelectItem = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Item>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item> >(({ className, children, ...props }, ref) => ( <SelectPrimitive.Item ref={ref} className={cn( "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} {...props} > <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> <SelectPrimitive.ItemIndicator> <Check className="h-4 w-4" /> </SelectPrimitive.ItemIndicator> </span> <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> </SelectPrimitive.Item> )) SelectItem.displayName = SelectPrimitive.Item.displayName const SelectSeparator = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Separator>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator> >(({ className, ...props }, ref) => ( <SelectPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} /> )) SelectSeparator.displayName = SelectPrimitive.Separator.displayName export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem, SelectSeparator, SelectScrollUpButton, SelectScrollDownButton, }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/ui/input.tsx
import * as React from "react" import { cn } from "@/lib/utils" export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {} const Input = React.forwardRef<HTMLInputElement, InputProps>( ({ className, type, ...props }, ref) => { return ( <input type={type} className={cn( "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50", className )} ref={ref} {...props} /> ) } ) Input.displayName = "Input" export { Input }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/ui/skeleton.tsx
import { cn } from "@/lib/utils"; function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) { return ( <div className={cn("animate-pulse rounded-md bg-muted", className)} {...props} /> ); } export { Skeleton };
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/ui/form.tsx
import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label" import { Slot } from "@radix-ui/react-slot" import { Controller, ControllerProps, FieldPath, FieldValues, FormProvider, useFormContext, } from "react-hook-form" import { cn } from "@/lib/utils" import { Label } from "@/components/ui/label" const Form = FormProvider type FormFieldContextValue< TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues> > = { name: TName } const FormFieldContext = React.createContext<FormFieldContextValue>( {} as FormFieldContextValue ) const FormField = < TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues> >({ ...props }: ControllerProps<TFieldValues, TName>) => { return ( <FormFieldContext.Provider value={{ name: props.name }}> <Controller {...props} /> </FormFieldContext.Provider> ) } const useFormField = () => { const fieldContext = React.useContext(FormFieldContext) const itemContext = React.useContext(FormItemContext) const { getFieldState, formState } = useFormContext() const fieldState = getFieldState(fieldContext.name, formState) if (!fieldContext) { throw new Error("useFormField should be used within <FormField>") } const { id } = itemContext return { id, name: fieldContext.name, formItemId: `${id}-form-item`, formDescriptionId: `${id}-form-item-description`, formMessageId: `${id}-form-item-message`, ...fieldState, } } type FormItemContextValue = { id: string } const FormItemContext = React.createContext<FormItemContextValue>( {} as FormItemContextValue ) const FormItem = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => { const id = React.useId() return ( <FormItemContext.Provider value={{ id }}> <div ref={ref} className={cn("space-y-2", className)} {...props} /> </FormItemContext.Provider> ) }) FormItem.displayName = "FormItem" const FormLabel = React.forwardRef< React.ElementRef<typeof LabelPrimitive.Root>, React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> >(({ className, ...props }, ref) => { const { error, formItemId } = useFormField() return ( <Label ref={ref} className={cn(error && "text-destructive", className)} htmlFor={formItemId} {...props} /> ) }) FormLabel.displayName = "FormLabel" const FormControl = React.forwardRef< React.ElementRef<typeof Slot>, React.ComponentPropsWithoutRef<typeof Slot> >(({ ...props }, ref) => { const { error, formItemId, formDescriptionId, formMessageId } = useFormField() return ( <Slot ref={ref} id={formItemId} aria-describedby={ !error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}` } aria-invalid={!!error} {...props} /> ) }) FormControl.displayName = "FormControl" const FormDescription = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement> >(({ className, ...props }, ref) => { const { formDescriptionId } = useFormField() return ( <p ref={ref} id={formDescriptionId} className={cn("text-sm text-muted-foreground", className)} {...props} /> ) }) FormDescription.displayName = "FormDescription" const FormMessage = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement> >(({ className, children, ...props }, ref) => { const { error, formMessageId } = useFormField() const body = error ? String(error?.message) : children if (!body) { return null } return ( <p ref={ref} id={formMessageId} className={cn("text-sm font-medium text-destructive", className)} {...props} > {body} </p> ) }) FormMessage.displayName = "FormMessage" export { useFormField, Form, FormItem, FormLabel, FormControl, FormDescription, FormMessage, FormField, }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/providers/theme-provider.tsx
"use client"; import * as React from "react"; import { ThemeProvider as NextThemesProvider } from "next-themes"; import { type ThemeProviderProps } from "next-themes/dist/types"; export function ThemeProvider({ children, ...props }: ThemeProviderProps) { return <NextThemesProvider {...props}>{children}</NextThemesProvider>; }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/providers/pyth-pricefeed-provider.tsx
"use client"; import React, { createContext, useContext, useEffect, useState } from "react"; import { PriceServiceConnection, PriceFeed, } from "@pythnetwork/price-service-client"; import { PublicKey } from "@solana/web3.js"; const SOL_PRICE_FEED_ID = "0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d"; const SOL_USD_PRICE_FEED_ACCOUNT = new PublicKey( "7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE", ); // Shared state for pyth price feed interface PythPriceContextType { solPriceFeed: PriceFeed | null; solUsdPriceFeedAccount: PublicKey; isLoading: boolean; error: string | null; } const PythPriceContext = createContext<PythPriceContextType | undefined>( undefined, ); export function usePythPrice() { const context = useContext(PythPriceContext); if (context === undefined) { throw new Error("usePythPrice must be used within a PythPriceProvider"); } return context; } export function PythPriceProvider({ children }: { children: React.ReactNode }) { const [solPriceFeed, setSolPriceFeed] = useState<PriceFeed | null>(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState<string | null>(null); useEffect(() => { const priceServiceConnection = new PriceServiceConnection( "https://hermes.pyth.network", ); const fetchInitialPrice = async () => { try { const priceFeed = await priceServiceConnection.getLatestPriceFeeds([ SOL_PRICE_FEED_ID, ]); if (priceFeed && priceFeed.length > 0) { setSolPriceFeed(priceFeed[0]); } else { setError("No price feeds returned"); } setIsLoading(false); } catch (err) { setError("Failed to fetch initial SOL price"); setIsLoading(false); } }; fetchInitialPrice(); priceServiceConnection.subscribePriceFeedUpdates( [SOL_PRICE_FEED_ID], (priceFeed) => { setSolPriceFeed(priceFeed); }, ); return () => { priceServiceConnection.closeWebSocket(); }; }, []); return ( <PythPriceContext.Provider value={{ solPriceFeed, solUsdPriceFeedAccount: SOL_USD_PRICE_FEED_ACCOUNT, isLoading, error, }} > {children} </PythPriceContext.Provider> ); }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/providers/wallet-provider.tsx
"use client"; import { WalletAdapterNetwork } from "@solana/wallet-adapter-base"; import { ConnectionProvider, WalletProvider, } from "@solana/wallet-adapter-react"; import { WalletModalProvider } from "@solana/wallet-adapter-react-ui"; import { clusterApiUrl } from "@solana/web3.js"; import "@solana/wallet-adapter-react-ui/styles.css"; import { useMemo } from "react"; export function SolanaWalletProvider({ children, }: { children: React.ReactNode; }) { const network = WalletAdapterNetwork.Devnet; const endpoint = useMemo(() => clusterApiUrl(network), [network]); return ( <ConnectionProvider endpoint={endpoint}> <WalletProvider wallets={[]} autoConnect> <WalletModalProvider>{children}</WalletModalProvider> </WalletProvider> </ConnectionProvider> ); }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/providers/config-account-provider.tsx
"use client"; import React, { createContext, useContext, useEffect, useState } from "react"; import { useConnection } from "@solana/wallet-adapter-react"; import { AccountInfo } from "@solana/web3.js"; import { program, configPDA, ConfigAccount } from "@/anchor/setup"; // Shared state for program config account interface ConfigContextType { config: ConfigAccount | null; isLoading: boolean; error: string | null; } const ConfigContext = createContext<ConfigContextType | undefined>(undefined); export function useConfig() { const context = useContext(ConfigContext); if (context === undefined) { throw new Error("useConfig must be used within a ConfigProvider"); } return context; } export function ConfigProvider({ children }: { children: React.ReactNode }) { const { connection } = useConnection(); const [config, setConfig] = useState<ConfigAccount | null>(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState<string | null>(null); const handleAccountChange = (accountInfo: AccountInfo<Buffer>) => { try { const decodedData = program.coder.accounts.decode( "config", accountInfo.data, ) as ConfigAccount; setConfig(decodedData); setError(null); } catch (error) { console.error("Error decoding config account data:", error); setError("Failed to decode config account data"); } finally { setIsLoading(false); } }; useEffect(() => { // Fetch initial account data program.account.config .fetch(configPDA) .then(setConfig) .catch((error) => { console.error("Error fetching config account:", error); setError("Failed to fetch config account"); setIsLoading(false); }); // Subscribe to account changes const subscriptionId = connection.onAccountChange( configPDA, handleAccountChange, ); return () => { connection.removeAccountChangeListener(subscriptionId); }; }, [connection]); return ( <ConfigContext.Provider value={{ config, isLoading, error }}> {children} </ConfigContext.Provider> ); }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/providers/collateral-account-provider.tsx
"use client"; import React, { createContext, useContext, useEffect, useState, useCallback, } from "react"; import { useConnection, useWallet } from "@solana/wallet-adapter-react"; import { AccountInfo, PublicKey } from "@solana/web3.js"; import { program, CollateralAccount } from "@/anchor/setup"; // Shared state for program collateral accounts interface CollateralContextType { collateral: CollateralAccount | null; collateralAccountPDA: PublicKey | null; allCollateralAccounts: { publicKey: PublicKey; account: CollateralAccount }[]; isLoading: boolean; error: string | null; refetchCollateralAccount: (pubkey: PublicKey) => Promise<void>; } const CollateralContext = createContext<CollateralContextType | undefined>( undefined, ); export function useCollateral() { const context = useContext(CollateralContext); if (context === undefined) { throw new Error("useCollateral must be used within a CollateralProvider"); } return context; } export function CollateralProvider({ children, }: { children: React.ReactNode; }) { const { connection } = useConnection(); const { publicKey, connected } = useWallet(); const [collateral, setCollateral] = useState<CollateralAccount | null>(null); const [collateralAccountPDA, setCollateralAccountPDA] = useState<PublicKey | null>(null); const [allCollateralAccounts, setAllCollateralAccounts] = useState< { publicKey: PublicKey; account: CollateralAccount }[] >([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState<string | null>(null); const handleAccountChange = (accountInfo: AccountInfo<Buffer>) => { try { const decodedData = program.coder.accounts.decode( "collateral", accountInfo.data, ) as CollateralAccount; setCollateral(decodedData); setError(null); } catch (error) { console.error("Error decoding collateral account data:", error); setError("Failed to decode collateral account data"); } finally { setIsLoading(false); } }; const fetchAllCollateralAccounts = async () => { try { const accounts = await program.account.collateral.all(); setAllCollateralAccounts(accounts); } catch (error) { console.error("Error fetching all collateral accounts:", error); setError("Failed to fetch all collateral accounts"); } }; const refetchCollateralAccount = useCallback(async (pubkey: PublicKey) => { try { const account = await program.account.collateral.fetch(pubkey); setAllCollateralAccounts((prevAccounts) => { const index = prevAccounts.findIndex((a) => a.publicKey.equals(pubkey)); if (index !== -1) { const newAccounts = [...prevAccounts]; newAccounts[index] = { publicKey: pubkey, account }; return newAccounts; } return prevAccounts; }); } catch (error) { console.error("Error refetching collateral account:", error); setError("Failed to refetch collateral account"); } }, []); useEffect(() => { // Fetch all collateral accounts fetchAllCollateralAccounts(); if (!connected || !publicKey) { setCollateral(null); setCollateralAccountPDA(null); setIsLoading(false); setError(null); return; } setIsLoading(true); const [collateralPDA] = PublicKey.findProgramAddressSync( [Buffer.from("collateral"), publicKey.toBuffer()], program.programId, ); setCollateralAccountPDA(collateralPDA); // Fetch initial account data program.account.collateral .fetch(collateralPDA) .then((data) => { setCollateral(data as CollateralAccount); setError(null); }) .catch((error) => { if (error.message.includes("Account does not exist")) { setCollateral(null); setError(null); } else { console.error("Error fetching collateral account:", error); setError("Failed to fetch collateral account"); } }) .finally(() => setIsLoading(false)); // Subscribe to account changes const subscriptionId = connection.onAccountChange( collateralPDA, handleAccountChange, ); return () => { connection.removeAccountChangeListener(subscriptionId); }; }, [connection, publicKey, connected]); return ( <CollateralContext.Provider value={{ collateral, collateralAccountPDA, allCollateralAccounts, isLoading, error, refetchCollateralAccount, }} > {children} </CollateralContext.Provider> ); }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/stablecoin/deposit.tsx
import React, { useState, useEffect, useCallback } from "react"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Slider } from "@/components/ui/slider"; import { Button } from "@/components/ui/button"; import { AlertCircle } from "lucide-react"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { useConfig } from "../providers/config-account-provider"; import { useCollateral } from "../providers/collateral-account-provider"; import { usePythPrice } from "../providers/pyth-pricefeed-provider"; import { calculateHealthFactor, getUsdValue, BASE_UNIT } from "@/app/utils"; import { useConnection, useWallet } from "@solana/wallet-adapter-react"; import { program } from "@/anchor/setup"; import { BN } from "@coral-xyz/anchor"; import { LAMPORTS_PER_SOL } from "@solana/web3.js"; import { Loader2 } from "lucide-react"; import { useTransactionToast } from "./toast"; // UI to invoke depositCollateralAndMint instruction const CollateralMintUI = () => { const [depositAmount, setDepositAmount] = useState(0); const [mintAmount, setMintAmount] = useState(0); const [maxMintAmount, setMaxMintAmount] = useState(0); const [healthFactor, setHealthFactor] = useState(0); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(false); const { config } = useConfig(); const { collateral } = useCollateral(); const { solPriceFeed, solUsdPriceFeedAccount } = usePythPrice(); const { connection } = useConnection(); const { publicKey, connected, sendTransaction } = useWallet(); const { showTransactionToast } = useTransactionToast(); const updateCalculations = useCallback(() => { if (solPriceFeed && config) { const existingCollateral = Number(collateral?.lamportBalance) || 0; const existingMinted = Number(collateral?.amountMinted) || 0; const depositLamports = depositAmount * LAMPORTS_PER_SOL; const totalCollateralLamports = existingCollateral + depositLamports; const totalCollateralUsd = getUsdValue( totalCollateralLamports, solPriceFeed, ); const newMaxMintAmount = Math.floor( (totalCollateralUsd * config.liquidationThreshold) / 100, ); setMaxMintAmount(Math.max(0, newMaxMintAmount - existingMinted)); const totalMintedAmount = existingMinted + mintAmount; if (totalMintedAmount > 0) { const newHealthFactor = calculateHealthFactor( totalCollateralLamports, totalMintedAmount, config.liquidationThreshold, solPriceFeed, ); setHealthFactor(newHealthFactor); if (newHealthFactor < config.minHealthFactor) { setError("Warning: Health factor would be below minimum"); } else { setError(""); } } else { setHealthFactor(0); } } }, [depositAmount, mintAmount, solPriceFeed, config, collateral]); useEffect(() => { updateCalculations(); }, [updateCalculations]); const handleDepositAmountChange = (value: number) => { setDepositAmount(value); }; const handleMintAmountChange = (value: number) => { setMintAmount(value); }; const resetAmounts = () => { setDepositAmount(0); setMintAmount(0); }; const handleDeposit = async () => { if (!publicKey || !solPriceFeed) { setError("Wallet not connected or price feed unavailable"); return; } setIsLoading(true); try { const amountCollateral = new BN(depositAmount * LAMPORTS_PER_SOL); const amountToMint = new BN(mintAmount); const tx = await program.methods .depositCollateralAndMint(amountCollateral, amountToMint) .accounts({ depositor: publicKey, priceUpdate: solUsdPriceFeedAccount, }) .transaction(); const transactionSignature = await sendTransaction(tx, connection, { skipPreflight: true, }); console.log("Transaction signature", transactionSignature); showTransactionToast(transactionSignature); resetAmounts(); } catch (err) { console.error("Error depositing collateral and minting:", err); // setError("Failed to deposit collateral and mint tokens"); } finally { setIsLoading(false); } }; return ( <div className="grid w-full items-center gap-4"> <div className="flex flex-col space-y-1.5"> <Label htmlFor="depositAmount">Deposit Amount (SOL)</Label> <Input id="depositAmount" type="number" value={depositAmount} onChange={(e) => handleDepositAmountChange(parseFloat(e.target.value) || 0) } /> </div> <div className="flex flex-col space-y-1.5"> <Label htmlFor="mintAmount">Mint Amount ($)</Label> <Slider id="mintAmount" max={maxMintAmount} step={BASE_UNIT / 100} value={[mintAmount]} onValueChange={(value) => handleMintAmountChange(value[0])} /> <div className="text-sm text-muted-foreground"> ${(mintAmount / BASE_UNIT).toFixed(2)} / $ {(maxMintAmount / BASE_UNIT).toFixed(2)} </div> </div> <div className="flex flex-col space-y-1.5"> <Label>Health Factor</Label> <progress value={healthFactor} max={config?.minHealthFactor * 2 || 0} className="w-full" ></progress> <div className="text-sm text-muted-foreground"> {healthFactor === 0 ? "N/A (No tokens minted)" : healthFactor.toFixed(2)} </div> </div> {error && ( <Alert variant="destructive"> <AlertCircle className="h-4 w-4" /> <AlertTitle>Error</AlertTitle> <AlertDescription>{error}</AlertDescription> </Alert> )} <Button onClick={handleDeposit} disabled={!connected || !!error || isLoading} > {isLoading ? ( <Loader2 className="h-6 w-6 animate-spin" /> ) : ( "Deposit and Mint" )} </Button> </div> ); }; export default CollateralMintUI;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/stablecoin/withdraw.tsx
import React, { useState, useEffect, useCallback } from "react"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Slider } from "@/components/ui/slider"; import { Button } from "@/components/ui/button"; import { AlertCircle } from "lucide-react"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Switch } from "@/components/ui/switch"; import { useConfig } from "../providers/config-account-provider"; import { useCollateral } from "../providers/collateral-account-provider"; import { usePythPrice } from "../providers/pyth-pricefeed-provider"; import { calculateHealthFactor, BASE_UNIT } from "@/app/utils"; import { useConnection, useWallet } from "@solana/wallet-adapter-react"; import { program } from "@/anchor/setup"; import { BN } from "@coral-xyz/anchor"; import { LAMPORTS_PER_SOL } from "@solana/web3.js"; import { Loader2 } from "lucide-react"; import { useTransactionToast } from "./toast"; // UI to invoke redeemCollateralAndBurnTokens instruction const RedeemBurnUI = () => { const [burnAmount, setBurnAmount] = useState(0); const [redeemAmount, setRedeemAmount] = useState(0); const [maxRedeemAmount, setMaxRedeemAmount] = useState(0); const [healthFactor, setHealthFactor] = useState(0); const [error, setError] = useState(""); const [isMaxRedeem, setIsMaxRedeem] = useState(false); const [isLoading, setIsLoading] = useState(false); const { config } = useConfig(); const { collateral, collateralAccountPDA } = useCollateral(); const { solPriceFeed, solUsdPriceFeedAccount } = usePythPrice(); const { connection } = useConnection(); const { publicKey, connected, sendTransaction } = useWallet(); const { showTransactionToast } = useTransactionToast(); const updateCalculations = useCallback(() => { if (solPriceFeed && config && collateral) { const remainingMinted = Math.max(collateral.amountMinted - burnAmount, 0); const maxRedeemLamports = collateral.lamportBalance; setMaxRedeemAmount(maxRedeemLamports); if (isMaxRedeem) { setRedeemAmount(maxRedeemLamports); } if (remainingMinted === 0) { setHealthFactor(Number.POSITIVE_INFINITY); } else { const newHealthFactor = calculateHealthFactor( collateral.lamportBalance - redeemAmount, remainingMinted, config.liquidationThreshold, solPriceFeed, ); setHealthFactor(newHealthFactor); if (newHealthFactor < config.minHealthFactor && !isMaxRedeem) { setError("Warning: Health factor would be below minimum"); } else { setError(""); } } } }, [solPriceFeed, config, collateral, burnAmount, redeemAmount, isMaxRedeem]); useEffect(() => { updateCalculations(); }, [updateCalculations]); const handleBurnAmountChange = (value: number) => { const burnAmountInBaseUnits = Math.floor(value * BASE_UNIT); setBurnAmount(burnAmountInBaseUnits); updateCalculations(); }; const handleRedeemAmountChange = (value: number) => { setRedeemAmount(value); updateCalculations(); }; const handleMaxRedeemToggle = (checked: boolean) => { setIsMaxRedeem(checked); if (checked) { setRedeemAmount(maxRedeemAmount); setBurnAmount(collateral?.amountMinted); } }; const resetAmounts = () => { setRedeemAmount(0); setBurnAmount(0); }; const handleRedeemAndBurn = async () => { if (!publicKey || !solPriceFeed || !collateralAccountPDA) { setError( "Wallet not connected, price feed unavailable, or collateral account not found", ); return; } setIsLoading(true); try { const amountCollateral = new BN(redeemAmount); const amountToBurn = new BN(burnAmount); const tx = await program.methods .redeemCollateralAndBurnTokens(amountCollateral, amountToBurn) .accounts({ depositor: publicKey, priceUpdate: solUsdPriceFeedAccount, }) .transaction(); const transactionSignature = await sendTransaction(tx, connection, { skipPreflight: true, }); console.log("Transaction signature", transactionSignature); showTransactionToast(transactionSignature); resetAmounts(); } catch (err) { console.error("Error redeeming collateral and burning tokens:", err); // setError("Failed to redeem collateral and burn tokens"); } finally { setIsLoading(false); } }; return ( <div className="grid w-full items-center gap-4"> <div className="flex flex-col space-y-1.5"> <Label htmlFor="burnAmount">Burn Amount ($)</Label> <Input id="burnAmount" type="number" value={burnAmount / BASE_UNIT} onChange={(e) => handleBurnAmountChange(parseFloat(e.target.value) || 0) } max={(collateral?.amountMinted || 0) / BASE_UNIT} // step="0.000000001" /> </div> <div className="flex flex-col space-y-1.5"> <Label htmlFor="redeemAmount">Redeem Amount (SOL)</Label> <Slider id="redeemAmount" max={maxRedeemAmount} step={LAMPORTS_PER_SOL / 1e6} value={[redeemAmount]} onValueChange={(value) => handleRedeemAmountChange(value[0])} disabled={isMaxRedeem} /> <div className="flex items-center justify-between"> <div className="text-sm text-muted-foreground"> {(redeemAmount / LAMPORTS_PER_SOL).toFixed(3)} / {(maxRedeemAmount / LAMPORTS_PER_SOL).toFixed(3)} SOL </div> <div className="flex items-center space-x-2"> <Switch id="maxRedeem" checked={isMaxRedeem} onCheckedChange={handleMaxRedeemToggle} /> <Label htmlFor="maxRedeem">Max</Label> </div> </div> </div> <div className="flex flex-col space-y-1.5"> <Label>Health Factor</Label> <progress value={healthFactor} max={config?.minHealthFactor * 2 || 200} className="w-full" ></progress> <div className="text-sm text-muted-foreground"> {healthFactor === Number.POSITIVE_INFINITY ? "N/A (All tokens burned)" : healthFactor.toFixed(2)} </div> </div> <Button onClick={handleRedeemAndBurn} disabled={!connected || !!error || isLoading} > {isLoading ? ( <Loader2 className="h-6 w-6 animate-spin" /> ) : ( "Redeem and Burn" )} </Button> {error && ( <Alert variant="destructive"> <AlertCircle className="h-4 w-4" /> <AlertTitle>Error</AlertTitle> <AlertDescription>{error}</AlertDescription> </Alert> )} </div> ); }; export default RedeemBurnUI;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/stablecoin/liquidate.tsx
import React, { useState, useEffect, useCallback } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Label } from "@/components/ui/label"; import { Slider } from "@/components/ui/slider"; import { Button } from "@/components/ui/button"; import { AlertCircle, Loader2 } from "lucide-react"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Switch } from "@/components/ui/switch"; import { useConfig } from "../providers/config-account-provider"; import { usePythPrice } from "../providers/pyth-pricefeed-provider"; import { calculateHealthFactor, getLamportsFromUsd, BASE_UNIT, } from "@/app/utils"; import { useConnection, useWallet } from "@solana/wallet-adapter-react"; import { program } from "@/anchor/setup"; import { BN } from "@coral-xyz/anchor"; import { LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js"; import { useCollateral } from "../providers/collateral-account-provider"; import { useTransactionToast } from "./toast"; interface SelectedAccount { pubkey: PublicKey; lamportBalanceInSol: number; amountMintedInUsd: number; healthFactor: number; } interface LiquidateUIProps { selectedAccount: SelectedAccount; } // UI to invoke liquidate instruction const LiquidateUI: React.FC<LiquidateUIProps> = ({ selectedAccount }) => { const [liquidateAmount, setLiquidateAmount] = useState(0); const [maxLiquidateAmount, setMaxLiquidateAmount] = useState(0); const [isMaxLiquidate, setIsMaxLiquidate] = useState(false); const [solToReceive, setSolToReceive] = useState(0); const [liquidationBonus, setLiquidationBonus] = useState(0); const [remainingMinted, setRemainingMinted] = useState(0); const [healthFactor, setHealthFactor] = useState(0); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(false); const { config } = useConfig(); const { refetchCollateralAccount } = useCollateral(); const { solPriceFeed, solUsdPriceFeedAccount } = usePythPrice(); const { connection } = useConnection(); const { publicKey, connected, sendTransaction } = useWallet(); const { showTransactionToast } = useTransactionToast(); const updateCalculations = useCallback(() => { if (solPriceFeed && config && selectedAccount) { const effectiveLiquidateAmount = isMaxLiquidate ? selectedAccount.amountMintedInUsd * BASE_UNIT : liquidateAmount; const lamports = getLamportsFromUsd( effectiveLiquidateAmount / BASE_UNIT, solPriceFeed, ); const bonus = (lamports * Number(config.liquidationBonus)) / 100; const totalSolToReceive = lamports + bonus; setSolToReceive(totalSolToReceive); setLiquidationBonus(bonus); const remainingMinted = Math.max( selectedAccount.amountMintedInUsd * BASE_UNIT - effectiveLiquidateAmount, 0, ); setRemainingMinted(remainingMinted); const remainingCollateral = selectedAccount.lamportBalanceInSol * LAMPORTS_PER_SOL - totalSolToReceive; const newHealthFactor = calculateHealthFactor( remainingCollateral, remainingMinted, config.liquidationThreshold, solPriceFeed, ); setHealthFactor(newHealthFactor); setMaxLiquidateAmount(selectedAccount.amountMintedInUsd * BASE_UNIT); console.log(newHealthFactor); } }, [solPriceFeed, config, selectedAccount, liquidateAmount, isMaxLiquidate]); useEffect(() => { updateCalculations(); }, [updateCalculations]); const handleLiquidateAmountChange = (value: number[]) => { setLiquidateAmount(value[0]); updateCalculations(); }; const handleMaxLiquidateToggle = (checked: boolean) => { setIsMaxLiquidate(checked); if (checked) { setLiquidateAmount(maxLiquidateAmount); } updateCalculations(); }; const resetAmounts = () => { setLiquidateAmount(0); setIsMaxLiquidate(false); updateCalculations(); }; const handleLiquidate = async () => { if (!publicKey || !solPriceFeed) { setError("Wallet not connected or price feed unavailable"); return; } setIsLoading(true); try { const amountToBurn = new BN(liquidateAmount); const tx = await program.methods .liquidate(amountToBurn) .accounts({ liquidator: publicKey, collateralAccount: selectedAccount.pubkey, priceUpdate: solUsdPriceFeedAccount, }) .transaction(); const transactionSignature = await sendTransaction(tx, connection, { skipPreflight: true, }); await connection.confirmTransaction(transactionSignature, "confirmed"); refetchCollateralAccount(selectedAccount.pubkey); showTransactionToast(transactionSignature); resetAmounts(); } catch (err) { console.error("Error during liquidation:", err); setError("Liquidation failed. Please try again."); } finally { setIsLoading(false); } }; return ( <Card className="w-[350px]"> <CardHeader> <CardTitle>Liquidate Tokens</CardTitle> </CardHeader> <CardContent> <div className="grid w-full items-center gap-4"> <div className="flex flex-col space-y-1.5"> <Label htmlFor="liquidateAmount">Amount to Burn ($)</Label> <Slider id="liquidateAmount" max={maxLiquidateAmount} value={[liquidateAmount]} step={BASE_UNIT / 100} onValueChange={handleLiquidateAmountChange} disabled={isMaxLiquidate} /> <div className="flex items-center justify-between"> <div className="text-sm text-muted-foreground"> ${(liquidateAmount / BASE_UNIT).toFixed(3)} / $ {(maxLiquidateAmount / BASE_UNIT).toFixed(3)} tokens </div> <div className="flex items-center space-x-2"> <Switch id="maxLiquidate" checked={isMaxLiquidate} onCheckedChange={handleMaxLiquidateToggle} /> <Label htmlFor="maxLiquidate">Max</Label> </div> </div> </div> <div className="flex flex-col space-y-1.5"> <Label>SOL to Receive</Label> <div className="text-2xl font-bold"> {solToReceive.toFixed(3)} SOL </div> <div className="text-sm text-muted-foreground"> Including {liquidationBonus.toFixed(3)} SOL bonus ( {Number(config?.liquidationBonus)}%) </div> </div> <div className="flex flex-col space-y-1.5"> <Label>Health Factor</Label> <progress value={healthFactor} max={ config?.minHealthFactor ? Number(config.minHealthFactor) * 2 : 200 } className="w-full" ></progress> <div className="text-sm text-muted-foreground"> {remainingMinted === 0 ? "N/A (All tokens burned)" : `${healthFactor.toFixed(2)} (Min: ${Number(config?.minHealthFactor) || 0})`} </div> </div> <Button onClick={handleLiquidate} disabled={!connected || !!error || isLoading} > {isLoading ? ( <Loader2 className="h-6 w-6 animate-spin" /> ) : ( "Liquidate" )} </Button> {error && ( <Alert variant="destructive"> <AlertCircle className="h-4 w-4" /> <AlertTitle>Error</AlertTitle> <AlertDescription>{error}</AlertDescription> </Alert> )} </div> </CardContent> </Card> ); }; export default LiquidateUI;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/stablecoin/collateral.tsx
import React from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table"; import { useCollateral } from "../providers/collateral-account-provider"; import { usePythPrice } from "../providers/pyth-pricefeed-provider"; import { useConfig } from "../providers/config-account-provider"; import { calculateHealthFactor, getUsdValue } from "@/app/utils"; import { LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js"; import { ExternalLink } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; // Display connected wallet's collateral account on deposit/withdraw page const CollateralAccountDisplay = () => { const { collateral, collateralAccountPDA, isLoading, error } = useCollateral(); const { solPriceFeed } = usePythPrice(); const { config } = useConfig(); if (isLoading) { return ( <Card className="w-[400px]"> <CardHeader> <CardTitle>Collateral Account Details</CardTitle> </CardHeader> <CardContent> <Skeleton className="mb-2 h-4 w-full" /> <Skeleton className="mb-2 h-4 w-full" /> <Skeleton className="mb-2 h-4 w-full" /> <Skeleton className="h-4 w-full" /> </CardContent> </Card> ); } if (error) { return ( <Card className="w-[400px]"> <CardHeader> <CardTitle>Error</CardTitle> </CardHeader> <CardContent> <p className="text-red-500">{error}</p> </CardContent> </Card> ); } if (!collateral || !solPriceFeed || !config) { return ( <Card className="w-[400px]"> <CardHeader> <CardTitle>No Data</CardTitle> </CardHeader> <CardContent> <p>No collateral data available</p> </CardContent> </Card> ); } const lamportBalanceInSol = collateral.lamportBalance / LAMPORTS_PER_SOL; const lamportBalanceInUsd = getUsdValue(collateral.lamportBalance, solPriceFeed) / LAMPORTS_PER_SOL; const amountMintedInUsd = collateral.amountMinted / 1e9; const healthFactor = calculateHealthFactor( collateral.lamportBalance, collateral.amountMinted, config.liquidationThreshold, solPriceFeed, ); return ( <Card className="w-[400px]"> <CardHeader> <CardTitle>Collateral Account Details</CardTitle> </CardHeader> <CardContent> <Table> <TableBody> <InfoRow label="Collateral PDA" value={ collateralAccountPDA ? ( <AddressLink pubkey={collateralAccountPDA} /> ) : ( "N/A" ) } /> <InfoRow label="Depositor" value={<AddressLink pubkey={collateral.depositor} />} /> <InfoRow label="SOL Account" value={<AddressLink pubkey={collateral.solAccount} />} /> <InfoRow label="Token Account" value={<AddressLink pubkey={collateral.tokenAccount} />} /> <InfoRow label="SOL Collateral Balance" value={`${lamportBalanceInSol.toFixed(3)} SOL ($${lamportBalanceInUsd.toFixed(2)})`} /> <InfoRow label="Stablecoins Owed" value={`$${amountMintedInUsd.toFixed(3)}`} /> <InfoRow label="Health Factor" value={ <span className={ healthFactor < config.minHealthFactor ? "text-red-500" : "text-green-500" } > {healthFactor.toFixed(2)} </span> } /> </TableBody> </Table> </CardContent> </Card> ); }; export default CollateralAccountDisplay; const InfoRow = ({ label, value, }: { label: string; value: React.ReactNode; }) => ( <TableRow> <TableCell className="font-medium">{label}</TableCell> <TableCell className="text-right">{value}</TableCell> </TableRow> ); const AddressLink = ({ pubkey }: { pubkey: PublicKey }) => { const address = pubkey.toString(); const shortenedAddress = `${address.slice(0, 4)}...${address.slice(-4)}`; const explorerUrl = `https://explorer.solana.com/address/${address}?cluster=devnet`; return ( <a href={explorerUrl} target="_blank" rel="noopener noreferrer" className="flex items-center justify-end text-blue-500 hover:underline" > {shortenedAddress} <ExternalLink className="ml-1 h-3 w-3" /> </a> ); };
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/stablecoin/update-config.tsx
import React, { useState } from "react"; import { Card, CardContent, CardHeader, CardTitle, CardDescription, } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Button } from "@/components/ui/button"; import { AlertCircle, Loader2 } from "lucide-react"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { useConnection, useWallet } from "@solana/wallet-adapter-react"; import { program } from "@/anchor/setup"; import { BN } from "@coral-xyz/anchor"; // UI to invoke updateConfig instruction, can be invoked by anyone to test liquidation const UpdateConfigUI = () => { const [configValue, setConfigValue] = useState(100); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(false); const { connection } = useConnection(); const { publicKey, connected, sendTransaction } = useWallet(); const handleConfigValueChange = (value: string) => { const intValue = parseInt(value, 10); if (!isNaN(intValue) && intValue > 0) { setConfigValue(intValue); } }; const handleUpdateConfig = async () => { if (!publicKey) { setError("Wallet not connected"); return; } setIsLoading(true); setError(""); try { const tx = await program.methods .updateConfig(new BN(configValue)) .accounts({ // Add necessary accounts here }) .transaction(); const transactionSignature = await sendTransaction(tx, connection, { skipPreflight: true, }); console.log("Transaction signature", transactionSignature); // Handle successful transaction (e.g., show success message, update UI) } catch (err) { console.error("Error updating config:", err); // setError("Failed to update config. Please try again."); } finally { setIsLoading(false); } }; return ( <Card className="w-[350px]"> <CardHeader> <CardTitle>Update Config</CardTitle> <CardDescription> Increase the minimum health factor to test liquidation. A higher value makes it easier to trigger liquidations. </CardDescription> </CardHeader> <CardContent> <div className="grid w-full items-center gap-4"> <div className="flex flex-col space-y-1.5"> <Label htmlFor="configValue">Minimum Health Factor</Label> <Input id="configValue" type="number" value={configValue} onChange={(e) => handleConfigValueChange(e.target.value)} min="1" step="1" className="w-full" /> </div> <Button onClick={handleUpdateConfig} disabled={!connected || isLoading} className="w-full" > {isLoading ? ( <Loader2 className="mr-2 h-6 w-6 animate-spin" /> ) : null} {isLoading ? "Updating..." : "Update Health Factor"} </Button> {error && ( <Alert variant="destructive"> <AlertCircle className="h-4 w-4" /> <AlertTitle>Error</AlertTitle> <AlertDescription>{error}</AlertDescription> </Alert> )} </div> </CardContent> </Card> ); }; export default UpdateConfigUI;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/stablecoin/deposit-withdraw.tsx
import React, { useState } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import CollateralMintUI from "@/components/stablecoin/deposit"; import RedeemBurnUI from "@/components/stablecoin/withdraw"; // deposit/withdraw widget const DepositWithdrawUI = () => { const [mode, setMode] = useState("deposit"); return ( <Card className="w-[350px]"> <CardHeader> <CardTitle>Deposit and Withdraw</CardTitle> </CardHeader> <CardContent> <Tabs value={mode} onValueChange={setMode} className="w-full"> <TabsList className="grid w-full grid-cols-2"> <TabsTrigger value="deposit">Deposit</TabsTrigger> <TabsTrigger value="withdraw">Withdraw</TabsTrigger> </TabsList> <TabsContent value="deposit"> <CollateralMintUI /> </TabsContent> <TabsContent value="withdraw"> <RedeemBurnUI /> </TabsContent> </Tabs> </CardContent> </Card> ); }; export default DepositWithdrawUI;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/stablecoin/toast.tsx
import React from "react"; import { useToast } from "@/components/ui/use-toast"; import { Button } from "@/components/ui/button"; import { ExternalLink } from "lucide-react"; // Toast with link to solana explorer transaction export const useTransactionToast = () => { const { toast } = useToast(); const showTransactionToast = (transactionSignature: string) => { toast({ title: "Transaction Sent", description: ( <Button variant="link" className="p-0 text-blue-500 hover:text-blue-600" asChild > <a href={`https://explorer.solana.com/tx/${transactionSignature}?cluster=devnet`} target="_blank" rel="noopener noreferrer" className="flex items-center" > View on Solana Explorer <ExternalLink className="ml-1 h-4 w-4" /> </a> </Button> ), duration: 3000, }); }; return { showTransactionToast }; };
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/components/stablecoin/collateral-table.tsx
import React, { useState, useMemo, useEffect } from "react"; import { useCollateral } from "../providers/collateral-account-provider"; import { usePythPrice } from "../providers/pyth-pricefeed-provider"; import { useConfig } from "../providers/config-account-provider"; import { calculateHealthFactor, getUsdValue } from "@/app/utils"; import { LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js"; import { ExternalLink } from "lucide-react"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog"; import LiquidateUI from "./liquidate"; interface SelectedAccount { pubkey: PublicKey; lamportBalanceInSol: number; lamportBalanceInUsd: number; amountMintedInUsd: number; healthFactor: number; } // Display all collateral accounts on liquidation page const CollateralAccountsTable = () => { const { allCollateralAccounts } = useCollateral(); const { solPriceFeed } = usePythPrice(); const { config } = useConfig(); const [selectedAccount, setSelectedAccount] = useState<SelectedAccount | null>(null); const accountsData = useMemo(() => { if (!allCollateralAccounts || !solPriceFeed || !config) return []; return allCollateralAccounts.map((account) => { const lamportBalanceInSol = account.account.lamportBalance / LAMPORTS_PER_SOL; const lamportBalanceInUsd = getUsdValue(account.account.lamportBalance, solPriceFeed) / LAMPORTS_PER_SOL; const amountMintedInUsd = account.account.amountMinted / 1e9; const healthFactor = calculateHealthFactor( account.account.lamportBalance, account.account.amountMinted, config.liquidationThreshold, solPriceFeed, ); return { pubkey: account.publicKey, lamportBalanceInSol, lamportBalanceInUsd, amountMintedInUsd, healthFactor, }; }); }, [allCollateralAccounts, solPriceFeed, config]); useEffect(() => { if (selectedAccount) { const updatedAccount = accountsData.find( (account) => account.pubkey.toString() === selectedAccount.pubkey.toString(), ); if (updatedAccount) { setSelectedAccount(updatedAccount); } } }, [accountsData, selectedAccount]); return ( <div> <Card> <CardHeader> <CardTitle>Collateral Account Details</CardTitle> </CardHeader> <CardContent> <Table> <TableHeader> <TableRow> <TableHead>Collateral Account</TableHead> <TableHead>SOL Balance</TableHead> <TableHead>Tokens Owed ($)</TableHead> <TableHead>Health Factor</TableHead> <TableHead>Action</TableHead> </TableRow> </TableHeader> <TableBody> {accountsData.map((account) => ( <TableRow key={account.pubkey.toString()}> <TableCell> <AddressLink pubkey={account.pubkey} /> </TableCell> <TableCell> {account.lamportBalanceInSol.toFixed(3)} ($ {account.lamportBalanceInUsd.toFixed(2)}) </TableCell> <TableCell>${account.amountMintedInUsd.toFixed(2)}</TableCell> <TableCell className={ isNaN(account.healthFactor) ? "" : account.healthFactor < config?.minHealthFactor ? "text-red-500" : "text-green-500" } > {account.healthFactor.toFixed(2)} </TableCell> <TableCell> <Dialog> <DialogTrigger asChild> <Button onClick={() => setSelectedAccount(account)} disabled={ isNaN(account.healthFactor) || account.healthFactor >= (Number(config?.minHealthFactor) || 0) } > Liquidate </Button> </DialogTrigger> <DialogContent className="flex items-center justify-center border-none bg-transparent"> {selectedAccount && ( <LiquidateUI selectedAccount={selectedAccount} /> )} </DialogContent> </Dialog> </TableCell> </TableRow> ))} </TableBody> </Table> </CardContent> </Card> </div> ); }; export default CollateralAccountsTable; const AddressLink = ({ pubkey }: { pubkey: PublicKey }) => { const address = pubkey.toString(); const shortenedAddress = `${address.slice(0, 4)}...${address.slice(-4)}`; const explorerUrl = `https://explorer.solana.com/address/${address}?cluster=devnet`; return ( <a href={explorerUrl} target="_blank" rel="noopener noreferrer" className="flex items-center text-blue-500 hover:underline" > {shortenedAddress} <ExternalLink className="ml-1 h-3 w-3" /> </a> ); };
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/public/vercel.svg
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/public/next.svg
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/lib/fonts.ts
import { JetBrains_Mono as FontMono, Inter as FontSans, } from "next/font/google"; export const fontSans = FontSans({ subsets: ["latin"], variable: "--font-sans", }); export const fontMono = FontMono({ subsets: ["latin"], variable: "--font-mono", });
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/lib/utils.ts
import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/anchor/idl.json
{ "address": "6DjiD8tQhJ9ZS3WZrwNubfoBRBrqfWacNR3bXBQ7ir91", "metadata": { "name": "stablecoin", "version": "0.1.0", "spec": "0.1.0", "description": "Created with Anchor" }, "instructions": [ { "name": "deposit_collateral_and_mint", "discriminator": [186, 99, 85, 148, 89, 72, 66, 57], "accounts": [ { "name": "depositor", "writable": true, "signer": true }, { "name": "config_account", "pda": { "seeds": [ { "kind": "const", "value": [99, 111, 110, 102, 105, 103] } ] } }, { "name": "collateral_account", "writable": true, "pda": { "seeds": [ { "kind": "const", "value": [99, 111, 108, 108, 97, 116, 101, 114, 97, 108] }, { "kind": "account", "path": "depositor" } ] } }, { "name": "sol_account", "writable": true, "pda": { "seeds": [ { "kind": "const", "value": [115, 111, 108] }, { "kind": "account", "path": "depositor" } ] } }, { "name": "mint_account", "writable": true, "relations": ["config_account"] }, { "name": "price_update" }, { "name": "token_account", "writable": true, "pda": { "seeds": [ { "kind": "account", "path": "depositor" }, { "kind": "account", "path": "token_program" }, { "kind": "account", "path": "mint_account" } ], "program": { "kind": "const", "value": [ 140, 151, 37, 143, 78, 36, 137, 241, 187, 61, 16, 41, 20, 142, 13, 131, 11, 90, 19, 153, 218, 255, 16, 132, 4, 142, 123, 216, 219, 233, 248, 89 ] } } }, { "name": "token_program", "address": "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb" }, { "name": "associated_token_program", "address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" }, { "name": "system_program", "address": "11111111111111111111111111111111" } ], "args": [ { "name": "amount_collateral", "type": "u64" }, { "name": "amount_to_mint", "type": "u64" } ] }, { "name": "initialize_config", "discriminator": [208, 127, 21, 1, 194, 190, 196, 70], "accounts": [ { "name": "authority", "writable": true, "signer": true }, { "name": "config_account", "writable": true, "pda": { "seeds": [ { "kind": "const", "value": [99, 111, 110, 102, 105, 103] } ] } }, { "name": "mint_account", "writable": true, "pda": { "seeds": [ { "kind": "const", "value": [109, 105, 110, 116] } ] } }, { "name": "token_program", "address": "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb" }, { "name": "system_program", "address": "11111111111111111111111111111111" } ], "args": [] }, { "name": "liquidate", "discriminator": [223, 179, 226, 125, 48, 46, 39, 74], "accounts": [ { "name": "liquidator", "writable": true, "signer": true }, { "name": "price_update" }, { "name": "config_account", "pda": { "seeds": [ { "kind": "const", "value": [99, 111, 110, 102, 105, 103] } ] } }, { "name": "collateral_account", "writable": true }, { "name": "sol_account", "writable": true, "relations": ["collateral_account"] }, { "name": "mint_account", "writable": true, "relations": ["config_account"] }, { "name": "token_account", "writable": true, "pda": { "seeds": [ { "kind": "account", "path": "liquidator" }, { "kind": "account", "path": "token_program" }, { "kind": "account", "path": "mint_account" } ], "program": { "kind": "const", "value": [ 140, 151, 37, 143, 78, 36, 137, 241, 187, 61, 16, 41, 20, 142, 13, 131, 11, 90, 19, 153, 218, 255, 16, 132, 4, 142, 123, 216, 219, 233, 248, 89 ] } } }, { "name": "token_program", "address": "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb" }, { "name": "system_program", "address": "11111111111111111111111111111111" } ], "args": [ { "name": "amount_to_burn", "type": "u64" } ] }, { "name": "redeem_collateral_and_burn_tokens", "discriminator": [133, 209, 165, 17, 145, 53, 164, 84], "accounts": [ { "name": "depositor", "writable": true, "signer": true }, { "name": "price_update" }, { "name": "config_account", "pda": { "seeds": [ { "kind": "const", "value": [99, 111, 110, 102, 105, 103] } ] } }, { "name": "collateral_account", "writable": true, "pda": { "seeds": [ { "kind": "const", "value": [99, 111, 108, 108, 97, 116, 101, 114, 97, 108] }, { "kind": "account", "path": "depositor" } ] } }, { "name": "sol_account", "writable": true, "relations": ["collateral_account"] }, { "name": "mint_account", "writable": true, "relations": ["config_account"] }, { "name": "token_account", "writable": true, "relations": ["collateral_account"] }, { "name": "token_program", "address": "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb" }, { "name": "system_program", "address": "11111111111111111111111111111111" } ], "args": [ { "name": "amount_collateral", "type": "u64" }, { "name": "amount_to_burn", "type": "u64" } ] }, { "name": "update_config", "discriminator": [29, 158, 252, 191, 10, 83, 219, 99], "accounts": [ { "name": "config_account", "writable": true, "pda": { "seeds": [ { "kind": "const", "value": [99, 111, 110, 102, 105, 103] } ] } } ], "args": [ { "name": "min_health_factor", "type": "u64" } ] } ], "accounts": [ { "name": "Collateral", "discriminator": [123, 130, 234, 63, 255, 240, 255, 92] }, { "name": "Config", "discriminator": [155, 12, 170, 224, 30, 250, 204, 130] }, { "name": "PriceUpdateV2", "discriminator": [34, 241, 35, 99, 157, 126, 244, 205] } ], "errors": [ { "code": 6000, "name": "BelowMinimumHealthFactor", "msg": "Below Minimum Health Factor" }, { "code": 6001, "name": "AboveMinimumHealthFactor", "msg": "Above Minimum Health Factor, Cannot Liquidate Healthy Account" }, { "code": 6002, "name": "InvalidPrice", "msg": "Price should not be negative" } ], "types": [ { "name": "Collateral", "type": { "kind": "struct", "fields": [ { "name": "depositor", "type": "pubkey" }, { "name": "sol_account", "type": "pubkey" }, { "name": "token_account", "type": "pubkey" }, { "name": "lamport_balance", "type": "u64" }, { "name": "amount_minted", "type": "u64" }, { "name": "bump", "type": "u8" }, { "name": "bump_sol_account", "type": "u8" }, { "name": "is_initialized", "type": "bool" } ] } }, { "name": "Config", "type": { "kind": "struct", "fields": [ { "name": "authority", "type": "pubkey" }, { "name": "mint_account", "type": "pubkey" }, { "name": "liquidation_threshold", "type": "u64" }, { "name": "liquidation_bonus", "type": "u64" }, { "name": "min_health_factor", "type": "u64" }, { "name": "bump", "type": "u8" }, { "name": "bump_mint_account", "type": "u8" } ] } }, { "name": "PriceFeedMessage", "repr": { "kind": "c" }, "type": { "kind": "struct", "fields": [ { "name": "feed_id", "type": { "array": ["u8", 32] } }, { "name": "price", "type": "i64" }, { "name": "conf", "type": "u64" }, { "name": "exponent", "type": "i32" }, { "name": "publish_time", "docs": ["The timestamp of this price update in seconds"], "type": "i64" }, { "name": "prev_publish_time", "docs": [ "The timestamp of the previous price update. This field is intended to allow users to", "identify the single unique price update for any moment in time:", "for any time t, the unique update is the one such that prev_publish_time < t <= publish_time.", "", "Note that there may not be such an update while we are migrating to the new message-sending logic,", "as some price updates on pythnet may not be sent to other chains (because the message-sending", "logic may not have triggered). We can solve this problem by making the message-sending mandatory", "(which we can do once publishers have migrated over).", "", "Additionally, this field may be equal to publish_time if the message is sent on a slot where", "where the aggregation was unsuccesful. This problem will go away once all publishers have", "migrated over to a recent version of pyth-agent." ], "type": "i64" }, { "name": "ema_price", "type": "i64" }, { "name": "ema_conf", "type": "u64" } ] } }, { "name": "PriceUpdateV2", "docs": [ "A price update account. This account is used by the Pyth Receiver program to store a verified price update from a Pyth price feed.", "It contains:", "- `write_authority`: The write authority for this account. This authority can close this account to reclaim rent or update the account to contain a different price update.", "- `verification_level`: The [`VerificationLevel`] of this price update. This represents how many Wormhole guardian signatures have been verified for this price update.", "- `price_message`: The actual price update.", "- `posted_slot`: The slot at which this price update was posted." ], "type": { "kind": "struct", "fields": [ { "name": "write_authority", "type": "pubkey" }, { "name": "verification_level", "type": { "defined": { "name": "VerificationLevel" } } }, { "name": "price_message", "type": { "defined": { "name": "PriceFeedMessage" } } }, { "name": "posted_slot", "type": "u64" } ] } }, { "name": "VerificationLevel", "docs": [ "Pyth price updates are bridged to all blockchains via Wormhole.", "Using the price updates on another chain requires verifying the signatures of the Wormhole guardians.", "The usual process is to check the signatures for two thirds of the total number of guardians, but this can be cumbersome on Solana because of the transaction size limits,", "so we also allow for partial verification.", "", "This enum represents how much a price update has been verified:", "- If `Full`, we have verified the signatures for two thirds of the current guardians.", "- If `Partial`, only `num_signatures` guardian signatures have been checked.", "", "# Warning", "Using partially verified price updates is dangerous, as it lowers the threshold of guardians that need to collude to produce a malicious price update." ], "type": { "kind": "enum", "variants": [ { "name": "Partial", "fields": [ { "name": "num_signatures", "type": "u8" } ] }, { "name": "Full" } ] } } ], "constants": [ { "name": "FEED_ID", "type": "string", "value": "\"0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d\"" } ] }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/anchor/setup.ts
import { clusterApiUrl, Connection, PublicKey } from "@solana/web3.js"; import { IdlAccounts, Program } from "@coral-xyz/anchor"; import type { Stablecoin } from "./idlType"; import idl from "./idl.json"; const connection = new Connection(clusterApiUrl("devnet"), "confirmed"); export const program = new Program(idl as Stablecoin, { connection, }); export const [configPDA] = PublicKey.findProgramAddressSync( [Buffer.from("config")], program.programId, ); export type ConfigAccount = IdlAccounts<Stablecoin>["config"]; export type CollateralAccount = IdlAccounts<Stablecoin>["collateral"];
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/frontend/anchor/idlType.ts
/** * Program IDL in camelCase format in order to be used in JS/TS. * * Note that this is only a type helper and is not the actual IDL. The original * IDL can be found at `target/idl/stablecoin.json`. */ export type Stablecoin = { address: "6DjiD8tQhJ9ZS3WZrwNubfoBRBrqfWacNR3bXBQ7ir91"; metadata: { name: "stablecoin"; version: "0.1.0"; spec: "0.1.0"; description: "Created with Anchor"; }; instructions: [ { name: "depositCollateralAndMint"; discriminator: [186, 99, 85, 148, 89, 72, 66, 57]; accounts: [ { name: "depositor"; writable: true; signer: true; }, { name: "configAccount"; pda: { seeds: [ { kind: "const"; value: [99, 111, 110, 102, 105, 103]; }, ]; }; }, { name: "collateralAccount"; writable: true; pda: { seeds: [ { kind: "const"; value: [99, 111, 108, 108, 97, 116, 101, 114, 97, 108]; }, { kind: "account"; path: "depositor"; }, ]; }; }, { name: "solAccount"; writable: true; pda: { seeds: [ { kind: "const"; value: [115, 111, 108]; }, { kind: "account"; path: "depositor"; }, ]; }; }, { name: "mintAccount"; writable: true; relations: ["configAccount"]; }, { name: "priceUpdate"; }, { name: "tokenAccount"; writable: true; pda: { seeds: [ { kind: "account"; path: "depositor"; }, { kind: "account"; path: "tokenProgram"; }, { kind: "account"; path: "mintAccount"; }, ]; program: { kind: "const"; value: [ 140, 151, 37, 143, 78, 36, 137, 241, 187, 61, 16, 41, 20, 142, 13, 131, 11, 90, 19, 153, 218, 255, 16, 132, 4, 142, 123, 216, 219, 233, 248, 89, ]; }; }; }, { name: "tokenProgram"; address: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"; }, { name: "associatedTokenProgram"; address: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"; }, { name: "systemProgram"; address: "11111111111111111111111111111111"; }, ]; args: [ { name: "amountCollateral"; type: "u64"; }, { name: "amountToMint"; type: "u64"; }, ]; }, { name: "initializeConfig"; discriminator: [208, 127, 21, 1, 194, 190, 196, 70]; accounts: [ { name: "authority"; writable: true; signer: true; }, { name: "configAccount"; writable: true; pda: { seeds: [ { kind: "const"; value: [99, 111, 110, 102, 105, 103]; }, ]; }; }, { name: "mintAccount"; writable: true; pda: { seeds: [ { kind: "const"; value: [109, 105, 110, 116]; }, ]; }; }, { name: "tokenProgram"; address: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"; }, { name: "systemProgram"; address: "11111111111111111111111111111111"; }, ]; args: []; }, { name: "liquidate"; discriminator: [223, 179, 226, 125, 48, 46, 39, 74]; accounts: [ { name: "liquidator"; writable: true; signer: true; }, { name: "priceUpdate"; }, { name: "configAccount"; pda: { seeds: [ { kind: "const"; value: [99, 111, 110, 102, 105, 103]; }, ]; }; }, { name: "collateralAccount"; writable: true; }, { name: "solAccount"; writable: true; relations: ["collateralAccount"]; }, { name: "mintAccount"; writable: true; relations: ["configAccount"]; }, { name: "tokenAccount"; writable: true; pda: { seeds: [ { kind: "account"; path: "liquidator"; }, { kind: "account"; path: "tokenProgram"; }, { kind: "account"; path: "mintAccount"; }, ]; program: { kind: "const"; value: [ 140, 151, 37, 143, 78, 36, 137, 241, 187, 61, 16, 41, 20, 142, 13, 131, 11, 90, 19, 153, 218, 255, 16, 132, 4, 142, 123, 216, 219, 233, 248, 89, ]; }; }; }, { name: "tokenProgram"; address: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"; }, { name: "systemProgram"; address: "11111111111111111111111111111111"; }, ]; args: [ { name: "amountToBurn"; type: "u64"; }, ]; }, { name: "redeemCollateralAndBurnTokens"; discriminator: [133, 209, 165, 17, 145, 53, 164, 84]; accounts: [ { name: "depositor"; writable: true; signer: true; }, { name: "priceUpdate"; }, { name: "configAccount"; pda: { seeds: [ { kind: "const"; value: [99, 111, 110, 102, 105, 103]; }, ]; }; }, { name: "collateralAccount"; writable: true; pda: { seeds: [ { kind: "const"; value: [99, 111, 108, 108, 97, 116, 101, 114, 97, 108]; }, { kind: "account"; path: "depositor"; }, ]; }; }, { name: "solAccount"; writable: true; relations: ["collateralAccount"]; }, { name: "mintAccount"; writable: true; relations: ["configAccount"]; }, { name: "tokenAccount"; writable: true; relations: ["collateralAccount"]; }, { name: "tokenProgram"; address: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"; }, { name: "systemProgram"; address: "11111111111111111111111111111111"; }, ]; args: [ { name: "amountCollateral"; type: "u64"; }, { name: "amountToBurn"; type: "u64"; }, ]; }, { name: "updateConfig"; discriminator: [29, 158, 252, 191, 10, 83, 219, 99]; accounts: [ { name: "configAccount"; writable: true; pda: { seeds: [ { kind: "const"; value: [99, 111, 110, 102, 105, 103]; }, ]; }; }, ]; args: [ { name: "minHealthFactor"; type: "u64"; }, ]; }, ]; accounts: [ { name: "collateral"; discriminator: [123, 130, 234, 63, 255, 240, 255, 92]; }, { name: "config"; discriminator: [155, 12, 170, 224, 30, 250, 204, 130]; }, { name: "priceUpdateV2"; discriminator: [34, 241, 35, 99, 157, 126, 244, 205]; }, ]; errors: [ { code: 6000; name: "belowMinimumHealthFactor"; msg: "Below Minimum Health Factor"; }, { code: 6001; name: "aboveMinimumHealthFactor"; msg: "Above Minimum Health Factor, Cannot Liquidate Healthy Account"; }, { code: 6002; name: "invalidPrice"; msg: "Price should not be negative"; }, ]; types: [ { name: "collateral"; type: { kind: "struct"; fields: [ { name: "depositor"; type: "pubkey"; }, { name: "solAccount"; type: "pubkey"; }, { name: "tokenAccount"; type: "pubkey"; }, { name: "lamportBalance"; type: "u64"; }, { name: "amountMinted"; type: "u64"; }, { name: "bump"; type: "u8"; }, { name: "bumpSolAccount"; type: "u8"; }, { name: "isInitialized"; type: "bool"; }, ]; }; }, { name: "config"; type: { kind: "struct"; fields: [ { name: "authority"; type: "pubkey"; }, { name: "mintAccount"; type: "pubkey"; }, { name: "liquidationThreshold"; type: "u64"; }, { name: "liquidationBonus"; type: "u64"; }, { name: "minHealthFactor"; type: "u64"; }, { name: "bump"; type: "u8"; }, { name: "bumpMintAccount"; type: "u8"; }, ]; }; }, { name: "priceFeedMessage"; repr: { kind: "c"; }; type: { kind: "struct"; fields: [ { name: "feedId"; type: { array: ["u8", 32]; }; }, { name: "price"; type: "i64"; }, { name: "conf"; type: "u64"; }, { name: "exponent"; type: "i32"; }, { name: "publishTime"; docs: ["The timestamp of this price update in seconds"]; type: "i64"; }, { name: "prevPublishTime"; docs: [ "The timestamp of the previous price update. This field is intended to allow users to", "identify the single unique price update for any moment in time:", "for any time t, the unique update is the one such that prev_publish_time < t <= publish_time.", "", "Note that there may not be such an update while we are migrating to the new message-sending logic,", "as some price updates on pythnet may not be sent to other chains (because the message-sending", "logic may not have triggered). We can solve this problem by making the message-sending mandatory", "(which we can do once publishers have migrated over).", "", "Additionally, this field may be equal to publish_time if the message is sent on a slot where", "where the aggregation was unsuccesful. This problem will go away once all publishers have", "migrated over to a recent version of pyth-agent.", ]; type: "i64"; }, { name: "emaPrice"; type: "i64"; }, { name: "emaConf"; type: "u64"; }, ]; }; }, { name: "priceUpdateV2"; docs: [ "A price update account. This account is used by the Pyth Receiver program to store a verified price update from a Pyth price feed.", "It contains:", "- `write_authority`: The write authority for this account. This authority can close this account to reclaim rent or update the account to contain a different price update.", "- `verification_level`: The [`VerificationLevel`] of this price update. This represents how many Wormhole guardian signatures have been verified for this price update.", "- `price_message`: The actual price update.", "- `posted_slot`: The slot at which this price update was posted.", ]; type: { kind: "struct"; fields: [ { name: "writeAuthority"; type: "pubkey"; }, { name: "verificationLevel"; type: { defined: { name: "verificationLevel"; }; }; }, { name: "priceMessage"; type: { defined: { name: "priceFeedMessage"; }; }; }, { name: "postedSlot"; type: "u64"; }, ]; }; }, { name: "verificationLevel"; docs: [ "Pyth price updates are bridged to all blockchains via Wormhole.", "Using the price updates on another chain requires verifying the signatures of the Wormhole guardians.", "The usual process is to check the signatures for two thirds of the total number of guardians, but this can be cumbersome on Solana because of the transaction size limits,", "so we also allow for partial verification.", "", "This enum represents how much a price update has been verified:", "- If `Full`, we have verified the signatures for two thirds of the current guardians.", "- If `Partial`, only `num_signatures` guardian signatures have been checked.", "", "# Warning", "Using partially verified price updates is dangerous, as it lowers the threshold of guardians that need to collude to produce a malicious price update.", ]; type: { kind: "enum"; variants: [ { name: "partial"; fields: [ { name: "numSignatures"; type: "u8"; }, ]; }, { name: "full"; }, ]; }; }, ]; constants: [ { name: "feedId"; type: "string"; value: '"0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d"'; }, ]; };
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/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-11-programmable-money
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/.prettierignore
.anchor .DS_Store target node_modules dist build test-ledger
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/Anchor.toml
[toolchain] [features] resolution = true skip-lint = false [programs.localnet] stablecoin = "6DjiD8tQhJ9ZS3WZrwNubfoBRBrqfWacNR3bXBQ7ir91" [registry] url = "https://api.apr.dev" [provider] cluster = "devnet" wallet = "~/.config/solana/id.json" [scripts] test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts" [test] startup_wait = 5000 shutdown_wait = 2000 upgradeable = false [test.validator] bind_address = "0.0.0.0" url = "https://api.mainnet-beta.solana.com" ledger = ".anchor/test-ledger" rpc_port = 8899 [[test.validator.clone]] address = "7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE"
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/package.json
{ "license": "ISC", "scripts": { "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" }, "dependencies": { "@coral-xyz/anchor": "^0.30.1", "@pythnetwork/price-service-client": "^1.9.0", "@pythnetwork/pyth-solana-receiver": "0.7.0", "@solana/web3.js": "1.73.0", "rpc-websockets": "7.11.0" }, "devDependencies": { "@types/bn.js": "^5.1.0", "@types/chai": "^4.3.0", "@types/mocha": "^9.0.0", "chai": "^4.3.4", "mocha": "^9.0.3", "prettier": "^2.6.2", "ts-mocha": "^10.0.0", "typescript": "^4.3.5" } }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/tsconfig.json
{ "compilerOptions": { "types": ["mocha", "chai"], "typeRoots": ["./node_modules/@types"], "lib": ["es2015"], "module": "commonjs", "target": "es6", "esModuleInterop": true } }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/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. const anchor = require("@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-11-programmable-money/program
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/tests/stablecoin.ts
import * as anchor from "@coral-xyz/anchor"; import { Program } from "@coral-xyz/anchor"; import { Stablecoin } from "../target/types/stablecoin"; import { PythSolanaReceiver } from "@pythnetwork/pyth-solana-receiver"; describe("stablecoin", () => { const provider = anchor.AnchorProvider.env(); const connection = provider.connection; const wallet = provider.wallet as anchor.Wallet; anchor.setProvider(provider); const program = anchor.workspace.Stablecoin as Program<Stablecoin>; const pythSolanaReceiver = new PythSolanaReceiver({ connection, wallet }); const SOL_PRICE_FEED_ID = "0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d"; const solUsdPriceFeedAccount = pythSolanaReceiver .getPriceFeedAccountAddress(0, SOL_PRICE_FEED_ID) .toBase58(); console.log(solUsdPriceFeedAccount); const [collateralAccount] = anchor.web3.PublicKey.findProgramAddressSync( [Buffer.from("collateral"), wallet.publicKey.toBuffer()], program.programId ); it("Is initialized!", async () => { const tx = await program.methods .initializeConfig() .accounts({}) .rpc({ skipPreflight: true, commitment: "confirmed" }); console.log("Your transaction signature", tx); }); it("Deposit Collateral and Mint USDS", async () => { const amountCollateral = 1_000_000_000; const amountToMint = 1_000_000_000; const tx = await program.methods .depositCollateralAndMint( new anchor.BN(amountCollateral), new anchor.BN(amountToMint) ) .accounts({ priceUpdate: solUsdPriceFeedAccount }) .rpc({ skipPreflight: true, commitment: "confirmed" }); console.log("Your transaction signature", tx); }); it("Redeem Collateral and Burn USDS", async () => { const amountCollateral = 500_000_000; const amountToBurn = 500_000_000; const tx = await program.methods .redeemCollateralAndBurnTokens( new anchor.BN(amountCollateral), new anchor.BN(amountToBurn) ) .accounts({ priceUpdate: solUsdPriceFeedAccount }) .rpc({ skipPreflight: true, commitment: "confirmed" }); console.log("Your transaction signature", tx); }); // Increase minimum health threshold to test liquidate it("Update Config", async () => { const tx = await program.methods .updateConfig(new anchor.BN(100)) .accounts({}) .rpc({ skipPreflight: true, commitment: "confirmed" }); console.log("Your transaction signature", tx); }); it("Liquidate", async () => { const amountToBurn = 500_000_000; const tx = await program.methods .liquidate(new anchor.BN(amountToBurn)) .accounts({ collateralAccount, priceUpdate: solUsdPriceFeedAccount }) .rpc({ skipPreflight: true, commitment: "confirmed" }); console.log("Your transaction signature", tx); }); it("Update Config", async () => { const tx = await program.methods .updateConfig(new anchor.BN(1)) .accounts({}) .rpc({ skipPreflight: true, commitment: "confirmed" }); console.log("Your transaction signature", tx); }); });
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/Cargo.toml
[package] name = "stablecoin" version = "0.1.0" description = "Created with Anchor" edition = "2021" [lib] crate-type = ["cdylib", "lib"] name = "stablecoin" [features] default = [] cpi = ["no-entrypoint"] no-entrypoint = [] no-idl = [] no-log-ix-name = [] idl-build = ["anchor-lang/idl-build", "anchor-spl/idl-build"] [dependencies] anchor-lang = { version = "0.30.1", features = ["init-if-needed"] } anchor-spl = "0.30.1" pyth-solana-receiver-sdk = "0.2.0"
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/Xargo.toml
[target.bpfel-unknown-unknown.dependencies.std] features = []
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/constants.rs
use anchor_lang::prelude::*; pub const SEED_CONFIG_ACCOUNT: &[u8] = b"config"; pub const SEED_COLLATERAL_ACCOUNT: &[u8] = b"collateral"; pub const SEED_SOL_ACCOUNT: &[u8] = b"sol"; pub const SEED_MINT_ACCOUNT: &[u8] = b"mint"; #[constant] pub const FEED_ID: &str = "0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d"; pub const MAXIMUM_AGE: u64 = 100; // allow pricefeed 100 sec old, to avoid stale price feed errors pub const PRICE_FEED_DECIMAL_ADJUSTMENT: u128 = 10; // price feed returns 1e8, multiple by 10 to match lamports 10e9 // Constants for configuration values pub const LIQUIDATION_THRESHOLD: u64 = 50; // 200% over-collateralized pub const LIQUIDATION_BONUS: u64 = 10; // 10% bonus lamports when liquidating pub const MIN_HEALTH_FACTOR: u64 = 1; pub const MINT_DECIMALS: u8 = 9;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/error.rs
use anchor_lang::prelude::*; #[error_code] pub enum CustomError { #[msg("Below Minimum Health Factor")] BelowMinimumHealthFactor, #[msg("Above Minimum Health Factor, Cannot Liquidate Healthy Account")] AboveMinimumHealthFactor, #[msg("Price should not be negative")] InvalidPrice, }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/lib.rs
use anchor_lang::prelude::*; use constants::*; use instructions::*; use state::*; mod constants; mod error; mod instructions; mod state; declare_id!("6DjiD8tQhJ9ZS3WZrwNubfoBRBrqfWacNR3bXBQ7ir91"); #[program] pub mod stablecoin { use super::*; pub fn initialize_config(ctx: Context<InitializeConfig>) -> Result<()> { process_initialize_config(ctx) } pub fn update_config(ctx: Context<UpdateConfig>, min_health_factor: u64) -> Result<()> { process_update_config(ctx, min_health_factor) } pub fn deposit_collateral_and_mint( ctx: Context<DepositCollateralAndMintTokens>, amount_collateral: u64, amount_to_mint: u64, ) -> Result<()> { process_deposit_collateral_and_mint_tokens(ctx, amount_collateral, amount_to_mint) } pub fn redeem_collateral_and_burn_tokens( ctx: Context<RedeemCollateralAndBurnTokens>, amount_collateral: u64, amount_to_burn: u64, ) -> Result<()> { process_redeem_collateral_and_burn_tokens(ctx, amount_collateral, amount_to_burn) } pub fn liquidate(ctx: Context<Liquidate>, amount_to_burn: u64) -> Result<()> { process_liquidate(ctx, amount_to_burn) } }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/state.rs
use anchor_lang::prelude::*; #[account] #[derive(InitSpace, Debug)] pub struct Collateral { pub depositor: Pubkey, // depositor wallet address pub sol_account: Pubkey, // depositor pda collateral account (deposit SOL to this account) pub token_account: Pubkey, // depositor ata token account (mint stablecoins to this account) pub lamport_balance: u64, // current lamport balance of depositor sol_account (for health check calculation) pub amount_minted: u64, // current amount stablecoins minted, base unit adjusted for decimal precision (for health check calculation) pub bump: u8, // store bump seed for this collateral account PDA pub bump_sol_account: u8, // store bump seed for the sol_account PDA pub is_initialized: bool, // indicate if account data has already been initialized (for check to prevent overriding certain fields) } #[account] #[derive(InitSpace, Debug)] pub struct Config { pub authority: Pubkey, // authority of the this program config account pub mint_account: Pubkey, // the stablecoin mint address, which is a PDA pub liquidation_threshold: u64, // determines how much extra collateral is required pub liquidation_bonus: u64, // % bonus lamports to liquidator for liquidating an account pub min_health_factor: u64, // minimum health factor, if below min then Collateral account can be liquidated pub bump: u8, // store bump seed for this config account pub bump_mint_account: u8, // store bump seed for the stablecoin mint account PDA }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/mod.rs
pub use admin::*; pub mod admin; pub use deposit::*; pub mod deposit; pub use withdraw::*; pub mod withdraw; pub use utils::*; pub mod utils;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/utils.rs
use crate::{ error::CustomError, Collateral, Config, FEED_ID, MAXIMUM_AGE, PRICE_FEED_DECIMAL_ADJUSTMENT, }; use anchor_lang::{prelude::*, solana_program::native_token::LAMPORTS_PER_SOL}; use pyth_solana_receiver_sdk::price_update::{get_feed_id_from_hex, PriceUpdateV2}; // Check health factor for Collateral account is greater than minimum required health factor pub fn check_health_factor( collateral: &Account<Collateral>, config: &Account<Config>, price_feed: &Account<PriceUpdateV2>, ) -> Result<()> { let health_factor = calculate_health_factor(collateral, config, price_feed)?; require!( health_factor >= config.min_health_factor, CustomError::BelowMinimumHealthFactor ); Ok(()) } // Calcuate health factor for a given Collateral account pub fn calculate_health_factor( collateral: &Account<Collateral>, config: &Account<Config>, price_feed: &Account<PriceUpdateV2>, ) -> Result<u64> { // Get the collateral value in USD // Assuming 1 SOL = $1.00 and $1 = 1_000_000_000 // Example: get_usd_value(1_000_000_000 lamports, price_feed) // collateral_value_in_usd = 1_000_000_000 let collateral_value_in_usd = get_usd_value(&collateral.lamport_balance, price_feed)?; // Adjust the collateral value for the liquidation threshold (require overcollateralize) // Example: (1_000_000_000 * 50) / 100 = 500_000_000 let collateral_adjusted_for_liquidation_threshold = (collateral_value_in_usd * config.liquidation_threshold) / 100; msg!( "Minted Amount : {:.9}", collateral.amount_minted as f64 / 1e9 ); if collateral.amount_minted == 0 { msg!("Health Factor Max"); return Ok(u64::MAX); } // Calculate the health factor // Ratio of (adjusted collateral value) / (amount stablecoins minted) // Example: 500_000_000 / 500_000_000 = 1 let health_factor = (collateral_adjusted_for_liquidation_threshold) / collateral.amount_minted; msg!("Health Factor : {}", health_factor); Ok(health_factor) } // Given lamports, return USD value based on current SOL price. fn get_usd_value(amount_in_lamports: &u64, price_feed: &Account<PriceUpdateV2>) -> Result<u64> { let feed_id = get_feed_id_from_hex(FEED_ID)?; let price = price_feed.get_price_no_older_than(&Clock::get()?, MAXIMUM_AGE, &feed_id)?; // Check price is positive require!(price.price > 0, CustomError::InvalidPrice); // Adjust price to match lamports precision (9 decimals) // Example: Assuming 1 SOL = $2.00 // price.price = 200_000_000 (from Pyth, 8 decimals) // price_in_usd = 200_000_000 * 10 = 2_000_000_000 (9 decimals) let price_in_usd = price.price as u128 * PRICE_FEED_DECIMAL_ADJUSTMENT; // Calculate USD value // Example: Convert 0.5 SOL to USD when 1 SOL = $2.00 // amount_in_lamports = 500_000_000 (0.5 SOL) // price_in_usd = 2_000_000_000 (as calculated above) // LAMPORTS_PER_SOL = 1_000_000_000 // amount_in_usd = (500_000_000 * 2_000_000_000) / 1_000_000_000 = 1_000_000_000 ($1.00) let amount_in_usd = (*amount_in_lamports as u128 * price_in_usd) / (LAMPORTS_PER_SOL as u128); // EXAMPLE LOGS // Program log: Price in USD (for 1 SOL): 136.194634200 // Program log: SOL Amount: 0.500000000 // Program log: USD Value: 68.097317100 // Program log: Outstanding Token Amount (Minted): 1.500000000 // Program log: Health Factor: 22 msg!("*** CONVERT USD TO SOL ***"); msg!("SOL/USD Price : {:.9}", price_in_usd as f64 / 1e9); msg!("SOL Amount : {:.9}", *amount_in_lamports as f64 / 1e9); msg!("USD Value : {:.9}", amount_in_usd as f64 / 1e9); // msg!("Price exponent?: {}", price.exponent); Ok(amount_in_usd as u64) } // Given USD amount, return lamports based on current SOL price pub fn get_lamports_from_usd( amount_in_usd: &u64, price_feed: &Account<PriceUpdateV2>, ) -> Result<u64> { let feed_id = get_feed_id_from_hex(FEED_ID)?; let price = price_feed.get_price_no_older_than(&Clock::get()?, MAXIMUM_AGE, &feed_id)?; // Check price is positive require!(price.price > 0, CustomError::InvalidPrice); // Adjust price to match lamports precision (9 decimals) // Example: Assuming 1 SOL = $2.00 // price.price = 200_000_000 (from Pyth, 8 decimals) // price_in_usd = 200_000_000 * 10 = 2_000_000_000 (9 decimals) let price_in_usd = price.price as u128 * PRICE_FEED_DECIMAL_ADJUSTMENT; // Calculate lamports // Example: Convert $0.50 to lamports when 1 SOL = $2.00 // amount_in_usd = 500_000_000 (user input, 9 decimals for $0.50) // LAMPORTS_PER_SOL = 1_000_000_000 // price_in_usd = 2_000_000_000 (as calculated above) // amount_in_lamports = (500_000_000 * 1_000_000_000) / 2_000_000_000 = 250_000_000 (0.25 SOL) let amount_in_lamports = ((*amount_in_usd as u128) * (LAMPORTS_PER_SOL as u128)) / price_in_usd; // EXAMPLE LOGS // Program log: *** CONVERT SOL TO USD *** // Program log: Price in USD (for 1 SOL): 136.194634200 // Program log: USD Amount: 1.500000000 // Program log: SOL Value: 0.011013649 msg!("*** CONVERT SOL TO USD ***"); msg!("SOL/USD Price : {:.9}", price_in_usd as f64 / 1e9); msg!("USD Amount : {:.9}", *amount_in_usd as f64 / 1e9); msg!("SOL Value : {:.9}", amount_in_lamports as f64 / 1e9); Ok(amount_in_lamports as u64) }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/deposit/mod.rs
pub use deposit_collateral_and_mint_tokens::*; pub mod deposit_collateral_and_mint_tokens; pub use utils::*; pub mod utils;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/deposit/deposit_collateral_and_mint_tokens.rs
use crate::{ check_health_factor, deposit_sol_internal, mint_tokens_internal, Collateral, Config, SEED_COLLATERAL_ACCOUNT, SEED_CONFIG_ACCOUNT, SEED_SOL_ACCOUNT, }; use anchor_lang::prelude::*; use anchor_spl::{ associated_token::AssociatedToken, token_interface::{Mint, Token2022, TokenAccount}, }; use pyth_solana_receiver_sdk::price_update::PriceUpdateV2; #[derive(Accounts)] pub struct DepositCollateralAndMintTokens<'info> { #[account(mut)] pub depositor: Signer<'info>, #[account( seeds = [SEED_CONFIG_ACCOUNT], bump = config_account.bump, has_one = mint_account )] pub config_account: Box<Account<'info, Config>>, #[account( init_if_needed, payer = depositor, space = 8 + Collateral::INIT_SPACE, seeds = [SEED_COLLATERAL_ACCOUNT, depositor.key().as_ref()], bump, )] pub collateral_account: Account<'info, Collateral>, #[account( mut, seeds = [SEED_SOL_ACCOUNT, depositor.key().as_ref()], bump, )] pub sol_account: SystemAccount<'info>, #[account(mut)] pub mint_account: InterfaceAccount<'info, Mint>, pub price_update: Account<'info, PriceUpdateV2>, #[account( init_if_needed, payer = depositor, associated_token::mint = mint_account, associated_token::authority = depositor, associated_token::token_program = token_program )] pub token_account: InterfaceAccount<'info, TokenAccount>, pub token_program: Program<'info, Token2022>, pub associated_token_program: Program<'info, AssociatedToken>, pub system_program: Program<'info, System>, } // https://github.com/Cyfrin/foundry-defi-stablecoin-cu/blob/main/src/DSCEngine.sol#L140 pub fn process_deposit_collateral_and_mint_tokens( ctx: Context<DepositCollateralAndMintTokens>, amount_collateral: u64, amount_to_mint: u64, ) -> Result<()> { let collateral_account = &mut ctx.accounts.collateral_account; collateral_account.lamport_balance = ctx.accounts.sol_account.lamports() + amount_collateral; collateral_account.amount_minted += amount_to_mint; if !collateral_account.is_initialized { collateral_account.is_initialized = true; collateral_account.depositor = ctx.accounts.depositor.key(); collateral_account.sol_account = ctx.accounts.sol_account.key(); collateral_account.token_account = ctx.accounts.token_account.key(); collateral_account.bump = ctx.bumps.collateral_account; collateral_account.bump_sol_account = ctx.bumps.sol_account; } check_health_factor( &ctx.accounts.collateral_account, &ctx.accounts.config_account, &ctx.accounts.price_update, )?; deposit_sol_internal( &ctx.accounts.depositor, &ctx.accounts.sol_account, &ctx.accounts.system_program, amount_collateral, )?; mint_tokens_internal( &ctx.accounts.mint_account, &ctx.accounts.token_account, &ctx.accounts.token_program, ctx.accounts.config_account.bump_mint_account, amount_to_mint, )?; Ok(()) }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/deposit/utils.rs
use crate::SEED_MINT_ACCOUNT; use anchor_lang::prelude::*; use anchor_lang::system_program::{transfer, Transfer}; use anchor_spl::{ token_2022::{mint_to, MintTo}, token_interface::{Mint, Token2022, TokenAccount}, }; pub fn mint_tokens_internal<'info>( mint_account: &InterfaceAccount<'info, Mint>, token_account: &InterfaceAccount<'info, TokenAccount>, token_program: &Program<'info, Token2022>, bump: u8, amount: u64, ) -> Result<()> { let signer_seeds: &[&[&[u8]]] = &[&[SEED_MINT_ACCOUNT, &[bump]]]; mint_to( CpiContext::new_with_signer( token_program.to_account_info(), MintTo { mint: mint_account.to_account_info(), to: token_account.to_account_info(), authority: mint_account.to_account_info(), }, signer_seeds, ), amount, ) } pub fn deposit_sol_internal<'info>( from: &Signer<'info>, to: &SystemAccount<'info>, system_program: &Program<'info, System>, amount: u64, ) -> Result<()> { transfer( CpiContext::new( system_program.to_account_info(), Transfer { from: from.to_account_info(), to: to.to_account_info(), }, ), amount, ) }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/admin/mod.rs
pub use initialize_config::*; pub mod update_config; pub use update_config::*; pub mod initialize_config;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/admin/initialize_config.rs
use anchor_lang::prelude::*; use anchor_spl::token_interface::{ Mint, Token2022, }; use crate::{Config, LIQUIDATION_BONUS, LIQUIDATION_THRESHOLD, MINT_DECIMALS, MIN_HEALTH_FACTOR, SEED_CONFIG_ACCOUNT, SEED_MINT_ACCOUNT}; #[derive(Accounts)] pub struct InitializeConfig<'info> { #[account(mut)] pub authority: Signer<'info>, #[account( init, payer = authority, space = 8 + Config::INIT_SPACE, seeds = [SEED_CONFIG_ACCOUNT], bump, )] pub config_account: Account<'info, Config>, #[account( init, payer = authority, seeds = [SEED_MINT_ACCOUNT], bump, mint::decimals = MINT_DECIMALS, mint::authority = mint_account, mint::freeze_authority = mint_account, mint::token_program = token_program )] pub mint_account: InterfaceAccount<'info, Mint>, pub token_program: Program<'info, Token2022>, pub system_program: Program<'info, System>, } pub fn process_initialize_config(ctx: Context<InitializeConfig>) -> Result<()> { *ctx.accounts.config_account = Config { authority: ctx.accounts.authority.key(), mint_account: ctx.accounts.mint_account.key(), liquidation_threshold: LIQUIDATION_THRESHOLD, liquidation_bonus: LIQUIDATION_BONUS, min_health_factor: MIN_HEALTH_FACTOR, bump: ctx.bumps.config_account, bump_mint_account: ctx.bumps.mint_account, }; msg!("Initialized Config Acccount:{:#?}", ctx.accounts.config_account); Ok(()) }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/admin/update_config.rs
use crate::{Config, SEED_CONFIG_ACCOUNT}; use anchor_lang::prelude::*; #[derive(Accounts)] pub struct UpdateConfig<'info> { #[account( mut, seeds = [SEED_CONFIG_ACCOUNT], bump = config_account.bump, )] pub config_account: Account<'info, Config>, } // Change health factor to test liquidate instruction, no authority check, anyone can invoke pub fn process_update_config(ctx: Context<UpdateConfig>, min_health_factor: u64) -> Result<()> { let config_account = &mut ctx.accounts.config_account; config_account.min_health_factor = min_health_factor; msg!("Update Config Acccount:{:#?}", ctx.accounts.config_account); Ok(()) }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/withdraw/redeem_collateral_and_burn_tokens.rs
use crate::{ burn_tokens_internal, check_health_factor, withdraw_sol_internal, Collateral, Config, SEED_COLLATERAL_ACCOUNT, SEED_CONFIG_ACCOUNT, }; use anchor_lang::prelude::*; use anchor_spl::token_interface::{Mint, Token2022, TokenAccount}; use pyth_solana_receiver_sdk::price_update::PriceUpdateV2; #[derive(Accounts)] pub struct RedeemCollateralAndBurnTokens<'info> { #[account(mut)] pub depositor: Signer<'info>, pub price_update: Account<'info, PriceUpdateV2>, #[account( seeds = [SEED_CONFIG_ACCOUNT], bump = config_account.bump, has_one = mint_account )] pub config_account: Account<'info, Config>, #[account( mut, seeds = [SEED_COLLATERAL_ACCOUNT, depositor.key().as_ref()], bump = collateral_account.bump, has_one = sol_account, has_one = token_account )] pub collateral_account: Account<'info, Collateral>, #[account(mut)] pub sol_account: SystemAccount<'info>, #[account(mut)] pub mint_account: InterfaceAccount<'info, Mint>, #[account(mut)] pub token_account: InterfaceAccount<'info, TokenAccount>, pub token_program: Program<'info, Token2022>, pub system_program: Program<'info, System>, } // https://github.com/Cyfrin/foundry-defi-stablecoin-cu/blob/main/src/DSCEngine.sol#L157 pub fn process_redeem_collateral_and_burn_tokens( ctx: Context<RedeemCollateralAndBurnTokens>, amount_collateral: u64, amount_to_burn: u64, ) -> Result<()> { let collateral_account = &mut ctx.accounts.collateral_account; collateral_account.lamport_balance = ctx.accounts.sol_account.lamports() - amount_collateral; collateral_account.amount_minted -= amount_to_burn; check_health_factor( &ctx.accounts.collateral_account, &ctx.accounts.config_account, &ctx.accounts.price_update, )?; burn_tokens_internal( &ctx.accounts.mint_account, &ctx.accounts.token_account, &ctx.accounts.depositor, &ctx.accounts.token_program, amount_to_burn, )?; withdraw_sol_internal( &ctx.accounts.sol_account, &ctx.accounts.depositor.to_account_info(), &ctx.accounts.system_program, &ctx.accounts.depositor.key(), ctx.accounts.collateral_account.bump_sol_account, amount_collateral, )?; Ok(()) }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/withdraw/mod.rs
pub use redeem_collateral_and_burn_tokens::*; pub mod redeem_collateral_and_burn_tokens; pub use liquidate::*; pub mod liquidate; pub use utils::*; pub mod utils;
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/withdraw/utils.rs
use crate::SEED_SOL_ACCOUNT; use anchor_lang::prelude::*; use anchor_lang::system_program::{transfer, Transfer}; use anchor_spl::{ token_2022::{burn, Burn}, token_interface::{Mint, Token2022, TokenAccount}, }; pub fn withdraw_sol_internal<'info>( from: &SystemAccount<'info>, to: &AccountInfo<'info>, system_program: &Program<'info, System>, depositor_key: &Pubkey, bump: u8, amount: u64, ) -> Result<()> { let signer_seeds: &[&[&[u8]]] = &[&[SEED_SOL_ACCOUNT, depositor_key.as_ref(), &[bump]]]; transfer( CpiContext::new_with_signer( system_program.to_account_info(), Transfer { from: from.to_account_info(), to: to.to_account_info(), }, signer_seeds, ), amount, ) } pub fn burn_tokens_internal<'info>( mint_account: &InterfaceAccount<'info, Mint>, token_account: &InterfaceAccount<'info, TokenAccount>, authority: &Signer<'info>, token_program: &Program<'info, Token2022>, amount: u64, ) -> Result<()> { burn( CpiContext::new( token_program.to_account_info(), Burn { mint: mint_account.to_account_info(), from: token_account.to_account_info(), authority: authority.to_account_info(), }, ), amount, ) }
0
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions
solana_public_repos/developer-bootcamp-2024/project-11-programmable-money/program/programs/stablecoin/src/instructions/withdraw/liquidate.rs
use crate::{ burn_tokens_internal, calculate_health_factor, error::CustomError, get_lamports_from_usd, withdraw_sol_internal, Collateral, Config, SEED_CONFIG_ACCOUNT, }; use anchor_lang::prelude::*; use anchor_spl::token_interface::{Mint, Token2022, TokenAccount}; use pyth_solana_receiver_sdk::price_update::PriceUpdateV2; #[derive(Accounts)] pub struct Liquidate<'info> { #[account(mut)] pub liquidator: Signer<'info>, pub price_update: Account<'info, PriceUpdateV2>, #[account( seeds = [SEED_CONFIG_ACCOUNT], bump = config_account.bump, has_one = mint_account )] pub config_account: Account<'info, Config>, #[account( mut, has_one = sol_account )] pub collateral_account: Account<'info, Collateral>, #[account(mut)] pub sol_account: SystemAccount<'info>, #[account(mut)] pub mint_account: InterfaceAccount<'info, Mint>, #[account( mut, associated_token::mint = mint_account, associated_token::authority = liquidator, associated_token::token_program = token_program )] pub token_account: InterfaceAccount<'info, TokenAccount>, pub token_program: Program<'info, Token2022>, pub system_program: Program<'info, System>, } // https://github.com/Cyfrin/foundry-defi-stablecoin-cu/blob/main/src/DSCEngine.sol#L215 pub fn process_liquidate(ctx: Context<Liquidate>, amount_to_burn: u64) -> Result<()> { let health_factor = calculate_health_factor( &ctx.accounts.collateral_account, &ctx.accounts.config_account, &ctx.accounts.price_update, )?; require!( health_factor < ctx.accounts.config_account.min_health_factor, CustomError::AboveMinimumHealthFactor ); let lamports = get_lamports_from_usd(&amount_to_burn, &ctx.accounts.price_update)?; let liquidation_bonus = lamports * ctx.accounts.config_account.liquidation_bonus / 100; let amount_to_liquidate = lamports + liquidation_bonus; msg!("*** LIQUIDATION ***"); msg!("Bonus {}%", ctx.accounts.config_account.liquidation_bonus); msg!("Bonus Amount : {:.9}", liquidation_bonus as f64 / 1e9); msg!("SOL Liquidated: {:.9}", amount_to_liquidate as f64 / 1e9); withdraw_sol_internal( &ctx.accounts.sol_account, &ctx.accounts.liquidator.to_account_info(), &ctx.accounts.system_program, &ctx.accounts.collateral_account.depositor, ctx.accounts.collateral_account.bump_sol_account, amount_to_liquidate, )?; burn_tokens_internal( &ctx.accounts.mint_account, &ctx.accounts.token_account, &ctx.accounts.liquidator, &ctx.accounts.token_program, amount_to_burn, )?; let collateral_account = &mut ctx.accounts.collateral_account; collateral_account.lamport_balance = ctx.accounts.sol_account.lamports(); collateral_account.amount_minted -= amount_to_burn; // Optional, logs new health factor calculate_health_factor( &ctx.accounts.collateral_account, &ctx.accounts.config_account, &ctx.accounts.price_update, )?; Ok(()) }
0
solana_public_repos/developer-bootcamp-2024
solana_public_repos/developer-bootcamp-2024/project-5-tokens/create-token-metadata.ts
// This uses "@metaplex-foundation/mpl-token-metadata@2" to create tokens import "dotenv/config"; import { getKeypairFromEnvironment, getExplorerLink, } from "@solana-developers/helpers"; import { Connection, clusterApiUrl, PublicKey, Transaction, sendAndConfirmTransaction, } from "@solana/web3.js"; import { DataV2, createCreateMetadataAccountV3Instruction, } from "@metaplex-foundation/mpl-token-metadata"; const user = getKeypairFromEnvironment("SECRET_KEY"); const connection = new Connection(clusterApiUrl("devnet")); console.log( `🔑 We've loaded our keypair securely, using an env file! Our public key is: ${user.publicKey.toBase58()}` ); const TOKEN_METADATA_PROGRAM_ID = new PublicKey( "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s" ); // Subtitute in your token mint account const tokenMintAccount = new PublicKey("YOUR_TOKEN_MINT_ADDRESS_HERE"); const metadataData: DataV2 = { name: "Solana Training Token", symbol: "TRAINING", // An off-chain link to more information about the token using Metaplex standard for off-chain data // We are using a GitHub link here, but in production this content would be hosted on an immutable storage like // Arweave / IPFS / Pinata etc uri: "https://raw.githubusercontent.com/solana-developers/professional-education/main/labs/sample-token-metadata.json", sellerFeeBasisPoints: 0, creators: null, collection: null, uses: null, }; const metadataPDAAndBump = PublicKey.findProgramAddressSync( [ Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), tokenMintAccount.toBuffer(), ], TOKEN_METADATA_PROGRAM_ID ); const metadataPDA = metadataPDAAndBump[0]; const transaction = new Transaction(); const createMetadataAccountInstruction = createCreateMetadataAccountV3Instruction( { metadata: metadataPDA, mint: tokenMintAccount, mintAuthority: user.publicKey, payer: user.publicKey, updateAuthority: user.publicKey, }, { createMetadataAccountArgsV3: { collectionDetails: null, data: metadataData, isMutable: true, }, } ); transaction.add(createMetadataAccountInstruction); const transactionSignature = await sendAndConfirmTransaction( connection, transaction, [user] ); const transactionLink = getExplorerLink( "transaction", transactionSignature, "devnet" ); console.log(`✅ Transaction confirmed, explorer link is: ${transactionLink}!`); const tokenMintLink = getExplorerLink( "address", tokenMintAccount.toString(), "devnet" ); console.log(`✅ Look at the token mint again: ${tokenMintLink}!`);
0
solana_public_repos/developer-bootcamp-2024
solana_public_repos/developer-bootcamp-2024/project-5-tokens/send-spl-tokens.ts
import "dotenv/config"; import { getExplorerLink, getKeypairFromEnvironment, } from "@solana-developers/helpers"; import { Connection, PublicKey, clusterApiUrl } from "@solana/web3.js"; import { getOrCreateAssociatedTokenAccount, transfer } from "@solana/spl-token"; const connection = new Connection(clusterApiUrl("devnet")); const sender = getKeypairFromEnvironment("SECRET_KEY"); console.log( `🔑 Loaded our keypair securely, using an env file! Our public key is: ${sender.publicKey.toBase58()}` ); // Add the recipient public key here const recipient = new PublicKey("YOUR_RECIPIENT_HERE"); // Subtitute in your token mint account const tokenMintAccount = new PublicKey("YOUR_TOKEN_MINT_ADDRESS_HERE"); // Our token has two decimal places const MINOR_UNITS_PER_MAJOR_UNITS = Math.pow(10, 2); console.log(`💸 Attempting to send 1 token to ${recipient.toBase58()}...`); // Get or create the source and destination token accounts to store this token const sourceTokenAccount = await getOrCreateAssociatedTokenAccount( connection, sender, tokenMintAccount, sender.publicKey ); const destinationTokenAccount = await getOrCreateAssociatedTokenAccount( connection, sender, tokenMintAccount, recipient ); // Transfer the tokens const signature = await transfer( connection, sender, sourceTokenAccount.address, destinationTokenAccount.address, sender, 1 * MINOR_UNITS_PER_MAJOR_UNITS ); const explorerLink = getExplorerLink("transaction", signature, "devnet"); console.log(`✅ Transaction confirmed, explorer link is: ${explorerLink}!`);
0
solana_public_repos/developer-bootcamp-2024
solana_public_repos/developer-bootcamp-2024/project-5-tokens/create-token-mint.ts
import { createMint } from "@solana/spl-token"; import "dotenv/config"; import { getKeypairFromEnvironment, getExplorerLink, } from "@solana-developers/helpers"; import { Connection, clusterApiUrl } from "@solana/web3.js"; const connection = new Connection(clusterApiUrl("devnet")); const user = getKeypairFromEnvironment("SECRET_KEY"); console.log( `🔑 Loaded our keypair securely, using an env file! Our public key is: ${user.publicKey.toBase58()}` ); // This is a shortcut that runs: // SystemProgram.createAccount // token.createInitializeMintInstruction // See https://www.soldev.app/course/token-program const tokenMint = await createMint(connection, user, user.publicKey, null, 2); const link = getExplorerLink("address", tokenMint.toString(), "devnet"); console.log(`✅ Success! Created token mint: ${link}`);
0
solana_public_repos/developer-bootcamp-2024
solana_public_repos/developer-bootcamp-2024/project-5-tokens/mint-tokens.ts
import { getOrCreateAssociatedTokenAccount, mintTo } from "@solana/spl-token"; import "dotenv/config"; import { getExplorerLink, getKeypairFromEnvironment, } from "@solana-developers/helpers"; import { Connection, PublicKey, clusterApiUrl } from "@solana/web3.js"; // mintTo() doesn't default to a commitment level (unlike, say, sendAndConfirmTransaction() ), so we need to specify it const connection = new Connection(clusterApiUrl("devnet"), "confirmed"); // Our token has two decimal places const MINOR_UNITS_PER_MAJOR_UNITS = Math.pow(10, 2); const user = getKeypairFromEnvironment("SECRET_KEY"); // Subtitute in your token mint account from create-token-mint.ts const tokenMintAccount = new PublicKey("YOUR_TOKEN_MINT_HERE"); // Let's mint the tokens to ourselves for now! const recipientAssociatedTokenAccount = await getOrCreateAssociatedTokenAccount( connection, user, tokenMintAccount, user.publicKey ); const transactionSignature = await mintTo( connection, user, tokenMintAccount, recipientAssociatedTokenAccount.address, user, 10 * MINOR_UNITS_PER_MAJOR_UNITS ); const link = getExplorerLink("transaction", transactionSignature, "devnet"); console.log(`✅ Success! Mint Token Transaction: ${link}`);
0
solana_public_repos/developer-bootcamp-2024
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/nx.json
{ "$schema": "./node_modules/nx/schemas/nx-schema.json", "targetDefaults": { "build": { "cache": true, "dependsOn": ["^build"], "inputs": ["production", "^production"] }, "lint": { "cache": true, "inputs": [ "default", "{workspaceRoot}/.eslintrc.json", "{workspaceRoot}/.eslintignore", "{workspaceRoot}/eslint.config.js" ] }, "@nx/jest:jest": { "cache": true, "inputs": ["default", "^production", "{workspaceRoot}/jest.preset.js"], "options": { "passWithNoTests": true }, "configurations": { "ci": { "ci": true, "codeCoverage": true } } } }, "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": [] }, "generators": { "@nx/react": { "application": { "babel": true } }, "@nx/next": { "application": { "style": "css", "linter": "eslint" } } } }
0
solana_public_repos/developer-bootcamp-2024
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/LICENSE
MIT License Copyright (c) 2024 brimigs 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-4-crud-app/vercel.json
{ "buildCommand": "npm run build", "outputDirectory": "dist/web/.next" }
0
solana_public_repos/developer-bootcamp-2024
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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/*"], "@journal/anchor": ["anchor/src/index.ts"] } }, "exclude": ["node_modules", "tmp"] }
0
solana_public_repos/developer-bootcamp-2024
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/package.json
{ "name": "@journal/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.1", "@solana-developers/preset-next": "2.2.0", "@solana/spl-token": "0.4.1", "@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.90.0", "@swc/helpers": "~0.5.2", "@tabler/icons-react": "2.47.0", "@tailwindcss/typography": "0.5.10", "@tanstack/react-query": "5.24.1", "@tanstack/react-query-next-experimental": "5.24.1", "bs58": "5.0.0", "buffer": "6.0.3", "daisyui": "4.7.2", "encoding": "0.1.13", "jotai": "2.6.5", "next": "13.4.4", "react": "18.2.0", "react-dom": "18.2.0", "react-hot-toast": "2.4.1", "tslib": "^2.3.0" }, "devDependencies": { "@nx/eslint": "17.2.7", "@nx/eslint-plugin": "17.2.7", "@nx/jest": "17.2.7", "@nx/js": "17.2.7", "@nx/next": "17.2.7", "@nx/react": "17.2.7", "@nx/rollup": "17.2.7", "@nx/workspace": "17.2.7", "@swc-node/register": "~1.6.7", "@swc/cli": "~0.1.62", "@swc/core": "~1.3.85", "@swc/jest": "0.2.20", "@testing-library/react": "14.0.0", "@types/jest": "^29.4.0", "@types/node": "18.16.9", "@types/react": "18.2.33", "@types/react-dom": "18.2.14", "@typescript-eslint/eslint-plugin": "^6.9.1", "@typescript-eslint/parser": "^6.9.1", "autoprefixer": "10.4.13", "eslint": "~8.48.0", "eslint-config-next": "13.4.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": "17.2.7", "postcss": "8.4.21", "prettier": "^2.6.2", "tailwindcss": "3.2.7", "ts-jest": "^29.1.0", "ts-node": "10.9.1", "typescript": "~5.2.2" } }
0
solana_public_repos/developer-bootcamp-2024
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/jest.config.ts
import { getJestProjects } from '@nx/jest'; export default { projects: getJestProjects(), };
0
solana_public_repos/developer-bootcamp-2024/project-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web/project.json
{ "name": "web", "$schema": "../node_modules/nx/schemas/project-schema.json", "sourceRoot": "web", "projectType": "application", "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", "outputs": ["{options.outputFile}"] } }, "tags": [] }
0
solana_public_repos/developer-bootcamp-2024/project-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web/app/page.module.css
.page { }
0
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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: 'journal', description: 'Generated by create-solana-dapp', }; const links: { label: string; path: string }[] = [ { label: 'Account', path: '/account' }, { label: 'Clusters', path: '/clusters' }, { label: 'Journal Program', path: '/journal' }, ]; 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-4-crud-app/web
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web/app/journal/page.tsx
import JournalFeature from '@/components/journal/journal-feature'; export default function Page() { return <JournalFeature />; }
0
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web/app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/app/api
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/app/account
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web/components/journal/journal-data-access.tsx
"use client"; import { getJournalProgram, getJournalProgramId, JournalIDL, } from "@journal/anchor"; import { Program } 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 toast from "react-hot-toast"; import { useCluster } from "../cluster/cluster-data-access"; import { useAnchorProvider } from "../solana/solana-provider"; import { useTransactionToast } from "../ui/ui-layout"; import { useMemo } from "react"; import { get } from "http"; interface CreateEntryArgs { title: string; message: string; owner: PublicKey; } export function useJournalProgram() { const { connection } = useConnection(); const { cluster } = useCluster(); const transactionToast = useTransactionToast(); const provider = useAnchorProvider(); const programId = useMemo( () => getJournalProgramId(cluster.network as Cluster), [cluster] ); const program = getJournalProgram(provider); const accounts = useQuery({ queryKey: ["journal", "all", { cluster }], queryFn: () => program.account.journalEntryState.all(), }); const getProgramAccount = useQuery({ queryKey: ["get-program-account", { cluster }], queryFn: () => connection.getParsedAccountInfo(programId), }); const createEntry = useMutation<string, Error, CreateEntryArgs>({ mutationKey: ["journalEntry", "create", { cluster }], mutationFn: async ({ title, message, owner }) => { const [journalEntryAddress] = await PublicKey.findProgramAddress( [Buffer.from(title), owner.toBuffer()], programId ); return program.methods.createJournalEntry(title, message).rpc(); }, onSuccess: (signature) => { transactionToast(signature); accounts.refetch(); }, onError: (error) => { toast.error(`Failed to create journal entry: ${error.message}`); }, }); return { program, programId, accounts, getProgramAccount, createEntry, }; } export function useJournalProgramAccount({ account }: { account: PublicKey }) { const { cluster } = useCluster(); const transactionToast = useTransactionToast(); const { program, accounts } = useJournalProgram(); const programId = new PublicKey( "8sddtWW1q7fwzspAfZj4zNpeQjpvmD3EeCCEfnc3JnuP" ); const accountQuery = useQuery({ queryKey: ["journal", "fetch", { cluster, account }], queryFn: () => program.account.journalEntryState.fetch(account), }); const updateEntry = useMutation<string, Error, CreateEntryArgs>({ mutationKey: ["journalEntry", "update", { cluster }], mutationFn: async ({ title, message, owner }) => { const [journalEntryAddress] = await PublicKey.findProgramAddress( [Buffer.from(title), owner.toBuffer()], programId ); return program.methods.updateJournalEntry(title, message).rpc(); }, onSuccess: (signature) => { transactionToast(signature); accounts.refetch(); }, onError: (error) => { toast.error(`Failed to update journal entry: ${error.message}`); }, }); const deleteEntry = useMutation({ mutationKey: ["journal", "deleteEntry", { cluster, account }], mutationFn: (title: string) => program.methods.deleteJournalEntry(title).rpc(), onSuccess: (tx) => { transactionToast(tx); return accounts.refetch(); }, }); return { accountQuery, updateEntry, deleteEntry, }; }
0
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web/components/journal/journal-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 { useJournalProgram } from "./journal-data-access"; import { JournalCreate, JournalList } from "./journal-ui"; export default function JournalFeature() { const { publicKey } = useWallet(); const { programId } = useJournalProgram(); return publicKey ? ( <div> <AppHero title="My Solana Journal" subtitle={"Create your journal here!"}> <p className="mb-6"> <ExplorerLink path={`account/${programId}`} label={ellipsify(programId.toString())} /> </p> <JournalCreate /> </AppHero> <JournalList /> </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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web/components/journal/journal-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 { useJournalProgram, useJournalProgramAccount, } from "./journal-data-access"; import { useWallet } from "@solana/wallet-adapter-react"; import { useState } from "react"; export function JournalCreate() { const { createEntry } = useJournalProgram(); const { publicKey } = useWallet(); const [title, setTitle] = useState(""); const [message, setMessage] = useState(""); const isFormValid = title.trim() !== "" && message.trim() !== ""; const handleSubmit = () => { if (publicKey && isFormValid) { createEntry.mutateAsync({ title, message, owner: publicKey }); } }; if (!publicKey) { return <p>Connect your wallet</p>; } return ( <div> <input type="text" placeholder="Title" value={title} onChange={(e) => setTitle(e.target.value)} className="input input-bordered w-full max-w-xs" /> <textarea placeholder="Message" value={message} onChange={(e) => setMessage(e.target.value)} className="textarea textarea-bordered w-full max-w-xs" /> <br></br> <button className="btn btn-xs lg:btn-md btn-primary" onClick={handleSubmit} disabled={createEntry.isPending || !isFormValid} > Create Journal Entry {createEntry.isPending && "..."} </button> </div> ); } export function JournalList() { const { accounts, getProgramAccount } = useJournalProgram(); if (getProgramAccount.isLoading) { return <span className="loading loading-spinner loading-lg"></span>; } if (!getProgramAccount.data?.value) { return ( <div className="flex justify-center alert alert-info"> <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 gap-4 md:grid-cols-2"> {accounts.data?.map((account) => ( <JournalCard 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 JournalCard({ account }: { account: PublicKey }) { const { accountQuery, updateEntry, deleteEntry } = useJournalProgramAccount({ account, }); const { publicKey } = useWallet(); const [message, setMessage] = useState(""); const title = accountQuery.data?.title; const isFormValid = message.trim() !== ""; const handleSubmit = () => { if (publicKey && isFormValid && title) { updateEntry.mutateAsync({ title, message, owner: publicKey }); } }; if (!publicKey) { return <p>Connect your wallet</p>; } 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()} > {accountQuery.data?.title} </h2> <p>{accountQuery.data?.message}</p> <div className="card-actions justify-around"> <textarea placeholder="Update message here" value={message} onChange={(e) => setMessage(e.target.value)} className="textarea textarea-bordered w-full max-w-xs" /> <button className="btn btn-xs lg:btn-md btn-primary" onClick={handleSubmit} disabled={updateEntry.isPending || !isFormValid} > Update Journal Entry {updateEntry.isPending && "..."} </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; } const title = accountQuery.data?.title; if (title) { return deleteEntry.mutateAsync(title); } }} disabled={deleteEntry.isPending} > Close </button> </div> </div> </div> </div> ); }
0
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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="Solana Logo" src="/solana-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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app/web/components
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/anchor/project.json
{ "name": "anchor", "$schema": "../node_modules/nx/schemas/project-schema.json", "sourceRoot": "anchor/src", "projectType": "library", "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", "outputs": ["{options.outputFile}"] }, "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" } } }, "tags": [] }
0
solana_public_repos/developer-bootcamp-2024/project-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/anchor/Anchor.toml
[toolchain] [features] seeds = false skip-lint = false [programs.localnet] journal = "94L2mJxVu6ZMmHaGsCHRQ65Kk2mea6aTnwWjSdfSsmBC" [registry] url = "https://api.apr.dev" [provider] cluster = "Localnet" wallet = "/Users/brimigs/.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-4-crud-app
solana_public_repos/developer-bootcamp-2024/project-4-crud-app/anchor/package.json
{ "name": "@journal/anchor", "version": "0.0.1", "dependencies": { "@coral-xyz/anchor": "^0.30.1", "@solana/web3.js": "1.90.0" }, "type": "commonjs", "main": "./index.cjs", "module": "./index.js" }
0