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 verification feature #631

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
32 changes: 32 additions & 0 deletions src/api/hooks/useVerificationCheck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {useCallback} from "react";
import {useGlobalState} from "../../global-config/GlobalConfig";
import {VerificationStatus} from "../../constants";

export interface AptosVerificationCheckDto {
network: string;
account: string;
moduleName: string;
status?: VerificationStatus;
errMsg?: string;
}
const useVerificationChecker = () => {
const [, , endpoint] = useGlobalState();

return useCallback(
async (params: {
network: string;
account: string;
moduleName: string;
}): Promise<AptosVerificationCheckDto> => {
const queryString = new URLSearchParams(params).toString();
const res = await fetch(`${endpoint}?${queryString}`);
if (!res.ok) {
throw new Error("Verification service is not working.");
}
return res.json();
},
[endpoint],
);
};

export default useVerificationChecker;
39 changes: 39 additions & 0 deletions src/api/hooks/useVerificationRequester.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {useCallback} from "react";
import {useGlobalState} from "../../global-config/GlobalConfig";

export interface AptosVerificationResultDto {
network: string;
account: string;
moduleName: string;
errMsg?: string;
status?: "VERIFIED_SAME" | "VERIFIED_DIFFERENT" | "NOT_VERIFIED";
onChainByteCode?: string;
compiledByteCode?: string;
}

const useVerificationRequester = () => {
const [, , endpoint] = useGlobalState();

return useCallback(
async (body: {
network: string;
account: string;
moduleName: string;
}): Promise<AptosVerificationResultDto> => {
const res = await fetch(endpoint, {
method: "post",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
},
});
if (!res.ok) {
throw new Error("Verification service is not working.");
}
return res.json();
},
[endpoint],
);
};

export default useVerificationRequester;
8 changes: 8 additions & 0 deletions src/constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ export function isValidNetworkName(value: string): value is NetworkName {
return value in networks;
}

export const defaultVerificationServiceUrl =
"https://verify.welldonestudio.io/aptos";

Comment on lines +23 to +25
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there's a service for this, we should possibly provide help details somewhere for how someone can run it themselves. Since, this is essentially trusting this URL entirely, it would be good to provide a more trustless system (you can run it yourself), or that the foundation will run it.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will inform you once I have prepared for it.

export type VerificationStatus =
| "VERIFIED_SAME"
| "VERIFIED_DIFFERENT"
| "NOT_VERIFIED";

