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

Fix/support custom chain for EVM wallet #1235

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

### Bug fixes

- [#1235](https://github.com/alleslabs/celatone-frontend/pull/1235) Support EVM custom chain id and minor bug fixes
- [#1191](https://github.com/alleslabs/celatone-frontend/pull/1191) Fix contract address form validation
- [#1190](https://github.com/alleslabs/celatone-frontend/pull/1190) Fix EVM contract details verify boarding and verification page

Expand Down
5 changes: 1 addition & 4 deletions src/lib/app-provider/hooks/useExampleAddresses.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { toBech32, toHex } from "@cosmjs/encoding";
import { toBech32 } from "@cosmjs/encoding";
import { useMemo } from "react";

import type { BechAddr20, BechAddr32 } from "lib/types";
Expand All @@ -14,8 +14,6 @@ export const useExampleAddresses = () => {
const bytes20 = bytes32.slice(0, 20);
const user = toBech32(bech32Prefix, Uint8Array.from(bytes20)) as BechAddr20;

// reverse the bytes so the initial characters are different from the user address
const evmContract = "0x" + toHex(Uint8Array.from(bytes20).reverse());
const contract = toBech32(
bech32Prefix,
Uint8Array.from(bytes32.reverse())
Expand All @@ -26,7 +24,6 @@ export const useExampleAddresses = () => {
return {
user,
contract,
evmContract,
validator,
};
};
Expand Down
42 changes: 40 additions & 2 deletions src/lib/app-provider/hooks/useSignAndBroadcastEvm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TxReceiptJsonRpc } from "lib/services/types";
import { convertCosmosChainIdToEvmChainId, sleep } from "lib/utils";
import { useCelatoneApp } from "../contexts";
import { useCurrentChain } from "./useCurrentChain";
import { useEvmParams } from "lib/services/evm";

const getEvmTxResponse = async (jsonRpcEndpoint: string, txHash: string) => {
const TIME_OUT_MS = 3000;
Expand Down Expand Up @@ -51,23 +52,60 @@ export type SignAndBroadcastEvm = (
) => Promise<TxReceiptJsonRpc>;

export const useSignAndBroadcastEvm = () => {
const { walletProvider, chainId } = useCurrentChain();
const {
chainConfig: {
prettyName,
logo_URIs,
features: { evm },
registry,
},
} = useCelatoneApp();
const { walletProvider, chainId } = useCurrentChain();
const { data } = useEvmParams();

return useCallback(
async (request: TransactionRequest): Promise<TxReceiptJsonRpc> => {
if (evm.enabled && walletProvider.type === "initia-widget") {
const { requestEthereumTx, ethereum } = walletProvider.context;
const evmChainId = convertCosmosChainIdToEvmChainId(chainId);
const evmChainId = "0x".concat(
convertCosmosChainIdToEvmChainId(chainId).toString(16)
);

const feeDenom = data?.params.feeDenom.slice(-40) ?? "";
const foundAsset = registry?.assets.find((asset) =>
asset.denom_units.find(
(denom_unit) => denom_unit.denom.slice(-40) === feeDenom
)
);

if (foundAsset) {
const denomUnit = foundAsset.denom_units.reduce((max, unit) =>
unit.exponent > max.exponent ? unit : max
);

await ethereum?.request({
method: "wallet_addEthereumChain",
params: [
{
chainId: evmChainId,
chainName: prettyName,
iconUrls: Object.values(logo_URIs ?? {}),
nativeCurrency: {
name: foundAsset.name,
symbol: foundAsset.symbol,
decimals: denomUnit.exponent,
},
rpcUrls: [evm.jsonRpc],
},
],
});
}

await ethereum?.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: evmChainId }],
});

const txHash = await requestEthereumTx(
{ ...request, chainId: evmChainId },
{ chainId }
Expand Down
8 changes: 7 additions & 1 deletion src/lib/pages/deploy-script/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { useRouter } from "next/router";
import { useCallback, useEffect, useMemo, useState } from "react";

import { AmpEvent, track } from "lib/amplitude";
import { useCurrentChain, useFabricateFee } from "lib/app-provider";
import {
useCurrentChain,
useFabricateFee,
useWasmConfig,
} from "lib/app-provider";
import { useDeployScriptTx } from "lib/app-provider/tx/script";
import ActionPageContainer from "lib/components/ActionPageContainer";
import { ConnectWalletAlert } from "lib/components/ConnectWalletAlert";
Expand Down Expand Up @@ -34,6 +38,8 @@ const DEFAULT_FILE_STATE: FileState = {
};

export const DeployScript = () => {
useWasmConfig({ shouldRedirect: true });

const router = useRouter();
const { address } = useCurrentChain();
const fabricateFee = useFabricateFee();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useExampleAddresses } from "lib/app-provider";
import { ControllerInput } from "lib/components/forms";
import { truncate } from "lib/utils";
import { bech32AddressToHex, truncate } from "lib/utils";
import {
Control,
FieldPath,
Expand All @@ -17,7 +17,7 @@ export const ContractLibrary = <T extends FieldValues>({
control,
name,
}: ContractLibraryProps<T>) => {
const { evmContract: exampleContractAddress } = useExampleAddresses();
const { user: exampleBechContractAddress } = useExampleAddresses();
const { field } = useController({
control,
name,
Expand All @@ -42,7 +42,7 @@ export const ContractLibrary = <T extends FieldValues>({
rules={{
required: "",
}}
placeholder={`ex. ${truncate(exampleContractAddress)}`}
placeholder={`ex. ${truncate(bech32AddressToHex(exampleBechContractAddress))}`}
name={`${name}.address` as FieldPath<T>}
control={control}
variant="fixed-floating"
Expand Down
6 changes: 3 additions & 3 deletions src/lib/pages/evm-contract-verify/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import {
useSubmitEvmVerify,
} from "lib/services/verification/evm";
import { HexAddr20, Option } from "lib/types";
import { isHex20Bytes, truncate } from "lib/utils";
import { bech32AddressToHex, isHex20Bytes, truncate } from "lib/utils";
import { useRouter } from "next/router";
import { useEffect, useMemo } from "react";
import { useForm } from "react-hook-form";
Expand Down Expand Up @@ -79,7 +79,7 @@ export const EvmContractVerifyBody = ({
const router = useRouter();
const queryClient = useQueryClient();
const { currentChainId } = useCelatoneApp();
const { evmContract: exampleContractAddress } = useExampleAddresses();
const { user: exampleBechContractAddress } = useExampleAddresses();
const { mutate, isLoading, isError } = useSubmitEvmVerify();

useEffect(() => {
Expand Down Expand Up @@ -245,7 +245,7 @@ export const EvmContractVerifyBody = ({
<ControllerInput
label="Contract Address"
isRequired
placeholder={`ex. ${truncate(exampleContractAddress)}`}
placeholder={`ex. ${truncate(bech32AddressToHex(exampleBechContractAddress))}`}
name="contractAddress"
control={control}
variant="fixed-floating"
Expand Down
2 changes: 1 addition & 1 deletion src/lib/utils/evm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export const convertCosmosChainIdToEvmChainId = (chainId: string) => {

const hash = keccak256(Buffer.from(chainId));
const rawEvmChainId = Buffer.from(hash).readBigUInt64BE();
return big(rawEvmChainId.toString()).mod(METAMASK_MAX).toFixed();
return big(rawEvmChainId.toString()).mod(METAMASK_MAX).toNumber();
};

export const encodeEvmFunctionData = (
Expand Down