Skip to content

Commit

Permalink
useSweepWallet hook for sweeping private key
Browse files Browse the repository at this point in the history
  • Loading branch information
Avelous committed Feb 13, 2024
1 parent e8bd171 commit 33221d1
Show file tree
Hide file tree
Showing 7 changed files with 110 additions and 35 deletions.
35 changes: 3 additions & 32 deletions packages/nextjs/components/dicedemo/Congrats.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import { Dispatch, SetStateAction } from "react";
import { Hex, createWalletClient } from "viem";
import { http } from "viem";
import { parseEther } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { useBalance, useFeeData } from "wagmi";
import { useTransactor } from "~~/hooks/scaffold-eth";
import useGameData from "~~/hooks/useGameData";
import { getTargetNetwork } from "~~/utils/scaffold-eth";
import useSweepWallet from "~~/hooks/useSweepWallet";

const Congrats = ({
isOpen,
Expand All @@ -21,21 +15,9 @@ const Congrats = ({
setIsOpen(false);
};

const configuredNetwork = getTargetNetwork();
const { data } = useFeeData();

const walletClient = createWalletClient({
chain: configuredNetwork,
transport: http(),
});

const { loadGameState } = useGameData();
const transferTx = useTransactor(walletClient);
const { game } = loadGameState();
const privateKey = "0x" + game?.privateKey;

const account = privateKeyToAccount(privateKey as Hex);
const prize = useBalance({ address: game?.adminAddress });
const { sweepWallet } = useSweepWallet();

return (
<div className=" overflow-hidden w-fit text-xs bg-base-200 h-full">
Expand All @@ -48,18 +30,7 @@ const Congrats = ({
<p className="text-center mt-4">{message}</p>
<button
onClick={() => {
const gasCost = (21000 * Number(data?.formatted.maxFeePerGas)) / 1000000000;
console.log(gasCost);
const prizeMinusFee = Number(prize.data?.formatted) - gasCost;
const value = parseEther(prizeMinusFee.toString());

transferTx({
account: account,
to: game.winner,
value,
chain: configuredNetwork,
gas: BigInt("21000"),
});
sweepWallet(game.privateKey);
}}
className="btn btn-primary"
>
Expand Down
2 changes: 0 additions & 2 deletions packages/nextjs/components/dicedemo/RestartWithNewPk.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,6 @@ const RestartWithNewPk = ({ isOpen, setIsOpen }: { isOpen: boolean; setIsOpen: D
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

console.log(formData);

return (
<div className=" overflow-hidden w-fit text-xs bg-base-200 h-full">
{isOpen && (
Expand Down
File renamed without changes.
93 changes: 93 additions & 0 deletions packages/nextjs/hooks/useSweepWallet.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { ethers } from "ethers";
import { useAccount } from "wagmi";
import { getApiKey, getBlockExplorerTxLink, getTargetNetwork } from "~~/utils/scaffold-eth";
import { notification } from "~~/utils/scaffold-eth";

const TxnNotification = ({ message, blockExplorerLink }: { message: string; blockExplorerLink?: string }) => {
return (
<div className={`flex flex-col ml-1 cursor-default`}>
<p className="my-0">{message}</p>
{blockExplorerLink && blockExplorerLink.length > 0 ? (
<a href={blockExplorerLink} target="_blank" rel="noreferrer" className="block underline text-md">
check out transaction
</a>
) : null}
</div>
);
};

const useSweepWallet = () => {
const { address } = useAccount();
const configuredNetwork = getTargetNetwork();
const apiKey = getApiKey();

const provider = new ethers.providers.AlchemyProvider(configuredNetwork.network, apiKey);

const sweepWallet = async (privateKey: string) => {
const wallet = new ethers.Wallet(privateKey, provider);
const balance = await wallet.getBalance();
if (balance.eq(0)) {
console.log("Wallet balance is 0");
notification.info("Wallet balance is 0");
return;
}

const gasPrice = await provider.getGasPrice();

const gasLimit = 21000;
const gasCost = gasPrice.mul(gasLimit);

// const totalToSend = balance.sub(gasCost.mul(2));
let totalToSend = balance.sub(gasCost);

const overshotPercentage = 2;
const overshotAmount = totalToSend.mul(overshotPercentage).div(100);
totalToSend = totalToSend.sub(overshotAmount);

if (totalToSend.lte(0)) {
console.log("Balance is not enough to cover gas fees.");
notification.info("Balance is not enough to cover gas fees.");
return;
}

const tx = {
to: address,
value: totalToSend,
gasLimit: gasLimit,
gasPrice: gasPrice,
};

let txReceipt = null;

let notificationId = null;
try {
txReceipt = await wallet.sendTransaction(tx);
const transactionHash = txReceipt.hash;

notificationId = notification.loading(<TxnNotification message="Sweeping Wallet" />);

const blockExplorerTxURL = configuredNetwork ? getBlockExplorerTxLink(configuredNetwork.id, transactionHash) : "";
await txReceipt.wait();
notification.remove(notificationId);

notification.success(
<TxnNotification message="Transaction completed successfully!" blockExplorerLink={blockExplorerTxURL} />,
{
icon: "🎉",
},
);
} catch (error: any) {
if (notificationId) {
notification.remove(notificationId);
}
console.error("⚡️ ~ Sweep Wallet ~ error", error);
notification.error(error.message);
}

console.log("Transaction sent:", txReceipt);
};

return { sweepWallet };
};

export default useSweepWallet;
8 changes: 8 additions & 0 deletions packages/nextjs/pages/game/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,14 @@ function GamePage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [game]);

useEffect(() => {
setAutoRolling(false);
setBruteRolling(false);
setIsRolling(false);
setSpinning(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [game?.mode]);

if (game) {
return (
<div>
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@
"~~/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*/*.ts"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
5 changes: 5 additions & 0 deletions packages/nextjs/utils/scaffold-eth/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,8 @@ export function getTargetNetwork(): chains.Chain & Partial<TChainAttributes> {
...NETWORKS_EXTRA_DATA[configuredNetwork.id],
};
}

export function getApiKey() {
const apiKey = scaffoldConfig.alchemyApiKey;
return apiKey;
}

0 comments on commit 33221d1

Please sign in to comment.