cosmology-tech / telescope

A TypeScript Transpiler for Cosmos Protobufs ⚛️
https://cosmology.zone/products/telescope
Apache License 2.0
146 stars 43 forks source link

Generating leaner helper functions #659

Open Zetazzz opened 3 weeks ago

Zetazzz commented 3 weeks ago

leaner helper functions need to generate for smaller bundle size.

cca poc:

https://github.com/cosmology-tech/create-cosmos-app/blob/feat/helpers-poc/examples/interchainjs/pages/helpers.tsx

util:

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

hook(generated):

// generated react hook helper function for sending tokens
const useSend = (options: HelperOptions) => {
  // getting signingClient from chainName
  const { signingClient } = useChain(options.chainName ?? '');
  let client = options.signingClient ?? signingClient;

  if (!client) {
    return null;
  }

  // register all related encoders and converters
  // at this case, we only need MsgSend
  signingClient?.addEncoders(toEncoders(MsgSend));
  signingClient?.addConverters(toConverters(MsgSend));

  // return the actual send function
  return async (
    signerAddress: string,
    message: MsgSend,
    fee: StdFee | 'auto' = 'auto',
    memo: string = ''
  ): Promise<DeliverTxResponse> => {
    const data = [
      {
        typeUrl: MsgSend.typeUrl,
        value: message,
      },
    ];
    return signingClient.signAndBroadcast!(signerAddress, data, fee, memo);
  };
};

usage:

  const send = useSend({ chainName });

      const response = await send(
        address,
        {
          fromAddress: address,
          toAddress: address,
          amount: [{ denom: coin.base, amount: '1' }],
        },
        fee,
        'using interchainjs'
      );
Zetazzz commented 1 week ago

Created a PR for this:

https://github.com/cosmology-tech/telescope/pull/664