Skip to content

Commit

Permalink
Make writing allocations work
Browse files Browse the repository at this point in the history
  • Loading branch information
sembrestels committed Sep 17, 2024
1 parent 4c8ec97 commit 9daa763
Show file tree
Hide file tree
Showing 9 changed files with 476 additions and 48 deletions.
19 changes: 12 additions & 7 deletions apps/web/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import "@repo/ui/globals.css";
import { ToastProvider } from "@repo/ui/components/ui/toast";
import { Toaster } from "@repo/ui/components/ui/toaster";
import type { Metadata } from "next";
import { Newsreader } from "next/font/google";
import Footer from "../components/Footer";
Expand Down Expand Up @@ -26,13 +28,16 @@ export default function RootLayout({
<html lang="en">
<body className={newsreader.className}>
<WalletProvider>
<div className="flex flex-col min-h-screen">
<Header />
<main className="flex-grow px-4 container max-w-3xl mx-auto">
{children}
</main>
<Footer />
</div>
<ToastProvider>
<div className="flex flex-col min-h-screen">
<Header />
<main className="flex-grow px-4 container max-w-3xl mx-auto">
{children}
</main>
<Toaster />
<Footer />
</div>
</ToastProvider>
</WalletProvider>
</body>
</html>
Expand Down
64 changes: 64 additions & 0 deletions apps/web/src/components/VotingButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"use client";

import { Button } from "@repo/ui/components/ui/button";
import { useToast } from "@repo/ui/hooks/use-toast";
import { cn } from "@repo/ui/lib/utils";
import { useState } from "react";
import { useAccount } from "wagmi";
import { useWriteAllocation } from "../hooks/useWriteAllocation";

type VotingButtonProps = {
votes: Record<string, number>;
council: `0x${string}` | undefined;
disabled: boolean;
className?: string;
};

const VotingButton = ({
votes,
council,
disabled,
className,
}: VotingButtonProps) => {
const { address } = useAccount();
const vote = useWriteAllocation(council);
const totalVotes = Object.values(votes).reduce((a, b) => a + b, 0);
const [isLoading, setIsLoading] = useState(false);
const toast = useToast();

return (
<Button
disabled={disabled || !address || isLoading}
className={cn("w-full py-2 rounded-lg mt-4 font-bold", className)}
onClick={() => {
setIsLoading(true);
vote(
Object.entries(votes)
.filter(([, voteCount]) => voteCount > 0)
.map(([grantee, voteCount]) => ({
account: grantee as `0x${string}`,
ratio: (BigInt(voteCount) * 2n ** 128n) / BigInt(totalVotes),
})),
)
.then(() => {
setIsLoading(false);
toast.toast({
title: "Voted",
description: "You have successfully voted",
});
})
.catch(() => {
setIsLoading(false);
toast.toast({
title: "Failed to vote",
description: "Please try again",
});
});
}}
>
{isLoading ? "Voting..." : address ? "Vote" : "Wallet not connected"}
</Button>
);
};

export default VotingButton;
25 changes: 7 additions & 18 deletions apps/web/src/components/VotingCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Skeleton } from "@repo/ui/components/ui/skeleton";
import React, { useState } from "react";
import { useAccount } from "wagmi";
import { useWriteAllocation } from "../hooks/useWriteAllocation";
import VotingButton from "./VotingButton";

type Project = { grantee: `0x${string}`; name: string };

Expand All @@ -29,12 +30,11 @@ const VotingCard = ({
maxVotedProjects?: number;
isLoading: boolean;
}) => {
const { address } = useAccount();

const [votes, setVotes] = useState<{ [grantee: `0x${string}`]: number }>(
Object.fromEntries(projects.map((project) => [project.grantee, 0])),
);

// Array of project addresses that have been voted on
const votedProjects = Object.keys(votes).filter(
(grantee) => (votes[grantee as `0x${string}`] ?? 0) > 0,
);
Expand Down Expand Up @@ -118,22 +118,11 @@ const VotingCard = ({
)}
</CardContent>
<CardFooter>
<Button
disabled={votedProjects.length < 1 || !address}
className="w-full py-2 rounded-lg mt-4 font-bold"
onClick={() =>
vote(
Object.entries(votes)
.filter(([, voteCount]) => voteCount > 0)
.map(([grantee, voteCount]) => ({
account: grantee as `0x${string}`,
ratio: (BigInt(voteCount) * 2n ** 128n) / BigInt(totalVotes),
})),
)
}
>
{address ? "Vote" : "Wallet not connected"}
</Button>
<VotingButton
votes={votes}
council={council}
disabled={votedProjects.length < 1}
/>
</CardFooter>
</Card>
);
Expand Down
61 changes: 38 additions & 23 deletions apps/web/src/hooks/useWriteAllocation.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
import { useAccount, useBalance } from "wagmi";

function alertAllocation(
allocation: { account: `0x${string}`; amount: bigint }[],
) {
console.log(allocation.reduce((acc, { amount }) => acc + amount, BigInt(0)));
alert(
allocation
.map(
({ account, amount }) =>
`${account.slice(0, 6)}...${account.slice(-4)}: ${amount}`,
)
.join("\n"),
);
}
import { parseAbi } from "viem";
import {
useAccount,
useBalance,
usePublicClient,
useWalletClient,
} from "wagmi";

export const useWriteAllocation = (council: `0x${string}` | undefined) => {
const { address } = useAccount();
Expand All @@ -23,13 +15,36 @@ export const useWriteAllocation = (council: `0x${string}` | undefined) => {
enabled: !!council,
},
});
return (allocation: { account: `0x${string}`; ratio: bigint }[]) => {
console.log(allocation);
alertAllocation(
allocation.map(({ account, ratio }) => ({
account,
amount: (ratio * BigInt(balance.data?.value ?? 0)) / 2n ** 128n,
})),
);
const publicClient = usePublicClient();
const { data: walletClient } = useWalletClient();

return async (allocation: { account: `0x${string}`; ratio: bigint }[]) => {
if (!council || !walletClient || !publicClient) {
throw new Error("Council or client is not set");
}

const hash = await walletClient.writeContract({
abi: parseAbi([
"struct Allocation { address[] accounts; uint128[] amounts; }",
"function allocateBudget(Allocation memory _allocation) public",
]),
address: council,
functionName: "allocateBudget",
args: [
{
accounts: allocation.map(({ account }) => account),
amounts: allocation.map(
({ ratio }) =>
(ratio * BigInt(balance.data?.value ?? 0)) / 2n ** 128n,
),
},
],
});

const receipt = await publicClient.waitForTransactionReceipt({ hash });

if (receipt.status !== "success") {
throw new Error("Transaction failed");
}
};
};
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
},
"dependencies": {
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.2.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"lucide-react": "^0.395.0",
Expand Down
129 changes: 129 additions & 0 deletions packages/ui/src/components/ui/toast.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"use client";

import * as ToastPrimitives from "@radix-ui/react-toast";
import { type VariantProps, cva } from "class-variance-authority";
import { X } from "lucide-react";
import * as React from "react";

import { cn } from "@repo/ui/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,
};
31 changes: 31 additions & 0 deletions packages/ui/src/components/ui/toaster.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"use client";

import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@repo/ui/components/ui/toast";
import { useToast } from "@repo/ui/hooks/use-toast";

export function Toaster() {
const { toasts } = useToast();

return (
<ToastProvider>
{toasts.map(({ id, title, description, action, ...props }) => (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && <ToastDescription>{description}</ToastDescription>}
</div>
{action}
<ToastClose />
</Toast>
))}
<ToastViewport />
</ToastProvider>
);
}
Loading

0 comments on commit 9daa763

Please sign in to comment.