> ## Documentation Index
> Fetch the complete documentation index at: https://base-a060aa97-eb-mini-app-ia-overhaul.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Defi Your App

> Add common financial features like token swaps and yield generating strategies to your app with pre-built React components from OnchainKit.

export const Danger = ({children}) => {
  return <div class="my-4 px-5 py-4 overflow-hidden rounded-2xl flex gap-3 border danger-admonition dark:danger-admonition">
      <div class="mt-0.5 w-4">
        <svg width="14" height="14" viewBox="0 0 14 14" fill="rgb(239, 68, 68)" xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-sky-500" aria-label="Danger">
          <path fill-rule="evenodd" clip-rule="evenodd" d="M7 1.3C10.14 1.3 12.7 3.86 12.7 7C12.7 10.14 10.14 12.7 7 12.7C5.48908 12.6974 4.0408 12.096 2.97241 11.0276C1.90403 9.9592 1.30264 8.51092 1.3 7C1.3 3.86 3.86 1.3 7 1.3ZM7 0C3.14 0 0 3.14 0 7C0 10.86 3.14 14 7 14C10.86 14 14 10.86 14 7C14 3.14 10.86 0 7 0ZM8 3H6V8H8V3ZM8 9H6V11H8V9Z"></path>
        </svg>
      </div>
      <div class="text-sm prose min-w-0">
        {children}
      </div>
    </div>;
};

When businesses and individuals make financial transactions, it often includes swapping assets and then storing eligible assets in a yield generating strategy. This guide will show you how to quickly add these features to your app with pre-built React components from OnchainKit.

## Ready-to-use components

* [`<Swap />`](/onchainkit/swap/swap): Swap assets directly within your app.
* [`<Earn />`](/onchainkit/earn/earn): Generate yield directly within your app.
* [`<FundCard />`](/onchainkit/fund/fund-card): Fund their wallets with fiat (via USDC, Apple Pay, or debit card) without leaving your appi
* [`<Buy />`](/onchainkit/buy/buy): Purchase tokens directly within your app.

By embedding the `Swap` and `Earn` components, your users don't need to leave your app to execute these common actions. For users who lack onchain funds, the `Fund` and `Buy` components offer an integrated fiat-to-crypto onramp.

## Swap Component Integration

The `Swap` component lets users exchange one token for another directly in your application. It fetches live quotes, builds transactions, and executes swaps—abstracting the underlying complexity.

Lets add the `Swap` component to your app.

<Steps>
  <Step title="Install and Configure OnchainKit">
    Create a new OnchainKit app

    ```bash Terminal
    npm create onchain@latest
    ```
  </Step>

  <Step title="Import and Render the Swap Component">
    ```typescript App.tsx
     import { SwapDefault } from '@coinbase/onchainkit/swap'; // [!code focus]
     import type { Token } from '@coinbase/onchainkit/token';

     const eth: Token = {
     name: 'ETH',
     address: '',
     symbol: 'ETH',
     decimals: 18,
     image:
         'https://wallet-api-production.s3.amazonaws.com/uploads/tokens/eth_288.png',
     chainId: 8453,
     };

     const usdc: Token = {
     name: 'USDC',
     address: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
     symbol: 'USDC',
     decimals: 6,
     image:
         'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/44/2b/442b80bd16af0c0d9b22e03a16753823fe826e5bfd457292b55fa0ba8c1ba213-ZWUzYjJmZGUtMDYxNy00NDcyLTg0NjQtMWI4OGEwYjBiODE2',
     chainId: 8453,
     };

     <SwapDefault // [!code focus]
     from={[eth]} // [!code focus]
     to={[usdc]} // [!code focus]
     /> // [!code focus]
    ```
  </Step>
</Steps>

You should now see the following swap component in your app:

<iframe src="https://684b5e62b1ff46bc5bf83966-aijszlfakk.chromatic.com/iframe.html?args=&id=onchainkit-swap-wallet--not-connected&viewMode=story&dark=true&hero=true" width="100%" height="auto" />

