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

Feat/code hash #372

Merged
merged 4 commits into from
Jun 7, 2023
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Features

- [#372](https://github.com/alleslabs/celatone-frontend/pull/372) Add code hash to code details and upload section
- [#329](https://github.com/alleslabs/celatone-frontend/pull/329) Add allowed user to store code flow
- [#321](https://github.com/alleslabs/celatone-frontend/pull/321) Add amplitude to proposal to store code page
- [#274](https://github.com/alleslabs/celatone-frontend/pull/274) Add proposal to store code page
Expand Down
36 changes: 36 additions & 0 deletions src/lib/components/upload/CodeHashBox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Flex, Text } from "@chakra-ui/react";

import type { Option } from "lib/types";

interface CodeHashBoxProps {
codeHash: Option<string>;
}

export const CodeHashBox = ({ codeHash }: CodeHashBoxProps) => (
<Flex position="relative">
<Text
position="absolute"
variant="body3"
color="text.dark"
px="1px"
top="-10px"
left={3}
>
Code Hash
</Text>
<Flex
border="1px"
borderRadius="5px"
px={3}
py={4}
borderColor="gray.700"
bg="gray.800"
h="56px"
w="full"
overflowX="auto"
overflowY="hidden"
>
<Text>{codeHash}</Text>
</Flex>
</Flex>
);
20 changes: 16 additions & 4 deletions src/lib/components/upload/UploadSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ import type {
UploadSectionState,
} from "lib/types";
import { AccessType } from "lib/types";
import { getCodeHash } from "lib/utils";

import { CodeHashBox } from "./CodeHashBox";
import { InstantiatePermissionRadio } from "./InstantiatePermissionRadio";
import { SimulateMessageRender } from "./SimulateMessageRender";
import { UploadCard } from "./UploadCard";
Expand All @@ -46,6 +48,7 @@ export const UploadSection = ({
const postUploadTx = useUploadContractTx(isMigrate);
const { validateUserAddress, validateContractAddress } = useValidateAddress();

const [codeHash, setCodeHash] = useState<string>();
const [estimatedFee, setEstimatedFee] = useState<StdFee>();
const [simulateStatus, setSimulateStatus] = useState<SimulateStatus>({
status: "default",
Expand Down Expand Up @@ -161,6 +164,15 @@ export const UploadSection = ({
JSON.stringify(addresses),
]);

// Generate hash value from wasm file
const setHashValue = useCallback(async () => {
setCodeHash(await getCodeHash(wasmFile));
}, [wasmFile]);

useEffect(() => {
setHashValue();
}, [setHashValue]);

useEffect(() => {
if (!wasmFile) {
setDefaultBehavior();
Expand All @@ -173,7 +185,7 @@ export const UploadSection = ({
}, [wasmFile, address, shouldNotSimulate, permission, setValue]);

return (
<>
<Flex direction="column" gap={8} maxW="550px">
{wasmFile ? (
<UploadCard
file={wasmFile}
Expand All @@ -185,6 +197,7 @@ export const UploadSection = ({
) : (
<DropZone setFile={(file) => setValue("wasmFile", file)} />
)}
<CodeHashBox codeHash={codeHash} />
<ControllerInput
name="codeName"
control={control}
Expand All @@ -196,15 +209,14 @@ export const UploadSection = ({
}}
error={errors.codeName && getMaxCodeNameLengthError(codeName.length)}
variant="floating"
my={8}
/>
<InstantiatePermissionRadio
control={control}
setValue={setValue}
trigger={trigger}
/>

<Box mt={10} width="full">
<Box width="full">
{(simulateStatus.status !== "default" || isSimulating) && (
<SimulateMessageRender
value={
Expand Down Expand Up @@ -256,6 +268,6 @@ export const UploadSection = ({
Upload
</Button>
</Flex>
</>
</Flex>
);
};
25 changes: 24 additions & 1 deletion src/lib/model/code.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { useWallet } from "@cosmos-kit/react";
import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";

import { useChainId } from "lib/app-provider";
import { useChainId, useLCDEndpoint } from "lib/app-provider";
import type { PermissionFilterValue } from "lib/hooks";
import {
useUserKey,
useCodePermissionFilter,
useCodeSearchFilter,
} from "lib/hooks";
import { useCodeStore } from "lib/providers/store";
import { getCodeIdInfo } from "lib/services/code";
import {
useCodeDataByCodeId,
useCodeListByCodeIds,
Expand All @@ -32,25 +34,46 @@ export interface CodeDataState {
isLoading: boolean;
chainId: string;
codeData: Option<CodeData>;
lcdCodeData: {
codeHash: Option<string>;
isLcdCodeLoading: boolean;
isLcdCodeError: unknown;
};
publicProject: {
publicCodeData: Option<PublicCode>;
publicDetail: Option<PublicDetail>;
};
}

export const useCodeData = (codeId: number): CodeDataState => {
const endpoint = useLCDEndpoint();

const { data: codeInfo, isLoading } = useCodeDataByCodeId(codeId);
const { data: publicCodeInfo } = usePublicProjectByCodeId(codeId);
const { data: publicInfoBySlug } = usePublicProjectBySlug(
publicCodeInfo?.slug
);
const {
data: lcdCode,
isLoading: isLcdCodeLoading,
error: isLcdCodeError,
} = useQuery(
["query", "code_data", endpoint, codeId],
async () => getCodeIdInfo(endpoint, codeId),
{ enabled: Boolean(endpoint) && Boolean(codeId), retry: false }
);

const chainId = useChainId();

return {
isLoading,
chainId,
codeData: codeInfo as CodeData,
lcdCodeData: {
codeHash: lcdCode?.code_info.data_hash,
isLcdCodeLoading,
isLcdCodeError,
},
publicProject: {
publicCodeData: publicCodeInfo,
publicDetail: publicInfoBySlug?.details,
Expand Down
41 changes: 39 additions & 2 deletions src/lib/pages/code-details/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Divider, Flex, Heading, Text, Image } from "@chakra-ui/react";
import { Divider, Flex, Heading, Text, Image, Spinner } from "@chakra-ui/react";
import { observer } from "mobx-react-lite";
import { useRouter } from "next/router";
import { useEffect } from "react";
Expand All @@ -15,6 +15,7 @@ import type { CodeDataState } from "lib/model/code";
import { useCodeData } from "lib/model/code";
import { useCodeStore } from "lib/providers/store";
import { AmpEvent, AmpTrack } from "lib/services/amplitude";
import type { Option } from "lib/types";
import { AccessConfigPermission } from "lib/types";
import { getCw2Info, getFirstQueryParam, isCodeId } from "lib/utils";

Expand All @@ -29,11 +30,37 @@ interface CodeDetailsBodyProps {

const InvalidCode = () => <InvalidState title="Code does not exist" />;

const CodeHashInfo = ({
isLcdCodeLoading,
isLcdCodeError,
codeHash,
}: {
isLcdCodeLoading: boolean;
isLcdCodeError: unknown;
codeHash: Option<string>;
}) => {
if (isLcdCodeLoading) return <Spinner size="sm" />;
if (codeHash)
return (
<CopyLink value={codeHash} amptrackSection="code_hash" type="code_hash" />
);
return (
<Text color="text.disabled" variant="body2">
{isLcdCodeError ? "Error fetching data" : "N/A"}
</Text>
);
};

const CodeDetailsBody = observer(
({ codeDataState, codeId }: CodeDetailsBodyProps) => {
const { getCodeLocalInfo } = useCodeStore();
const localCodeInfo = getCodeLocalInfo(codeId);
const { chainId, codeData, publicProject } = codeDataState;
const {
chainId,
codeData,
publicProject,
lcdCodeData: { codeHash, isLcdCodeLoading, isLcdCodeError },
} = codeDataState;

if (!codeData) return <InvalidCode />;

Expand Down Expand Up @@ -107,6 +134,16 @@ const CodeDetailsBody = observer(
type="code_id"
/>
</Flex>
<Flex gap={2}>
<Text fontWeight={500} color="text.dark" variant="body2">
Code Hash:
</Text>
<CodeHashInfo
isLcdCodeError={isLcdCodeError}
isLcdCodeLoading={isLcdCodeLoading}
codeHash={codeHash}
/>
</Flex>
<Flex gap={2}>
<Text fontWeight={500} color="text.dark" variant="body2">
CW2 Info:
Expand Down
1 change: 0 additions & 1 deletion src/lib/pages/proposal/constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ export const PROPOSAL_STORE_CODE_TEXT = {
runAsHelperText: "This address will be stored as code creator.",
runAsRequired: "Creator is required",
uploadHeader: "Upload Wasm File",
codeHashHeader: "Code Hash",
unpinLabel: "Unpin code",
unpinTooltip:
"Unpin removes the guarantee of a contract to be pinned. After calling this, the code may or may not remain in memory depending on the implementor's choice. Unpin is idempotent.",
Expand Down
45 changes: 8 additions & 37 deletions src/lib/pages/proposal/store-code/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
Checkbox,
Box,
} from "@chakra-ui/react";
import { Sha256 } from "@cosmjs/crypto";
import type { Coin, StdFee } from "@cosmjs/stargate";
import { useWallet } from "@cosmos-kit/react";
import { useRouter } from "next/router";
Expand Down Expand Up @@ -41,6 +40,7 @@ import { CustomIcon } from "lib/components/icon";
import PageContainer from "lib/components/PageContainer";
import { StickySidebar } from "lib/components/StickySidebar";
import { Tooltip } from "lib/components/Tooltip";
import { CodeHashBox } from "lib/components/upload/CodeHashBox";
import { InstantiatePermissionRadio } from "lib/components/upload/InstantiatePermissionRadio";
import { SimulateMessageRender } from "lib/components/upload/SimulateMessageRender";
import { UploadCard } from "lib/components/upload/UploadCard";
Expand All @@ -64,7 +64,11 @@ import type {
UploadSectionState,
} from "lib/types";
import { AccessType } from "lib/types";
import { composeStoreCodeProposalMsg, getAmountToVote } from "lib/utils";
import {
composeStoreCodeProposalMsg,
getAmountToVote,
getCodeHash,
} from "lib/utils";

interface StoreCodeProposalState {
title: string;
Expand Down Expand Up @@ -231,14 +235,7 @@ const StoreCodeProposal = () => {

// Generate hash value from wasm file
const setHashValue = useCallback(async () => {
if (wasmFile) {
const wasmFileBytes = new Sha256(
new Uint8Array(await wasmFile.arrayBuffer())
).digest();
setValue("codeHash", Buffer.from(wasmFileBytes).toString("hex"));
} else {
setValue("codeHash", "");
}
setValue("codeHash", await getCodeHash(wasmFile));
}, [setValue, wasmFile]);

useEffect(() => {
Expand Down Expand Up @@ -443,33 +440,7 @@ const StoreCodeProposal = () => {
)}

{/* Code hash */}
<Flex position="relative">
<Text
position="absolute"
variant="body3"
color="text.dark"
px="1px"
top="-10px"
left={3}
>
{PROPOSAL_STORE_CODE_TEXT.codeHashHeader}
</Text>
<Flex
border="1px"
borderRadius="5px"
px={3}
py={4}
borderColor="gray.700"
bg="gray.800"
h="56px"
w="full"
overflowX="auto"
overflowY="hidden"
>
<Text>{codeHash}</Text>
</Flex>
</Flex>

<CodeHashBox codeHash={codeHash} />
{/* Unpin code */}
<Flex direction="row" alignItems="center" gap={1}>
<Checkbox
Expand Down
13 changes: 13 additions & 0 deletions src/lib/utils/codeHash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Sha256 } from "@cosmjs/crypto";

import type { Option } from "lib/types";

export const getCodeHash = async (wasmFile: Option<File>) => {
if (wasmFile) {
const wasmFileBytes = new Sha256(
new Uint8Array(await wasmFile.arrayBuffer())
).digest();
return Buffer.from(wasmFileBytes).toString("hex");
}
return "";
};
1 change: 1 addition & 0 deletions src/lib/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ export * from "./executeTags";
export * from "./cw2";
export * from "./bech32";
export * from "./proposal";
export * from "./codeHash";