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

# Embedded Fees

> Monetize your integration by embedding fees directly in transaction payloads. When users deposit, withdraw, or swap, fees are automatically collected and routed to your address.

export const GithubCodeBlock = ({typescript, python}) => {
  const [typescriptCode, setTypescriptCode] = useState("");
  const [pythonCode, setPythonCode] = useState("");
  function removeWhitespace(strings, x) {
    return strings.map(str => {
      let count = 0;
      let i = 0;
      while (i < str.length && count < x && str[i] === " ") {
        count++;
        i++;
      }
      return str.slice(i);
    });
  }
  function cropToSnippet({text, from, to}) {
    const lines = text.split("\n");
    let result = [];
    let isCollecting = false;
    for (const line of lines) {
      if (line.trim() === from) {
        isCollecting = true;
        continue;
      }
      if (line.trim() === to) {
        break;
      }
      if (isCollecting) {
        result.push(line);
      }
    }
    const whitespaceToDelete = result[0].length - result[0].trimStart().length;
    result = removeWhitespace(result, whitespaceToDelete);
    return result.join("\n");
  }
  function removeSnippetComments(code) {
    return code.replace(/(\/\/|#) SNIPPET (START|END) \d+(\n|$)/g, "");
  }
  useEffect(() => {
    if (!typescript) return;
    fetch(typescript.url).then(response => response.text()).then(text => {
      let code = text;
      if (typescript.snippetNumber) {
        code = cropToSnippet({
          text,
          from: `// SNIPPET START ${typescript.snippetNumber}`,
          to: `// SNIPPET END ${typescript.snippetNumber}`
        });
      } else {
        code = removeSnippetComments(code);
      }
      setTypescriptCode(code);
    }).catch(error => {
      console.error("Error loading file:", error);
    });
  }, [typescript]);
  useEffect(() => {
    if (!python) return;
    fetch(python.url).then(response => response.text()).then(text => {
      let code = text;
      if (python.snippetNumber) {
        code = cropToSnippet({
          text,
          from: `# SNIPPET START ${python.snippetNumber}`,
          to: `# SNIPPET END ${python.snippetNumber}`
        });
      } else {
        code = removeSnippetComments(code);
      }
      setPythonCode(code);
    }).catch(error => {
      console.error("Error loading file:", error);
    });
  }, [python]);
  if (!python && !typescript) return null;
  if (!python) {
    return <CodeBlock language="typescript" filename={typescript.name} expandable={typescript?.numOfLinesExpandable ? "true" : null} lines="true" icon="https://upload.wikimedia.org/wikipedia/commons/f/f5/Typescript.svg" code={typescriptCode} children={typescriptCode || !typescript?.numOfLinesExpandable || <div style={{
      whiteSpace: "pre-wrap"
    }}>
        {Array(typescript?.numOfLinesExpandable).fill("-").map(x => x).join("\n")}
      </div>} />;
  }
  if (!typescript) {
    return <CodeBlock language="python" filename={python.name} expandable={python?.numOfLinesExpandable ? "true" : null} lines="true" icon="https://upload.wikimedia.org/wikipedia/commons/c/c3/Python-logo-notext.svg" code={pythonCode} children={pythonCode || !python?.numOfLinesExpandable || <div style={{
      whiteSpace: "pre-wrap"
    }}>
        {Array(python?.numOfLinesExpandable).fill("-").map(x => x).join("\n")}
      </div>} />;
  }
  return <CodeGroup>
  <CodeBlock language="typescript" filename={typescript.name} expandable={typescript?.numOfLinesExpandable ? "true" : null} lines="true" icon="https://upload.wikimedia.org/wikipedia/commons/f/f5/Typescript.svg" code={typescriptCode} children={typescriptCode || !typescript?.numOfLinesExpandable || <div style={{
    whiteSpace: "pre-wrap"
  }}>
          {Array(typescript?.numOfLinesExpandable).fill("-").map(x => x).join("\n")}
        </div>} />
  <CodeBlock language="python" filename={python.name} expandable={python?.numOfLinesExpandable ? "true" : null} lines="true" icon="https://upload.wikimedia.org/wikipedia/commons/c/c3/Python-logo-notext.svg" code={pythonCode} children={pythonCode || !python?.numOfLinesExpandable || <div style={{
    whiteSpace: "pre-wrap"
  }}>
          {Array(python?.numOfLinesExpandable).fill("-").map(x => x).join("\n")}
        </div>} />
</CodeGroup>;
};

## Why This Matters

Monetize your DeFi integration from day one without building payment infrastructure.

**The problem**: Building payment rails for collecting fees is complex. You need to make new smart contracts for fee collection and separate transactions. Most teams delay monetization for months while building infrastructure.

**What Compass enables**: Fees are embedded directly in transaction payloads and collected atomically with the primary operation. No separate transfers, no new smart contracts and no delays. Charge on yield generated and start generating revenue immediately.

**Revenue example**: User deposits \$10,000, earns \$500 yield, you charge 20% performance fee = \$100 revenue per profitable withdrawal.

***

## How It Works

**Example: Withdraw with 20% performance fee on yield**

User deposited \$10,000 USDC, vault grew to \$10,500 (\$500 yield):

* \$100 USDC (20% of \$500 yield) → your fee address
* \$10,400 USDC → user
* Single atomic transaction

**Fee timing**:

* **Deposits**: Fee deducted BEFORE vault deposit
* **Withdrawals**: Fee deducted AFTER vault withdrawal
* **Performance fees**: Calculated on realized profit only (FIFO cost basis)

If the operation fails, the fee transfer also reverts. No partial execution.

***

## Fee Object Structure

Fees are configured using a `fee` object in the [`/v2/earn/manage`](/v2/api-reference/earn/manage-earn-position) endpoint with three parameters:

```json theme={"system"}
{
  "recipient": "0xYourFeeAddress",
  "amount": 20,
  "denomination": "PERFORMANCE"
}
```

### Parameters

**`recipient`** (string, required)

* The wallet address that receives the fee
* Example: `"0xb8340945eBc917D2Aa0368a5e4E79C849c461511"`

**`amount`** (number, required)

* The fee amount (meaning depends on denomination)
* For PERCENTAGE: fee as % of transaction (e.g., `1.5` = 1.5%, `10` = 10 bps = 0.1%)
* For FIXED: fixed amount in token units (e.g., `0.1` = 0.1 USDC)
* For PERFORMANCE: fee as % of realized profit (e.g., `20` = 20% of profit)

**`denomination`** (string, required)

* The unit type for the fee amount
* Options: `"PERCENTAGE"`, `"FIXED"`, `"PERFORMANCE"`
* Default: `"PERCENTAGE"`

***

## Implementation Example

### Withdraw with Performance Fee

Charge 20% on realized yield when users withdraw. This walk-through withdraws from a vault with an embedded performance fee. Compass calculates profit using FIFO cost basis and collects 20% of any realized gains.

Load environment variables and initialize the SDK:

<GithubCodeBlock
  typescript={{
name: "index.ts",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v2/embedding_a_fee/typescript/src/index.ts",
snippetNumber: 1,
}}
  python={{
name: "main.py",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v2/embedding_a_fee/python/main.py",
snippetNumber: 1,
}}
/>

Initialize the Compass API client:

<GithubCodeBlock
  typescript={{
name: "index.ts",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v2/embedding_a_fee/typescript/src/index.ts",
snippetNumber: 2,
}}
  python={{
name: "main.py",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v2/embedding_a_fee/python/main.py",
snippetNumber: 2,
}}
/>

Generate the unsigned transaction with the embedded performance fee:

<GithubCodeBlock
  typescript={{
name: "index.ts",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v2/embedding_a_fee/typescript/src/index.ts",
snippetNumber: 3,
}}
  python={{
name: "main.py",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v2/embedding_a_fee/python/main.py",
snippetNumber: 3,
}}
/>

Sign and broadcast the transaction:

<GithubCodeBlock
  typescript={{
name: "index.ts",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v2/embedding_a_fee/typescript/src/index.ts",
snippetNumber: 4,
}}
  python={{
name: "main.py",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v2/embedding_a_fee/python/main.py",
snippetNumber: 4,
}}
/>

**What happens**:

* User withdraws from vault
* Compass calculates realized profit using FIFO cost basis
* 20% of profit goes to your fee address
* Remaining amount goes to the user
* No fee charged if withdrawal results in a loss

***

## Next Steps

Start monetizing your integration:

<CardGroup cols={3}>
  <Card title="Product Accounts" icon="wallet" href="/v2/Products/Accounts">
    Create isolated accounts to enable bundled transactions with embedded fees.
  </Card>

  <Card title="Gas Sponsorship" icon="gas-pump" href="/v2/Products/gas-sponsorship">
    Combine fees with gas sponsorship for better UX while covering costs.
  </Card>

  <Card title="Earn" icon="chart-line" href="/v2/Products/Earn">
    Explore all Earn endpoints that support embedded fees.
  </Card>
</CardGroup>
