Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add contract's txn hash for batch actions #65

Merged
merged 6 commits into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 32 additions & 14 deletions packages/hardhat/contracts/BGGrants.sol
Original file line number Diff line number Diff line change
Expand Up @@ -10,35 +10,53 @@ contract BGGrants is Ownable, ReentrancyGuard {
error INVALID_RECIPIENT();
error INSUFFICIENT_RECIPIENT_COUNT();
error TRANSFER_FAILED();
error INSUFFICIENT_SPLIT_AMOUNT();
error INVALID_INPUT();

event EthSplitEqual(address indexed sender, uint256 totalAmount, address payable[] recipients);
event EthSplit(address indexed sender, uint256 totalAmount, address payable[] recipients, uint256[] amounts);

constructor(address _owner) {
super.transferOwnership(_owner);
}

function splitEqualETH(address payable[] calldata recipients) external payable nonReentrant {
uint256 totalAmount = msg.value;
uint256 rLength = recipients.length;
uint256 equalAmount = totalAmount / rLength;
uint256 remainingAmount = totalAmount % rLength;
function splitETH(
address payable[] calldata recipients,
uint256[] calldata amounts
) external payable nonReentrant {
uint256 remainingAmount = _splitETH(recipients, amounts, msg.value);
emit EthSplit(msg.sender, msg.value, recipients, amounts);

if (rLength > 25) revert INSUFFICIENT_RECIPIENT_COUNT();
if (remainingAmount > 0) {
(bool success, ) = msg.sender.call{value: remainingAmount, gas: 20000}("");
if (!success) revert TRANSFER_FAILED();
}
}

function _splitETH(
address payable[] calldata recipients,
uint256[] calldata amounts,
uint256 totalAvailable
) internal returns (uint256 remainingAmount) {
uint256 length = recipients.length;
if (length != amounts.length) revert INVALID_INPUT();

for (uint256 i = 0; i < rLength; ) {
if (length > 25) revert INSUFFICIENT_RECIPIENT_COUNT();

uint256 totalAmount = 0;
for (uint256 i = 0; i < length; ) {
if (recipients[i] == address(0)) revert INVALID_RECIPIENT();
uint256 amountToSend = equalAmount;
if (i == 0) {
amountToSend = amountToSend + remainingAmount;
}
(bool success, ) = recipients[i].call{value: amountToSend, gas: 20000}("");
if (amounts[i] == 0) revert INSUFFICIENT_SPLIT_AMOUNT();

totalAmount = totalAmount + amounts[i];

(bool success, ) = recipients[i].call{value: amounts[i], gas: 20000}("");
if (!success) revert TRANSFER_FAILED();
unchecked {
++i;
}
}

emit EthSplitEqual(msg.sender, msg.value, recipients);
return totalAvailable - totalAmount;
}

/**
Expand Down
20 changes: 12 additions & 8 deletions packages/nextjs/app/admin/_components/GrantReview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import Image from "next/image";
import { useReviewGrant } from "../hooks/useReviewGrant";
import { ActionModal } from "./ActionModal";
import { parseEther } from "viem";
import { useNetwork, useSendTransaction } from "wagmi";
import { useNetwork } from "wagmi";
import { ArrowTopRightOnSquareIcon } from "@heroicons/react/20/solid";
import TelegramIcon from "~~/components/assets/TelegramIcon";
import TwitterIcon from "~~/components/assets/TwitterIcon";
import { Address } from "~~/components/scaffold-eth";
import { useTransactor } from "~~/hooks/scaffold-eth";
import { useScaffoldContractWrite } from "~~/hooks/scaffold-eth";
import { GrantDataWithBuilder, SocialLinks } from "~~/services/database/schema";
import { PROPOSAL_STATUS } from "~~/utils/grants";

Expand Down Expand Up @@ -50,11 +50,12 @@ export const GrantReview = ({ grant, selected, toggleSelection }: GrantReviewPro
const modalRef = useRef<HTMLDialogElement>(null);
const { chain: connectedChain } = useNetwork();

const { data: txnHash, sendTransactionAsync } = useSendTransaction({
to: grant.builder,
value: parseEther((grant.askAmount / 2).toString()),
const { data: txResult, writeAsync: splitEqualETH } = useScaffoldContractWrite({
contractName: "BGGrants",
functionName: "splitETH",
args: [undefined, undefined],
});
const sendTx = useTransactor();

const { handleReviewGrant, isLoading } = useReviewGrant(grant);

if (grant.status !== PROPOSAL_STATUS.PROPOSED && grant.status !== PROPOSAL_STATUS.SUBMITTED) return null;
Expand Down Expand Up @@ -114,7 +115,10 @@ export const GrantReview = ({ grant, selected, toggleSelection }: GrantReviewPro
className={`btn btn-sm btn-neutral ${isLoading ? "opacity-50" : ""} ${completeActionDisableClassName}`}
data-tip={completeActionDisableToolTip}
onClick={async () => {
const resHash = await sendTx(sendTransactionAsync);
const resHash = await splitEqualETH({
args: [[grant.builder], [parseEther((grant.askAmount / 2).toString())]],
value: parseEther((grant.askAmount / 2).toString()),
});
// Transactor eats the error, so we need to handle by checking resHash
if (resHash && modalRef.current) modalRef.current.showModal();
}}
Expand All @@ -134,7 +138,7 @@ export const GrantReview = ({ grant, selected, toggleSelection }: GrantReviewPro
</button>
</div>
</div>
<ActionModal ref={modalRef} grant={grant} initialTxLink={txnHash?.hash} />
<ActionModal ref={modalRef} grant={grant} initialTxLink={txResult?.hash} />
</div>
);
};
42 changes: 31 additions & 11 deletions packages/nextjs/app/admin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { useRef, useState } from "react";
import { BatchActionModal } from "./_components/BatchActionModal";
import { GrantReview } from "./_components/GrantReview";
import useSWR from "swr";
import { parseEther } from "viem";
import { useScaffoldContractWrite } from "~~/hooks/scaffold-eth";
import { GrantDataWithBuilder } from "~~/services/database/schema";
import { PROPOSAL_STATUS } from "~~/utils/grants";
import { notification } from "~~/utils/scaffold-eth";
Expand Down Expand Up @@ -43,6 +45,30 @@ const AdminPage = () => {
}
};

const { data: txResult, writeAsync: splitEqualETH } = useScaffoldContractWrite({
contractName: "BGGrants",
functionName: "splitETH",
args: [undefined, undefined],
});

const handleBatchAction = async (filteredGrants: GrantDataWithBuilder[], action: "approve" | "complete") => {
const selectedGrantsWithMetaData = filteredGrants.filter(grant => {
if (action === "approve") return selectedApproveGrants.includes(grant.id);
return selectedCompleteGrants.includes(grant.id);
});
const builders = selectedGrantsWithMetaData.map(grant => grant.builder);
const buildersAmount = selectedGrantsWithMetaData.map(grant => parseEther((grant.askAmount / 2).toString()));
const totalAmount = selectedGrantsWithMetaData.reduce((acc, grant) => acc + grant.askAmount, 0);
console.log("totalAmount amount is :", totalAmount);
const value = parseEther((totalAmount / 2).toString());
const hash = await splitEqualETH({
args: [builders, buildersAmount],
value: value,
});
setModalBtnLabel(action === "approve" ? "Approve" : "Complete");
if (hash && modalRef.current) modalRef.current.showModal();
};

const completedGrants = grants?.filter(grant => grant.status === PROPOSAL_STATUS.SUBMITTED);
const newGrants = grants?.filter(grant => grant.status === PROPOSAL_STATUS.PROPOSED);

Expand All @@ -54,13 +80,10 @@ const AdminPage = () => {
<div className="p-8 bg-warning/5 lg:w-1/2">
<div className="flex justify-between items-center">
<h2 className="font-bold text-xl">New Grant Proposals</h2>
{newGrants?.length !== 0 && (
{newGrants && newGrants.length !== 0 && (
<button
className="btn btn-sm btn-primary"
onClick={async () => {
setModalBtnLabel("Approve");
if (modalRef.current) modalRef.current.showModal();
}}
onClick={() => handleBatchAction(newGrants, "approve")}
disabled={selectedApproveGrants.length === 0}
>
Batch Approve
Expand All @@ -80,13 +103,10 @@ const AdminPage = () => {
<div className="p-8 bg-success/5 lg:w-1/2">
<div className="flex justify-between items-center">
<h2 className="font-bold text-xl">Completed Grants</h2>
{completedGrants?.length !== 0 && (
{completedGrants && completedGrants.length !== 0 && (
<button
className="btn btn-sm btn-primary"
onClick={async () => {
setModalBtnLabel("Complete");
if (modalRef.current) modalRef.current.showModal();
}}
onClick={() => handleBatchAction(completedGrants, "complete")}
disabled={selectedCompleteGrants.length === 0}
>
Batch Complete
Expand All @@ -109,7 +129,7 @@ const AdminPage = () => {
ref={modalRef}
selectedGrants={modalBtnLabel === "Approve" ? selectedApproveGrants : selectedCompleteGrants}
btnLabel={modalBtnLabel}
initialTxLink={"0xdummyTransactionHash"}
initialTxLink={txResult?.hash}
closeModal={() => {
if (modalRef.current) modalRef.current.close();
}}
Expand Down
Loading