Skip to content

Feat/helpers poc #209

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

Closed
wants to merge 11 commits into from
Closed
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
8 changes: 4 additions & 4 deletions examples/interchainjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@
"@cosmos-kit/react": "2.17.0",
"@emotion/react": "11.10.6",
"@emotion/styled": "11.10.6",
"@interchain-kit/core": "0.0.1-beta.8",
"@interchain-kit/keplr-extension": "0.0.1-beta.8",
"@interchain-kit/react": "0.0.1-beta.8",
"@interchain-kit/core": "0.0.1-beta.21",
"@interchain-kit/keplr-extension": "0.0.1-beta.21",
"@interchain-kit/react": "0.0.1-beta.21",
"@interchain-ui/react": "^1.23.29",
"@interchain-ui/react-no-ssr": "^0.1.6",
"@tanstack/react-query": "4.32.0",
Expand All @@ -44,7 +44,7 @@
"dayjs": "^1.11.11",
"fast-fuzzy": "^1.12.0",
"framer-motion": "9.0.7",
"interchainjs": "0.0.1-beta.12",
"interchainjs": "0.0.1-beta.14",
"mobx": "^6.7.0",
"mobx-react": "^7.6.0",
"next": "^13",
Expand Down
283 changes: 283 additions & 0 deletions examples/interchainjs/pages/helpers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,283 @@
import { useState } from 'react';
import Head from 'next/head';
import BigNumber from 'bignumber.js';

import {
Box,
Button,
Center,
Container,
Divider,
Flex,
Grid,
Heading,
Icon,
Link,
Stack,
Text,
useColorMode,
useColorModeValue,
} from '@chakra-ui/react';
import { BsFillMoonStarsFill, BsFillSunFill } from 'react-icons/bs';
import {
chainassets,
chainName,
coin,
dependencies,
products,
} from '../config';

import {
Dependency,
handleChangeColorModeValue,
Product,
WalletSection,
} from '../components';
import { SendTokensCard } from '../components/react/send-tokens-card';

import { DEFAULT_SIGNING_CLIENT_QUERY_KEY, useRpcClient } from '../src/codegen';
import {
useChainWallet,
useWalletManager,
useChain,
} from '@interchain-kit/react';
import {} from '@interchain-kit/keplr-extension';
// import { CosmWasmSigningClient } from 'interchainjs/cosmwasm-stargate';
import { toEncoders, toConverters } from '@interchainjs/cosmos/utils';
import { SigningClient } from 'interchainjs/signing-client';
import { MsgSend } from '../src/codegen/cosmos/bank/v1beta1/tx';
import { DeliverTxResponse, StdFee } from '@interchainjs/cosmos-types/types';
import { useBalance } from '../src/codegen/cosmos/bank/v1beta1/query.rpc.funcs';
import { useSend } from '../src/codegen/cosmos/bank/v1beta1/tx.rpc.func';
import { useQueryClient } from '@tanstack/react-query';

const library = {
title: 'InterchainJS',
text: 'interchainjs',
href: 'https://github.com/cosmology-tech/interchainjs',
};

/**
* common helper options for generated helper functions.
* For getting signingClient;
* Or using chainName for getting signingClient.
*/
class HelperOptions {
signingClient?: SigningClient;
chainName?: string;
}

// Get the display exponent
// we can get the exponent from chain registry asset denom_units
const COIN_DISPLAY_EXPONENT = coin.denom_units.find(
(unit) => unit.denom === coin.display
)?.exponent as number;

