@cowprotocol/sdk-flash-loans

中文文档
4.1.3发布于 2026/11/04MITTypeScriptESM + CJS构建来源已验证近 30 天下载 2587

Flash loans for CoW Protocol

原始使用文档
文档目录31 节
  1. Test coverage
  2. How It Works
  3. Why Use Flash Loans?
  4. Installation
  5. Setup
  6. Usage
  7. Basic Collateral Swap
  8. Advanced Usage with Quote Review
  9. Flash Loan Fee
  10. Collateral Token Parameter
  11. What are aTokens?
  12. Common aTokens on Gnosis Chain
  13. Usage Example
  14. Collateral Token Approval
  15. Automatic Approval
  16. Manual Approval with getCollateralAllowance and approveColl…
  17. Gasless Approval with EIP-2612 Permit
  18. Custom Hook Gas Limits
  19. Default Gas Limits
  20. Customizing Gas Limits
  21. How Hooks Work
  22. Pre-Hook
  23. Post-Hook
  24. Error Handling
  25. Advanced Topics
  26. EIP-1271 Signatures
  27. Gas Optimization
  28. Adapter Contracts
  29. Limitations
  30. Security Considerations
  31. Resources

Flash Loans SDK

Test coverage

StatementsBranchesFunctionsLines
StatementsBranchesFunctionsLines

Execute flash loan-based collateral swaps using Aave Protocol V3 integrated with CoW Protocol for optimal trading execution.

This SDK facilitates complex flash loan operations where you can:

  • Borrow assets via Aave flash loans
  • Swap collateral using CoW Protocol's intent-based trading
  • Repay flash loans automatically with optimized execution
  • Use CoW Protocol hooks to manage the entire flow

How It Works

  1. 💸 Borrow tokens via Aave flash loan
  2. 🔄 Execute a CoW Protocol swap to desired collateral
  3. ⚙️ Use CoW hooks to deploy adapter contracts and manage the swap
  4. ✅ Automatically repay the flash loan with fees

The order is signed using EIP-1271 with a deterministically generated smart contract address as the signer.

Why Use Flash Loans?

  • Capital Efficiency - No upfront capital required to swap collateral
  • Atomic Execution - The entire operation succeeds or reverts atomically
  • Gas Optimization - Single transaction for complex multi-step operations
  • Aave Integration - Leverage Aave V3's flash loan infrastructure
  • CoW Protocol Benefits - MEV protection and optimal execution via batch auctions

Installation

npm install @cowprotocol/sdk-flash-loans
# or
pnpm add @cowprotocol/sdk-flash-loans
# or
yarn add @cowprotocol/sdk-flash-loans

You'll also need the trading SDK:

npm install @cowprotocol/sdk-trading

Setup

You need:

  • chainId - Supported chain ID (see SDK config)
  • appCode - Unique app identifier for tracking orders
  • signer - Private key, ethers signer, or Eip1193 provider
  • TradingSdk instance - For getting quotes and posting orders

Usage

Basic Collateral Swap

import { AaveCollateralSwapSdk } from '@cowprotocol/sdk-flash-loans'
import { TradingSdk } from '@cowprotocol/sdk-trading'
import { SupportedChainId } from '@cowprotocol/sdk-config'
import { OrderKind } from '@cowprotocol/sdk-order-book'
import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter'
import { createPublicClient, http, privateKeyToAccount } from 'viem'
import { gnosis } from 'viem/chains'

// Set up adapter
const adapter = new ViemAdapter({
  provider: createPublicClient({
    chain: gnosis,
    transport: http('YOUR_RPC_URL')
  }),
  signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
})

// Initialize the Trading SDK
const tradingSdk = new TradingSdk(
  {
    chainId: SupportedChainId.GNOSIS_CHAIN,
    appCode: 'aave-v3-flashloan',
  },
  {},
  adapter
)

// Initialize the Flash Loan SDK
const flashLoanSdk = new AaveCollateralSwapSdk()

