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

# Affiliate Fees

> Implement affiliate fees to earn revenue from Garden swaps through your integration

Garden allows partners to charge an affiliate fee for each swap initiated through their SDK or API integration. This fee must be specified when requesting a quote and is charged in addition to protocol and solver fees.

<Info>
  Fees are expressed in basis points (bps), where 1 bps = 0.01%. For example, a 30 bps fee equals 0.3% of the source asset value.
</Info>

Affiliates can earn rewards in USDC or cbBTC on [supported chains](/developers/supported-chains). Fees can be sent entirely to a single address in one asset, or split across multiple addresses and assets.

For example, a 30 bps fee could be split by sending 10 bps in USDC to an Ethereum address, and 20 bps in cbBTC to a Base address.

<Note>
  The amount of each asset the affiliate will receive is calculated based on prices at the time of the quote and is also stored in the order data. All affiliate fees collected during the week are distributed to the specified addresses at the end of the week.
</Note>

## Implementation

<Tabs>
  <Tab title="Using API">
    To apply an affiliate fee via API, include the `affiliate_fee` parameter when requesting a quote:

    ```shell theme={null}
    curl -X 'GET' \
        'https://testnet.api.garden.finance/v2/quote?from=bitcoin_testnet:btc&to=base_sepolia:wbtc&from_amount=100000&affiliate_fee=30' \
        -H 'garden-app-id: YOUR_APP_ID' \
        -H 'accept: application/json'
    ```

    In this example, we've added a 30 bps affiliate fee.

    To include affiliate fees, add the `affiliate_fees` field when **creating an order**.

    Here's a sample create order request:

    ```shell highlight={15-19} theme={null}
    curl --location 'http://testnet.api.garden.finance/v2/orders' \
        --header 'garden-app-id: f242ea49332293424c96c562a6ef575a819908c878134dcb4fce424dc84ec796' \
        --header 'Content-Type: application/json' \
        --data '{
            "source": {
                "asset": "bitcoin_testnet:btc",
                "owner": "tb1p4pr78swsn60y4ushe05v28mqpqppxxkfkxu2wun5jw6duc8unj3sjrh4gd",
                "amount": "50000"
            },
            "destination": {
                "asset": "base_sepolia:wbtc",
                "owner": "0x004Cc75ACF4132Fc08cB6a252E767804F303F729",
                "amount": "49850"
            },
            "affiliate_fees": [{
                "asset": "base_sepolia:wbtc",
                "address": "0x7A3d05c70581bD345fe117c06e45f9669205384f",
                "fee": 30
            }]
        }'
    ```
  </Tab>

  <Tab title="Using SDK">
    This process involves two steps:

    <Steps>
      <Step title="Request quote">
        Requesting a quote with the affiliate fee applied
      </Step>

      <Step title="Create order">
        Submitting the order using the selected quote
      </Step>
    </Steps>

    To request a quote with an affiliate fee, include the `affiliateFee` parameter in the `options` object.

    <CodeGroup>
      ```ts React theme={null}
      import { SupportedAssets } from "@gardenfi/orderbook";
      import { useGarden } from "@gardenfi/react-hooks";

      const { swapAndInitiate, getQuote } = useGarden();

      const fromAsset = SupportedAssets.testnet.ethereum_sepolia_WBTC;
      const toAsset = SupportedAssets.testnet.arbitrum_sepolia_WBTC;
      const amount = 100000;
      const isExactOut = false;

      const quoteRes = await getQuote({
          fromAsset,
          toAsset,
          amount,
          isExactOut,
          options: {
              affiliateFee: 30 // in bps
          },
      });
      ```

      ```ts NodeJS theme={null}
      const orderpair = 'ethereum_sepolia:0x29C9C37D0Fec7E64AFab0f806c8049d9e2f9B0b6::arbitrum_sepolia:0x795Dcb58d1cd4789169D5F938Ea05E17ecEB68cA'
      const amount = 100000
      const isExactOut = false

      const quoteRes = await garden.quote.getQuote(
          orderpair,
          amount,
          isExactOut,
          {
              affiliateFee: 30, // in bps
          },
      );
      ```
    </CodeGroup>

    While creating the order using the `swap` function, you can include the `affiliateFee` property to specify the recipient addresses, the fee amounts (in bps), and optionally the assets and chains you want the payout to be in. Garden supports payout in USDC and cbBTC.

    <CodeGroup>
      ```ts React theme={null}
      const [_strategyId, quoteAmount] = Object.entries(quoteRes.val.quotes)[0];
      const response = await swapAndInitiate({
          fromAsset,
          toAsset,
          sendAmount: amount.toString(),
          receiveAmount: quoteAmount,
          additionalData: {
              strategyId: _strategyId,
          },
          affiliateFee: [
              {
                  address: "<affiliate_address_1>",
                  asset: "<asset_1>",
                  fee: 30
              },
              // Add more splits as needed
          ]
      });
      ```

      ```ts Node.js theme={null}
      const [_strategyId, quoteAmount] = Object.entries(quoteRes.val.quotes)[0];
      const swapParams: SwapParams = {
          fromAsset,
          toAsset,
          sendAmount,
          receiveAmount: quoteAmount,
          additionalData: {
              strategyId: _strategyId,
          },
          affiliateFee:[
              {
                  address: "<affiliate_address_1>",
                  chain: "<chain_1>",
                  asset: "<asset_1>",
                  fee: 30
              },
              // Add more splits as needed
          ]
      };

      const swapResult = await garden.swap(swapParams);
      ```
    </CodeGroup>
  </Tab>
