> ## Documentation Index
> Fetch the complete documentation index at: https://docs.near.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Using FTs

> Learn how to create, transfer, and integrate FT in your dApp

export const Github = ({url, start, end, fname, withSourceLink = true}) => {
  const [code, setCode] = useState(null);
  function toRaw(ref) {
    const fullUrl = ref.slice(ref.indexOf('https'));
    const [url] = fullUrl.split('#');
    const [org, repo, , branch, ...pathSeg] = new URL(url).pathname.split('/').slice(1);
    return `https://raw.githubusercontent.com/${org}/${repo}/${branch}/${pathSeg.join('/')}`;
  }
  async function fetchCode(url, fromLine, toLine) {
    let res;
    if (typeof window !== 'undefined') {
      const validUntil = localStorage.getItem(`${url}-until`);
      if (validUntil && Number(validUntil) > Date.now()) {
        res = localStorage.getItem(url);
      }
    }
    if (!res) {
      try {
        res = await (await fetch(url)).text();
        if (typeof window !== 'undefined') {
          localStorage.setItem(url, res);
          localStorage.setItem(`${url}-until`, String(Date.now() + 60000));
        }
      } catch {
        return 'Error fetching code, please try reloading';
      }
    }
    let body = res.split('\n');
    const from = fromLine ? Number(fromLine) - 1 : 0;
    const to = toLine ? Number(toLine) : body.length;
    body = body.slice(from, to);
    const precedingSpace = body.reduce((prev, line) => {
      if (line.length === 0) return prev;
      const spaces = line.match(/^\s+/);
      if (spaces) return Math.min(prev, spaces[0].length);
      return 0;
    }, Infinity);
    return body.map(line => line.slice(precedingSpace === Infinity ? 0 : precedingSpace)).join('\n');
  }
  function buildSourceUrl(url, start, end) {
    const base = url.split('#')[0];
    if (start && end) return `${base}#L${start}-L${end}`;
    if (start) return `${base}#L${start}`;
    return base;
  }
  useEffect(() => {
    const rawUrl = toRaw(url);
    fetchCode(rawUrl, start, end).then(res => setCode(res));
  }, [url, start, end]);
  const sourceUrl = buildSourceUrl(url, start, end);
  const startLine = start ? Number(start) : 1;
  const fileName = fname ?? sourceUrl.split('/').pop();
  return <div className="rounded-[0.625rem] border border-[#d0d7de] dark:border-[#30363d] overflow-hidden my-5 text-[0.8125rem] font-mono shadow-sm dark:shadow-[0_4px_24px_rgba(0,0,0,0.18)]">

      {}
      <div className="flex items-center justify-between py-2 px-[0.875rem] bg-[#f6f8fa] dark:bg-[#161b22] border-b border-[#d0d7de] dark:border-[#30363d]">
        <div className="flex items-center gap-2 text-[#656d76] dark:text-[#8b949e]">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" />
          </svg>
          <span className="text-xs font-medium text-[#1f2328] dark:text-[#e6edf3]">
            {fileName}
          </span>
        </div>
        {start && end && <span className="text-[0.6875rem] text-[#656d76] dark:text-[#8b949e] bg-[#eaeef2] dark:bg-[#21262d] border border-[#d0d7de] dark:border-[#30363d] rounded-full py-0.5 px-2">
            Lines {start}–{end}
          </span>}
      </div>

      {}
      <div className="overflow-auto max-h-[480px] bg-white dark:bg-[#0d1117] [&_tr]:border-b-0 [&_td]:border-b-0">
        {code === null ? <div className="py-5 px-4 text-xs text-[#656d76] dark:text-[#6e7681]">
            Loading...
          </div> : <table className="w-full border-collapse leading-[1.6]">
            <tbody>
              {code.split('\n').map((line, i) => <tr key={i} className="align-top border-0">
                  <td style={{
    minWidth: '60px'
  }} className="select-none pl-2 pr-3 text-right text-[0.7rem] text-[#8c959f] dark:text-[#3d444d] w-[1%] whitespace-nowrap border-r border-0 border-r-[#d0d7de] dark:border-r-[#21262d]">
                    {startLine + i}
                  </td>
                  <td className="pl-4 pr-6 text-[0.8125rem] text-[#1f2328] dark:text-[#e6edf3] whitespace-pre">
                    {line || ' '}
                  </td>
                </tr>)}
            </tbody>
          </table>}
      </div>

      {}
      {withSourceLink && <div className="flex justify-end py-1.5 px-[0.875rem] bg-[#f6f8fa] dark:bg-[#161b22] border-t border-[#d0d7de] dark:border-[#21262d]">
          <a href={sourceUrl} target="_blank" rel="noreferrer noopener" className="text-[0.6875rem] font-medium text-[#656d76] dark:text-[#8b949e] no-underline flex items-center gap-[0.3rem] hover:text-[#1f2328] dark:hover:text-[#e6edf3] transition-colors">
            View on GitHub
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
              <polyline points="15 3 21 3 21 9" />
              <line x1="10" y1="14" x2="21" y2="3" />
            </svg>
          </a>
        </div>}
    </div>;
};