{/* <App>
  <SwapWrapper>
      {({ address, swappableTokens }) => {
      if (address) {
          return (
          <SwapDefault from={swappableTokens} to={swappableTokens.slice().reverse()} disabled />
          )
      }
      return <>
          <Wallet>
          <ConnectWallet>
              <Avatar className="h-6 w-6" />
              <Name />
          </ConnectWallet>
          </Wallet>
      </>;
      }}
  </SwapWrapper>
</App> */}

The Swap component uses **Uniswap V3** as the default router, but you can also use the **0x Aggregator** by setting the `experimental.useAggregator` prop to `true`.

### Swap Settings

The Swap component comes preconfigured but is highly customizable. Just a couple of the settings you can customize:

* Swap settings
* bidirectional or unidirectional swaps
* Gasless swaps with paymasters

To learn more about how to customize the Swap component, check out the [Swap docs](/onchainkit/swap/swap).

## Earn Component Integration

The `Earn` component enables users to deposit assets into yield-generating vaults and withdraw them later—all within your app. The `Earn` component currently supports Morpho vaults on Base.

<Info>
  **Get a vault address**

  You can get a vault address from Morpho's [Vaults page](https://app.morpho.org/base/earn). You will use this address when setting up the `Earn` component.
</Info>

```tsx
// @noErrors: 2307
import { Earn } from '@coinbase/onchainkit/earn'; // [!code focus]

<Earn vaultAddress="0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A" /> // [!code focus]
```

Just like that, you've added a yield-generating vault to your app.

<iframe src="https://684b5e62b1ff46bc5bf83966-aijszlfakk.chromatic.com/iframe.html?args=&id=onchainkit-earn--main&viewMode=story&dark=true&hero=true" width="100%" height="400px" />

{/* <EarnMain /> */}

### Advanced Customizations

Similar to the Swap component, the Earn component is highly customizable. Lets customize our component to include custom deposit buttons for a streamlined user experience.

* `useEarnContext` to access the component's context values, `EarnDeposit` and `EarnDetails`
* `DepositButton` to render custom deposit buttons

<CodeGroup>
  ```tsx index.tsx
  // @noErrors: 2307
  import { Earn, useEarnContext } from '@coinbase/onchainkit/earn';
  import { CustomDepositButtons } from '@/custom-deposit-buttons';

    <Earn vaultAddress="0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A">
        <CustomDepositButtons />
    </Earn>

  ```

  ```tsx custom-deposit-buttons.tsx
  import {EarnDetails,
          EarnDeposit,
          useEarnContext,
          DepositButton} from '@coinbase/onchainkit/earn';

  const predefinedAmounts = ['0.1', '1', '10'];

  function CustomDepositButtons() {
    const { depositAmount, setDepositAmount } = useEarnContext();

    return (
      <EarnDeposit>
        <EarnDetails />
        <div className="grid grid-cols-3 gap-2">
          {predefinedAmounts.map((amount) => {
            const selected = amount === depositAmount;
            return (
              <button
                key={amount}
                type="button"
                onClick={() => setDepositAmount(amount)}
                className={`rounded-md px-4 py-2
                ${selected ? 'bg-[var(--ock-bg-primary)] text-[var(--ock-text-inverse)]'
                : 'bg-[var(--ock-bg-secondary)] text-[var(--ock-text-primary)]'}`}
              >
                {amount}
              </button>
            );
          })}
        </div>
        <DepositButton />
      </EarnDeposit>
    );
  }
  ```
</CodeGroup>

<iframe src="https://684b5e62b1ff46bc5bf83966-aijszlfakk.chromatic.com/iframe.html?args=&id=onchainkit-earn--predefined-deposit&viewMode=story&dark=true&hero=true" width="100%" height="280px" />

{/* <PredefinedInputDeposit /> */}

## Onboarding Users in DeFi

In order to leverage the `<FundCard/>` and `<Buy />` components, users need to have funds in their wallet. If user's don't have funds, they'll need to onramp fiat or buy tokens in order to transact. We'll explore two out-of-the-box solutions from OnchainKit below.

The `Fund` component (via `<FundCard />`) offers a complete fiat onramp experience, allowing users to add funds to their wallet directly in your app.  It provides:

* Amount input with fiat/crypto switching
* Payment method selection (Coinbase, Apple Pay, Debit Card)
* Automatic exchange rate updates
* Smart handling of payment method restrictions (based on country and subdivision)