</Tabs>

## How to claim

The claiming process involves two steps: checking your available earnings through the API, then submitting an on-chain transaction to withdraw them.

### Check available earnings

First, call the earnings endpoint to get your claimable amounts:

```bash cURL theme={null}
curl -X 'GET' 'https://api.garden.finance/v2/apps/earnings' \
    -H 'garden-app-id: YOUR_APP_ID' \
    -H 'accept: application/json'
```

Example response:

```json Success theme={null}
{
  "status": "Ok",
  "result": [
    {
      "total_earnings": "15075000000",
      "total_earnings_usd": "15075",
      "affiliate": "0x004Cc75ACF4132Fc08cB6a252E767804F303F729",
      "asset": "ethereum:usdc",
      "token_address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
      "claim_amount": "5075000000",
      "claim_amount_usd": "5075",
      "claim_signature": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b",
      "claim_contract": "0x5EbEC4D8DA437b2BAD656D43d40fE412bA5D217a"
    }
  ]
}
```

<Note>
  The `claim_amount`, `claim_amount_usd`, `claim_signature`, and `claim_contract` fields are only included when you have unclaimed earnings available.
</Note>

### Claim your earnings

To claim your earnings, you need to call the `claim` function on the distributor contract. Here's how to construct the transaction:

<Note>
  Make sure to call the claim function on the same chain where you received the rewards. For example, if your earnings are in `ethereum:usdc`, you should use the Ethereum mainnet RPC URL and chain configuration.
</Note>

```javascript JavaScript theme={null}
import { createWalletClient, createPublicClient, http, parseAbi } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { mainnet } from 'viem/chains';

async function claimAffiliateEarnings(claimData) {
  const account = privateKeyToAccount('<YOUR_PRIVATE_KEY>');
  
  // Create wallet client for sending transactions
  const walletClient = createWalletClient({
    account,
    chain: mainnet,
    transport: http('YOUR_RPC_URL'),
  });

  // Create public client for reading transaction receipts
  const publicClient = createPublicClient({
    chain: mainnet,
    transport: http('YOUR_RPC_URL'),
  });

  // Parse the ABI for the claim function
  const abi = parseAbi([
    'function claim((address toAddress, address tokenAddress, uint256 totalRewards) _claim, bytes _signature)'
  ]);

  // Prepare claim parameters
  const claimParams = {
    toAddress: claimData.affiliate,
    tokenAddress: claimData.token_address,
    totalRewards: BigInt(claimData.total_earnings)
  };

  // Execute the claim transaction
  const hash = await walletClient.writeContract({
    address: claimData.claim_contract,
    abi,
    functionName: 'claim',
    args: [claimParams, claimData.claim_signature]
  });

  // Wait for transaction receipt
  const receipt = await publicClient.waitForTransactionReceipt({ hash });
  return receipt;
}
```
