Chromia
Start Building

15 / 16Module 3: The frontend applicationIntermediate

Part 6: Transferring assets

This lesson shows you how to move assets from one account to another with the FT4 token standard.

To read account balances, call the useGetBalances hook from the @chromia/react package. Once you have the balances, you can confirm that the account holds enough tokens before sending a transfer.

asset_management/src/hooks/token-hooks.ts
import { useCallback } from "react";import { createAmount, op } from "@chromia/ft4";import {  useFtAccounts,  useFtSession,  useGetAllAssets,  useGetBalances,  usePostchainClient,} from "@chromia/react";import { useAccount } from "wagmi";import { ensureBuffer } from "@/utils/ensure-buffer";import { publicClientConfig as clientConfig } from "@/utils/generate-client-config";export function useTransferTokens({  onSuccess,  onError,}: {  onSuccess?: (token: MintTokenParams) => void;  onError?: (token: MintTokenParams) => void;}) {  const { data: ftAccounts } = useFtAccounts({ clientConfig });  const { data: session } = useFtSession(    ftAccounts?.length ? { clientConfig, account: ftAccounts[0] } : null,  );  const { flatData: balances } = useGetBalances(    ftAccounts?.length      ? {          clientConfig,          account: ftAccounts[0],          params: [10],          swrInfiniteConfiguration: {            refreshInterval: 20_000,          },        }      : null,  );  const transferTokens = useCallback(    async (recipient: string, amount: number) => {      if (!balances?.length) {        return;      }      const asset = balances[0].asset;      try {        await session?.account.transfer(          ensureBuffer(recipient),          ensureBuffer(asset.id),          createAmount(amount),        );        onSuccess?.({ ticker: asset.symbol, name: asset.name, amount });      } catch (error) {        console.error(error);        onError?.({ ticker: asset.symbol, name: asset.name, amount });      }    },    [balances, onError, onSuccess, session?.account],  );  return transferTokens;}

The snippet defines a custom hook, useTransferTokens. It obtains the current session through useFtSession, and it fetches the account balances through useGetBalances to verify that enough tokens are available. When the balance is sufficient, the hook calls the transfer method on the session object's account property, which sends the requested amount to the recipient account.

Written for this site from Chromia’s public course. Code samples are the course’s own.