// Execute collateral swap
const result = await flashLoanSdk.collateralSwap(
  {
    chainId: SupportedChainId.GNOSIS_CHAIN,
    tradeParameters: {
      sellToken: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', // WXDAI
      sellTokenDecimals: 18,
      buyToken: '0x2a22f9c3b484c3629090FeED35F17Ff8F88f76F0', // USDC.e
      buyTokenDecimals: 6,
      amount: '20000000000000000000', // 20 WXDAI
      kind: OrderKind.SELL,
      validFor: 600, // 10 minutes
      slippageBps: 50, // 0.5% slippage
    },
    collateralToken: '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533', // aGnoWXDAI (Aave interest-bearing WXDAI)
    flashLoanFeePercent: 0.05, // 0.05% flash loan fee
  },
  tradingSdk
)

console.log('Flash loan order created:', result.orderId)

Advanced Usage with Quote Review

For maximum control over the process, including manual approval management:

import { AaveCollateralSwapSdk } from '@cowprotocol/sdk-flash-loans'
import { TradingSdk } from '@cowprotocol/sdk-trading'
import { SupportedChainId } from '@cowprotocol/sdk-config'
import { OrderKind } from '@cowprotocol/sdk-order-book'

const flashLoanSdk = new AaveCollateralSwapSdk()

const collateralToken = '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533' // aGnoWXDAI

// Step 1: Prepare quote parameters
const params = {
  chainId: SupportedChainId.GNOSIS_CHAIN,
  tradeParameters: {
    sellToken: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d',
    sellTokenDecimals: 18,
    buyToken: '0x2a22f9c3b484c3629090FeED35F17Ff8F88f76F0',
    buyTokenDecimals: 6,
    amount: '20000000000000000000',
    kind: OrderKind.SELL,
  },
  collateralToken,
  flashLoanFeePercent: 0.05,
}

const quoteParams = await flashLoanSdk.getSwapQuoteParams(params)

// Step 2: Get quote
const quoteAndPost = await tradingSdk.getQuote(quoteParams)
const { quoteResults } = quoteAndPost

// Step 3: Review the quote
const buyAmount = quoteResults.amountsAndCosts.afterSlippage.buyAmount
console.log(`You will receive at least: ${buyAmount} tokens`)

// Step 4: Generate order settings and get instance address
const { swapSettings, instanceAddress } = await flashLoanSdk.getOrderPostingSettings(
  params,
  quoteParams,
  quoteResults
)

// Step 5: Check collateral allowance
const sellAmount = BigInt(params.tradeParameters.amount)
const allowance = await flashLoanSdk.getCollateralAllowance({
  trader: quoteParams.owner,
  collateralToken,
  amount: sellAmount,
  instanceAddress,
})

console.log(`Current allowance: ${allowance.toString()}`)
console.log(`Required amount: ${sellAmount.toString()}`)

// Step 6: Approve collateral if needed
if (allowance < sellAmount) {
  console.log('Insufficient allowance, approving...')
  const txResponse = await flashLoanSdk.approveCollateral({
    trader: quoteParams.owner,
    collateralToken,
    amount: sellAmount,
    instanceAddress,
  })
  console.log('Approval transaction:', txResponse.hash)
  // Optionally wait for confirmation here
} else {
  console.log('Sufficient allowance already exists')
}

// Step 7: Post the order
const result = await quoteAndPost.postSwapOrderFromQuote(swapSettings)
console.log('Order posted:', result.orderId)

Flash Loan Fee

Aave flash loans typically charge a fee (currently 0.05% on most assets). This fee is:

  • Deducted from the sell amount before getting the quote
  • Ensures the swap proceeds cover both the desired output and flash loan repayment
  • Configurable via flashLoanFeePercent parameter

Example:

// With 0.05% flash loan fee on 20 WXDAI:
// - Flash loan: 20 WXDAI
// - Fee: 0.01 WXDAI (0.05% of 20)
// - Actual swap amount: 19.99 WXDAI
{
  amount: '20000000000000000000',
  flashLoanFeePercent: 0.05, // 0.05%
}

Collateral Token Parameter

The collateralToken parameter specifies which Aave interest-bearing token (aToken) will be used as collateral for the flash loan operation.

What are aTokens?

When you deposit assets into Aave, you receive aTokens (e.g., aWXDAI, aUSDC) that:

  • Represent your deposited collateral
  • Accrue interest automatically
  • Can be used for flash loan collateral swaps
  • Need approval for the flash loan adapter to spend

Common aTokens on Gnosis Chain

const AAVE_TOKENS = {
  aGnoWXDAI: '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533', // Aave WXDAI
  aGnoUSDC: '0xc6B7AcA6DE8a6044E0e32d0c841a89244A10D284',  // Aave USDC
  // Add more as needed
}

