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: add instantiate permission to store code message #279

Merged
merged 17 commits into from
Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from 14 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

- [#279](https://github.com/alleslabs/celatone-frontend/pull/279) Add instantiate permission to msg store code, change error display design, and upgrade cosmjs to version 0.30.1
- [#268](https://github.com/alleslabs/celatone-frontend/pull/268) Wireup create proposal to whitelisting
- [#266](https://github.com/alleslabs/celatone-frontend/pull/250) Add proposal whitelisting page
- [#286](https://github.com/alleslabs/celatone-frontend/pull/286) Add block proposer
Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@
"@chakra-ui/icons": "^2.0.11",
"@chakra-ui/react": "^2.3.6",
"@chakra-ui/styled-system": "^2.3.5",
"@cosmjs/cosmwasm-stargate": "^0.29.3",
"@cosmjs/encoding": "^0.29.5",
"@cosmjs/proto-signing": "^0.29.5",
"@cosmjs/stargate": "^0.29.3",
"@cosmjs/cosmwasm-stargate": "^0.30.1",
"@cosmjs/encoding": "^0.30.1",
"@cosmjs/proto-signing": "^0.30.1",
"@cosmjs/stargate": "^0.30.1",
"@cosmos-kit/core": "^0.20.0",
"@cosmos-kit/keplr": "^0.20.0",
"@cosmos-kit/react": "^0.19.0",
Expand Down
38 changes: 22 additions & 16 deletions src/lib/app-fns/tx/upload.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import type {
SigningCosmWasmClient,
UploadResult,
} from "@cosmjs/cosmwasm-stargate";
import type { StdFee } from "@cosmjs/stargate";
import type { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import type { DeliverTxResponse, logs, StdFee } from "@cosmjs/stargate";
import { pipe } from "@rx-stream/pipe";
import type { Observable } from "rxjs";

import { ExplorerLink } from "lib/components/ExplorerLink";
import { CustomIcon } from "lib/components/icon";
import { AmpEvent, AmpTrack } from "lib/services/amplitude";
import { TxStreamPhase } from "lib/types";
import type { HumanAddr, TxResultRendering } from "lib/types";
import type { HumanAddr, TxResultRendering, ComposedMsg } from "lib/types";
import { findAttr } from "lib/utils";
import { formatUFee } from "lib/utils/formatter/denom";

import { catchTxError } from "./common/catchTxError";
Expand All @@ -19,8 +17,8 @@ import { sendingTx } from "./common/sending";

interface UploadTxParams {
address: HumanAddr;
codeDesc: string;
wasmCode: Uint8Array;
codeName: string;
messages: ComposedMsg[];
wasmFileName: string;
fee: StdFee;
memo?: string;
Expand All @@ -31,8 +29,8 @@ interface UploadTxParams {

export const uploadContractTx = ({
address,
codeDesc,
wasmCode,
codeName,
messages,
wasmFileName,
fee,
memo,
Expand All @@ -42,12 +40,20 @@ export const uploadContractTx = ({
}: UploadTxParams): Observable<TxResultRendering> => {
return pipe(
sendingTx(fee),
postTx<UploadResult>({
postFn: () => client.upload(address, wasmCode, fee, memo),
postTx<DeliverTxResponse>({
postFn: () => client.signAndBroadcast(address, messages, fee, memo),
}),
({ value: txInfo }) => {
AmpTrack(AmpEvent.TX_SUCCEED);
onTxSucceed?.(txInfo.codeId);
const mimicLog: logs.Log = {
msg_index: 0,
log: "",
events: txInfo.events,
};

const codeId = findAttr(mimicLog, "store_code", "code_id") ?? "0";

onTxSucceed?.(parseInt(codeId, 10));
const txFee = txInfo.events.find((e) => e.type === "tx")?.attributes[0]
.value;
return {
Expand All @@ -56,10 +62,10 @@ export const uploadContractTx = ({
receipts: [
{
title: "Code ID",
value: txInfo.codeId,
value: codeId,
html: (
<div style={{ display: "inline-flex", alignItems: "center" }}>
<ExplorerLink type="code_id" value={txInfo.codeId.toString()} />
<ExplorerLink type="code_id" value={codeId} />
</div>
),
},
Expand All @@ -80,7 +86,7 @@ export const uploadContractTx = ({
description: (
<>
<span style={{ fontWeight: 700 }}>
‘{codeDesc || `${wasmFileName}(${txInfo.codeId})`}’
‘{codeName || `${wasmFileName}(${codeId})`}’
</span>{" "}
is has been uploaded. Would you like to{" "}
{isMigrate ? "migrate" : "instantiate"} your code now?
Expand Down
65 changes: 64 additions & 1 deletion src/lib/app-provider/queries/simulateFee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,15 @@ import { useWallet } from "@cosmos-kit/react";
import { useQuery } from "@tanstack/react-query";

import { useDummyWallet } from "../hooks";
import type { ComposedMsg, Gas } from "lib/types";
import type {
AccessType,
Addr,
ComposedMsg,
Gas,
HumanAddr,
Option,
} from "lib/types";
import { composeStoreCodeMsg } from "lib/utils";

interface SimulateQueryParams {
enabled: boolean;
Expand Down Expand Up @@ -59,3 +67,58 @@ export const useSimulateFeeQuery = ({
onError,
});
};

interface SimulateQueryParamsForStoreCode {
enabled: boolean;
wasmFile: Option<File>;
permission: AccessType;
addresses: Addr[];
onSuccess?: (gas: Gas<number> | undefined) => void;
onError?: (err: Error) => void;
}

export const useSimulateFeeForStoreCode = ({
enabled,
wasmFile,
permission,
addresses,
onSuccess,
onError,
}: SimulateQueryParamsForStoreCode) => {
const { address, getCosmWasmClient, currentChainName } = useWallet();

const simulateFn = async () => {
if (!address) throw new Error("Please check your wallet connection.");
if (!wasmFile) throw new Error("Fail to get Wasm file");

const client = await getCosmWasmClient();
if (!client) throw new Error("Fail to get client");

const submitStoreCodeProposalMsg = async () => {
return composeStoreCodeMsg({
sender: address as HumanAddr,
wasmByteCode: new Uint8Array(await wasmFile.arrayBuffer()),
permission,
addresses,
});
};
const craftMsg = await submitStoreCodeProposalMsg();
return (await client.simulate(address, [craftMsg], undefined)) as Gas;
};
return useQuery({
queryKey: [
"simulate_fee_store_code",
currentChainName,
wasmFile,
permission,
addresses,
],
queryFn: async () => simulateFn(),
enabled,
retry: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
onSuccess,
onError,
});
};
22 changes: 17 additions & 5 deletions src/lib/app-provider/tx/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ import { useWallet } from "@cosmos-kit/react";
import { useCallback } from "react";

import { uploadContractTx } from "lib/app-fns/tx/upload";
import type { HumanAddr, Option } from "lib/types";
import type { AccessType, Addr, HumanAddr, Option } from "lib/types";
import { composeStoreCodeMsg } from "lib/utils";

export interface UploadStreamParams {
wasmFileName: Option<string>;
wasmCode: Option<Promise<ArrayBuffer>>;
codeDesc: string;
addresses: Addr[];
permission: AccessType;
codeName: string;
estimatedFee: Option<StdFee>;
onTxSucceed?: (codeId: number) => void;
}
Expand All @@ -20,7 +23,9 @@ export const useUploadContractTx = (isMigrate: boolean) => {
async ({
wasmFileName,
wasmCode,
codeDesc,
addresses,
permission,
codeName,
estimatedFee,
onTxSucceed,
}: UploadStreamParams) => {
Expand All @@ -29,10 +34,17 @@ export const useUploadContractTx = (isMigrate: boolean) => {
throw new Error("Please check your wallet connection.");
if (!wasmFileName || !wasmCode || !estimatedFee) return null;

const message = composeStoreCodeMsg({
sender: address as Addr,
wasmByteCode: new Uint8Array(await wasmCode),
permission,
addresses,
});

return uploadContractTx({
address: address as HumanAddr,
wasmCode: new Uint8Array(await wasmCode),
codeDesc,
messages: [message],
codeName,
wasmFileName,
fee: estimatedFee,
client,
Expand Down
147 changes: 147 additions & 0 deletions src/lib/components/upload/InstantiatePermissionRadio.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { Text, Box, Radio, RadioGroup, Button, Flex } from "@chakra-ui/react";
import { useWallet } from "@cosmos-kit/react";
import type { Control, UseFormSetValue, UseFormTrigger } from "react-hook-form";
import { useController, useFieldArray, useWatch } from "react-hook-form";

import { AddressInput } from "../AddressInput";
import { AssignMe } from "../AssignMe";
import { CustomIcon } from "lib/components/icon";
import { AmpEvent, AmpTrack } from "lib/services/amplitude";
import type { Addr, UploadSectionState } from "lib/types";
import { AccessType } from "lib/types";

interface InstantiatePermissionRadioProps {
control: Control<UploadSectionState>;
setValue: UseFormSetValue<UploadSectionState>;
trigger: UseFormTrigger<UploadSectionState>;
}

interface PermissionRadioProps {
isSelected: boolean;
value: AccessType;
text: string;
}

const PermissionRadio = ({ isSelected, value, text }: PermissionRadioProps) => (
<Radio value={value} py={2} width="100%" size="lg">
<Text fontWeight={isSelected ? "600" : "400"}>{text} </Text>
</Radio>
);

export const InstantiatePermissionRadio = ({
control,
setValue,
trigger,
}: InstantiatePermissionRadioProps) => {
const { address: walletAddress } = useWallet();

const { fields, append, remove } = useFieldArray({
control,
name: "addresses",
});

const [permission, addresses] = useWatch({
control,
name: ["permission", "addresses"],
});

const {
formState: { errors },
} = useController({
control,
name: "addresses",
});

return (
<RadioGroup
name="instantiatePermission"
onChange={(nextValue: string) => {
const value = parseInt(nextValue, 10);
setValue("permission", value);
}}
value={permission}
>
<Box>
<PermissionRadio
isSelected={permission === AccessType.ACCESS_TYPE_EVERYBODY}
value={AccessType.ACCESS_TYPE_EVERYBODY}
text="Anyone can instantiate (Everybody)"
/>
<PermissionRadio
isSelected={permission === AccessType.ACCESS_TYPE_NOBODY}
value={AccessType.ACCESS_TYPE_NOBODY}
text="Instantiate through governance only (Nobody)"
/>
<Box>
<PermissionRadio
isSelected={permission === AccessType.ACCESS_TYPE_ANY_OF_ADDRESSES}
value={AccessType.ACCESS_TYPE_ANY_OF_ADDRESSES}
text="Only a set of addresses can instantiate (AnyOfAddresses)"
/>
{permission === AccessType.ACCESS_TYPE_ANY_OF_ADDRESSES && (
<Box>
{fields.map((field, idx) => (
<Flex gap={2} my={6} key={field.id}>
<AddressInput
name={`addresses.${idx}.address`}
control={control}
label="Address"
variant="floating"
error={
(addresses[idx]?.address &&
addresses.find(
({ address }, i) =>
i < idx && address === addresses[idx]?.address
) &&
"You already input this address") ||
errors.addresses?.[idx]?.address?.message
}
helperAction={
<AssignMe
onClick={() => {
AmpTrack(AmpEvent.USE_ASSIGN_ME);
setValue(
`addresses.${idx}.address`,
walletAddress as Addr
);
trigger(`addresses.${idx}.address`);
}}
isDisable={
addresses.findIndex(
(x) => x.address === walletAddress
) > -1
}
/>
}
/>
<Button
w="56px"
h="56px"
variant="outline-gray"
size="lg"
disabled={fields.length <= 1}
onClick={() => remove(idx)}
>
<CustomIcon
name="delete"
color={fields.length <= 1 ? "pebble.600" : "text.dark"}
/>
</Button>
</Flex>
))}
<Button
variant="outline-primary"
mt={3}
mx="auto"
onClick={() => append({ address: "" as Addr })}
leftIcon={<CustomIcon name="plus" color="violet.light" />}
>
Add More Address
</Button>
</Box>
)}
</Box>
</Box>
</RadioGroup>
);
};
Loading