> ## 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.

# Leverage on Aave with Transaction Bundler 

> Learn how to use Compass Transaction Bundler for Aave leverage lending. Bundle lend–borrow–swap steps into one atomic transaction to multiply exposure, save gas, and reduce risk.

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>;
};

🕐 Time to complete: ±10 minutes

🧰 What you need:

* Free [Compass API Key](https://www.compasslabs.ai/login)
* Wallet (EOA or [smart account guide](/v1/wallet-support/overview))

## Introduction

Leverage lending (also know as "looping") lets you boost yield by borrowing against your deposit, swapping the loan, and re-depositing — all to multiply exposure. With Compass SDK, you can run the entire leverage workflow in one atomic transaction, no Solidity, no manual steps, minimal gas.

Normally this would require complex smart contract logic and multiple transaction steps. With Compass SDK, you abstract all of that away. This tutorial walks you through implementing Aave leverage strategies to achieve your target leverage.

## Example Aave Leverage Lending

<img src="https://mintcdn.com/compasslabs-f07467e0/PdnWgUgZ4GeU5N3g/images/looping.png?fit=max&auto=format&n=PdnWgUgZ4GeU5N3g&q=85&s=af436b63fd6a4169d18bc98ae4be80e2" alt="Aave Looping Diagram" width="2350" height="1200" data-path="images/looping.png" />

In this example, you're depositing USDC, borrowing ETH, swapping it back into USDC, and re-supplying — on repeat — to achieve a target leverage (e.g. 2.19x). Compass bundles all of this into one atomic transaction.

This illustration demonstrates Aave leverage strategy with the following parameters, assuming that the price of ETH is 2333 USDC:

* Collateral Asset: USDC
* Loan Asset: ETH
* Initial Collateral Amount: 1000 USDC
* Loan to Value Ratio: 70%
* Leverage: 2.19x

The API will figure out the optimal values for each loop and automate all actions.

## Setup

<Steps>
  <Step title="Install Dependencies">
    Install the required packages.

    <CodeGroup>
      ```shellscript Typescript theme={"system"}
      npm install @compass-labs/api-sdk viem dotenv
      ```

      ```shellscript Python theme={"system"}
      pip install compass-api-sdk python-dotenv web3
      ```
    </CodeGroup>
  </Step>

  <Step title="Set Environment Variables">
    Create a .env file in your project root.

    ```dotenv .env theme={"system"}
    PRIVATE_KEY="your_wallet_private_key"
    RPC_URL="your_ethereum_rpc_url"
    COMPASS_API_KEY="your_compass_api_key"
    ```
  </Step>

  <Step title="Import Libraries & Environment Variables">
    <GithubCodeBlock
      typescript={{
name: "index.ts",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v1/aave_looping/typescript/src/index.ts",
snippetNumber: 1,
}}
      python={{
name: "main.py",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v1/aave_looping/python/src/main.py",
snippetNumber: 1,
}}
    />
  </Step>

  <Step title="Initialize SDK and Account">
    <GithubCodeBlock
      typescript={{
name: "index.ts",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v1/aave_looping/typescript/src/index.ts",
snippetNumber: 2,
}}
      python={{
name: "main.py",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v1/aave_looping/python/src/main.py",
snippetNumber: 2,
}}
    />
  </Step>
</Steps>

<Note>
  The full, uninterrupted code is available at the end of the tutorial.
</Note>

## Get Authorization

Before you can execute Aave leverage, you need to get an authorization from the Compass API and sign it with your private key. This ensures only you can execute the batch.

<Steps>
  <Step title="Get and Sign Authorization">
    Request authorization from the Compass API and sign it with your wallet to authenticate the transaction batching.

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

## Configure Aave Leverage Strategy

Now that we have authorization, let's configure the Aave leverage strategy. This involves setting up the parameters for your leverage strategy including collateral token, borrow token, initial amount, and target multiplier.

<Steps>
  <Step title="Configure Leverage Parameters">
    Set up the Aave leverage strategy with your desired parameters. This includes specifying the collateral and borrow tokens, initial amount, leverage multiplier, and risk parameters.

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

## Execute the Transaction

The final step is to sign and broadcast the transaction to the network. This will execute your Aave leverage strategy in a single atomic transaction.

<Steps>
  <Step title="Sign and Broadcast Transaction">
    Sign the returned transaction with your private key and broadcast it to the network. This is the final step to actually send your Aave leveraged transaction to Ethereum.

    <GithubCodeBlock
      typescript={{
name: "index.ts",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v1/aave_looping/typescript/src/index.ts",
snippetNumber: 5,
}}
      python={{
name: "main.py",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v1/aave_looping/python/src/main.py",
snippetNumber: 5,
}}
    />
  </Step>
</Steps>

## Understanding the Parameters

Let's break down the key parameters for the Aave leverage strategy:

### Aave Loop Parameters

* **collateral\_token**: The token you want to supply as collateral (e.g., "USDC", "WETH", "WBTC")
* **borrow\_token**: The token you want to borrow (e.g., "WETH", "USDC")
* **initial\_collateral\_amount**: The amount of collateral token to supply initially
* **multiplier**: The leverage multiplier (e.g., 2.0 means double exposure)
* **max\_slippage\_percent**: Maximum allowed slippage for token swaps (1-100)
* **loan\_to\_value**: The loan-to-value ratio in percentage (0-100)

<Note>
  The loan-to-value (LTV) ratio determines how much you can borrow against your collateral. For example, if LTV is 80%, you can borrow up to 80% of your collateral's value. Be cautious with high LTV ratios as they increase liquidation risk.

  The maximum possible multiplier is determined by the formula: `1 / (1 - loan_to_value/100)`. For example, with an LTV of 80%, the maximum multiplier would be `1 / (1 - 80/100) = 1 / 0.2 = 5`. This represents the theoretical maximum leverage possible at that LTV ratio.
</Note>

## Example Strategies

Here are some example configurations for different risk appetites:

### Conservative Strategy

```typescript theme={"system"}
// TypeScript
const loopingTx = await sdk.transactionBatching.aaveLoop({
  // ... other parameters ...
  collateral_token: "USDC",
  borrow_token: "WETH",
  initial_collateral_amount: 1000,
  multiplier: 1.5,
  max_slippage_percent: 0.5,
  loan_to_value: 65
});
```

```python theme={"system"}
# Python
looping_tx = sdk.transaction_batching.aave_loop(
    # ... other parameters ...
    collateral_token="USDC",
    borrow_token="WETH",
    initial_collateral_amount=1000,
    multiplier=1.5,
    max_slippage_percent=0.5,
    loan_to_value=65
)
```

### Moderate Strategy

```typescript theme={"system"}
// TypeScript
const loopingTx = await sdk.transactionBatching.aaveLoop({
  // ... other parameters ...
  collateral_token: "WETH",
  borrow_token: "USDC",
  initial_collateral_amount: 1,
  multiplier: 2.0,
  max_slippage_percent: 1,
  loan_to_value: 75
});
```

```python theme={"system"}
# Python
looping_tx = sdk.transaction_batching.aave_loop(
    # ... other parameters ...
    collateral_token="WETH",
    borrow_token="USDC",
    initial_collateral_amount=1,
    multiplier=2.0,
    max_slippage_percent=1,
    loan_to_value=75
)
```

### Aggressive Strategy

```typescript theme={"system"}
// TypeScript
const loopingTx = await sdk.transactionBatching.aaveLoop({
  // ... other parameters ...
  collateral_token: "WBTC",
  borrow_token: "USDC",
  initial_collateral_amount: 0.1,
  multiplier: 2.5,
  max_slippage_percent: 1,
  loan_to_value: 80
});
```

```python theme={"system"}
# Python
looping_tx = sdk.transaction_batching.aave_loop(
    # ... other parameters ...
    collateral_token="WBTC",
    borrow_token="USDC",
    initial_collateral_amount=0.1,
    multiplier=2.5,
    max_slippage_percent=1,
    loan_to_value=80
)
```

## Risk Considerations

When implementing Aave leverage strategies, consider the following risks:

1. **Liquidation Risk**: Higher LTV ratios increase the risk of liquidation if the collateral value drops
2. **Interest Rate Risk**: Borrowing rates may increase, affecting the profitability of your position
3. **Slippage Risk**: Large trades may experience significant slippage, especially in volatile markets
4. **Smart Contract Risk**: Always verify contract addresses and permissions

<Tip>
  For further practice, try different token pairs, test with various leverage multipliers, or explore other [Compass Bundler](/v1/transaction-bundler/introduction) features to bundle additional transactions.
</Tip>

## Full Code

Here is the full script from the tutorial. Copy and paste into your code editor and play around!

<GithubCodeBlock
  typescript={{
name: "index.ts",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v1/aave_looping/typescript/src/index.ts",
numOfLinesExpandable: 56,
}}
  python={{
name: "main.py",
url: "https://raw.githubusercontent.com/CompassLabs/api_usecases/main/v1/aave_looping/python/src/main.py",
numOfLinesExpandable: 56,
}}
/>

## Resources

<CardGroup cols={2}>
  <Card title="Compass API Docs" icon="compass" href="https://docs.compasslabs.ai/v1/api-reference/transaction-bundler/aave-leverage-longshort">
    Access detailed API documentation and references
  </Card>

  <Card title="AAVE Documentation" icon="book" href="https://docs.aave.com">
    Learn more about AAVE's lending protocol
  </Card>

  <Card title="GitHub Examples" icon="github" href="https://github.com/CompassLabs/api_usecases/tree/main/v1/aave_looping">
    View more code examples and implementations
  </Card>
</CardGroup>