export enum Network {
MAINNET = "mainnet",
TESTNET = "testnet",
Expand Down
19 changes: 17 additions & 2 deletions src/global-config/GlobalConfig.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import {AptosClient, IndexerClient} from "aptos";
import React, {useMemo} from "react";
import React, {Dispatch, SetStateAction, useMemo, useState} from "react";
import {
FeatureName,
NetworkName,
defaultNetworkName,
networks,
defaultVerificationServiceUrl,
} from "../constants";
import {
getSelectedFeatureFromLocalStorage,
Expand Down Expand Up @@ -59,6 +60,12 @@ const initialGlobalState = deriveGlobalState({

export const GlobalStateContext = React.createContext(initialGlobalState);
export const GlobalActionsContext = React.createContext({} as GlobalActions);
export const GlobalVerificationApiContext = React.createContext<string>(
defaultVerificationServiceUrl,
);
export const GlobalVerificationApiDispatchContext = React.createContext<
Dispatch<SetStateAction<string>>
>(() => {});

export const GlobalStateProvider = ({
children,
Expand All @@ -67,6 +74,8 @@ export const GlobalStateProvider = ({
}) => {
const [selectedFeature, selectFeature] = useFeatureSelector();
const [selectedNetwork, selectNetwork] = useNetworkSelector();
const [endpoint, setEndpoint] = useState(defaultVerificationServiceUrl);

const globalState: GlobalState = useMemo(
() =>
deriveGlobalState({
Expand All @@ -87,7 +96,11 @@ export const GlobalStateProvider = ({
return (
<GlobalStateContext.Provider value={globalState}>
<GlobalActionsContext.Provider value={globalActions}>
{children}
<GlobalVerificationApiContext.Provider value={endpoint}>
<GlobalVerificationApiDispatchContext.Provider value={setEndpoint}>
{children}
</GlobalVerificationApiDispatchContext.Provider>
</GlobalVerificationApiContext.Provider>
</GlobalActionsContext.Provider>
</GlobalStateContext.Provider>
);
Expand All @@ -97,4 +110,6 @@ export const useGlobalState = () =>
[
React.useContext(GlobalStateContext),
React.useContext(GlobalActionsContext),
React.useContext(GlobalVerificationApiContext),
React.useContext(GlobalVerificationApiDispatchContext),
] as const;
78 changes: 74 additions & 4 deletions src/pages/Account/Components/CodeSnippet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@
} from "../../../themes/colors/aptosColorPalette";
import {useParams} from "react-router-dom";
import {useLogEventWithBasic} from "../hooks/useLogEventWithBasic";
import {useGlobalState} from "../../../global-config/GlobalConfig";
import {VerificationStatus} from "../../../constants";
import useVerificationChecker, {
AptosVerificationCheckDto,
} from "../../../api/hooks/useVerificationCheck";
import VerificationButton from "./VerificationButton";
import VerificationServiceUrlInput from "./VerificationServiceUrlInput";
import {
CODE_DESCRIPTION_NOT_VERIFIED,
genCodeDescription,
} from "./codeDescription";

function useStartingLineNumber(sourceCode?: string) {
const functionToHighlight = useParams().selectedFnName;
Expand Down Expand Up @@ -106,7 +117,7 @@
}

export function Code({bytecode}: {bytecode: string}) {
const {selectedModuleName} = useParams();
const {address, selectedModuleName} = useParams();
const logEvent = useLogEventWithBasic();

const TOOLTIP_TIME = 2000; // 2s
Expand All @@ -116,6 +127,16 @@
const theme = useTheme();
const [tooltipOpen, setTooltipOpen] = useState<boolean>(false);

const checkVerification = useVerificationChecker();
const [state, , verificationServiceEndpoint] = useGlobalState();
const [codeDescription, setCodeDescription] = useState<string>(
CODE_DESCRIPTION_NOT_VERIFIED,
);
const [verificationStatus, setVerificationStatus] =
useState<VerificationStatus>("NOT_VERIFIED");
const [verificationServerErr, setVerificationServerErr] =
useState<string>("");

async function copyCode() {
if (!sourceCode) return;

Expand All @@ -134,7 +155,36 @@
codeBoxScrollRef.current.scrollTop =
LINE_HEIGHT_IN_PX * startingLineNumber;
}
});

if (state.network_name && address && selectedModuleName) {
checkVerification({
network: state.network_name,
account: address,
moduleName: selectedModuleName,
})
.then((dto: AptosVerificationCheckDto) => {
if (dto.errMsg) {
setVerificationStatus("NOT_VERIFIED");
setVerificationServerErr(`${dto.errMsg}`);
}

if (!dto.status) {
setVerificationStatus("NOT_VERIFIED");
return;
}

setVerificationStatus(dto.status);
setCodeDescription(genCodeDescription(dto.status));
setVerificationServerErr("");
})
.catch((reason: Error) => {
console.error(reason);
setVerificationStatus("NOT_VERIFIED");
setCodeDescription(genCodeDescription("NOT_VERIFIED"));
setVerificationServerErr("Verification service is not working.");
});
}
}, [address, selectedModuleName, verificationServiceEndpoint]);

Check warning on line 187 in src/pages/Account/Components/CodeSnippet.tsx

View workflow job for this annotation

GitHub Actions / lint

React Hook useEffect has missing dependencies: 'checkVerification', 'startingLineNumber', and 'state.network_name'. Either include them or remove the dependency array

return (
<Box>
Expand All @@ -155,6 +205,27 @@
Code
</Typography>
<StyledLearnMoreTooltip text="Please be aware that this code was provided by the owner and it could be different to the real code on blockchain. We can not not verify it." />
gregnazario marked this conversation as resolved.
Show resolved Hide resolved
<Stack>
<Stack
direction="row"
spacing={1}
alignItems={"center"}
justifyContent="center"
>
<VerificationButton
network={state.network_name}
account={address}
moduleName={selectedModuleName}
verificationStatus={verificationStatus}
setVerificationServerErr={setVerificationServerErr}
setVerificationStatus={setVerificationStatus}
setCodeDescription={setCodeDescription}
/>
<VerificationServiceUrlInput
verificationServerErr={verificationServerErr}
/>
</Stack>
</Stack>
</Stack>
{sourceCode && (
<Stack direction="row" spacing={2}>
Expand Down Expand Up @@ -204,8 +275,7 @@
marginBottom={"16px"}
color={theme.palette.mode === "dark" ? grey[400] : grey[600]}
>
The source code is plain text uploaded by the deployer, which can be
different from the actual bytecode.
{codeDescription}
</Typography>
)}
{!sourceCode ? (
Expand Down
109 changes: 109 additions & 0 deletions src/pages/Account/Components/VerificationButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import React, {useState} from "react";
import {Button, CircularProgress} from "@mui/material";
import useVerificationRequester from "../../../api/hooks/useVerificationRequester";
import {VerificationStatus} from "../../../constants";
import {genCodeDescription} from "./codeDescription";

interface VerificationButtonProps {
network: string;
account?: string;
moduleName?: string;
verificationStatus?: VerificationStatus;
setVerificationStatus: React.Dispatch<
React.SetStateAction<VerificationStatus>
>;
setVerificationServerErr: React.Dispatch<React.SetStateAction<string>>;
setCodeDescription: React.Dispatch<React.SetStateAction<string>>;
}

export default function VerificationButton({
network,
account,
moduleName,
verificationStatus,
setVerificationStatus,
setVerificationServerErr,
setCodeDescription,
}: VerificationButtonProps) {
const [isInProgress, setIsInProgress] = useState(false);
const verificationRequester = useVerificationRequester();

const verifyClick = () => {
if (!(account && moduleName)) {
return;
}
setIsInProgress(true);
verificationRequester({
network: network,
account: account,
moduleName: moduleName,
})
.then((dto) => {
setIsInProgress(false);
if (dto.errMsg) {
setVerificationStatus("NOT_VERIFIED");
setVerificationServerErr(`${dto.errMsg}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My main concern is the messages that currently come out of this need to be cleaned up a bit. Would be great to see some of the code for the verification service.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I fixed verification server to show the actual error message.
(ex. Move compilation failed: Unable to resolve packages for package 'AptosFramework': While resolving dependency 'AptosStdlib' in package 'AptosFramework': While processing dependency 'AptosStdlib': Unable to find package manifest for 'AptosStdlib' at "~/mainnet/0x1/1704956814227/../aptos-stdlib" )

}

if (!dto.status) {
setVerificationStatus("NOT_VERIFIED");
return;
}

setVerificationStatus(dto.status);
setCodeDescription(genCodeDescription(dto.status));
setVerificationServerErr("");
})
.catch((reason: Error) => {
console.error(reason);
setVerificationStatus("NOT_VERIFIED");
setCodeDescription(genCodeDescription("NOT_VERIFIED"));
setVerificationServerErr("Verification service is not working.");
})
.finally(() => {
setIsInProgress(false);
});
};

if (verificationStatus === "VERIFIED_DIFFERENT") {
return (
<Button
type="submit"
disabled={true}
variant="contained"
sx={{width: "10rem", height: "3rem"}}
>
<span style={{color: "red"}}>No Match</span>
gregnazario marked this conversation as resolved.
Show resolved Hide resolved
</Button>
);
}

if (verificationStatus === "VERIFIED_SAME") {
return (
<Button
type="submit"
disabled={true}
variant="contained"
sx={{width: "10rem", height: "3rem"}}
>
<span style={{color: "green"}}>Match</span>
gregnazario marked this conversation as resolved.
Show resolved Hide resolved
</Button>
);
}

return (
<Button
type="submit"
disabled={isInProgress}
variant="contained"
sx={{width: "10rem", height: "3rem"}}
onClick={verifyClick}
>
{verificationStatus === undefined || isInProgress ? (
<CircularProgress size={30}></CircularProgress>
) : (
"Verify"
gregnazario marked this conversation as resolved.
Show resolved Hide resolved
)}
</Button>
);
}
Loading
Loading