export const TryOutOnLantstool = ({path, user = 'lantstool', repo = 'examples.near-protocol', branch = 'main'}) => {
  const lantstoolUrl = `https://app.lantstool.dev/import/gh/${user}/${repo}/${branch}/${path}`;
  const githubUrl = `https://github.com/${user}/${repo}/blob/${branch}/${path}`;
  const [code, setCode] = useState(null);
  function toRaw(ref) {
    const [org, repoName, , branchName, ...pathSeg] = new URL(ref).pathname.split('/').slice(1);
    return `https://raw.githubusercontent.com/${org}/${repoName}/${branchName}/${pathSeg.join('/')}`;
  }
  useEffect(() => {
    const rawUrl = toRaw(githubUrl);
    (async () => {
      try {
        let res;
        const validUntil = typeof window !== 'undefined' && localStorage.getItem(`${rawUrl}-until`);
        if (validUntil && Number(validUntil) > Date.now()) {
          res = localStorage.getItem(rawUrl);
        }
        if (!res) {
          res = await (await fetch(rawUrl)).text();
          if (typeof window !== 'undefined') {
            localStorage.setItem(rawUrl, res);
            localStorage.setItem(`${rawUrl}-until`, String(Date.now() + 60000));
          }
        }
        setCode(res);
      } catch {
        setCode('Error fetching code, please try reloading');
      }
    })();
  }, [githubUrl]);
  return <div>
      <p>
        Try it out on{' '}
        <a href={lantstoolUrl} target="_blank" rel="noopener noreferrer">
          Lantstool
        </a>
      </p>
      <div className="rounded-[0.625rem] border border-[#d0d7de] dark:border-[#30363d] overflow-hidden my-3 text-[0.8125rem] font-mono shadow-sm dark:shadow-[0_4px_24px_rgba(0,0,0,0.18)]">
        <div className="flex items-center gap-2 py-2 px-[0.875rem] bg-[#f6f8fa] dark:bg-[#161b22] border-b border-[#d0d7de] dark:border-[#30363d]">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" className="text-[#656d76] dark:text-[#8b949e]">
            <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" />
          </svg>
          <span className="text-xs font-medium text-[#1f2328] dark:text-[#e6edf3]">
            {githubUrl.split('/').pop()}
          </span>
        </div>
        <div className="overflow-auto max-h-[480px] bg-white dark:bg-[#0d1117] [&_tr]:border-b-0 [&_td]:border-b-0">
          {code === null ? <div className="py-5 px-4 text-xs text-[#656d76] dark:text-[#6e7681]">Loading...</div> : <table className="w-full border-collapse leading-[1.6]">
              <tbody>
                {code.split('\n').map((line, i) => <tr key={i} className="align-top border-0">
                    <td style={{
    minWidth: '60px'
  }} className="select-none pl-2 pr-3 text-right text-[0.7rem] text-[#8c959f] dark:text-[#3d444d] w-[1%] whitespace-nowrap border-r border-0 border-r-[#d0d7de] dark:border-r-[#21262d]">
                      {i + 1}
                    </td>
                    <td className="pl-4 pr-6 text-[0.8125rem] text-[#1f2328] dark:text-[#e6edf3] whitespace-pre">
                      {line || ' '}
                    </td>
                  </tr>)}
              </tbody>
            </table>}
        </div>
      </div>
    </div>;
};

Wanting to use Fungible Tokens (FT) in your dApp? Here you will find all the information you need to get started creating your own tokens, registering users
, querying balances, transferring tokens, and integrating them into your smart contracts.

***

## Creating a New Token

The simplest way to create a new Fungible Token is by interacting with a factory contract, to which you only need to provide the token metadata, and they will automatically deploy and initialize a [canonical FT contract](https://github.com/near-examples/FT).

<Accordion title="Manual Interaction">
  Here is how to directly interact with the factory contract through your application:

  <Tabs>
    <Tab title="🌐 WebApp">
      ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
      import { useNearWallet } from "near-connect-hooks";

      const TOKEN_FACTORY_ADDRESS = 'token.primitives.near';

      const { callFunction } = useNearWallet();

      const args = {
        args: {
          owner_id: 'bob.near',
          total_supply: '1000000000',
          metadata: {
            spec: 'ft-1.0.0',
            name: 'Test Token',
            symbol: 'test',
            icon: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
            decimals: 18,
          },
        },
        account_id: 'bob.near',
      };

      await callFunction({
        contractId: TOKEN_FACTORY_ADDRESS,
        method: 'create_token',
        args,
        gas: 300000000000000,
        deposit: '2234830000000000000000',
      });
      ```

      Learn more about adding [Near Connect](../../web3-apps/tutorials/wallet-login) to your application
    </Tab>

    <Tab title="🖥️ CLI">
      ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
      near call token.primitives.near create_token '{"args":{"owner_id": "bob.near","total_supply": "1000000000","metadata":{"spec": "ft-1.0.0","name": "Test Token","symbol": "TTTEST","icon": "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","decimals": 18}},"account_id": "bob.near"}' --gas 300000000000000 --depositYocto 2234830000000000000000000 --useAccount bob.near
      ```
    </Tab>

    <Tab title="Lantstool" icon="https://mintcdn.com/neardocs/qO2GD-gji1aakHqN/assets/docs/tools/lantstool-logo-circle.svg?fit=max&auto=format&n=qO2GD-gji1aakHqN&q=85&s=e40405f8a9eda7a97dd89b9cc07a9ca9" width="100" height="100" data-path="assets/docs/tools/lantstool-logo-circle.svg">
      <TryOutOnLantstool path="docs/2.build/5.primitives/ft/create-ft-via-factory.json" />
    </Tab>
  </Tabs>

  The FT you create will live in the account `<your_token_symbol>.token.primitives.near` (e.g. `test.token.primitives.near`).
</Accordion>

***

## Deploying Your Own Contract

You can also create a fungible token by deploying and initializing a [canonical FT contract](https://github.com/near-examples/FT).

On initialization, you will define the token's metadata such as its name (e.g. Ethereum), symbol (e.g. ETH) and total supply (e.g. 10M). You will also define an `owner`, which will own the tokens **total supply**.

To initialize a FT contract you will need to deploy it and then call the `new` method defining the token's metadata.

<Tabs>
  <Tab title="🖥️ CLI">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    cargo near deploy build-non-reproducible-wasm <account-id> \
      with-init-call new \
      json-args '{
        "owner_id": "<owner-account>",
        "total_supply": "1000000000000000",
        "metadata": {
          "spec": "ft-1.0.0",
          "name": "Example Token Name",
          "symbol": "EXLT",
          "decimals": 8
        }
      }' \
      prepaid-gas '100.0 Tgas' \
      attached-deposit '0 NEAR' \
      network-config testnet \
      sign-with-keychain send
    ```
  </Tab>

  <Tab title="Lantstool" icon="https://mintcdn.com/neardocs/qO2GD-gji1aakHqN/assets/docs/tools/lantstool-logo-circle.svg?fit=max&auto=format&n=qO2GD-gji1aakHqN&q=85&s=e40405f8a9eda7a97dd89b9cc07a9ca9" width="100" height="100" data-path="assets/docs/tools/lantstool-logo-circle.svg">
    <TryOutOnLantstool path="docs/2.build/5.primitives/ft/create-ft-manually.json" />
  </Tab>
</Tabs>

### Global Contracts

You can deploy a new Fungible Token using our global FT contract - a pre-deployed [standard FT contract](https://github.com/near-examples/FT) that you can reuse. [Global contracts](../../smart-contracts/global-contracts) are deployed once and can be reused by any account without incurring high storage costs.

<Tabs>
  <Tab title="By Account">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    near contract deploy <account-id> use-global-account-id ft.globals.primitives.testnet \
      with-init-call \
      new_default_meta \
      json-args '{"owner_id": "<account-id>", "total_supply": "100000000000000000000000000000"}' \
      prepaid-gas '100.0 Tgas' \
      attached-deposit '0 NEAR' \
      network-config testnet \
      sign-with-keychain send
    ```
  </Tab>

  <Tab title="By Hash">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    near contract deploy <account-id> use-global-hash 3vaopJ7aRoivvzZLngPQRBEd8VJr2zPLTxQfnRCoFgNX \
      with-init-call \
      new_default_meta \
      json-args '{"owner_id": "<account-id>", "total_supply": "100000000000000000000000000000"}' \
      prepaid-gas '100.0 Tgas' \
      attached-deposit '0 NEAR' \
      network-config testnet \
      sign-with-keychain send
    ```
  </Tab>
</Tabs>

<Note>
  Deploying by **hash** creates an immutable contract that never changes. Deploying by **account ID** creates an updatable contract that changes when the referenced account's contract is updated. Choose based on whether you want your FT contract to be updatable or permanent.
</Note>

***

## Querying Metadata

You can query the FT's metadata by calling the `ft_metadata`.

<Tabs>
  <Tab title="🌐 WebApp">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import { useNearWallet } from "near-connect-hooks";

    const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';

    const { viewFunction } = useNearWallet();

    await viewFunction({
      method: 'ft_metadata',
      args: {},
      contractId: TOKEN_CONTRACT_ADDRESS,
    });
    ```

    <Accordion title="Example response">
      <p>
        ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
        {
          "spec": "ft-1.0.0",
          "name": "Ref Finance Token",
          "symbol": "REF",
          "icon": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='16 24 248 248' style='background: %23000'%3E%3Cpath d='M164,164v52h52Zm-45-45,20.4,20.4,20.6-20.6V81H119Zm0,18.39V216h41V137.19l-20.6,20.6ZM166.5,81H164v33.81l26.16-26.17A40.29,40.29,0,0,0,166.5,81ZM72,153.19V216h43V133.4l-11.6-11.61Zm0-18.38,31.4-31.4L115,115V81H72ZM207,121.5h0a40.29,40.29,0,0,0-7.64-23.66L164,133.19V162h2.5A40.5,40.5,0,0,0,207,121.5Z' fill='%23fff'/%3E%3Cpath d='M189 72l27 27V72h-27z' fill='%2300c08b'/%3E%3C/svg%3E%0A",
          "reference": null,
          "reference_hash": null,
          "decimals": 18
        }
        ```
      </p>
    </Accordion>

    Learn more about adding [Near Connect](../../web3-apps/tutorials/wallet-login) to your application
  </Tab>

  <Tab title="🖥️ CLI">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    near view token.v2.ref-finance.near ft_metadata
    ```

    <Accordion title="Example response">
      <p>
        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        {
          spec: "ft-1.0.0",
          name: "Ref Finance Token",
          symbol: "REF",
          icon: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='16 24 248 248' style='background: %23000'%3E%3Cpath d='M164,164v52h52Zm-45-45,20.4,20.4,20.6-20.6V81H119Zm0,18.39V216h41V137.19l-20.6,20.6ZM166.5,81H164v33.81l26.16-26.17A40.29,40.29,0,0,0,166.5,81ZM72,153.19V216h43V133.4l-11.6-11.61Zm0-18.38,31.4-31.4L115,115V81H72ZM207,121.5h0a40.29,40.29,0,0,0-7.64-23.66L164,133.19V162h2.5A40.5,40.5,0,0,0,207,121.5Z' fill='%23fff'/%3E%3Cpath d='M189 72l27 27V72h-27z' fill='%2300c08b'/%3E%3C/svg%3E%0A",
          reference: null,
          reference_hash: null,
          decimals: 18
        }
        ```
      </p>
    </Accordion>
  </Tab>

  <Tab title="Lantstool" icon="https://mintcdn.com/neardocs/qO2GD-gji1aakHqN/assets/docs/tools/lantstool-logo-circle.svg?fit=max&auto=format&n=qO2GD-gji1aakHqN&q=85&s=e40405f8a9eda7a97dd89b9cc07a9ca9" width="100" height="100" data-path="assets/docs/tools/lantstool-logo-circle.svg">
    <TryOutOnLantstool path="docs/2.build/5.primitives/ft/query-ft-metadata.json" />
  </Tab>
</Tabs>

***

## Checking Balance

To know how many coins a user has you will need to query the method `ft_balance_of`.

<Tabs>
  <Tab title="🌐 WebApp">
    <Info>
      Remember about fungible token precision. You may need this value to show a response of balance requests in an understandable-to-user way in your app. How to get precision value (decimals) you may find [here](#querying-metadata).
    </Info>

    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import { useNearWallet } from "near-connect-hooks";

    const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';

    const { viewFunction } = useNearWallet();

    await viewFunction({
      method: 'ft_balance_of',
      args: {
        account_id: 'bob.near',
      },
      contractId: TOKEN_CONTRACT_ADDRESS,
    });
    ```

    <Accordion title="Example response">
      <p>
        ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
        "3479615037675962643842"
        ```
      </p>
    </Accordion>

    Learn more about adding [Near Connect](../../web3-apps/tutorials/wallet-login) to your application
  </Tab>

  <Tab title="🖥️ CLI">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    near view token.v2.ref-finance.near ft_balance_of '{"account_id": "bob.near"}'
    ```

    <Accordion title="Example response">
      <p>
        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        '376224322825327177426'
        ```
      </p>
    </Accordion>
  </Tab>

  <Tab title="Lantstool" icon="https://mintcdn.com/neardocs/qO2GD-gji1aakHqN/assets/docs/tools/lantstool-logo-circle.svg?fit=max&auto=format&n=qO2GD-gji1aakHqN&q=85&s=e40405f8a9eda7a97dd89b9cc07a9ca9" width="100" height="100" data-path="assets/docs/tools/lantstool-logo-circle.svg">
    <TryOutOnLantstool path="docs/2.build/5.primitives/ft/check-ft-balance.json" />
  </Tab>
</Tabs>

***

## Registering a User

In order for a user to own and transfer tokens they need to first **register** in the contract. This is done by calling `storage_deposit` and attaching 0.00125Ⓝ.

By calling this `storage_deposit` the user can register themselves or **register other users**.

<Tabs>
  <Tab title="🌐 WebApp">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import { useNearWallet } from "near-connect-hooks";

    const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';

    const { callFunction } = useNearWallet();

    await callFunction({
      contractId: TOKEN_CONTRACT_ADDRESS,
      method: 'storage_deposit',
      args: {
        account_id: 'alice.near',
      },
      deposit: 1250000000000000000000,
    });
    ```

    Learn more about adding [Near Connect](../../web3-apps/tutorials/wallet-login) to your application
  </Tab>

  <Tab title="🖥️ CLI">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    near call token.v2.ref-finance.near storage_deposit '{"account_id": "alice.near"}' --depositYocto 1250000000000000000000 --useAccount bob.near
    ```
  </Tab>

  <Tab title="Lantstool" icon="https://mintcdn.com/neardocs/qO2GD-gji1aakHqN/assets/docs/tools/lantstool-logo-circle.svg?fit=max&auto=format&n=qO2GD-gji1aakHqN&q=85&s=e40405f8a9eda7a97dd89b9cc07a9ca9" width="100" height="100" data-path="assets/docs/tools/lantstool-logo-circle.svg">
    <TryOutOnLantstool path="docs/2.build/5.primitives/ft/register-user.json" />
  </Tab>
</Tabs>

<Info>
  You can make sure a user is registered by calling `storage_balance_of`.
</Info>

<Tip>
  After a user calls the `storage_deposit` the FT will appear in their Wallets.
</Tip>

***

## Transferring Tokens

To send FT to another account you will use the `ft_transfer` method, indicating the receiver and the amount of FT you want to send.

<Tabs>
  <Tab title="🌐 WebApp">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import { useNearWallet } from "near-connect-hooks";

    const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';

    const { callFunction } = useNearWallet();

    await callFunction({
      contractId: TOKEN_CONTRACT_ADDRESS,
      method: 'ft_transfer',
      args: {
        receiver_id: 'alice.near',
        amount: '100000000000000000',
      },
      deposit: 1,
    });
    ```

    Learn more about adding [Near Connect](../../web3-apps/tutorials/wallet-login) to your application
  </Tab>

  <Tab title="🖥️ CLI">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    near call token.v2.ref-finance.near ft_transfer '{"receiver_id": "alice.near", "amount": "100000000000000000"}' --depositYocto 1 --useAccount bob.near
    ```
  </Tab>

  <Tab title="Lantstool" icon="https://mintcdn.com/neardocs/qO2GD-gji1aakHqN/assets/docs/tools/lantstool-logo-circle.svg?fit=max&auto=format&n=qO2GD-gji1aakHqN&q=85&s=e40405f8a9eda7a97dd89b9cc07a9ca9" width="100" height="100" data-path="assets/docs/tools/lantstool-logo-circle.svg">
    <TryOutOnLantstool path="docs/2.build/5.primitives/ft/transfer-tokens.json" />
  </Tab>

  <Tab title="📄 Contract">
    ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
    #[near]
    impl Contract {
      #[payable]
      pub fn send_tokens(&mut self, receiver_id: AccountId, amount: U128) -> Promise {
        assert_eq!(env::attached_deposit(), 1, "Requires attached deposit of exactly 1 yoctoNEAR");

        let promise = ext(self.ft_contract.clone())
          .with_attached_deposit(YOCTO_NEAR)
          .ft_transfer(receiver_id, amount, None);

        return promise.then( // Create a promise to callback query_greeting_callback
          Self::ext(env::current_account_id())
          .with_static_gas(Gas(30*TGAS))
          .external_call_callback()
        )
      }

      #[private] // Public - but only callable by env::current_account_id()
      pub fn external_call_callback(&self, #[callback_result] call_result: Result<(), PromiseError>) {
        // Check if the promise succeeded
        if call_result.is_err() {
          log!("There was an error contacting external contract");
        }
      }
    }
    ```

    *This snippet assumes that the contract is already holding some FTs and that you want to send them to another account.*
  </Tab>
</Tabs>

***

## Attaching FTs to a Call

Natively, only NEAR tokens (Ⓝ) can be attached to a function calls. However, the FT standard enables to **attach fungible tokens** in a call by using the FT-contract as intermediary.

This means that, instead of you attaching tokens directly to the call, you ask the FT-contract to do both a transfer and a function call in your name.

Let's assume that you need to deposit FTs on [Ref Finance](https://rhea.finance/).

<Tabs>
  <Tab title="🌐 WebApp">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import { useNearWallet } from "near-connect-hooks";

    const TOKEN_CONTRACT_ADDRESS = 'token.v2.ref-finance.near';

    const { callFunction } = useNearWallet();

    await callFunction({
      contractId: TOKEN_CONTRACT_ADDRESS,
      method: 'ft_transfer_call',
      args: {
        receiver_id: 'v2.ref-finance.near',
        amount: '100000000000000000',
        msg: '',
      },
      gas: 300000000000000,
      deposit: 1,
    });
    ```

    <Accordion title="Example response">
      <p>
        ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
        "100000000000000000"
        ```
      </p>
    </Accordion>

    Learn more about adding [Near Connect](../../web3-apps/tutorials/wallet-login) to your application
  </Tab>

  <Tab title="🖥️ CLI">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    near call token.v2.ref-finance.near ft_transfer_call '{"receiver_id": "v2.ref-finance.near", "amount": "100000000000000000", "msg": ""}' --gas 300000000000000 --depositYocto 1 --useAccount bob.near
    ```

    <Accordion title="Example response">
      <p>
        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        '100000000000000000'
        ```
      </p>
    </Accordion>
  </Tab>

  <Tab title="Lantstool" icon="https://mintcdn.com/neardocs/qO2GD-gji1aakHqN/assets/docs/tools/lantstool-logo-circle.svg?fit=max&auto=format&n=qO2GD-gji1aakHqN&q=85&s=e40405f8a9eda7a97dd89b9cc07a9ca9" width="100" height="100" data-path="assets/docs/tools/lantstool-logo-circle.svg">
    <TryOutOnLantstool path="docs/2.build/5.primitives/ft/attach-ft-to-call.json" />
  </Tab>

  <Tab title="📄 Contract">
    ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
    #[payable]
    pub fn call_with_attached_tokens(&mut self, receiver_id: AccountId, amount: U128) -> Promise {
      assert_eq!(env::attached_deposit(), 1, "Requires attached deposit of exactly 1 yoctoNEAR");

      let promise = ext(self.ft_contract.clone())
        .with_static_gas(Gas(150*TGAS))
        .with_attached_deposit(YOCTO_NEAR)
        .ft_transfer_call(receiver_id, amount, None, "".to_string());

      return promise.then( // Create a promise to callback query_greeting_callback
        Self::ext(env::current_account_id())
        .with_static_gas(Gas(100*TGAS))
        .external_call_callback()
      )
    }
    ```
  </Tab>
</Tabs>

How it works:

1. You call `ft_transfer_call` in the FT contract passing: the receiver, a message, and the amount.
2. The FT contract transfers the amount to the receiver.
3. The FT contract calls `receiver.ft_on_transfer(sender, msg, amount)`
4. The FT contract handles errors in the `ft_resolve_transfer` callback.
5. The FT contract returns you how much of the attached amount was actually used.

***

## Handling Deposits

If you want your contract to handle deposit in FTs you have to implement the `ft_on_transfer` method. When executed, such method will know:

* Which FT was transferred, since it is the predecessor account.
* Who is sending the FT, since it is a parameter
* How many FT were transferred, since it is a parameter
* If there are any parameters encoded as a message

The `ft_on_transfer` must return how many FT tokens have to **be refunded**, so the FT contract gives them back to the sender.

Here is an example from our [auctions tutorial](../../web3-apps/tutorials/mastering-near/3.2-ft) where we implement `ft_on_transfer` to handle bids in FTs:

<Github fname="lib.rs" language="rust" url="https://github.com/near-examples/auctions-tutorial/blob/main/contract-rs/03-bid-with-fts/src/lib.rs#L56-L87" start="56" end="87" />

*Note: The [`near_contract_standards::fungible_token::receiver`](https://docs.rs/near-contract-standards/latest/near_contract_standards/fungible_token/receiver/trait.FungibleTokenReceiver.html) module exposes a `FungibleTokenReceiver` trait that you could implement on your contract*

***

## Burn Tokens

While the FT standard does not define a `burn` method, you can simply transfer tokens to an account that no one controls, such as [`0000000000000000000000000000000000000000000000000000000000000000`](https://nearblocks.io/es/address/0000000000000000000000000000000000000000000000000000000000000000) (64 zeros).

<Tabs>
  <Tab title="🌐 WebApp">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import { useNearWallet } from "near-connect-hooks";

    const { callFunction } = useNearWallet();

    await callFunction({
      contractId: 'token.v2.ref-finance.near',
      method: 'ft_transfer',
      args: {
        receiver_id: '0000000000000000000000000000000000000000000000000000000000000000',
        amount: '100000000000000000',
      },
      deposit: 1,
    });
    ```

    Learn more about adding [Near Connect](../../web3-apps/tutorials/wallet-login) to your application
  </Tab>

  <Tab title="🖥️ CLI">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    near call token.v2.ref-finance.near ft_transfer '{"receiver_id": "0000000000000000000000000000000000000000000000000000000000000000", "amount": "100000000000000000"}' --depositYocto 1 --useAccount bob.near
    ```
  </Tab>
</Tabs>

***

## Additional Resources

1. [NEP-141 standard](https://github.com/near/NEPs/tree/master/neps/nep-0141.md)
2. [NEP-148 standard](https://github.com/near/NEPs/tree/master/neps/nep-0148.md)
3. [FT Event Standards](https://github.com/near/NEPs/blob/master/neps/nep-0300.md)
4. [FT reference implementation](https://github.com/near-examples/FT)
5. [Fungible Tokens 101](../../smart-contracts/tutorials/zero-to-hero/fts) - a set of tutorials that cover how to create a FT contract using Rust.
