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 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
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;
40 changes: 40 additions & 0 deletions src/api/hooks/useVerificationRequester.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {useCallback} from "react";
import {useGlobalState} from "../../global-config/GlobalConfig";
import {VerificationStatus} from "../../constants";

export interface AptosVerificationResultDto {
network: string;
account: string;
moduleName: string;
errMsg?: string;
status?: VerificationStatus;
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;
9 changes: 9 additions & 0 deletions src/constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ 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 enum VerificationStatus {
VERIFIED_SAME = "VERIFIED_SAME",
VERIFIED_DIFFERENT = "VERIFIED_DIFFERENT",
NOT_VERIFIED = "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 @@ -65,6 +66,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 @@ -73,6 +80,8 @@ export const GlobalStateProvider = ({
}) => {
const [selectedFeature, selectFeature] = useFeatureSelector();
const [selectedNetwork, selectNetwork] = useNetworkSelector();
const [endpoint, setEndpoint] = useState(defaultVerificationServiceUrl);

const globalState: GlobalState = useMemo(
() =>
deriveGlobalState({
Expand All @@ -93,7 +102,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 @@ -103,4 +116,6 @@ export const useGlobalState = () =>
[
React.useContext(GlobalStateContext),
React.useContext(GlobalActionsContext),
React.useContext(GlobalVerificationApiContext),
React.useContext(GlobalVerificationApiDispatchContext),
] as const;
97 changes: 87 additions & 10 deletions src/pages/Account/Components/CodeSnippet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ import {
} 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 @@ function ExpandCode({sourceCode}: {sourceCode: string | undefined}) {
}

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 @@ export function Code({bytecode}: {bytecode: string}) {
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>(VerificationStatus.NOT_VERIFIED);
const [verificationServerErr, setVerificationServerErr] =
useState<string>("");

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

Expand All @@ -129,12 +150,46 @@ export function Code({bytecode}: {bytecode: string}) {
const startingLineNumber = useStartingLineNumber(sourceCode);
const codeBoxScrollRef = useRef<any>(null);
const LINE_HEIGHT_IN_PX = 24;
useEffect(() => {
if (codeBoxScrollRef.current) {
codeBoxScrollRef.current.scrollTop =
LINE_HEIGHT_IN_PX * startingLineNumber;
}
});
useEffect(
() => {
if (codeBoxScrollRef.current) {
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(VerificationStatus.NOT_VERIFIED);
setVerificationServerErr(`${dto.errMsg}`);
}

if (!dto.status) {
setVerificationStatus(VerificationStatus.NOT_VERIFIED);
return;
}
setVerificationStatus(dto.status);
setCodeDescription(genCodeDescription(dto.status));
setVerificationServerErr("");
})
.catch((reason: Error) => {
console.error(reason);
setVerificationStatus(VerificationStatus.NOT_VERIFIED);
setCodeDescription(
genCodeDescription(VerificationStatus.NOT_VERIFIED),
);
setVerificationServerErr("Verification service is not working.");
});
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[address, selectedModuleName, verificationServiceEndpoint],
);

return (
<Box>
Expand All @@ -154,7 +209,30 @@ export function Code({bytecode}: {bytecode: string}) {
<Typography fontSize={20} fontWeight={700}>
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." />
{verificationStatus === VerificationStatus.NOT_VERIFIED ? (
<StyledLearnMoreTooltip text="Please be aware that this code was provided by the owner and it could be different to the real code on blockchain. Please click the 'Verify Source Code' button if you want to confirm that the provided source code matches the actual code on the blockchain." />
) : null}
<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 +282,7 @@ export function Code({bytecode}: {bytecode: string}) {
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
112 changes: 112 additions & 0 deletions src/pages/Account/Components/VerificationButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
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(VerificationStatus.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(VerificationStatus.NOT_VERIFIED);
return;
}

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

if (verificationStatus === VerificationStatus.VERIFIED_DIFFERENT) {
return (
<Button
type="submit"
disabled={true}
variant="contained"
sx={{width: "16rem", height: "3rem"}}
style={{textTransform: "none"}}
>
<span style={{color: "red"}}>Doesn't Match</span>
</Button>
);
}

if (verificationStatus === VerificationStatus.VERIFIED_SAME) {
return (
<Button
type="submit"
disabled={true}
variant="contained"
sx={{width: "16rem", height: "3rem"}}
style={{textTransform: "none"}}
>
<span style={{color: "green"}}>Matches</span>
</Button>
);
}

return (
<Button
type="submit"
disabled={isInProgress}
variant="contained"
sx={{width: "16rem", height: "3rem"}}
onClick={verifyClick}
style={{textTransform: "none"}}
>
{verificationStatus === undefined || isInProgress ? (
<CircularProgress size={30}></CircularProgress>
) : (
"Verify Source Code"
)}
</Button>
);
}
Loading