export default function Home() {
const { colorMode, toggleColorMode } = useColorMode();

// const { getSigningStargateClient, address, status, getRpcEndpoint } =
// useChain(chainName);
const walletManager = useWalletManager();
console.log('walletManager.chains', walletManager.chains);
const keplrExtension = walletManager.wallets.find(
(w) => w.option?.name === 'keplr-extension'
);
const { signingClient, address } = useChainWallet(
chainName,
keplrExtension?.option?.name as string
);

const queryClient = useQueryClient();

queryClient.setQueryData([DEFAULT_SIGNING_CLIENT_QUERY_KEY], signingClient);

const [resp, setResp] = useState('');

// const {
// data: rpcEndpoint
// } = useRpcEndpoint({
// //@ts-ignore
// getter: getRpcEndpoint
// });

const rpcEndpoint = 'https://rpc.cosmos.directory/cosmoshub';

const { data: rpcClient } = useRpcClient({
rpcEndpoint,
options: {
enabled: !!rpcEndpoint,
},
});

console.log({
rpcEndpoint,
rpcClient,
});

//@ts-ignore
// const hooks = cosmos.ClientFactory.createRPCQueryHooks({ rpc: rpcClient })
// const hooks = createRpcQueryHooks({ rpc: rpcClient });

const { mutate: send, isSuccess: isSendSuccess } = useSend({
options: {
onSuccess: (data) => {
setResp(JSON.stringify(data, null, 2));
},
},
});

const {
data: balance,
isSuccess: isBalanceLoaded,
isLoading: isFetchingBalance,
refetch: refetchBalance,
} = useBalance<BigNumber>({
request: {
address: address || '',
denom: chainassets?.assets[0].base as string,
},
options: {
enabled: !!address && !!rpcClient,
// transform the returned balance into a BigNumber
select: ({ balance }) =>
new BigNumber(balance?.amount ?? 0).multipliedBy(
10 ** -COIN_DISPLAY_EXPONENT
),
},
});

console.log(
JSON.stringify(
{
address,
balance,
isBalanceLoaded,
isFetchingBalance,
refetchBalance,
},
null,
2
)
);

return (
<Container maxW="5xl" py={10}>
<Head>
<title>InterchainJS - Create Cosmos App</title>
<meta name="description" content="Generated by create cosmos app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Flex justifyContent="end" mb={4}>
<Button variant="outline" px={0} onClick={toggleColorMode}>
<Icon as={useColorModeValue(BsFillMoonStarsFill, BsFillSunFill)} />
</Button>
</Flex>
<Box textAlign="center">
<Heading
as="h1"
fontSize={{ base: '3xl', md: '5xl' }}
fontWeight="extrabold"
mb={3}
>
Create Cosmos App
</Heading>
<Heading
as="h1"
fontWeight="bold"
fontSize={{ base: '2xl', md: '4xl' }}
>
<Text as="span">Welcome to&nbsp;</Text>
<Text
as="span"
color={handleChangeColorModeValue(
colorMode,
'primary.500',
'primary.200'
)}
>
Interchain Kit&nbsp;+&nbsp;Next.js&nbsp;+&nbsp;
<Link href={library.href} target="_blank" rel="noreferrer">
{library.title}
</Link>
</Text>
</Heading>
</Box>

<WalletSection />

<Center mb={16}>
<SendTokensCard
isConnectWallet={!!address}
balance={isBalanceLoaded ? balance.toNumber() : 0}
isFetchingBalance={isFetchingBalance}
response={resp}
sendTokensButtonText="Send Tokens"
handleClickSendTokens={() => {
send({
signerAddress: address,
message: {
fromAddress: address,
toAddress: address,
amount: [{ denom: coin.base, amount: '1' }],
},
fee: {
amount: [
{
denom: coin.base,
amount: '25000',
},
],
gas: '1000000',
},
memo: 'using interchainjs',
});
}}
handleClickGetBalance={refetchBalance}
/>
</Center>

<Box mb={16}>
<Divider />
</Box>
<Grid
templateColumns={{
md: 'repeat(2, 1fr)',
lg: 'repeat(3, 1fr)',
}}
gap={8}
mb={14}
>
{products.map((product) => (
<Product key={product.title} {...product} />
))}
</Grid>
<Grid templateColumns={{ md: 'repeat(3, 1fr)' }} gap={8} mb={20}>
<Dependency {...library} />
{dependencies.map((dependency) => (
<Dependency key={dependency.title} {...dependency} />
))}
</Grid>

<Box mb={3}>
<Divider />
</Box>
<Stack
isInline={true}
spacing={1}
justifyContent="center"
opacity={0.5}
fontSize="sm"
>
<Text>Built with</Text>
<Link
href="https://cosmology.zone/"
target="_blank"
rel="noopener noreferrer"
>
Cosmology
</Link>
</Stack>
</Container>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { buildQuery } from "../../../helper-func-types";
import { Rpc } from "../../../helpers";
import { UseQueryParams, buildUseQuery } from "../../../react-query";
import { QueryBalanceRequest, QueryBalanceResponse, QueryAllBalancesRequest, QueryAllBalancesResponse, QuerySpendableBalancesRequest, QuerySpendableBalancesResponse, QueryTotalSupplyRequest, QueryTotalSupplyResponse, QuerySupplyOfRequest, QuerySupplyOfResponse, QueryParamsRequest, QueryParamsResponse, QueryDenomMetadataRequest, QueryDenomMetadataResponse, QueryDenomsMetadataRequest, QueryDenomsMetadataResponse, QueryDenomOwnersRequest, QueryDenomOwnersResponse } from "./query";

// generated helper functions

// creators
export const createGetBalance = (getRpcInstance: () => Rpc | undefined) => buildQuery<QueryBalanceRequest, QueryBalanceResponse>({
reqEncoderFn: QueryBalanceRequest.encode,
resDecoderFn: QueryBalanceResponse.decode,
service: "cosmos.bank.v1beta1.Query",
method: "Balance",
getRpcInstance
});

export const createGetAllBalances = (getRpcInstance: () => Rpc | undefined) => buildQuery<QueryAllBalancesRequest, QueryAllBalancesResponse>({
reqEncoderFn: QueryAllBalancesRequest.encode,
resDecoderFn: QueryAllBalancesResponse.decode,
service: "cosmos.bank.v1beta1.Query",
method: "AllBalances",
getRpcInstance
});

// hooks
export const useBalance = buildUseQuery<QueryBalanceRequest, QueryBalanceResponse>({
builderQueryFn: createGetBalance,
queryKeyPrefix: 'balanceQuery'
});

export const useAllBalances = buildUseQuery<QueryAllBalancesRequest, QueryAllBalancesResponse>({
builderQueryFn: createGetAllBalances,
queryKeyPrefix: 'allBalancesQuery'
});

Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { buildTx, ISigningClient, SigningClientResolver } from "../../../helper-func-types";
import { MsgSend, MsgMultiSend } from "./tx";
import { toConverters, toEncoders } from "@interchainjs/cosmos/utils";
import { buildUseMutation } from "../../../react-query";

// generated helper functions

// creators
export const createSend = (getSigningClient: SigningClientResolver) => buildTx<MsgSend>({
getSigningClient,
typeUrl: MsgSend.typeUrl,
encoders: toEncoders(MsgSend),
converters: toConverters(MsgSend),
});

export const createMultiSend = (getSigningClient: SigningClientResolver) => buildTx<MsgMultiSend>({
getSigningClient,
typeUrl: MsgMultiSend.typeUrl,
encoders: toEncoders(MsgMultiSend),
converters: toConverters(MsgMultiSend),
});

// hooks
export const useSend = buildUseMutation<MsgSend, Error>({
builderMutationFn: createSend,
});

export const useMultiSend = buildUseMutation<MsgMultiSend, Error>({
builderMutationFn: createMultiSend,
});
Loading