Skip to content

Commit

Permalink
Merge pull request #385 from alleslabs/feat/cosmos-kit-upgrade
Browse files Browse the repository at this point in the history
feat: upgrade cosmos kit version and replace hooks
  • Loading branch information
evilpeach authored Jun 13, 2023
2 parents 11a93fe + 2d56b24 commit 5717931
Show file tree
Hide file tree
Showing 68 changed files with 2,222 additions and 965 deletions.
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

- [#385](https://github.com/alleslabs/celatone-frontend/pull/385) Upgrade cosmos kit major version and replace hooks
- [#380](https://github.com/alleslabs/celatone-frontend/pull/380) Support local network
- [#363](https://github.com/alleslabs/celatone-frontend/pull/363) Add config not found page and rewrite network logic
- [#343](https://github.com/alleslabs/celatone-frontend/pull/343) Apply fetching mechanism and keyboard arrow navigation to searchbar
Expand Down
10 changes: 4 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,9 @@
"@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",
"@emotion/react": "^11.10.4",
"@emotion/styled": "^11.10.4",
"@cosmos-kit/core": "^1.5.8",
"@cosmos-kit/keplr": "^0.33.38",
"@cosmos-kit/react": "^1.3.31",
"@graphql-codegen/cli": "^2.13.12",
"@graphql-codegen/client-preset": "^1.1.4",
"@rx-stream/pipe": "^0.7.1",
Expand All @@ -48,7 +46,7 @@
"axios": "^1.1.3",
"big.js": "^6.2.1",
"camelcase": "^7.0.0",
"chain-registry": "1.13.0",
"chain-registry": "^1.14.0",
"cosmjs-types": "^0.7.2",
"dayjs": "^1.11.6",
"framer-motion": "^7.6.12",
Expand Down
2 changes: 1 addition & 1 deletion src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export const CHAIN_CONFIGS: ChainConfigs = {
},
"osmo-test-5": {
chain: "osmosis",
registryChainName: "osmosistestnet",
registryChainName: "osmosistestnet5",
prettyName: "Osmosis Testnet",
lcd: "https://lcd.osmotest5.osmosis.zone",
rpc: "https://rpc.osmotest5.osmosis.zone",
Expand Down
27 changes: 15 additions & 12 deletions src/lib/app-provider/contexts/app.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useWallet } from "@cosmos-kit/react";
import { useModalTheme } from "@cosmos-kit/react";
import { GraphQLClient } from "graphql-request";
import { observer } from "mobx-react-lite";
import type { ReactNode } from "react";
Expand Down Expand Up @@ -49,23 +49,20 @@ const AppContext = createContext<AppContextInterface>({
});

export const AppProvider = observer(({ children }: AppProviderProps) => {
const { currentChainName, setCurrentChain } = useWallet();

const { setCodeUserKey, isCodeUserKeyExist } = useCodeStore();
const { setContractUserKey, isContractUserKeyExist } = useContractStore();
const { setProjectUserKey, isProjectUserKeyExist } = usePublicProjectStore();
const { setModalTheme } = useModalTheme();

const [currentChainName, setCurrentChainName] = useState<string>();
const [currentChainId, setCurrentChainId] = useState("");

// Remark: this function is only used in useSelectChain. Do not use in other places.
const handleOnChainIdChange = useCallback(
(newChainId: string) => {
const config = CHAIN_CONFIGS[newChainId];
setCurrentChainId(newChainId);
setCurrentChain(config?.registryChainName);
},
[setCurrentChain, setCurrentChainId]
);
const handleOnChainIdChange = useCallback((newChainId: string) => {
const config = CHAIN_CONFIGS[newChainId];
setCurrentChainId(newChainId);
setCurrentChainName(config?.registryChainName);
}, []);

const states = useMemo<AppContextInterface>(() => {
const chainConfig = CHAIN_CONFIGS[currentChainId] ?? DEFAULT_CHAIN_CONFIG;
Expand Down Expand Up @@ -99,9 +96,15 @@ export const AppProvider = observer(({ children }: AppProviderProps) => {
return () => window.removeEventListener("beforeunload", handler);
}, []);

useEffect(() => {
if (localStorage.getItem("cosmology-ui-theme") !== "dark") {
setModalTheme("dark");
}
}, [setModalTheme]);

useNetworkChange(handleOnChainIdChange);

useAmplitude();
useAmplitude(currentChainName);

if (currentChainId && !(currentChainId in CHAIN_CONFIGS))
return <NetworkErrorState />;
Expand Down
1 change: 1 addition & 0 deletions src/lib/app-provider/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ export * from "./useBaseApiRoute";
export * from "./useRPCEndpoint";
export * from "./useFaucetConfig";
export * from "./useWasmConfig";
export * from "./useCurrentChain";
35 changes: 20 additions & 15 deletions src/lib/app-provider/hooks/useAddress.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { fromBech32 } from "@cosmjs/encoding";
import type { ChainRecord } from "@cosmos-kit/core";
import { useWallet } from "@cosmos-kit/react";
import { useCallback, useMemo } from "react";

import { useCelatoneApp } from "../contexts";
import type { Option } from "lib/types";

import { useCurrentChain } from "./useCurrentChain";

export type AddressReturnType =
| "user_address"
| "contract_address"
Expand Down Expand Up @@ -48,14 +48,15 @@ const getPrefix = (basePrefix: string, addressType: AddressReturnType) => {
};

const validateAddress = (
currentChainRecord: ChainRecord | undefined,
bech32Prefix: string,
address: string,
addressType: AddressReturnType,
getAddressTypeByLength: GetAddressTypeByLengthFn
) => {
if (!currentChainRecord) return "Invalid network";
if (!bech32Prefix)
return "Can not retrieve bech32 prefix of the current network.";

const prefix = getPrefix(currentChainRecord.chain.bech32_prefix, addressType);
const prefix = getPrefix(bech32Prefix, addressType);

if (!address.startsWith(prefix))
return `Invalid prefix (expected "${prefix}")`;
Expand All @@ -72,7 +73,9 @@ const validateAddress = (
};

export const useGetAddressType = () => {
const { currentChainRecord } = useWallet();
const {
chain: { bech32_prefix: bech32Prefix },
} = useCurrentChain();
const getAddressTypeByLength = useGetAddressTypeByLength();
return useCallback(
(address: Option<string>): AddressReturnType => {
Expand All @@ -81,7 +84,7 @@ export const useGetAddressType = () => {
!address ||
addressType === "invalid_address" ||
validateAddress(
currentChainRecord,
bech32Prefix,
address,
addressType,
getAddressTypeByLength
Expand All @@ -90,45 +93,47 @@ export const useGetAddressType = () => {
return "invalid_address";
return addressType;
},
[currentChainRecord, getAddressTypeByLength]
[bech32Prefix, getAddressTypeByLength]
);
};

// TODO: refactor
export const useValidateAddress = () => {
const { currentChainRecord } = useWallet();
const {
chain: { bech32_prefix: bech32Prefix },
} = useCurrentChain();
const getAddressTypeByLength = useGetAddressTypeByLength();

return {
validateContractAddress: useCallback(
(address: string) =>
validateAddress(
currentChainRecord,
bech32Prefix,
address,
"contract_address",
getAddressTypeByLength
),
[currentChainRecord, getAddressTypeByLength]
[bech32Prefix, getAddressTypeByLength]
),
validateUserAddress: useCallback(
(address: string) =>
validateAddress(
currentChainRecord,
bech32Prefix,
address,
"user_address",
getAddressTypeByLength
),
[currentChainRecord, getAddressTypeByLength]
[bech32Prefix, getAddressTypeByLength]
),
validateValidatorAddress: useCallback(
(address: string) =>
validateAddress(
currentChainRecord,
bech32Prefix,
address,
"validator_address",
getAddressTypeByLength
),
[currentChainRecord, getAddressTypeByLength]
[bech32Prefix, getAddressTypeByLength]
),
};
};
16 changes: 10 additions & 6 deletions src/lib/app-provider/hooks/useAmplitude.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { init, setDeviceId, setUserId } from "@amplitude/analytics-browser";
import { useWallet } from "@cosmos-kit/react";
import { useChain } from "@cosmos-kit/react";
import { createHash } from "crypto";
import { useEffect } from "react";
import * as uuid from "uuid";

export const useAmplitude = () => {
const { address, currentChainName } = useWallet();
import type { Option } from "lib/types";

export const useAmplitude = (chainName: Option<string>) => {
/**
* @remarks Revisit default chain name
*/
const { address } = useChain(chainName ?? "osmosis");
if (typeof window !== "undefined") {
init(process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY ?? "", undefined, {
trackingOptions: {
Expand All @@ -31,13 +35,13 @@ export const useAmplitude = () => {

useEffect(() => {
const timeoutId = setTimeout(() => {
if (currentChainName) {
if (chainName) {
const userId = address
? createHash("sha256").update(address).digest("hex")
: undefined;
setUserId(`${currentChainName}/${userId}`);
setUserId(`${chainName}/${userId}`);
}
}, 300);
return () => clearTimeout(timeoutId);
}, [address, currentChainName]);
}, [address, chainName]);
};
11 changes: 5 additions & 6 deletions src/lib/app-provider/hooks/useChainRecordAsset.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
import type { Asset } from "@chain-registry/types";
import { useWallet } from "@cosmos-kit/react";
import { useCallback } from "react";

import type { SnakeToCamelCaseNested } from "lib/types";
import { snakeToCamel } from "lib/utils";

import { useCurrentChain } from "./useCurrentChain";

interface ChainRecordAsset extends Asset {
precision: number;
}

type InternalChainRecordAsset = SnakeToCamelCaseNested<ChainRecordAsset>;

export const useChainRecordAsset = () => {
const { currentChainRecord } = useWallet();
const { assets } = useCurrentChain();

return useCallback(
(denom: string): InternalChainRecordAsset | null => {
const assetInfo = currentChainRecord?.assetList.assets.find(
(asset) => asset.base === denom
);
const assetInfo = assets?.assets.find((asset) => asset.base === denom);
return assetInfo
? (snakeToCamel({
...assetInfo,
Expand All @@ -34,6 +33,6 @@ export const useChainRecordAsset = () => {
}) as InternalChainRecordAsset)
: null;
},
[currentChainRecord]
[assets]
);
};
10 changes: 10 additions & 0 deletions src/lib/app-provider/hooks/useCurrentChain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useChain } from "@cosmos-kit/react";

import { useCelatoneApp } from "../contexts";

export const useCurrentChain = () => {
const {
chainConfig: { registryChainName },
} = useCelatoneApp();
return useChain(registryChainName);
};
9 changes: 5 additions & 4 deletions src/lib/app-provider/hooks/useDummyWallet.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { useWallet } from "@cosmos-kit/react";
import { useEffect, useState } from "react";

import { DUMMY_MNEMONIC } from "env";
import type { HumanAddr } from "lib/types";

import { useCurrentChain } from "./useCurrentChain";

export const useDummyWallet = () => {
const { currentChainRecord } = useWallet();
const { chain } = useCurrentChain();
const [dummyWallet, setDummyWallet] = useState<DirectSecp256k1HdWallet>();
const [dummyAddress, setDummyAddress] = useState<HumanAddr>();
useEffect(() => {
Expand All @@ -15,7 +16,7 @@ export const useDummyWallet = () => {
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(
DUMMY_MNEMONIC,
{
prefix: currentChainRecord?.chain.bech32_prefix,
prefix: chain.bech32_prefix,
}
);

Expand All @@ -25,7 +26,7 @@ export const useDummyWallet = () => {
setDummyAddress(address as HumanAddr);
}
})();
}, [currentChainRecord?.chain.bech32_prefix]);
}, [chain.bech32_prefix]);

return { dummyWallet, dummyAddress };
};
11 changes: 7 additions & 4 deletions src/lib/app-provider/hooks/useLCDEndpoint.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { useWallet } from "@cosmos-kit/react";

import { useCelatoneApp } from "../contexts";

import { useCurrentChain } from "./useCurrentChain";

export const useLCDEndpoint = () => {
const { currentChainRecord } = useWallet();
const { chainWallet } = useCurrentChain();
const { chainConfig } = useCelatoneApp();
const restRecord = chainWallet?.chainRecord.preferredEndpoints?.rest?.[0];
const endpoint =
typeof restRecord === "string" ? restRecord : restRecord?.url;

return currentChainRecord?.preferredEndpoints?.rest?.[0] ?? chainConfig.lcd;
return endpoint ?? chainConfig.lcd;
};
10 changes: 6 additions & 4 deletions src/lib/app-provider/hooks/useRPCEndpoint.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { useWallet } from "@cosmos-kit/react";

import { useCelatoneApp } from "../contexts";

import { useCurrentChain } from "./useCurrentChain";

export const useRPCEndpoint = () => {
const { currentChainRecord } = useWallet();
const { chainWallet } = useCurrentChain();
const { chainConfig } = useCelatoneApp();
const rpcRecord = chainWallet?.chainRecord.preferredEndpoints?.rpc?.[0];
const endpoint = typeof rpcRecord === "string" ? rpcRecord : rpcRecord?.url;

return currentChainRecord?.preferredEndpoints?.rpc?.[0] ?? chainConfig.rpc;
return endpoint ?? chainConfig.rpc;
};
9 changes: 5 additions & 4 deletions src/lib/app-provider/hooks/useSimulateFee.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { useWallet } from "@cosmos-kit/react";
import { useCallback, useState } from "react";

import type { Gas } from "lib/types";
import type { ComposedMsg } from "lib/types/tx";

import { useCurrentChain } from "./useCurrentChain";

// TODO: remove this hook after migrating to useQuery version
export const useSimulateFee = () => {
const { address, getCosmWasmClient } = useWallet();
const { address, getSigningCosmWasmClient } = useCurrentChain();

const [loading, setLoading] = useState(false);

const simulate = useCallback(
async (messages: ComposedMsg[], memo?: string) => {
setLoading(true);
const client = await getCosmWasmClient();
const client = await getSigningCosmWasmClient();
if (!client || !address) {
setLoading(false);
return undefined;
Expand All @@ -27,7 +28,7 @@ export const useSimulateFee = () => {
throw e;
}
},
[address, getCosmWasmClient, setLoading]
[address, getSigningCosmWasmClient, setLoading]
);

return { simulate, loading };
Expand Down
Loading

0 comments on commit 5717931

Please sign in to comment.