Skip to content

Commit

Permalink
feat: access contract
Browse files Browse the repository at this point in the history
  • Loading branch information
lance10030 committed Sep 4, 2024
1 parent d5ef1bd commit ca28523
Show file tree
Hide file tree
Showing 8 changed files with 163 additions and 42 deletions.
120 changes: 107 additions & 13 deletions src/components/Charts/ClaimChart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ChartCard } from "./ChartCard";
import { ClaimData } from "@/types";
import { depth, shortenAddress } from "@/utils";
import { EChartOption } from "echarts";
import React, { FC, useState } from "react";
import React, { FC, useEffect, useMemo, useState } from "react";
import {
Dialog,
DialogBackdrop,
Expand All @@ -13,7 +13,12 @@ import { ConnectButton } from "@rainbow-me/rainbowkit";
import { Button } from "@/components/Button";
import { Input } from "@/components/Input";
import { useCalculateClaim } from "@/hooks/useCaculateClaim";
import { useWriteContract } from "wagmi";
import { useReadContract, useWriteContract } from "wagmi";
import { abi } from "@/utils/abi";
import { Abi, Address, Chain, Client, Transport, formatUnits, parseUnits } from "viem";
import { useNetworkConfig } from "@/hooks/useNetworkConfig";
import { waitForTransactionReceipt } from "viem/actions";
import { useWagmiConfig } from "@/hooks/useWagmiConfig";

const xGap = 45;
const yGap = 50;
Expand Down Expand Up @@ -126,7 +131,7 @@ const genNodesAndLinks = (data: ClaimData[]): any => {
};
};