<Tip>
  To use the `FundCard` component, you'll need to provide a Client API Key in `OnchainKitProvider`. You can get one following our [Getting Started](/onchainkit/installation/nextjs#get-your-client-api-key) steps.
</Tip>

```tsx App.tsx
import { FundCard } from '@coinbase/onchainkit/fund';

<FundCard
  assetSymbol="ETH"
  country="US"
  currency="USD"
/>;
```

<iframe src="https://684b5e62b1ff46bc5bf83966-aijszlfakk.chromatic.com/iframe.html?args=&id=onchainkit-fund-card--default&viewMode=story&dark=true&hero=true" width="100%" height="370px" />

{/* <App>
<FundWrapper>
  {({ address }) => {
    if (address) {
      return <FundCard assetSymbol="ETH" country="US" currency="USD" />;
    }
    return (
      <>
        <Wallet>
          <ConnectWallet>
            <Avatar className="h-6 w-6" />
            <Name />
          </ConnectWallet>
        </Wallet>
      </>
    );
  }}
</FundWrapper>
</App> */}

To learn more about the `FundCard` component and its features, check out the [FundCard docs](/onchainkit/fund/fund-card).

## The `Buy` Component

The `Buy` components provide a comprehensive interface for users to purchase [Tokens](/onchainkit/token/types#token).

The `Buy` component supports token swaps from USDC and ETH by default with the option to provide an additional token of choice using the `fromToken` prop. Users are able to purchase tokens using their Coinbase account, Apple Pay, or debit card.

<Note>
  This component requires a `projectId` to be set in the `OnchainKitProvider`. You can find your `projectId` on [Coinbase Developer Platform](https://portal.cdp.coinbase.com/products/onchainkit).
</Note>

```tsx
import { Buy } from '@coinbase/onchainkit/buy'; // [!code focus]
import type { Token } from '@coinbase/onchainkit/token';

export default function BuyComponents() { // [!code focus]
  const degenToken: Token = {
    name: 'DEGEN',
    address: '0x4ed4e862860bed51a9570b96d89af5e1b0efefed',
    symbol: 'DEGEN',
    decimals: 18,
    image:
    'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/3b/bf/3bbf118b5e6dc2f9e7fc607a6e7526647b4ba8f0bea87125f971446d57b296d2-MDNmNjY0MmEtNGFiZi00N2I0LWIwMTItMDUyMzg2ZDZhMWNm',
    chainId: 8453,
  };

  return ( // [!code focus]
    <Buy toToken={degenToken} /> // [!code focus]
  ) // [!code focus]
} // [!code focus]

```

<iframe src="https://684b5e62b1ff46bc5bf83966-aijszlfakk.chromatic.com/iframe.html?args=&id=onchainkit-buy--disabled&viewMode=story&dark=true&hero=true" width="100%" height="auto" />

{/* <App>
<BuyWrapper>
  {({ address, toToken }) => {
    return (
      <Buy toToken={toToken} disabled />
    )
  }}
</BuyWrapper>
</App> */}

<Danger>
  **Note: This interface is for demonstration purposes only.**

  Swap and Onramp flows will execute and work out of the box when you implement the component in your own app.
</Danger>

By combining Swap, Earn, Fund, and Buy with these additional tools, you can quickly build a robust in-app DeFi experience with minimal development overhead. This lets you focus on building your unique value proposition.

## Next Steps

If you're using these components, its likely you'll benefit from the following components:

* [`<Transaction/>`](/onchainkit/transaction/transaction): Provides a high-level transaction interface for executing custom onchain transactions.

* [`<TokenChip/>`](/onchainkit/token/token-chip): Offers utilities for token selection and display, ideal for building wallet-like interfaces.

* [`<WalletIsland/>`](/onchainkit/wallet/wallet-island): An advanced, draggable wallet widget that consolidates wallet management (QR code, buy options, swap, portfolio view) in one interface.

### Go Gasless

For the `<Buy />` and `<Swap/>` components, you can enable gasless transactions by setting the [`isSponsored`](/onchainkit/buy/buy#sponsor-gas-with-paymaster) prop to `true`.