Usage Example

const result = await flashLoanSdk.collateralSwap(
  {
    chainId: SupportedChainId.GNOSIS_CHAIN,
    tradeParameters: {
      sellToken: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', // WXDAI (what we're swapping)
      buyToken: '0x2a22f9c3b484c3629090FeED35F17Ff8F88f76F0',  // USDC.e (what we want)
      amount: '20000000000000000000',
      kind: OrderKind.SELL,
    },
    collateralToken: '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533', // aGnoWXDAI (our Aave collateral)
    flashLoanFeePercent: 0.05,
  },
  tradingSdk
)

Important Notes:

  • The collateralToken must be an Aave aToken address
  • You must have sufficient aToken balance for collateral
  • The SDK automatically handles approval of this token
  • This is different from sellToken (which is the underlying asset being swapped)

Collateral Token Approval

Before executing a collateral swap, the flash loan adapter needs approval to spend your collateral tokens. The SDK handles this automatically but also provides methods for manual control.

Automatic Approval

By default, collateralSwap() automatically checks and approves collateral if needed:

// Automatic approval happens here
const result = await flashLoanSdk.collateralSwap(
  {
    chainId: SupportedChainId.GNOSIS_CHAIN,
    tradeParameters: { /* ... */ },
    collateralToken: '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533', // aGnoWXDAI
  },
  tradingSdk
)

Manual Approval with getCollateralAllowance and approveCollateral

For more control over the approval process:

// Step 1: Get the adapter instance address
const quoteParams = await flashLoanSdk.getSwapQuoteParams(params)
const quoteAndPost = await tradingSdk.getQuote(quoteParams)
const { swapSettings, instanceAddress } = await flashLoanSdk.getOrderPostingSettings(
  params,
  quoteParams,
  quoteAndPost.quoteResults
)
const sellAmount = BigInt(params.tradeParameters.amount)

// Step 2: Check current allowance
const allowance = await flashLoanSdk.getCollateralAllowance({
  trader: quoteParams.owner,
  collateralToken: '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533',
  amount: sellAmount,
  instanceAddress,
})

console.log('Current allowance:', allowance.toString())

// Step 3: Approve if needed
if (allowance < sellAmount) {
  const txResponse = await flashLoanSdk.approveCollateral({
    trader: quoteParams.owner,
    collateralToken: '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533',
    amount: sellAmount,
    instanceAddress,
  })
  console.log('Approval transaction:', txResponse.hash)
  // Wait for confirmation...
}

// Step 4: Execute swap with approval prevention
const result = await flashLoanSdk.collateralSwap(
  {
    chainId: SupportedChainId.GNOSIS_CHAIN,
    tradeParameters: { /* ... */ },
    collateralToken: '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533',
    settings: {
      preventApproval: true, // Skip automatic approval
    },
  },
  tradingSdk
)

Gasless Approval with EIP-2612 Permit

For tokens that support EIP-2612, you can use permit for gasless approval:

// Generate permit signature (implementation varies by wallet)
const collateralPermit = {
  amount: 0,
  deadline: Math.floor(Date.now() / 1000) + 3600, // 1 hour
  v: 27,
  r: '0x...',
  s: '0x...',
}

const result = await flashLoanSdk.collateralSwap(
  {
    chainId: SupportedChainId.GNOSIS_CHAIN,
    tradeParameters: { /* ... */ },
    collateralToken: '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533',
    settings: {
      collateralPermit, // Use permit instead of approve
    },
  },
  tradingSdk
)

Custom Hook Gas Limits

The SDK uses default gas limits for pre and post-execution hooks (300,000 and 600,000 respectively). You can customize these limits per operation if needed.

Default Gas Limits

  • Pre-hook: 300,000 gas (deploys adapter and sets up flash loan)
  • Post-hook: 600,000 gas (executes swap and repays flash loan)

Customizing Gas Limits

You can override gas limits in two ways:

1. Per-Operation Override

Pass hooksGasLimit in the trade parameters:

const result = await flashLoanSdk.collateralSwap(
  {
    chainId: SupportedChainId.GNOSIS_CHAIN,
    tradeParameters: {
      sellToken: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d',
      sellTokenDecimals: 18,
      buyToken: '0x2a22f9c3b484c3629090FeED35F17Ff8F88f76F0',
      buyTokenDecimals: 6,
      amount: '20000000000000000000',
      kind: OrderKind.SELL,
      validFor: 600,
      slippageBps: 50,
    },
    settings: {
      hooksGasLimit: {
        preHookGasLimit: 500000n,  // Custom pre-hook gas limit
        postHookGasLimit: 800000n, // Custom post-hook gas limit
      },
    },
    collateralToken: '0xd0Dd6cEF72143E22cCED4867eb0d5F2328715533',
  },
  tradingSdk
)

2. SDK-Wide Default Override

Set custom defaults when initializing the SDK:

const flashLoanSdk = new AaveCollateralSwapSdk({
  hooksGasLimit: {
    pre: 500000n,  // Custom default pre-hook gas limit
    post: 800000n, // Custom default post-hook gas limit
  },
})

// All operations will now use these defaults unless overridden per-operation

How Hooks Work

The SDK uses CoW Protocol hooks to orchestrate the flash loan:

Pre-Hook

  • Deploys the Aave adapter contract deterministically
  • Transfers the flash loan to the adapter
  • Sets up the swap parameters

Post-Hook

  • Executes the collateral swap via the adapter
  • Repays the Aave flash loan with fees
  • Transfers remaining tokens to the owner

All hooks are automatically configured and gas estimated by the SDK.

Error Handling

Common errors and solutions:

Insufficient flash loan amount

// Error: Flash loan amount doesn't cover fee + swap
// Solution: Increase amount or adjust flash loan fee
{
  amount: '20000000000000000000', // Increase this
  flashLoanFeePercent: 0.05,
}

Slippage too tight

// Error: Slippage tolerance too low for current market conditions
// Solution: Increase slippageBps
{
  slippageBps: 100, // Increase from 50 to 100 (1%)
}

Order expired

// Error: Order validity period too short
// Solution: Increase validFor
{
  validFor: 1200, // 20 minutes instead of 10
}

Advanced Topics

EIP-1271 Signatures

Flash loan orders use EIP-1271 signature verification with a deterministically generated smart contract address. This enables:

  • Gasless order creation
  • Deterministic contract deployment
  • Secure flash loan execution

Gas Optimization

The SDK automatically:

  • Estimates gas for hook execution
  • Uses fallback gas limits if estimation fails
  • Optimizes hook call data encoding

Adapter Contracts

Adapter contracts are:

  • Deployed deterministically using CREATE2
  • Reusable across multiple flash loan operations
  • Managed automatically by the SDK

Limitations

  • Only supports Aave V3 flash loans
  • Requires sufficient liquidity in Aave pools
  • Flash loan fees apply (typically 0.05%)
  • Subject to CoW Protocol order limits
  • Network-specific contract deployments required

Security Considerations

  • Always review quotes before execution
  • Set appropriate slippage tolerances
  • Verify token addresses and decimals
  • Test with small amounts first
  • Monitor transaction execution
  • Be aware of flash loan fees and costs

Resources

版本与发布记录

@cowprotocol/sdk-flash-loans 共发布 84 个版本,首次发布于 2025/10/24;过去 12 个月发布了 76 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.1.3latest2026/11/046 天前
4.1.22026/11/046 天前
4.1.12026/11/037 天前
4.1.02026/10/2615 天前
4.0.12026/10/2318 天前
4.0.02026/10/1328 天前

关于 @cowprotocol/sdk-flash-loans 的常见问题

@cowprotocol/sdk-flash-loans 是什么?

Flash loans for CoW Protocol

如何安装 @cowprotocol/sdk-flash-loans?

在项目目录运行 npm install @cowprotocol/sdk-flash-loans,或使用 pnpm add / yarn add / bun add。

@cowprotocol/sdk-flash-loans 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cowprotocol/sdk-flash-loans 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cowprotocol/sdk-flash-loans 可以商用吗?

@cowprotocol/sdk-flash-loans 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cowprotocol/sdk-flash-loans 的下载量有多少?

根据 npm 官方下载统计,@cowprotocol/sdk-flash-loans 在 2026/10/11 – 2026/11/09 这 30 天内被下载 2,587 次,日均约 86 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cowprotocol/sdk-flash-loans 还在维护吗?

最新版本 4.1.3 发布于 2026/11/04(6 天前);至今共发布 84 个版本,其中过去 12 个月发布了 76 个;首次发布于 2025/10/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。