const ClaimChart: FC<{ claimData: ClaimData[] }> = ({ claimData }) => {
const ClaimChart: FC<{ claimData: ClaimData[], address: string }> = ({ claimData, address }) => {
const { nodes, links, maxDepth } = genNodesAndLinks(claimData);
const { isMutating, trigger } = useCalculateClaim();
const options: EChartOption<EChartOption.SeriesGraph> = {
Expand Down Expand Up @@ -185,14 +190,89 @@ const ClaimChart: FC<{ claimData: ClaimData[] }> = ({ claimData }) => {
const [showModal, setShowModal] = useState(false);
const [modalData, setModalData] = useState<Node>();
const [val, setVal] = useState("");
const { writeContract } = useWriteContract();
const [recommendAttackClaim, setAttackClaim] = useState("")
const [recommendDefendClaim, setDefendClaim] = useState("")
const config = useWagmiConfig()

const attackPosition = useMemo(() => {
if (modalData) {
return 2 * Number(modalData.position)
}
}, [modalData])
const defendPosition = useMemo(() => {
if (modalData) {
return 2 * (Number(modalData.position) + 1)
}
}, [modalData])
const { writeContractAsync } = useWriteContract();
const { data: index } = useReadContract({
abi: abi as Abi,
address: address as Address,
functionName: 'claimDataLen'
})
const { data: attackGas } = useReadContract({
abi: abi as Abi,
address: address as Address,
functionName: 'getRequiredBond',
args: [attackPosition]
})
const { data: defendGas } = useReadContract({
abi: abi as Abi,
address: address as Address,
functionName: 'getRequiredBond',
args: [defendPosition]
})
const handleClick = (e: any) => {
setShowModal(true);
setModalData(e.data);
};

const handleAttack = async () => {};
useEffect(() => {
if (attackPosition) {
trigger({ disputeGame: address, position: attackPosition }).then((res) => {
setAttackClaim(res.claims)
})
}
}, [attackPosition])
useEffect(() => {
if (defendPosition) {
trigger({ disputeGame: address, position: defendPosition }).then((res) => {
setDefendClaim(res.claims)
})

}
}, [defendPosition])

const handleAttack = async () => {
if (!val) return;
if (!index) return;
if (!attackGas) return;
const hash = await writeContractAsync({
abi: abi as Abi,
address: address as Address,
functionName: 'attack',
args: ['0x' + modalData?.claim, Number(index) - 1, val],
value: parseUnits(formatUnits(attackGas as bigint, 18), 18)
})
const res = await waitForTransactionReceipt(config as any, { hash })
console.log(res, 'res-defend')
};

const handleDefend = async () => {
if (!val) return;
if (!index) return;
if (!attackGas) return;
console.log(['0x' + modalData?.claim, Number(index) - 1, val])
const hash = await writeContractAsync({
abi: abi as Abi,
address: address as Address,
functionName: 'defend',
args: ['0x' + modalData?.claim, Number(index) - 1, val],
value: parseUnits(formatUnits(defendGas as bigint, 18), 18)
})
console.log(hash, 'hash')

}

return (
<>
Expand All @@ -215,13 +295,27 @@ const ClaimChart: FC<{ claimData: ClaimData[] }> = ({ claimData }) => {
<DialogTitle as="h3" className="text-base/7 font-medium">
Challenge
</DialogTitle>
<p className="mt-4 text-sm/6 text-white/50">
<div className="mt-4 text-sm/6 text-white/50">
<div>
<div className="text-sm font-semibold text-contentSecondary-light dark:text-warmGray-300 mb-1">
Claim
Claim:
</div>
<div className="text-sm text-contentSecondary-light dark:text-warmGray-300 mb-2 break-all">
{modalData?.claim}
{'0x' + modalData?.claim}
</div>
</div> <div>
<div className="text-sm font-semibold text-contentSecondary-light dark:text-warmGray-300 mb-1">
Recommend Attack Claim:
</div>
<div className="text-sm text-contentSecondary-light dark:text-warmGray-300 mb-2 break-all">
{recommendAttackClaim}
</div>
</div> <div>
<div className="text-sm font-semibold text-contentSecondary-light dark:text-warmGray-300 mb-1">
Recommend Defend Claim:
</div>
<div className="text-sm text-contentSecondary-light dark:text-warmGray-300 mb-2 break-all">
{recommendDefendClaim}
</div>
</div>
<div>
Expand All @@ -234,21 +328,21 @@ const ClaimChart: FC<{ claimData: ClaimData[] }> = ({ claimData }) => {
id="search"
value={val}
onChange={(e) => setVal(e.target.value)}
className={"rounded-none rounded-l-md"}
className={"rounded-none rounded-l-md text-black"}
placeholder={"challenge string"}
/>
</div>
</p>
</div>
<div className="mt-4 flex justify-end gap-4">
<Button
label="defend"
variant="outline"
onClick={() => setShowModal(false)}
></Button>{" "}
onClick={handleDefend}
></Button>
<Button
label="attack"
variant="outline"
onClick={() => setShowModal(false)}
onClick={handleAttack}
></Button>
</div>
</DialogPanel>
Expand Down
19 changes: 3 additions & 16 deletions src/components/Wallet/Provider.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,22 @@

"use client"
import '@rainbow-me/rainbowkit/styles.css';
import {
getDefaultConfig,
RainbowKitProvider,
} from '@rainbow-me/rainbowkit';
import { WagmiProvider } from 'wagmi';
import {
mainnet,
sepolia
} from 'wagmi/chains';
import {
QueryClientProvider,
QueryClient,
} from "@tanstack/react-query";
import { ReactNode, useMemo } from 'react';
import { useNetworkConfig } from '@/hooks/useNetworkConfig';
import useWagmiRainbowConfig from '@/hooks/useWagmiConfig';


const queryClient = new QueryClient();

const Provider = ({ children }: { children: ReactNode }) => {
const { network } = useNetworkConfig()
const isMainnet = useMemo(() => {
return network === 'mainnet'
}, [network])
const config = getDefaultConfig({
appName: 'SuperProof explorer',
projectId: '876a28d2d23153fe7f76c24bacbabb72',
chains: [isMainnet ? mainnet : sepolia],
ssr: true
});
const config = useWagmiRainbowConfig()
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
Expand Down
8 changes: 3 additions & 5 deletions src/hooks/useCaculateClaim.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { post } from '@/service';
import useSWRMutation, { SWRMutationResponse } from 'swr/mutation'

type CalculateArgs = {
disputeGame: string
position: string
position: number
}
export const useCalculateClaim = () => {
const url = `/api/disputegames/calculate/claim`;
async function fetcher(url: string, { arg }: { arg: CalculateArgs }) {
return await fetch(url, {
method: 'POST',
body: JSON.stringify(arg)
})
return await post(url, arg)
}
const res = useSWRMutation(url, fetcher);
return res
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useNetworkConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NetworkConfig, networkConfigs, Network } from "@/utils/env";
import { useMemo } from "react";

export const useNetworkConfig = (): NetworkConfig => {
const host = window.location.host;
const host = window?.location?.host;
const defaultNetwork = networkConfigs["sepolia"];
defaultNetwork.network = "sepolia";
const config = useMemo(() => {
Expand Down
42 changes: 42 additions & 0 deletions src/hooks/useWagmiConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useMemo } from "react";
import { useNetworkConfig } from "./useNetworkConfig";
import { getDefaultConfig } from "@rainbow-me/rainbowkit";
import { mainnet, sepolia } from "viem/chains";
import { http, createConfig } from 'wagmi'

const useWagmiRainbowConfig = () => {
const { network } = useNetworkConfig()

const isMainnet = useMemo(() => {
return network === 'mainnet'
}, [network])
const config = getDefaultConfig({
appName: 'SuperProof explorer',
projectId: '876a28d2d23153fe7f76c24bacbabb72',
chains: [isMainnet ? mainnet : sepolia],
ssr: true
});
return config
}

export default useWagmiRainbowConfig;


const useWagmiConfig = () => {
const { network } = useNetworkConfig()
const isMainnet = useMemo(() => {
return network === 'mainnet'
}, [network])
const config = useMemo(() => createConfig({
chains: [isMainnet ? mainnet : sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
}), [isMainnet])
return config
}

export {
useWagmiConfig
}
5 changes: 4 additions & 1 deletion src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { SkeletonTheme } from "react-loading-skeleton";
import AppLayout from "@/components/AppLayout/AppLayout";
import { useIsMounted } from "@/hooks/useIsMounted";
import Script from "next/script";
import WalletProvider from "@/components/Wallet/Provider";

const App = ({ Component, pageProps }: NextAppProps) => {
const { resolvedTheme } = useTheme();
Expand Down Expand Up @@ -41,7 +42,9 @@ const App = ({ Component, pageProps }: NextAppProps) => {
`}
</Script>
<AppLayout>
<Component {...pageProps} />
<WalletProvider>
<Component {...pageProps} />
</WalletProvider>
</AppLayout>
{/* <FeedbackWidget />
{env.NEXT_PUBLIC_VERCEL_ANALYTICS_ENABLED && <Analytics />} */}
Expand Down
7 changes: 1 addition & 6 deletions src/pages/game/[game].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,10 @@ import { Card } from "@/components/Cards/Card";
import ClaimCard from "@/components/Cards/SurfaceCards/ClaimCard";
import { SlidableList } from "@/components/SlidableList";
import { useNetworkConfig } from "@/hooks/useNetworkConfig";
import Challenge from "@/components/Challenge";
import Provider from "@/components/Wallet/Provider";

const GameDetail = () => {
const router = useRouter();
const address = (router.query.game as string | undefined) ?? "";

const { data, isLoading } = useClaimData(address);
const { data: game, isLoading: gameLoading } = useLatestGame({
hitsPerPage: 1,
Expand Down Expand Up @@ -92,9 +89,7 @@ const GameDetail = () => {
<ChartSkeleton itemsCount={6} />
</div>
) : (
<Provider>
<ClaimChart claimData={data?.data as ClaimData[]} />
</Provider>
<ClaimChart address={address} claimData={data?.data as ClaimData[]} />
)}
<Card
header={
Expand Down
2 changes: 2 additions & 0 deletions src/utils/env.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Address } from "viem";

export type Network = "mainnet" | "sepolia" | "base-sepolia";

export const ApiDoc = process.env.NEXT_PUBLIC_API_DOC || "";
Expand Down

0 comments on commit ca28523

Please sign in to comment.