Skip to content

Commit

Permalink
Merge pull request #34 from celo-org/add-custom-cusd-send
Browse files Browse the repository at this point in the history
feat: add "Send Custom cUSD Amount"
  • Loading branch information
therealharpaljadeja authored Oct 7, 2024
2 parents 0810915 + 34e8618 commit 6370070
Show file tree
Hide file tree
Showing 4 changed files with 201 additions and 112 deletions.
38 changes: 7 additions & 31 deletions packages/react-app/hooks/useSendErc20.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
import { useCallback } from "react";
import { encodeFunctionData, parseUnits } from "viem";
import { usePublicClient, useWalletClient } from "wagmi";
import toast from "react-hot-toast";
import { useWalletClient } from "wagmi";
import stableTokenAbi from "../abi/StableToken";
import { celo, celoAlfajores } from "viem/chains";
import { STABLE_TOKEN_ADDRESS, USDC_ADAPTER_ADDRESS } from "@/utils/constants";

export default function useSendErc20() {
const { data: walletClient } = useWalletClient();

const publicClient = usePublicClient();

const sendErc20 = useCallback(
async function (
tokenAddress: `0x${string}`,
receiverAddress: string,
transferValue: string,
tokenDecimals: number
) {
console.log("Transfer Value", transferValue);
let hash = await walletClient?.sendTransaction({
to: tokenAddress,
data: encodeFunctionData({
Expand All @@ -28,36 +27,13 @@ export default function useSendErc20() {
parseUnits(`${Number(transferValue)}`, tokenDecimals),
],
}),
// If the wallet is connected to a different network then you get an error.
chain: celoAlfajores,
// chain: celo,
});
console.log(tokenAddress);

if (publicClient && hash) {
let txToast = toast.loading(
"Transaction sent waiting for confirmation",
{
duration: 6000,
}
);

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

if (transaction.status === "success") {
toast.success("Transaction successful", {
id: txToast,
duration: 2000,
});
} else {
toast.error("Something went wrong", {
id: txToast,
duration: 2000,
});
}
if (hash) {
return hash;
}

return null;
},
[walletClient]
);
Expand Down
7 changes: 2 additions & 5 deletions packages/react-app/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,9 @@ const connectors = connectorsForWallets(

const config = createConfig({
connectors,
chains: [
// celo,
celoAlfajores,
],
chains: [celo, celoAlfajores],
transports: {
// [celo.id]: http(),
[celo.id]: http(),
[celoAlfajores.id]: http(),
},
});
Expand Down
221 changes: 166 additions & 55 deletions packages/react-app/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useEffect, useState } from "react";
import { useAccount, useChainId } from "wagmi";
import { useAccount, useChainId, usePublicClient } from "wagmi";
import toast from "react-hot-toast";
import { Button } from "@chakra-ui/react";
import useSendErc20 from "@/hooks/useSendErc20";
import { Address } from "viem";
import type { Address, Hex } from "viem";

const environment = process.env.NEXT_PUBLIC_ENVIRONMENT as
| "MAINNET"
Expand Down Expand Up @@ -50,11 +50,15 @@ export function validatePhoneNumber(phoneNumber: string): boolean {
}

export default function Home() {
const { isConnected } = useAccount();
const { isConnected, address } = useAccount();
const sendErc20 = useSendErc20();
const chainId = useChainId() as 42220 | 44787;

const [isMounted, setIsMounted] = useState(false);
const publicClient = usePublicClient();
const [transactionHash, setTransactionHash] = useState<Hex | null>(null);
const [tokenAmount, setTokenAmount] = useState("0");
const [receiverAddress, setReceiverAddress] = useState("0x000...");

useEffect(() => {
setIsMounted(true);
Expand All @@ -65,74 +69,181 @@ export default function Home() {
async function sendToken({
tokenAddress,
tokenDecimals,
tokenAmount = "1",
}: {
tokenAddress: Address;
tokenDecimals: number;
tokenAmount: string;
}) {
let txToast;
try {
await sendErc20(
txToast = toast.loading("Waiting for user confirmation", {
duration: 12000,
});

const hash = await sendErc20(
tokenAddress,
"0x22ae7Cf4cD59773f058B685a7e6B7E0984C54966",
"1",
receiverAddress,
tokenAmount,
tokenDecimals
);

toast.loading("Transaction sent waiting for onchain confirmation", {
id: txToast,
duration: 6000,
});

if (publicClient && hash) {
const transaction = await publicClient.waitForTransactionReceipt({
hash,
});

if (transaction) {
if (transaction.status === "success") {
toast.success("Transaction successful", {
id: txToast,
duration: 2000,
});
} else {
toast.error("Something went wrong", {
id: txToast,
duration: 2000,
});
}
setTransactionHash(transaction.transactionHash);
}
} else {
throw new Error();
}
} catch (error: any) {
toast.error("Something went wrong", { duration: 2000 });
toast.error("Something went wrong", { duration: 2000, id: txToast });
alert(error);
}
}

function handleValueChange({ target }: any) {
setTokenAmount(target.value);
}

function handleReceiverChange({ target }: any) {
setReceiverAddress(target.value);
}

return (
<div className="w-screen flex flex-col justify-center items-center gap-y-4">
{isConnected ? (
<div className="flex flex-col md:flex-row text-center gap-4 items-center">
<Button
textColor={"white"}
onClick={() => sendToken(tokens[chainId]["cUSD"])}
bg={"#46CD85"}
_hover={{ bg: "#46CD85" }}
_active={{ bg: "#46CD85" }}
leftIcon={
<img
className="h-[20px] w-[20px]"
src="https://s2.coinmarketcap.com/static/img/coins/64x64/7236.png"
/>
}
>
Send 1 cUSD
</Button>
<Button
textColor={"white"}
onClick={() => sendToken(tokens[chainId]["USDC"])}
bg={"#2775CA"}
_hover={{ bg: "#2775CA" }}
_active={{ bg: "#2775CA" }}
leftIcon={
<img
className="h-[20px] w-[20px]"
src="https://s2.coinmarketcap.com/static/img/coins/64x64/3408.png"
/>
}
>
Send 1 USDC
</Button>
{chainId === 42220 && (
<Button
textColor={"white"}
onClick={() => sendToken(tokens[chainId]["USDT"])}
bg={"#009393"}
_hover={{ bg: "#009393" }}
_active={{ bg: "#009393" }}
leftIcon={
<img
className="h-[20px] w-[20px]"
src="https://s2.coinmarketcap.com/static/img/coins/64x64/825.png"
<>
<div className="flex flex-col text-center gap-8 items-center">
<div className="flex flex-col space-y-4">
<p>Send Custom cUSD Amount</p>
<div className="flex space-x-4">
<input
value={receiverAddress}
onChange={handleReceiverChange}
className="border-2 px-4 border-black"
/>
<input
value={tokenAmount}
onChange={handleValueChange}
className="border-2 px-4 border-black"
/>
}
>
Send 1 USDT
</Button>
)}
</div>
<Button
bg={"#000000"}
_active={"#000"}
textColor={"white"}
onClick={() =>
sendToken({ ...tokens[chainId]["cUSD"], tokenAmount })
}
>
Send
</Button>
</div>
</div>
{/* <div className="flex flex-col md:flex-row gap-4 items-center">
<Button
textColor={"white"}
onClick={() => sendToken(tokens[chainId]["cUSD"])}
bg={"#46CD85"}
_hover={{ bg: "#46CD85" }}
_active={{ bg: "#46CD85" }}
leftIcon={
<img
className="h-[20px] w-[20px]"
src="https://s2.coinmarketcap.com/static/img/coins/64x64/7236.png"
/>
}
>
Send 1 cUSD
</Button>
<Button
textColor={"white"}
onClick={() => sendToken(tokens[chainId]["USDC"])}
bg={"#2775CA"}
_hover={{ bg: "#2775CA" }}
_active={{ bg: "#2775CA" }}
leftIcon={
<img
className="h-[20px] w-[20px]"
src="https://s2.coinmarketcap.com/static/img/coins/64x64/3408.png"
/>
}
>
Send 1 USDC
</Button>
{chainId === 42220 && (
<Button
textColor={"white"}
onClick={() => sendToken(tokens[chainId]["USDT"])}
bg={"#009393"}
_hover={{ bg: "#009393" }}
_active={{ bg: "#009393" }}
leftIcon={
<img
className="h-[20px] w-[20px]"
src="https://s2.coinmarketcap.com/static/img/coins/64x64/825.png"
/>
}
>
Send 1 USDT
</Button>
)}
</div> */}
</div>
{transactionHash ? (
<div>
<p>
Transaction Hash:
{chainId === 42220 ? (
<a
className="underline"
href={`https://celoscan.io/tx/${transactionHash}`}
>
{`${transactionHash.substring(
0,
5
)}...${transactionHash.substring(
transactionHash.length - 5,
transactionHash.length
)}`}
</a>
) : (
<a
className="underline"
href={`https://alfajores.celoscan.io/tx/${transactionHash}`}
>
{`${transactionHash.substring(
0,
5
)}...${transactionHash.substring(
transactionHash.length - 5,
transactionHash.length
)}`}
</a>
)}
</p>
</div>
) : null}
</>
) : (
<p>Please connect wallet first</p>
)}
Expand Down
Loading

0 comments on commit 6370070

Please sign in to comment.